[{"prompt": " \"\"\"\"\"\" import sys try : from urllib . parse import quote except ImportError : from urllib import quote PYTHON3 = True if sys . version_info > ( , , ) else False def is_string ( value ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import tornado . httpserver import tornado . ioloop import tornado . web import sys from scribe import scribe from thrift . transport import TTransport , TSocket from thrift . protocol import TBinaryProtocol import logging import hmac ", "answer": "import hashlib"}, {"prompt": " '''''' from python_toolbox . freezing import FreezerProperty , Freezer from python_toolbox import caching def test_lone_freezer_property ( ) : '''''' class A : lone_freezer = FreezerProperty ( ) a = A ( ) assert isinstance ( a . lone_freezer , Freezer ) assert a . lone_freezer . frozen == with a . lone_freezer : assert a . lone_freezer . frozen def test_decorate_happy_freezer_property ( ) : '''''' class C : decorate_happy_freeze_counter = caching . CachedProperty ( ) decorate_happy_thaw_counter = caching . CachedProperty ( ) decorate_happy_freezer = FreezerProperty ( ) @ decorate_happy_freezer . on_freeze def increment_decorate_happy_freeze_counter ( self ) : self . decorate_happy_freeze_counter += @ decorate_happy_freezer . on_thaw def increment_decorate_happy_thaw_counter ( self ) : self . decorate_happy_thaw_counter += b = C ( ) assert b . decorate_happy_freezer . frozen == assert b . decorate_happy_freeze_counter == assert b . decorate_happy_thaw_counter == with b . decorate_happy_freezer : assert b . decorate_happy_freezer . frozen == assert b . decorate_happy_freeze_counter == assert b . decorate_happy_thaw_counter == with b . decorate_happy_freezer : assert b . decorate_happy_freezer . frozen == assert b . decorate_happy_freeze_counter == assert b . decorate_happy_thaw_counter == assert b . decorate_happy_freezer . frozen == assert b . decorate_happy_freeze_counter == assert b . decorate_happy_thaw_counter == assert b . decorate_happy_freezer . frozen == assert b . decorate_happy_freeze_counter == assert b . decorate_happy_thaw_counter == with b . decorate_happy_freezer : assert b . decorate_happy_freezer . frozen == assert b . decorate_happy_freeze_counter == assert b . decorate_happy_thaw_counter == assert b . decorate_happy_freezer . frozen == assert b . decorate_happy_freeze_counter == assert b . decorate_happy_thaw_counter == def test_argument_happy_freezer_property ( ) : '''''' class C : argument_happy_freeze_counter = caching . CachedProperty ( ) argument_happy_thaw_counter = caching . CachedProperty ( ) def increment_argument_happy_freeze_counter ( self ) : self . argument_happy_freeze_counter += def increment_argument_happy_thaw_counter ( self ) : self . argument_happy_thaw_counter += argument_happy_freezer = FreezerProperty ( on_freeze = increment_argument_happy_freeze_counter , on_thaw = increment_argument_happy_thaw_counter , name = '' ) c = C ( ) assert c . argument_happy_freezer . frozen == assert c . argument_happy_freeze_counter == assert c . argument_happy_thaw_counter == with c . argument_happy_freezer : assert c . argument_happy_freezer . frozen == assert c . argument_happy_freeze_counter == assert c . argument_happy_thaw_counter == with c . argument_happy_freezer : assert c . argument_happy_freezer . frozen == assert c . argument_happy_freeze_counter == assert c . argument_happy_thaw_counter == assert c . argument_happy_freezer . frozen == assert c . argument_happy_freeze_counter == assert c . argument_happy_thaw_counter == assert c . argument_happy_freezer . frozen == assert c . argument_happy_freeze_counter == assert c . argument_happy_thaw_counter == with c . argument_happy_freezer : assert c . argument_happy_freezer . frozen == assert c . argument_happy_freeze_counter == assert c . argument_happy_thaw_counter == assert c . argument_happy_freezer . frozen == assert c . argument_happy_freeze_counter == assert c . argument_happy_thaw_counter == def test_mix_freezer_property ( ) : '''''' class D : mix_freeze_counter = caching . CachedProperty ( ) mix_thaw_counter = caching . CachedProperty ( ) def increment_mix_freeze_counter ( self ) : self . mix_freeze_counter += mix_freezer = FreezerProperty ( on_freeze = increment_mix_freeze_counter ) @ mix_freezer . on_thaw def increment_mix_thaw_counter ( self ) : self . mix_thaw_counter += d = D ( ) assert d . mix_freezer . frozen == assert d . mix_freeze_counter == assert d . mix_thaw_counter == with d . mix_freezer : assert d . mix_freezer . frozen == assert d . mix_freeze_counter == assert d . mix_thaw_counter == with d . mix_freezer : assert d . mix_freezer . frozen == assert d . mix_freeze_counter == assert d . mix_thaw_counter == assert d . mix_freezer . frozen == assert d . mix_freeze_counter == assert d . mix_thaw_counter == assert d . mix_freezer . frozen == assert d . mix_freeze_counter == assert d . mix_thaw_counter == with d . mix_freezer : assert d . mix_freezer . frozen == assert d . mix_freeze_counter == assert d . mix_thaw_counter == assert d . mix_freezer . frozen == assert d . mix_freeze_counter == assert d . mix_thaw_counter == def test_different_type_freezer_property ( ) : '''''' class CustomFreezer ( Freezer ) : def __init__ ( self , obj ) : self . obj = obj def freeze_handler ( self ) : self . obj . different_type_freeze_counter += def thaw_handler ( self ) : self . obj . different_type_thaw_counter += class E : different_type_freeze_counter = caching . CachedProperty ( ) different_type_thaw_counter = caching . CachedProperty ( ) different_type_freezer = FreezerProperty ( freezer_type = CustomFreezer , doc = '' ) e = E ( ) assert E . different_type_freezer . __doc__ == '' assert e . different_type_freezer . frozen == assert e . different_type_freeze_counter == assert e . different_type_thaw_counter == with e . different_type_freezer : assert e . different_type_freezer . frozen == assert e . different_type_freeze_counter == assert e . different_type_thaw_counter == with e . different_type_freezer : assert e . different_type_freezer . frozen == assert e . different_type_freeze_counter == assert e . different_type_thaw_counter == assert e . different_type_freezer . frozen == assert e . different_type_freeze_counter == assert e . different_type_thaw_counter == assert e . different_type_freezer . frozen == assert e . different_type_freeze_counter == assert e . different_type_thaw_counter == ", "answer": "with e . different_type_freezer :"}, {"prompt": " \"\"\"\"\"\" __all__ = [ '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " import pyexcel as pe from _compact import OrderedDict from nose . tools import raises class TestFormattableSheet : def setUp ( self ) : self . data = [ [ , , , , , , , ] , [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] , [ , , , , , , , ] , [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] , [ , , , , , , , ] , [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] ] def test_apply_row_formatter ( self ) : s = pe . sheets . FormattableSheet ( self . data ) s . apply_formatter ( pe . formatters . RowFormatter ( , str ) ) assert s . row [ ] == s . row [ ] def test_apply_column_formatter ( self ) : s = pe . sheets . FormattableSheet ( self . data ) s . apply_formatter ( pe . formatters . ColumnFormatter ( , float ) ) assert s . column [ ] == [ , , , , , ] def test_apply_sheet_formatter ( self ) : s = pe . sheets . FormattableSheet ( self . data ) s . apply_formatter ( pe . formatters . SheetFormatter ( float ) ) assert s . row [ ] == s . row [ ] assert s . column [ ] == [ , , , , , ] def test_freeze_formatter ( self ) : s = pe . sheets . FormattableSheet ( self . data ) s . freeze_formatters ( ) def test_empty_sheet ( self ) : s = pe . sheets . FormattableSheet ( [ ] ) ret = s . cell_value ( , ) assert ret is None ret = s . _cell_value ( , ) assert ret == \"\" class TestFilterSheet : def test_freeze_filters ( self ) : data = [ [ , , ] , [ , , ] ] s = pe . sheets . FilterableSheet ( data ) s . add_filter ( pe . filters . EvenRowFilter ( ) ) s . freeze_filters ( ) assert s . row [ ] == [ , , ] assert s . column [ ] == [ ] @ raises ( NotImplementedError ) def test_non_filter ( self ) : data = [ ] s = pe . sheets . FilterableSheet ( data ) s . filter ( \"\" ) class TestSheetNamedColumn : def setUp ( self ) : self . data = [ [ \"\" , \"\" , \"\" ] , [ , , ] , [ , , ] , [ , , ] ] def test_formatter_by_named_column ( self ) : \"\"\"\"\"\" s = pe . sheets . NominableSheet ( self . data , \"\" ) s . name_columns_by_row ( ) f = pe . formatters . NamedColumnFormatter ( \"\" , str ) s . apply_formatter ( f ) assert s . column [ \"\" ] == [ \"\" , \"\" , \"\" ] def test_formatter_by_named_columns ( self ) : \"\"\"\"\"\" s = pe . sheets . NominableSheet ( self . data , \"\" ) s . name_columns_by_row ( ) f = pe . formatters . NamedColumnFormatter ( [ \"\" , \"\" ] , str ) s . apply_formatter ( f ) assert s . column [ \"\" ] == [ \"\" , \"\" , \"\" ] assert s . column [ \"\" ] == [ \"\" , \"\" , \"\" ] @ raises ( IndexError ) def test_formatter_by_named_column3 ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import unittest import IECore import Gaffer import GafferTest import GafferScene import GafferSceneTest class SceneTimeWarpTest ( GafferSceneTest . SceneTestCase ) : def testConstruct ( self ) : s = Gaffer . ScriptNode ( ) s [ \"\" ] = GafferScene . SceneTimeWarp ( ) self . assertEqual ( s [ \"\" ] [ \"\" ] . getValue ( ) , ) self . assertEqual ( s [ \"\" ] [ \"\" ] . getValue ( ) , ) def testRunTimeTyped ( self ) : n = GafferScene . SceneTimeWarp ( ) self . failUnless ( n . isInstanceOf ( GafferScene . SceneTimeWarp . staticTypeId ( ) ) ) self . failUnless ( n . isInstanceOf ( GafferScene . SceneContextProcessor . staticTypeId ( ) ) ) self . failUnless ( n . isInstanceOf ( GafferScene . SceneProcessor . staticTypeId ( ) ) ) ", "answer": "self . failUnless ( n . isInstanceOf ( GafferScene . SceneNode . staticTypeId ( ) ) )"}, {"prompt": " \"\"\"\"\"\" import bz2 import gzip import sys from os . path import splitext GZIP_MAX_READ_CHUNK = * * class BufferedGzipFile ( gzip . GzipFile ) : \"\"\"\"\"\" if sys . version_info [ : ] == ( , , ) : def __init__ ( self , fileish , mode = '' , compresslevel = , buffer_size = ** - ) : super ( BufferedGzipFile , self ) . __init__ ( fileish , mode = mode , compresslevel = compresslevel ) self . buffer_size = buffer_size def readinto ( self , buf ) : \"\"\"\"\"\" n_bytes = len ( buf ) if n_bytes < ** : return super ( BufferedGzipFile , self ) . readinto ( buf ) mv = memoryview ( buf ) n_read = max_read = ** - while ( n_read < n_bytes ) : n_wanted = min ( n_bytes - n_read , max_read ) n_got = super ( BufferedGzipFile , self ) . readinto ( mv [ n_read : n_read + n_wanted ] ) n_read += n_got if n_got != n_wanted : break return n_read def _gzip_open ( fileish , * args , ** kwargs ) : gzip_file = BufferedGzipFile ( fileish , * args , ** kwargs ) if hasattr ( gzip_file , '' ) : gzip_file . max_read_chunk = GZIP_MAX_READ_CHUNK return gzip_file class Opener ( object ) : \"\"\"\"\"\" gz_def = ( _gzip_open , ( '' , '' ) ) bz2_def = ( bz2 . BZ2File , ( '' , '' , '' ) ) compress_ext_map = { '' : gz_def , '' : bz2_def , None : ( open , ( '' , '' ) ) } default_compresslevel = compress_ext_icase = True def __init__ ( self , fileish , * args , ** kwargs ) : if self . _is_fileobj ( fileish ) : self . fobj = fileish self . me_opened = False self . _name = None return opener , arg_names = self . _get_opener_argnames ( fileish ) full_kwargs = kwargs . copy ( ) n_args = len ( args ) full_kwargs . update ( dict ( zip ( arg_names [ : n_args ] , args ) ) ) if '' not in full_kwargs : kwargs [ '' ] = '' if '' in arg_names and '' not in kwargs : kwargs [ '' ] = self . default_compresslevel self . fobj = opener ( fileish , * args , ** kwargs ) self . _name = fileish self . me_opened = True def _get_opener_argnames ( self , fileish ) : _ , ext = splitext ( fileish ) if self . compress_ext_icase : ext = ext . lower ( ) for key in self . compress_ext_map : if key is None : continue if key . lower ( ) == ext : return self . compress_ext_map [ key ] elif ext in self . compress_ext_map : return self . compress_ext_map [ ext ] return self . compress_ext_map [ None ] def _is_fileobj ( self , obj ) : \"\"\"\"\"\" return hasattr ( obj , '' ) and hasattr ( obj , '' ) @ property def closed ( self ) : return self . fobj . closed @ property def name ( self ) : \"\"\"\"\"\" try : return self . fobj . name except AttributeError : return self . _name @ property def mode ( self ) : return self . fobj . mode def fileno ( self ) : return self . fobj . fileno ( ) def read ( self , * args , ** kwargs ) : return self . fobj . read ( * args , ** kwargs ) def write ( self , * args , ** kwargs ) : return self . fobj . write ( * args , ** kwargs ) def seek ( self , * args , ** kwargs ) : return self . fobj . seek ( * args , ** kwargs ) def tell ( self , * args , ** kwargs ) : return self . fobj . tell ( * args , ** kwargs ) def close ( self , * args , ** kwargs ) : return self . fobj . close ( * args , ** kwargs ) ", "answer": "def __iter__ ( self ) :"}, {"prompt": " from __future__ import absolute_import , unicode_literals , division import six from armet import http import flask from flask . globals import current_app from werkzeug . wsgi import get_current_url class RequestHeaders ( http . request . Headers ) : def __init__ ( self , handle ) : self . _handle = handle super ( RequestHeaders , self ) . __init__ ( ) def __getitem__ ( self , name ) : return self . _handle . headers [ name ] def __iter__ ( self ) : return ( key for key , _ in self . _handle . headers ) def __len__ ( self ) : return len ( self . _handle . headers ) def __contains__ ( self , name ) : return name in self . _handle . headers class Request ( http . Request ) : def __init__ ( self , * args , ** kwargs ) : request = flask . request async = kwargs [ '' ] self . _handle = request if not async else flask . Request ( request . environ ) self . headers = RequestHeaders ( self . _handle ) kwargs . update ( method = request . method ) super ( Request , self ) . __init__ ( * args , ** kwargs ) def _read ( self ) : return self . _handle . stream . read ( ) @ property def protocol ( self ) : return self . _handle . scheme . upper ( ) @ property def mount_point ( self ) : path = self . _handle . path return path [ : path . rfind ( self . path ) ] if self . path else path @ property def query ( self ) : if isinstance ( self . _handle . query_string , six . binary_type ) : return self . _handle . query_string . decode ( '' ) return self . _handle . query_string @ property def uri ( self ) : return get_current_url ( self . _handle . environ ) class ResponseHeaders ( http . response . Headers ) : def __init__ ( self , response , handle ) : self . _response = response self . _handle = handle super ( ResponseHeaders , self ) . __init__ ( ) def __getitem__ ( self , name ) : return self . _handle . headers [ name ] def __setitem__ ( self , name , value ) : self . _response . require_open ( ) self . _handle . headers [ self . normalize ( name ) ] = value def __contains__ ( self , name ) : return name in self . _handle . headers def __delitem__ ( self , name ) : self . _response . require_open ( ) del self . _handle . headers [ name ] def __iter__ ( self ) : return ( key for key , _ in self . _handle . headers ) def __len__ ( self ) : return len ( self . _handle . headers ) class Response ( http . Response ) : def __init__ ( self , * args , ** kwargs ) : self . _handle = current_app . response_class ( ) super ( Response , self ) . __init__ ( * args , ** kwargs ) if self . asynchronous : from gevent import queue self . _queue = queue . Queue ( ) self . headers = ResponseHeaders ( self , self . _handle ) def __iter__ ( self ) : return self . _queue @ property def status ( self ) : return self . _handle . status_code @ status . setter def status ( self , value ) : self . require_open ( ) self . _handle . status_code = value @ http . Response . body . setter def body ( self , value ) : if value : if self . asynchronous : super ( Response , Response ) . body . __set__ ( self , None ) self . _queue . put ( value ) return ", "answer": "super ( Response , Response ) . body . __set__ ( self , value )"}, {"prompt": " from __future__ import absolute_import , division from django . core . urlresolvers import reverse from django . http import Http404 , HttpResponseRedirect from django . shortcuts import get_object_or_404 ", "answer": "from sentry . models import Group , GroupMeta"}, {"prompt": " from __future__ import print_function from time import time import subprocess import random import numpy STEP = * SCALE = NI_NTIMES = MROW = * COLDCACHE = WARMCACHE = READ_TIMES = rdm_cod = [ '' , '' ] prec = def get_nrows ( nrows_str ) : if nrows_str . endswith ( \"\" ) : return int ( float ( nrows_str [ : - ] ) * ) elif nrows_str . endswith ( \"\" ) : return int ( float ( nrows_str [ : - ] ) * * ) elif nrows_str . endswith ( \"\" ) : return int ( float ( nrows_str [ : - ] ) * * * ) else : raise ValueError ( \"\" ) class DB ( object ) : def __init__ ( self , nrows , rng , userandom ) : global step , scale self . step = STEP self . scale = SCALE self . rng = rng self . userandom = userandom self . filename = '' . join ( [ rdm_cod [ userandom ] , nrows ] ) self . nrows = get_nrows ( nrows ) def get_db_size ( self ) : sout = subprocess . Popen ( \"\" % self . filename , shell = True , stdout = subprocess . PIPE ) . stdout line = [ l for l in sout ] [ ] return int ( line . split ( ) [ ] ) def print_mtime ( self , t1 , explain ) : mtime = time ( ) - t1 print ( \"\" % explain , round ( mtime , ) ) print ( \"\" , round ( ( self . nrows / ) / mtime , ) ) def print_qtime ( self , colname , ltimes ) : qtime1 = ltimes [ ] qtime2 = ltimes [ - ] print ( \"\" % colname , round ( qtime1 , ) ) print ( \"\" , round ( ( self . nrows / ( MROW ) ) / qtime1 , ) ) print ( \"\" % colname , round ( qtime2 , ) ) print ( \"\" , round ( ( self . nrows / ( MROW ) ) / qtime2 , ) ) def norm_times ( self , ltimes ) : \"\" lmean = ltimes . mean ( ) lstd = ltimes . std ( ) ntimes = ltimes [ ltimes < lmean + lstd ] nmean = ntimes . mean ( ) nstd = ntimes . std ( ) return nmean , nstd def print_qtime_idx ( self , colname , ltimes , repeated , verbose ) : if repeated : r = \"\" else : r = \"\" ltimes = numpy . array ( ltimes ) ntimes = len ( ltimes ) qtime1 = ltimes [ ] ctimes = ltimes [ : COLDCACHE ] cmean , cstd = self . norm_times ( ctimes ) wtimes = ltimes [ WARMCACHE : ] wmean , wstd = self . norm_times ( wtimes ) if verbose : print ( \"\" , ctimes ) print ( \"\" % numpy . histogram ( wtimes ) ) print ( \"\" % ( r , colname ) , round ( qtime1 , prec ) ) print ( \"\" % ( r , colname ) , round ( cmean , prec ) , \"\" , round ( cstd , prec ) ) print ( \"\" % ( r , colname ) , round ( wmean , prec ) , \"\" , round ( wstd , prec ) ) def print_db_sizes ( self , init , filled , indexed ) : table_size = ( filled - init ) / indexes_size = ( indexed - filled ) / print ( \"\" , round ( table_size , ) ) print ( \"\" , round ( indexes_size , ) ) print ( \"\" , round ( table_size + indexes_size , ) ) def fill_arrays ( self , start , stop ) : arr_f8 = numpy . arange ( start , stop , dtype = '' ) arr_i4 = numpy . arange ( start , stop , dtype = '' ) if self . userandom : arr_f8 += numpy . random . normal ( , stop * self . scale , size = stop - start ) arr_i4 = numpy . array ( arr_f8 , dtype = '' ) return arr_i4 , arr_f8 def create_db ( self , dtype , kind , optlevel , verbose ) : self . con = self . open_db ( remove = ) self . create_table ( self . con ) init_size = self . get_db_size ( ) t1 = time ( ) self . fill_table ( self . con ) table_size = self . get_db_size ( ) self . print_mtime ( t1 , '' ) self . index_db ( dtype , kind , optlevel , verbose ) indexes_size = self . get_db_size ( ) self . print_db_sizes ( init_size , table_size , indexes_size ) self . close_db ( self . con ) def index_db ( self , dtype , kind , optlevel , verbose ) : if dtype == \"\" : idx_cols = [ '' ] elif dtype == \"\" : idx_cols = [ '' ] else : idx_cols = [ '' , '' ] for colname in idx_cols : t1 = time ( ) self . index_col ( self . con , colname , kind , optlevel , verbose ) self . print_mtime ( t1 , '' % colname ) def query_db ( self , niter , dtype , onlyidxquery , onlynonidxquery , avoidfscache , verbose , inkernel ) : self . con = self . open_db ( ) if dtype == \"\" : reg_cols = [ '' ] idx_cols = [ '' ] elif dtype == \"\" : reg_cols = [ '' ] idx_cols = [ '' ] else : reg_cols = [ '' , '' ] idx_cols = [ '' , '' ] if avoidfscache : rseed = int ( numpy . random . randint ( self . nrows ) ) else : rseed = numpy . random . seed ( rseed ) base = numpy . random . randint ( self . nrows ) if not onlyidxquery : for colname in reg_cols : ltimes = [ ] random . seed ( rseed ) for i in range ( NI_NTIMES ) : t1 = time ( ) results = self . do_query ( self . con , colname , base , inkernel ) ltimes . append ( time ( ) - t1 ) if verbose : print ( \"\" , results ) self . print_qtime ( colname , ltimes ) self . close_db ( self . con ) self . con = self . open_db ( ) if not onlynonidxquery : for colname in idx_cols : ltimes = [ ] numpy . random . seed ( rseed ) rndbase = numpy . random . randint ( self . nrows , size = niter ) for i in range ( niter ) : base = rndbase [ i ] t1 = time ( ) results = self . do_query ( self . con , colname , base , inkernel ) ", "answer": "ltimes . append ( time ( ) - t1 )"}, {"prompt": " class BasicSerializer ( object ) : fields = ( ) @ classmethod def serialize ( cls , instance , fields = None ) : data_dict = { } use_fields = fields if fields else cls . fields if not use_fields : raise ValueError ( \"\" ) for field in use_fields : value = getattr ( instance , field ) if value is None : data_dict [ field ] = value else : ", "answer": "f = getattr ( instance . __class__ , field )"}, {"prompt": " import os import subprocess from threading import Timer from config import * from models import tweet timers = [ ] def cleanup ( ) : print \"\" for timer in timers : timer . cancel ( ) def initialize ( ) : global timers timer = Timer ( , read_tweet ) timer . start ( ) timers . append ( timer ) def get_text_sanitized ( text ) : text = text . replace ( '' , '' ) . replace ( \"\" , \"\" ) . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) . replace ( '' , '' ) . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) . replace ( '>' , '' ) text = text . replace ( '' , '' ) . replace ( '' , '' ) text = text . replace ( '' , '' ) . replace ( '' , '' ) text = text . replace ( '' , '' ) . replace ( '' , '' ) return text def read_tweet ( ) : global timers timer = Timer ( DELAY_TO_READ_TWEET , read_tweet ) timer . start ( ) ", "answer": "timers . append ( timer )"}, {"prompt": " \"\"\"\"\"\" import codecs import gzip import io import tarfile import six def open_ ( filename , mode = '' , encoding = None ) : \"\"\"\"\"\" ", "answer": "if filename . endswith ( '' ) :"}, {"prompt": " \"\"\"\"\"\" import re import struct __all__ = [ '' , '' , ] import pyhsm . exception import pyhsm . defines class YHSM_Cmd ( ) : \"\"\"\"\"\" response_status = None executed = False ", "answer": "def __init__ ( self , stick , command , payload = '' ) :"}, {"prompt": " \"\"\"\"\"\" import codecs , sys encode = codecs . utf_16_encode def decode ( input , errors = '' ) : return codecs . utf_16_decode ( input , errors , True ) class IncrementalEncoder ( codecs . IncrementalEncoder ) : def __init__ ( self , errors = '' ) : codecs . IncrementalEncoder . __init__ ( self , errors ) self . encoder = None def encode ( self , input , final = False ) : if self . encoder is None : result = codecs . utf_16_encode ( input , self . errors ) [ ] if sys . byteorder == '' : self . encoder = codecs . utf_16_le_encode else : self . encoder = codecs . utf_16_be_encode return result return self . encoder ( input , self . errors ) [ ] def reset ( self ) : codecs . IncrementalEncoder . reset ( self ) self . encoder = None def getstate ( self ) : return ( if self . encoder is None else ) def setstate ( self , state ) : if state : self . encoder = None else : if sys . byteorder == '' : self . encoder = codecs . utf_16_le_encode else : self . encoder = codecs . utf_16_be_encode class IncrementalDecoder ( codecs . BufferedIncrementalDecoder ) : def __init__ ( self , errors = '' ) : codecs . BufferedIncrementalDecoder . __init__ ( self , errors ) self . decoder = None def _buffer_decode ( self , input , errors , final ) : if self . decoder is None : ( output , consumed , byteorder ) = codecs . utf_16_ex_decode ( input , errors , , final ) if byteorder == - : self . decoder = codecs . utf_16_le_decode elif byteorder == : self . decoder = codecs . utf_16_be_decode elif consumed >= : raise UnicodeError ( \"\" ) return ( output , consumed ) return self . decoder ( input , self . errors , final ) def reset ( self ) : codecs . BufferedIncrementalDecoder . reset ( self ) self . decoder = None class StreamWriter ( codecs . StreamWriter ) : def __init__ ( self , stream , errors = '' ) : codecs . StreamWriter . __init__ ( self , stream , errors ) self . encoder = None def reset ( self ) : codecs . StreamWriter . reset ( self ) self . encoder = None def encode ( self , input , errors = '' ) : if self . encoder is None : result = codecs . utf_16_encode ( input , errors ) if sys . byteorder == '' : self . encoder = codecs . utf_16_le_encode ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" from collections import OrderedDict from sqlitedict import SqliteDict from openmdao . recorders . base_recorder import BaseRecorder from openmdao . util . record_util import format_iteration_coordinate from openmdao . core . mpi_wrap import MPI class SqliteRecorder ( BaseRecorder ) : \"\"\"\"\"\" def __init__ ( self , out , ** sqlite_dict_args ) : super ( SqliteRecorder , self ) . __init__ ( ) if MPI and MPI . COMM_WORLD . rank > : self . _open_close_sqlitedict = False else : self . _open_close_sqlitedict = True if self . _open_close_sqlitedict : sqlite_dict_args . setdefault ( '' , True ) sqlite_dict_args . setdefault ( '' , '' ) self . out = SqliteDict ( filename = out , flag = '' , ** sqlite_dict_args ) else : self . out = None def record_metadata ( self , group ) : \"\"\"\"\"\" params = group . params . iteritems ( ) resids = group . resids . iteritems ( ) unknowns = group . unknowns . iteritems ( ) data = OrderedDict ( [ ( '' , dict ( params ) ) , ( '' , dict ( unknowns ) ) , ] ) self . out [ '' ] = data def record_iteration ( self , params , unknowns , resids , metadata ) : \"\"\"\"\"\" data = OrderedDict ( ) iteration_coordinate = metadata [ '' ] timestamp = metadata [ '' ] ", "answer": "group_name = format_iteration_coordinate ( iteration_coordinate )"}, {"prompt": " \"\"\"\"\"\" from googleads import dfp ", "answer": "TEAM_ID = ''"}, {"prompt": " def generic_autodiscover ( module_name ) : \"\"\"\"\"\" from django . utils . importlib import import_module from django . core . exceptions import ImproperlyConfigured import imp import sys from django . conf import settings for app in settings . INSTALLED_APPS : try : import_module ( app ) app_path = sys . modules [ app ] . __path__ except AttributeError : continue try : ", "answer": "imp . find_module ( module_name , app_path )"}, {"prompt": " \"\"\"\"\"\" import logging try : import queue except : import Queue as queue import sleekxmpp from sleekxmpp . plugins . base import base_plugin log = logging . getLogger ( __name__ ) class kestrel_client ( base_plugin ) : def plugin_init ( self ) : self . description = \"\" self . submit_jid = self . config . get ( '' , '' ) self . pool_jid = self . config . get ( '' , '' ) self . submit_queue = queue . Queue ( ) self . status_queue = queue . Queue ( ) self . cancel_queue = queue . Queue ( ) ", "answer": "self . timeout = * self . xmpp . response_timeout"}, {"prompt": " from . . excel_comparsion_test import ExcelComparisonTest from ... workbook import Workbook class TestCompareXLSXFiles ( ExcelComparisonTest ) : \"\"\"\"\"\" def setUp ( self ) : self . maxDiff = None filename = '' test_dir = '' self . got_filename = test_dir + '' + filename self . exp_filename = test_dir + '' + filename ", "answer": "self . ignore_files = [ ]"}, {"prompt": " \"\"\"\"\"\" from pebl import prior , config , evaluator , result , network from pebl . learner . base import Learner from pebl . taskcontroller . base import Task class ListLearner ( Learner ) : _params = ( config . StringParameter ( '' , \"\"\"\"\"\" , default = '' ) ) def __init__ ( self , data_ = None , prior_ = None , networks = None ) : \"\"\"\"\"\" super ( ListLearner , self ) . __init__ ( data_ , prior_ ) self . networks = networks if not networks : variables = self . data . variables _net = lambda netstr : network . Network ( variables , netstr ) netstrings = config . get ( '' ) . splitlines ( ) self . networks = ( _net ( s ) for s in netstrings if s ) def run ( self ) : self . result = result . LearnerResult ( self ) self . evaluator = evaluator . fromconfig ( self . data , prior_ = self . prior ) ", "answer": "self . result . start_run ( )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "__author__ = ''"}, {"prompt": " from __future__ import absolute_import , unicode_literals from . base import BaseDataset ", "answer": "class SimpleDataset ( BaseDataset ) :"}, {"prompt": " from six import text_type , u , b , PY3 from six . moves . urllib . parse import parse_qs import base64 import hmac import hashlib def token_decoder ( token ) : token_data = { } encoded = token [ : ] decoded = base64 . b64decode ( encoded . encode ( '' ) ) if PY3 : decoded = decoded . decode ( ) parts = decoded . split ( u ( '' ) ) for decoded_part in iter ( parts ) : token_data . update ( parse_qs ( decoded_part ) ) ", "answer": "for k in iter ( token_data ) :"}, {"prompt": " \"\"\"\"\"\" from phonenumbers . util import u data = { '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , '' , '' , '' ) , ", "answer": "'' : ( '' , ) ,"}, {"prompt": " from django . db import models class Book ( models . Model ) : title = models . CharField ( max_length = ) ", "answer": "def __str__ ( self ) :"}, {"prompt": " from grammar import Grammar class ShellParser ( object ) : services = None def __init__ ( self ) : self . tokens = None def __call__ ( self , command_string ) : self . parse ( command_string ) def buildGrammar ( self ) : self . grammar = Grammar ( ) self . grammar . parser = self self . grammar . makeBNF ( ) return self . grammar def parse ( self , cmd ) : tokens = grammar . parseString ( cmd ) ", "answer": "out = \"\"\"\"\"\" % ( tokens . commandtype , tokens . servicetype , tokens . action )"}, {"prompt": " import vtk from vtk . util . colors import chocolate , mint cone = vtk . vtkCone ( ) cone . SetAngle ( ) vertPlane = vtk . vtkPlane ( ) vertPlane . SetOrigin ( , , ) vertPlane . SetNormal ( - , , ) basePlane = vtk . vtkPlane ( ) basePlane . SetOrigin ( , , ) basePlane . SetNormal ( , , ) iceCream = vtk . vtkSphere ( ) iceCream . SetCenter ( , , ) iceCream . SetRadius ( ) bite = vtk . vtkSphere ( ) bite . SetCenter ( , , ) bite . SetRadius ( ) theCone = vtk . vtkImplicitBoolean ( ) theCone . SetOperationTypeToIntersection ( ) theCone . AddFunction ( cone ) theCone . AddFunction ( vertPlane ) theCone . AddFunction ( basePlane ) theCream = vtk . vtkImplicitBoolean ( ) theCream . SetOperationTypeToDifference ( ) theCream . AddFunction ( iceCream ) theCream . AddFunction ( bite ) theConeSample = vtk . vtkSampleFunction ( ) theConeSample . SetImplicitFunction ( theCone ) theConeSample . SetModelBounds ( - , , - , , - , ) theConeSample . SetSampleDimensions ( , , ) theConeSample . ComputeNormalsOff ( ) theConeSurface = vtk . vtkContourFilter ( ) theConeSurface . SetInputConnection ( theConeSample . GetOutputPort ( ) ) theConeSurface . SetValue ( , ) coneMapper = vtk . vtkPolyDataMapper ( ) ", "answer": "coneMapper . SetInputConnection ( theConeSurface . GetOutputPort ( ) )"}, {"prompt": " import urlparse try : from keystoneclient . v2_0 import client as keystone_client import glanceclient from novaclient . v1_1 import client as nova_client from neutronclient . v2_0 import client as quantum_client has_openstack = True except : has_openstack = False from xos . config import Config def require_enabled ( callable ) : def wrapper ( * args , ** kwds ) : if has_openstack : return callable ( * args , ** kwds ) else : return None return wrapper def parse_novarc ( filename ) : opts = { } f = open ( filename , '' ) for line in f : try : line = line . replace ( '' , '' ) . strip ( ) parts = line . split ( '' ) if len ( parts ) > : value = parts [ ] . replace ( \"\" , \"\" ) value = value . replace ( '' , '' ) opts [ parts [ ] ] = value except : pass f . close ( ) return opts class Client : def __init__ ( self , username = None , password = None , tenant = None , url = None , token = None , endpoint = None , controller = None , cacert = None , admin = True , * args , ** kwds ) : self . has_openstack = has_openstack self . url = controller . auth_url if admin : self . username = controller . admin_user self . password = controller . admin_password self . tenant = controller . admin_tenant else : self . username = None self . password = None self . tenant = None if username : self . username = username if password : self . password = password if tenant : self . tenant = tenant if url : self . url = url if token : self . token = token if endpoint : self . endpoint = endpoint self . cacert = cacert class KeystoneClient ( Client ) : def __init__ ( self , * args , ** kwds ) : Client . __init__ ( self , * args , ** kwds ) if has_openstack : self . client = keystone_client . Client ( username = self . username , password = self . password , tenant_name = self . tenant , auth_url = self . url ) @ require_enabled def connect ( self , * args , ** kwds ) : self . __init__ ( * args , ** kwds ) @ require_enabled def __getattr__ ( self , name ) : return getattr ( self . client , name ) class Glance ( Client ) : def __init__ ( self , * args , ** kwds ) : Client . __init__ ( self , * args , ** kwds ) if has_openstack : self . client = glanceclient . get_client ( host = '' , username = self . username , password = self . password , tenant = self . tenant , auth_url = self . url ) @ require_enabled def __getattr__ ( self , name ) : return getattr ( self . client , name ) class GlanceClient ( Client ) : def __init__ ( self , version , endpoint , token , cacert = None , * args , ** kwds ) : Client . __init__ ( self , * args , ** kwds ) if has_openstack : self . client = glanceclient . Client ( version , endpoint = endpoint , token = token , cacert = cacert ) @ require_enabled def __getattr__ ( self , name ) : return getattr ( self . client , name ) class NovaClient ( Client ) : def __init__ ( self , * args , ** kwds ) : Client . __init__ ( self , * args , ** kwds ) if has_openstack : self . client = nova_client . Client ( username = self . username , api_key = self . password , project_id = self . tenant , auth_url = self . url , region_name = '' , extensions = [ ] , service_type = '' , service_name = '' , ) @ require_enabled def connect ( self , * args , ** kwds ) : self . __init__ ( * args , ** kwds ) @ require_enabled def __getattr__ ( self , name ) : return getattr ( self . client , name ) class NovaDB ( Client ) : def __init__ ( self , * args , ** kwds ) : Client . __init__ ( self , * args , ** kwds ) if has_openstack : self . ctx = get_admin_context ( ) nova_db_api . FLAGS ( default_config_files = [ '' ] ) self . client = nova_db_api @ require_enabled def connect ( self , * args , ** kwds ) : self . __init__ ( * args , ** kwds ) @ require_enabled def __getattr__ ( self , name ) : return getattr ( self . client , name ) class QuantumClient ( Client ) : def __init__ ( self , * args , ** kwds ) : Client . __init__ ( self , * args , ** kwds ) if has_openstack : self . client = quantum_client . Client ( username = self . username , password = self . password , tenant_name = self . tenant , auth_url = self . url , ca_cert = self . cacert ) @ require_enabled def connect ( self , * args , ** kwds ) : self . __init__ ( * args , ** kwds ) @ require_enabled def __getattr__ ( self , name ) : return getattr ( self . client , name ) class OpenStackClient : \"\"\"\"\"\" def __init__ ( self , * args , ** kwds ) : self . keystone = KeystoneClient ( * args , ** kwds ) url_parsed = urlparse . urlparse ( self . keystone . url ) hostname = url_parsed . netloc . split ( '' ) [ ] token = self . keystone . client . tokens . authenticate ( username = self . keystone . username , password = self . keystone . password , tenant_name = self . keystone . tenant ) glance_endpoint = self . keystone . service_catalog . url_for ( service_type = '' , endpoint_type = '' ) ", "answer": "self . glanceclient = GlanceClient ( '' , endpoint = glance_endpoint , token = token . id , ** kwds )"}, {"prompt": " '''''' __all__ = ( '' , '' ) import os from kivy . input . motionevent import MotionEvent from kivy . input . shape import ShapeRect class MTDMotionEvent ( MotionEvent ) : def depack ( self , args ) : self . is_touch = True self . sx = args [ '' ] self . sy = args [ '' ] self . profile = [ '' ] if '' in args and '' in args : self . shape = ShapeRect ( ) self . shape . width = args [ '' ] self . shape . height = args [ '' ] ", "answer": "self . profile . append ( '' )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function __docformat__ = '' __all__ = [ \"\" , \"\" , \"\" ] import sys old_sys_path = sys . path [ : ] sys . path = [ p for p in sys . path if \"\" not in p ] import inspect sys . path = old_sys_path try : set except NameError : from sets import Set as set def getinfo ( func ) : \"\"\"\"\"\" assert inspect . ismethod ( func ) or inspect . isfunction ( func ) regargs , varargs , varkwargs , defaults = inspect . getargspec ( func ) argnames = list ( regargs ) if varargs : argnames . append ( varargs ) if varkwargs : argnames . append ( varkwargs ) signature = inspect . formatargspec ( regargs , varargs , varkwargs , defaults , formatvalue = lambda value : \"\" ) [ : - ] if hasattr ( func , '' ) : _closure = func . __closure__ _globals = func . __globals__ else : _closure = func . func_closure _globals = func . func_globals return dict ( name = func . __name__ , argnames = argnames , signature = signature , defaults = func . __defaults__ , doc = func . __doc__ , module = func . __module__ , dict = func . __dict__ , globals = _globals , closure = _closure ) def update_wrapper ( wrapper , model , infodict = None ) : infodict = infodict or getinfo ( model ) wrapper . __name__ = infodict [ '' ] wrapper . __doc__ = infodict [ '' ] wrapper . __module__ = infodict [ '' ] wrapper . __dict__ . update ( infodict [ '' ] ) wrapper . __defaults__ = infodict [ '' ] wrapper . undecorated = model return wrapper def new_wrapper ( wrapper , model ) : \"\"\"\"\"\" if isinstance ( model , dict ) : infodict = model else : infodict = getinfo ( model ) assert not '' in infodict [ \"\" ] , ( '' ) src = \"\" % infodict funcopy = eval ( src , dict ( _wrapper_ = wrapper ) ) return update_wrapper ( funcopy , model , infodict ) def __call__ ( self , func ) : return new_wrapper ( lambda * a , ** k : self . call ( func , * a , ** k ) , func ) def decorator_factory ( cls ) : \"\"\"\"\"\" attrs = set ( dir ( cls ) ) if '' in attrs : raise TypeError ( '' '' ) ", "answer": "if '' not in attrs :"}, {"prompt": " import sys from oslo_config import cfg from oslo_service import service from neutron . agent . common import config from neutron . agent . dhcp import config as dhcp_config from neutron . agent . linux import interface from neutron . agent . metadata import config as metadata_config from neutron . common import config as common_config from neutron . common import topics from neutron import service as neutron_service def register_options ( conf ) : ", "answer": "config . register_interface_driver_opts_helper ( conf )"}, {"prompt": " from __future__ import absolute_import , division , print_function import pytest import numpy as np from numpy . testing import assert_array_equal from . . component_link import ComponentLink , BinaryComponentLink from . . data import ComponentID , Data , Component from . . data_collection import DataCollection from . . link_helpers import LinkSame from . . subset import InequalitySubsetState class TestComponentLink ( object ) : def toy_data ( self ) : data = Data ( ) from_comp = Component ( np . array ( [ , , ] ) ) to_comp = Component ( np . array ( [ , , ] ) ) return data , from_comp , to_comp def test_valid_init ( self ) : ComponentLink ( [ ComponentID ( '' ) ] , ComponentID ( '' ) ) def test_valid_init_using ( self ) : data , from_ , to_ = self . toy_data ( ) using = lambda x : x ComponentLink ( [ ComponentID ( '' ) ] , ComponentID ( '' ) , using ) def test_invalid_init_multi_from_no_using ( self ) : with pytest . raises ( TypeError ) as exc : ComponentLink ( [ ComponentID ( '' ) , ComponentID ( '' ) ] , ComponentID ( '' ) ) assert exc . value . args [ ] == ( \"\" \"\" ) def test_invalid_init_scalar_from ( self ) : with pytest . raises ( TypeError ) as exc : ComponentLink ( ComponentID ( '' ) , ComponentID ( '' ) ) assert exc . value . args [ ] . startswith ( \"\" ) def test_compute_direct ( self ) : data , from_ , to_ = self . toy_data ( ) from_id = data . add_component ( from_ , '' ) to_id = ComponentID ( '' ) link = ComponentLink ( [ from_id ] , to_id ) result = link . compute ( data ) expected = from_ . data assert_array_equal ( result , expected ) def test_compute_using ( self ) : data , from_ , to_ = self . toy_data ( ) from_id = data . add_component ( from_ , '' ) to_id = ComponentID ( '' ) using = lambda x : * x link = ComponentLink ( [ from_id ] , to_id , using ) result = link . compute ( data ) expected = from_ . data * assert_array_equal ( result , expected ) def test_getters ( self ) : data , from_ , to_ = self . toy_data ( ) from_id = data . add_component ( from_ , '' ) to_id = ComponentID ( '' ) using = lambda x : * x link = ComponentLink ( [ from_id ] , to_id , using ) ", "answer": "assert link . get_from_ids ( ) [ ] is from_id"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os from pants . backend . jvm . targets . import_jars_mixin import ImportJarsMixin from pants . base . payload import Payload from pants . base . payload_field import PrimitiveField from pants . util . memo import memoized_property from pants . contrib . android . android_manifest_parser import AndroidManifestParser from pants . contrib . android . targets . android_target import AndroidTarget class AndroidLibrary ( ImportJarsMixin , AndroidTarget ) : \"\"\"\"\"\" def __init__ ( self , payload = None , libraries = None , include_patterns = None , exclude_patterns = None , ** kwargs ) : \"\"\"\"\"\" payload = payload or Payload ( ) payload . add_fields ( { '' : PrimitiveField ( libraries or ( ) ) , '' : PrimitiveField ( include_patterns or ( ) ) , '' : PrimitiveField ( exclude_patterns or ( ) ) , } ) self . libraries = libraries super ( AndroidLibrary , self ) . __init__ ( payload = payload , ** kwargs ) @ property def imported_jar_library_specs ( self ) : \"\"\"\"\"\" return self . payload . library_specs @ memoized_property def manifest ( self ) : \"\"\"\"\"\" ", "answer": "if self . _manifest_file is None :"}, {"prompt": " class TabularQAgent ( object ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import sys ; import os ; path = os . path . split ( os . path . realpath ( __file__ ) ) [ ] ; sys . path . append ( path + \"\" ) ; sys . path . append ( path + \"\" ) ; from latent_factor import * ; from arffio import * ; import Logger ; import pickle ; import numpy as np ; import train_rep as train ; import unittest ; class TrainTester ( unittest . TestCase ) : def setUp ( self ) : self . argv = [ ] ; ", "answer": "self . argv . append ( \"\" ) ;"}, {"prompt": " from django . conf . urls import patterns , include , url ", "answer": "from django . contrib import admin"}, {"prompt": " \"\"\"\"\"\" def flag_calls ( func ) : \"\"\"\"\"\" def wrapper ( * args , ** kw ) : wrapper . called = False out = func ( * args , ** kw ) ", "answer": "wrapper . called = True"}, {"prompt": " \"\"\"\"\"\" from qisys import ui import qisrc . parsers import sys def configure_parser ( parser ) : qisrc . parsers . worktree_parser ( parser ) group = parser . add_argument_group ( \"\" ) group . add_argument ( \"\" ) group . add_argument ( \"\" , \"\" , action = \"\" , dest = \"\" , help = \"\" ) parser . set_defaults ( force = False ) def do ( args ) : branch = args . branch git_worktree = qisrc . parsers . get_git_worktree ( args ) manifest = git_worktree . manifest groups = manifest . groups branch = args . branch git_worktree . configure_manifest ( manifest . url , groups = groups , branch = branch ) ok = git_worktree . checkout ( branch , force = args . force ) ", "answer": "if not ok :"}, {"prompt": " import wx import wx . xrc import wx . lib . masked as masked class clsDataFilters ( wx . Dialog ) : def __init__ ( self , parent ) : wx . Dialog . __init__ ( self , parent , id = wx . ID_ANY , title = u\"\" , pos = wx . Point ( , ) , size = wx . Size ( , ) , style = wx . DEFAULT_DIALOG_STYLE | wx . RESIZE_BORDER ) self . SetSizeHintsSz ( wx . Size ( , ) , wx . DefaultSize ) bSizer1 = wx . BoxSizer ( wx . VERTICAL ) bSizer3 = wx . BoxSizer ( wx . VERTICAL ) bsValueThresh = wx . BoxSizer ( wx . HORIZONTAL ) self . rbThreshold = wx . RadioButton ( self , wx . ID_ANY , wx . EmptyString , wx . Point ( , ) , wx . DefaultSize , wx . RB_GROUP ) self . rbThreshold . SetValue ( True ) bsValueThresh . Add ( self . rbThreshold , , wx . ALL , ) sbThreshold = wx . StaticBoxSizer ( wx . StaticBox ( self , wx . ID_ANY , u\"\" ) , wx . VERTICAL ) fgSizer1 = wx . FlexGridSizer ( , , , ) fgSizer1 . SetFlexibleDirection ( wx . HORIZONTAL ) fgSizer1 . SetNonFlexibleGrowMode ( wx . FLEX_GROWMODE_SPECIFIED ) self . lblChangegt = wx . StaticText ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . DefaultSize , ) self . lblChangegt . Wrap ( - ) fgSizer1 . Add ( self . lblChangegt , , wx . ALL , ) self . txtThreshValGT = wx . TextCtrl ( self , wx . ID_ANY , wx . EmptyString , wx . DefaultPosition , wx . Size ( , - ) , ) fgSizer1 . Add ( self . txtThreshValGT , , wx . ALL | wx . EXPAND , ) self . lblChangelt = wx . StaticText ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . DefaultSize , ) self . lblChangelt . Wrap ( - ) fgSizer1 . Add ( self . lblChangelt , , wx . ALL , ) self . txtThreshValLT = wx . TextCtrl ( self , wx . ID_ANY , wx . EmptyString , wx . DefaultPosition , wx . Size ( , - ) , ) fgSizer1 . Add ( self . txtThreshValLT , , wx . ALL | wx . EXPAND , ) sbThreshold . Add ( fgSizer1 , , wx . EXPAND , ) bsValueThresh . Add ( sbThreshold , , , ) bSizer3 . Add ( bsValueThresh , , wx . EXPAND , ) bsGaps = wx . BoxSizer ( wx . HORIZONTAL ) self . rbDataGaps = wx . RadioButton ( self , wx . ID_ANY , wx . EmptyString , wx . DefaultPosition , wx . DefaultSize , ) bsGaps . Add ( self . rbDataGaps , , wx . ALL , ) sbGaps = wx . StaticBoxSizer ( wx . StaticBox ( self , wx . ID_ANY , u\"\" ) , wx . VERTICAL ) fgSizer2 = wx . FlexGridSizer ( , , , ) fgSizer2 . SetFlexibleDirection ( wx . HORIZONTAL ) fgSizer2 . SetNonFlexibleGrowMode ( wx . FLEX_GROWMODE_SPECIFIED ) self . lblGapsVal = wx . StaticText ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . DefaultSize , ) self . lblGapsVal . Wrap ( - ) fgSizer2 . Add ( self . lblGapsVal , , wx . ALL , ) self . txtGapsVal = wx . TextCtrl ( self , wx . ID_ANY , wx . EmptyString , wx . DefaultPosition , wx . Size ( , - ) , ) fgSizer2 . Add ( self . txtGapsVal , , wx . ALL , ) self . lblGapsTime = wx . StaticText ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . DefaultSize , ) self . lblGapsTime . Wrap ( - ) fgSizer2 . Add ( self . lblGapsTime , , wx . ALL , ) cbGapTimeChoices = [ u\"\" , u\"\" , u\"\" , u\"\" ] self . cbGapTime = wx . ComboBox ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . Size ( , - ) , cbGapTimeChoices , wx . CB_READONLY ) fgSizer2 . Add ( self . cbGapTime , , wx . ALL , ) sbGaps . Add ( fgSizer2 , , wx . EXPAND , ) bsGaps . Add ( sbGaps , , , ) bSizer3 . Add ( bsGaps , , , ) bsDate = wx . BoxSizer ( wx . HORIZONTAL ) self . rbDate = wx . RadioButton ( self , wx . ID_ANY , wx . EmptyString , wx . DefaultPosition , wx . DefaultSize , ) bsDate . Add ( self . rbDate , , wx . ALL , ) sbDate = wx . StaticBoxSizer ( wx . StaticBox ( self , wx . ID_ANY , u\"\" ) , wx . VERTICAL ) fgSizer3 = wx . FlexGridSizer ( , , , ) fgSizer3 . SetFlexibleDirection ( wx . HORIZONTAL ) fgSizer3 . SetNonFlexibleGrowMode ( wx . FLEX_GROWMODE_SPECIFIED ) self . lblDateAfter = wx . StaticText ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . DefaultSize , ) self . lblDateAfter . Wrap ( - ) fgSizer3 . Add ( self . lblDateAfter , , wx . ALL , ) self . dpAfter = wx . DatePickerCtrl ( self , wx . ID_ANY , wx . DefaultDateTime , wx . DefaultPosition , wx . Size ( , - ) , wx . DP_DROPDOWN | wx . DP_SHOWCENTURY ) fgSizer3 . Add ( self . dpAfter , , wx . ALL , ) self . sbAfter = wx . SpinButton ( self , wx . ID_ANY , wx . DefaultPosition , wx . Size ( , - ) , ) self . tpAfter = masked . TimeCtrl ( self , wx . ID_ANY , pos = wx . DefaultPosition , size = wx . Size ( , - ) , name = \"\" , fmt24hr = True , spinButton = self . sbAfter , oob_color = \"\" ) fgSizer3 . Add ( self . tpAfter , , wx . ALL , ) fgSizer3 . Add ( self . sbAfter , , wx . ALL , ) self . lblDateBefore = wx . StaticText ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . DefaultSize , ) self . lblDateBefore . Wrap ( - ) fgSizer3 . Add ( self . lblDateBefore , , wx . ALL , ) self . dpBefore = wx . DatePickerCtrl ( self , wx . ID_ANY , wx . DefaultDateTime , wx . DefaultPosition , wx . Size ( , - ) , wx . DP_DROPDOWN | wx . DP_SHOWCENTURY ) fgSizer3 . Add ( self . dpBefore , , wx . ALL , ) self . sbBefore = wx . SpinButton ( self , wx . ID_ANY , wx . DefaultPosition , wx . Size ( , - ) , wx . SP_WRAP ) self . tpBefore = masked . TimeCtrl ( self , wx . ID_ANY , pos = wx . DefaultPosition , size = wx . Size ( , - ) , name = \"\" , fmt24hr = True , spinButton = self . sbBefore , oob_color = '' ) fgSizer3 . Add ( self . tpBefore , , wx . ALL , ) fgSizer3 . Add ( self . sbBefore , , wx . ALL , ) sbDate . Add ( fgSizer3 , , wx . EXPAND , ) bsDate . Add ( sbDate , , wx . EXPAND , ) bSizer3 . Add ( bsDate , , wx . EXPAND , ) bsValChange = wx . BoxSizer ( wx . HORIZONTAL ) self . rbVChangeThresh = wx . RadioButton ( self , wx . ID_ANY , wx . EmptyString , wx . DefaultPosition , wx . DefaultSize , ) bsValChange . Add ( self . rbVChangeThresh , , wx . ALL , ) sbValChange = wx . StaticBoxSizer ( wx . StaticBox ( self , wx . ID_ANY , u\"\" ) , wx . VERTICAL ) fgSizer4 = wx . FlexGridSizer ( , , , ) fgSizer4 . SetFlexibleDirection ( wx . HORIZONTAL ) fgSizer4 . SetNonFlexibleGrowMode ( wx . FLEX_GROWMODE_SPECIFIED ) self . lblChangeGT = wx . StaticText ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . DefaultSize , ) self . lblChangeGT . Wrap ( - ) fgSizer4 . Add ( self . lblChangeGT , , wx . ALL , ) self . txtVChangeGT = wx . TextCtrl ( self , wx . ID_ANY , wx . EmptyString , wx . DefaultPosition , wx . Size ( , - ) , ) fgSizer4 . Add ( self . txtVChangeGT , , wx . ALL , ) self . lblChangeLT = wx . StaticText ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . DefaultSize , ) self . lblChangeLT . Wrap ( - ) fgSizer4 . Add ( self . lblChangeLT , , wx . ALL , ) self . txtVChangeLT = wx . TextCtrl ( self , wx . ID_ANY , wx . EmptyString , wx . DefaultPosition , wx . Size ( , - ) , ) fgSizer4 . Add ( self . txtVChangeLT , , wx . ALL , ) sbValChange . Add ( fgSizer4 , , wx . EXPAND , ) bsValChange . Add ( sbValChange , , , ) bSizer3 . Add ( bsValChange , , wx . EXPAND , ) self . chkToggleFilterSelection = wx . CheckBox ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . DefaultSize , ) bSizer3 . Add ( self . chkToggleFilterSelection , , wx . ALL | wx . EXPAND , ) bsButtons = wx . BoxSizer ( wx . HORIZONTAL ) self . btnOK = wx . Button ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . Size ( , ) , ) bsButtons . Add ( self . btnOK , , wx . ALL | wx . EXPAND , ) self . btnCancel = wx . Button ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . Size ( , ) , ) bsButtons . Add ( self . btnCancel , , wx . ALL | wx . EXPAND , ) self . btnApply = wx . Button ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . Size ( , ) , ) bsButtons . Add ( self . btnApply , , wx . ALL | wx . EXPAND , ) ", "answer": "self . btnClear = wx . Button ( self , wx . ID_ANY , u\"\" , wx . DefaultPosition , wx . Size ( , ) , )"}, {"prompt": " from optparse import make_option from django . core . management . base import BaseCommand from django . utils . translation import ugettext as _ from django_q . cluster import Cluster ", "answer": "class Command ( BaseCommand ) :"}, {"prompt": " import logging from collections import Counter from theano import tensor from toolz import merge from blocks . algorithms import ( GradientDescent , StepClipping , AdaDelta , CompositeRule ) from blocks . extensions import FinishAfter , Printing from blocks . extensions . monitoring import TrainingDataMonitoring from blocks . filter import VariableFilter from blocks . graph import ComputationGraph , apply_noise , apply_dropout from blocks . initialization import IsotropicGaussian , Orthogonal , Constant from blocks . main_loop import MainLoop from blocks . model import Model from blocks . select import Selector from machine_translation . checkpoint import CheckpointNMT , LoadNMT from machine_translation . model import BidirectionalEncoder , Decoder from machine_translation . sampling import BleuValidator , Sampler try : from blocks_extras . extensions . plot import Plot BOKEH_AVAILABLE = True except ImportError : BOKEH_AVAILABLE = False logger = logging . getLogger ( __name__ ) def main ( config , tr_stream , dev_stream , use_bokeh = False ) : logger . info ( '' ) source_sentence = tensor . lmatrix ( '' ) source_sentence_mask = tensor . matrix ( '' ) target_sentence = tensor . lmatrix ( '' ) target_sentence_mask = tensor . matrix ( '' ) sampling_input = tensor . lmatrix ( '' ) logger . info ( '' ) encoder = BidirectionalEncoder ( config [ '' ] , config [ '' ] , config [ '' ] ) decoder = Decoder ( config [ '' ] , config [ '' ] , config [ '' ] , config [ '' ] * ) cost = decoder . cost ( encoder . apply ( source_sentence , source_sentence_mask ) , source_sentence_mask , target_sentence , target_sentence_mask ) logger . info ( '' ) cg = ComputationGraph ( cost ) logger . info ( '' ) encoder . weights_init = decoder . weights_init = IsotropicGaussian ( config [ '' ] ) encoder . biases_init = decoder . biases_init = Constant ( ) encoder . push_initialization_config ( ) decoder . push_initialization_config ( ) encoder . bidir . prototype . weights_init = Orthogonal ( ) decoder . transition . weights_init = Orthogonal ( ) encoder . initialize ( ) decoder . initialize ( ) if config [ '' ] < : logger . info ( '' ) dropout_inputs = [ x for x in cg . intermediary_variables if x . name == '' ] cg = apply_dropout ( cg , dropout_inputs , config [ '' ] ) if config [ '' ] > : logger . info ( '' ) enc_params = Selector ( encoder . lookup ) . get_params ( ) . values ( ) enc_params += Selector ( encoder . fwd_fork ) . get_params ( ) . values ( ) enc_params += Selector ( encoder . back_fork ) . get_params ( ) . values ( ) dec_params = Selector ( decoder . sequence_generator . readout ) . get_params ( ) . values ( ) dec_params += Selector ( decoder . sequence_generator . fork ) . get_params ( ) . values ( ) dec_params += Selector ( decoder . state_init ) . get_params ( ) . values ( ) cg = apply_noise ( cg , enc_params + dec_params , config [ '' ] ) shapes = [ param . get_value ( ) . shape for param in cg . parameters ] logger . info ( \"\" ) for shape , count in Counter ( shapes ) . most_common ( ) : logger . info ( '' . format ( shape , count ) ) logger . info ( \"\" . format ( len ( shapes ) ) ) enc_dec_param_dict = merge ( Selector ( encoder ) . get_parameters ( ) , Selector ( decoder ) . get_parameters ( ) ) logger . info ( \"\" ) for name , value in enc_dec_param_dict . items ( ) : logger . info ( '' . format ( value . get_value ( ) . shape , name ) ) logger . info ( \"\" . format ( len ( enc_dec_param_dict ) ) ) logger . info ( \"\" ) training_model = Model ( cost ) logger . info ( \"\" ) extensions = [ FinishAfter ( after_n_batches = config [ '' ] ) , TrainingDataMonitoring ( [ cost ] , after_batch = True ) , Printing ( after_batch = True ) , CheckpointNMT ( config [ '' ] , every_n_batches = config [ '' ] ) ] if config [ '' ] >= or config [ '' ] is not None : logger . info ( \"\" ) sampling_representation = encoder . apply ( sampling_input , tensor . ones ( sampling_input . shape ) ) generated = decoder . generate ( sampling_input , sampling_representation ) search_model = Model ( generated ) _ , samples = VariableFilter ( bricks = [ decoder . sequence_generator ] , name = \"\" ) ( ComputationGraph ( generated [ ] ) ) if config [ '' ] >= : logger . info ( \"\" ) ", "answer": "extensions . append ("}, {"prompt": " from functools import wraps from django . conf import settings from django . http import HttpResponseBadRequest from django . template . loader import render_to_string from django . utils import six from django . utils . decorators import available_attrs def honeypot_equals ( val ) : \"\"\"\"\"\" expected = getattr ( settings , '' , '' ) if callable ( expected ) : expected = expected ( ) ", "answer": "return val == expected"}, {"prompt": " import json import requests from httpretty import HTTPretty from social . p3 import urlencode from social . tests . backends . oauth import OAuth1Test class YahooOAuth1Test ( OAuth1Test ) : backend_path = '' user_data_url = '' '' expected_username = '' access_token_body = json . dumps ( { '' : '' , '' : '' } ) request_token_body = urlencode ( { '' : '' , '' : '' , '' : '' } ) guid_body = json . dumps ( { '' : { '' : '' , '' : '' } } ) user_data_body = json . dumps ( { '' : { '' : True , '' : '' , '' : { '' : , '' : '' '' , '' : '' , '' : } , '' : '' , '' : '' , '' : False , '' : '' , '' : '' , '' : '' , '' : [ { '' : '' , '' : , '' : True , ", "answer": "'' : '' ,"}, {"prompt": " import logging import memcache __all__ = [ '' ] LOG = logging . getLogger ( __name__ ) LOG . addHandler ( logging . NullHandler ( ) ) ", "answer": "class MemcacheClient :"}, {"prompt": " import logging from logging . handlers import TimedRotatingFileHandler import jasmin . vendor . txredisapi as redis from twisted . internet import reactor from twisted . internet import defer from jasmin . redis . configs import RedisForJasminConfig LOG_CATEGORY = \"\" class RedisForJasminProtocol ( redis . RedisProtocol ) : def connectionMade ( self ) : redis . RedisProtocol . connectionMade ( self ) self . factory . log . info ( \"\" ) def execute_command ( self , * args , ** kwargs ) : self . factory . log . debug ( '' , args ) return redis . RedisProtocol . execute_command ( self , * args , ** kwargs ) class RedisForJasminFactory ( redis . RedisFactory ) : protocol = RedisForJasminProtocol def startedConnecting ( self , connector ) : redis . RedisFactory . startedConnecting ( self , connector ) self . log . info ( '' ) def clientConnectionLost ( self , connector , reason ) : redis . RedisFactory . clientConnectionLost ( self , connector , reason ) self . log . info ( '' , reason ) def clientConnectionFailed ( self , connector , reason ) : redis . RedisFactory . clientConnectionFailed ( self , connector , reason ) self . log . info ( '' , reason ) def __init__ ( self , uuid , dbid , poolsize , isLazy = True , handler = redis . ConnectionHandler , config = None ) : redis . RedisFactory . __init__ ( self , uuid , dbid , poolsize , isLazy , handler ) self . log = logging . getLogger ( LOG_CATEGORY ) if config is not None : self . log . setLevel ( config . log_level ) handler = TimedRotatingFileHandler ( filename = config . log_file , when = config . log_rotate ) formatter = logging . Formatter ( config . log_format , config . log_date_format ) handler . setFormatter ( formatter ) else : handler = logging . NullHandler ( ) if len ( self . log . handlers ) != : self . log . addHandler ( handler ) self . log . propagate = False def makeConnection ( host , port , dbid , poolsize , reconnect , isLazy , _RedisForJasminConfig = None ) : uuid = \"\" % ( host , port ) factory = RedisForJasminFactory ( uuid , None , poolsize , isLazy , redis . ConnectionHandler , _RedisForJasminConfig ) factory . continueTrying = reconnect for _ in xrange ( poolsize ) : reactor . connectTCP ( host , port , factory ) if isLazy : return factory . handler else : return factory . deferred def SimpleConnection ( host = \"\" , port = , dbid = None , reconnect = True ) : return makeConnection ( host , port , dbid , , reconnect , False ) def ConnectionWithConfiguration ( _RedisForJasminConfig ) : if _RedisForJasminConfig . password is not None : dbid = None else : ", "answer": "dbid = _RedisForJasminConfig . dbid"}, {"prompt": " import calendar import itertools import logging from datetime import datetime , timedelta , time from django import http from django . db import models from django . template . context import RequestContext from django . shortcuts import get_object_or_404 , render from swingtime . models import Event , Occurrence from swingtime import utils , forms from swingtime . conf import settings as swingtime_settings from dateutil import parser if swingtime_settings . CALENDAR_FIRST_WEEKDAY is not None : calendar . setfirstweekday ( swingtime_settings . CALENDAR_FIRST_WEEKDAY ) def event_listing ( request , template = '' , events = None , ** extra_context ) : '''''' if events is None : events = Event . objects . all ( ) extra_context [ '' ] = events return render ( request , template , extra_context ) def event_view ( request , pk , template = '' , event_form_class = forms . EventForm , recurrence_form_class = forms . MultipleOccurrenceForm ) : '''''' event = get_object_or_404 ( Event , pk = pk ) event_form = recurrence_form = None if request . method == '' : if '' in request . POST : event_form = event_form_class ( request . POST , instance = event ) if event_form . is_valid ( ) : event_form . save ( event ) return http . HttpResponseRedirect ( request . path ) elif '' in request . POST : recurrence_form = recurrence_form_class ( request . POST ) if recurrence_form . is_valid ( ) : recurrence_form . save ( event ) return http . HttpResponseRedirect ( request . path ) else : return http . HttpResponseBadRequest ( '' ) data = { '' : event , '' : event_form or event_form_class ( instance = event ) , '' : recurrence_form or recurrence_form_class ( initial = { '' : datetime . now ( ) } ) } return render ( request , template , data ) def occurrence_view ( request , event_pk , pk , template = '' , form_class = forms . SingleOccurrenceForm ) : '''''' occurrence = get_object_or_404 ( Occurrence , pk = pk , event__pk = event_pk ) if request . method == '' : form = form_class ( request . POST , instance = occurrence ) if form . is_valid ( ) : form . save ( ) return http . HttpResponseRedirect ( request . path ) else : form = form_class ( instance = occurrence ) return render ( request , template , { '' : occurrence , '' : form } ) def add_event ( request , template = '' , event_form_class = forms . EventForm , recurrence_form_class = forms . MultipleOccurrenceForm ) : '''''' dtstart = None if request . method == '' : event_form = event_form_class ( request . POST ) recurrence_form = recurrence_form_class ( request . POST ) if event_form . is_valid ( ) and recurrence_form . is_valid ( ) : event = event_form . save ( ) recurrence_form . save ( event ) return http . HttpResponseRedirect ( event . get_absolute_url ( ) ) else : if '' in request . GET : try : dtstart = parser . parse ( request . GET [ '' ] ) except ( TypeError , ValueError ) as exc : logging . warning ( exc ) dtstart = dtstart or datetime . now ( ) event_form = event_form_class ( ) recurrence_form = recurrence_form_class ( initial = { '' : dtstart } ) return render ( request , template , { '' : dtstart , '' : event_form , '' : recurrence_form } ) def _datetime_view ( request , template , dt , timeslot_factory = None , items = None , params = None ) : '''''' timeslot_factory = timeslot_factory or utils . create_timeslot_table params = params or { } return render ( request , template , { '' : dt , '' : dt + timedelta ( days = + ) , '' : dt + timedelta ( days = - ) , '' : timeslot_factory ( dt , items , ** params ) } ) def day_view ( request , year , month , day , template = '' , ** params ) : '''''' dt = datetime ( int ( year ) , int ( month ) , int ( day ) ) return _datetime_view ( request , template , dt , ** params ) def today_view ( request , template = '' , ** params ) : '''''' return _datetime_view ( request , template , datetime . now ( ) , ** params ) def year_view ( request , year , template = '' , queryset = None ) : '''''' year = int ( year ) queryset = queryset . _clone ( ) if queryset is not None else Occurrence . objects . select_related ( ) occurrences = queryset . filter ( models . Q ( start_time__year = year ) | models . Q ( end_time__year = year ) ) def group_key ( o ) : return datetime ( year , o . start_time . month if o . start_time . year == year else o . end_time . month , ) return render ( request , template , { '' : year , '' : [ ( dt , list ( o ) ) for dt , o in itertools . groupby ( occurrences , group_key ) ] , '' : year + , '' : year - } ) def month_view ( request , year , month , template = '' , queryset = None ) : '''''' year , month = int ( year ) , int ( month ) cal = calendar . monthcalendar ( year , month ) dtstart = datetime ( year , month , ) last_day = max ( cal [ - ] ) ", "answer": "dtend = datetime ( year , month , last_day )"}, {"prompt": " from __future__ import unicode_literals ", "answer": "from djng . forms import NgFormValidationMixin"}, {"prompt": " from __future__ import with_statement import sys import base64 import warnings from libcloud . utils . py3 import b from libcloud . utils . py3 import urlparse from libcloud . compute . providers import Provider from libcloud . common . cloudstack import CloudStackDriverMixIn from libcloud . compute . base import Node , NodeDriver , NodeImage , NodeLocation from libcloud . compute . base import NodeSize , StorageVolume , VolumeSnapshot from libcloud . compute . base import KeyPair from libcloud . compute . types import NodeState , LibcloudError from libcloud . compute . types import KeyPairDoesNotExistError , StorageVolumeState from libcloud . utils . networking import is_private_subnet def transform_int_or_unlimited ( value ) : try : return int ( value ) except ValueError : e = sys . exc_info ( ) [ ] if str ( value ) . lower ( ) == '' : return - raise e \"\"\"\"\"\" RESOURCE_EXTRA_ATTRIBUTES_MAP = { '' : { '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } } , '' : { '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : list } } , '' : { '' : { '' : '' , '' : str } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } } , '' : { '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } } , '' : { '' : { '' : '' , '' : str } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } } , '' : { '' : { '' : '' , '' : list } } , '' : { '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } } , '' : { '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : bool } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : transform_int_or_unlimited } , '' : { '' : '' , '' : str } } , '' : { '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } , '' : { '' : '' , '' : str } } } class CloudStackNode ( Node ) : \"\"\"\"\"\" def ex_allocate_public_ip ( self ) : \"\"\"\"\"\" return self . driver . ex_allocate_public_ip ( self ) def ex_release_public_ip ( self , address ) : \"\"\"\"\"\" return self . driver . ex_release_public_ip ( self , address ) def ex_create_ip_forwarding_rule ( self , address , protocol , start_port , end_port = None ) : \"\"\"\"\"\" return self . driver . ex_create_ip_forwarding_rule ( node = self , address = address , protocol = protocol , start_port = start_port , end_port = end_port ) def ex_create_port_forwarding_rule ( self , address , private_port , public_port , protocol , public_end_port = None , private_end_port = None , openfirewall = True ) : \"\"\"\"\"\" return self . driver . ex_create_port_forwarding_rule ( node = self , address = address , private_port = private_port , public_port = public_port , protocol = protocol , public_end_port = public_end_port , private_end_port = private_end_port , openfirewall = openfirewall ) def ex_delete_ip_forwarding_rule ( self , rule ) : \"\"\"\"\"\" return self . driver . ex_delete_ip_forwarding_rule ( node = self , rule = rule ) def ex_delete_port_forwarding_rule ( self , rule ) : \"\"\"\"\"\" return self . driver . ex_delete_port_forwarding_rule ( node = self , rule = rule ) def ex_start ( self ) : \"\"\"\"\"\" return self . driver . ex_start ( node = self ) def ex_stop ( self ) : \"\"\"\"\"\" return self . driver . ex_stop ( node = self ) class CloudStackAddress ( object ) : \"\"\"\"\"\" def __init__ ( self , id , address , driver , associated_network_id = None , vpc_id = None , virtualmachine_id = None ) : self . id = id self . address = address self . driver = driver self . associated_network_id = associated_network_id self . vpc_id = vpc_id self . virtualmachine_id = virtualmachine_id def release ( self ) : self . driver . ex_release_public_ip ( address = self ) def __str__ ( self ) : return self . address def __eq__ ( self , other ) : return self . __class__ is other . __class__ and self . id == other . id class CloudStackFirewallRule ( object ) : \"\"\"\"\"\" def __init__ ( self , id , address , cidr_list , protocol , icmp_code = None , icmp_type = None , start_port = None , end_port = None ) : \"\"\"\"\"\" self . id = id self . address = address self . cidr_list = cidr_list self . protocol = protocol self . icmp_code = icmp_code self . icmp_type = icmp_type self . start_port = start_port self . end_port = end_port def __eq__ ( self , other ) : return self . __class__ is other . __class__ and self . id == other . id class CloudStackEgressFirewallRule ( object ) : \"\"\"\"\"\" def __init__ ( self , id , network_id , cidr_list , protocol , icmp_code = None , icmp_type = None , start_port = None , end_port = None ) : \"\"\"\"\"\" self . id = id self . network_id = network_id self . cidr_list = cidr_list self . protocol = protocol self . icmp_code = icmp_code self . icmp_type = icmp_type self . start_port = start_port self . end_port = end_port def __eq__ ( self , other ) : return self . __class__ is other . __class__ and self . id == other . id class CloudStackIPForwardingRule ( object ) : \"\"\"\"\"\" def __init__ ( self , node , id , address , protocol , start_port , end_port = None ) : \"\"\"\"\"\" self . node = node self . id = id self . address = address self . protocol = protocol self . start_port = start_port self . end_port = end_port def delete ( self ) : self . node . ex_delete_ip_forwarding_rule ( rule = self ) def __eq__ ( self , other ) : return self . __class__ is other . __class__ and self . id == other . id class CloudStackPortForwardingRule ( object ) : \"\"\"\"\"\" def __init__ ( self , node , rule_id , address , protocol , public_port , private_port , public_end_port = None , private_end_port = None , network_id = None ) : \"\"\"\"\"\" self . node = node self . id = rule_id self . address = address self . protocol = protocol self . public_port = public_port self . public_end_port = public_end_port self . private_port = private_port self . private_end_port = private_end_port def delete ( self ) : self . node . ex_delete_port_forwarding_rule ( rule = self ) def __eq__ ( self , other ) : return self . __class__ is other . __class__ and self . id == other . id class CloudStackNetworkACLList ( object ) : \"\"\"\"\"\" def __init__ ( self , acl_id , name , vpc_id , driver , description = None ) : \"\"\"\"\"\" self . id = acl_id self . name = name self . vpc_id = vpc_id self . driver = driver self . description = description def __repr__ ( self ) : return ( ( '' '' ) % ( self . id , self . name , self . vpc_id , self . driver . name , self . description ) ) class CloudStackNetworkACL ( object ) : \"\"\"\"\"\" def __init__ ( self , id , protocol , acl_id , action , cidr_list , start_port , end_port , traffic_type = None ) : \"\"\"\"\"\" self . id = id self . protocol = protocol self . acl_id = acl_id self . action = action self . cidr_list = cidr_list self . start_port = start_port self . end_port = end_port self . traffic_type = traffic_type def __eq__ ( self , other ) : return self . __class__ is other . __class__ and self . id == other . id class CloudStackDiskOffering ( object ) : \"\"\"\"\"\" def __init__ ( self , id , name , size , customizable ) : self . id = id self . name = name self . size = size self . customizable = customizable def __eq__ ( self , other ) : return self . __class__ is other . __class__ and self . id == other . id class CloudStackNetwork ( object ) : \"\"\"\"\"\" def __init__ ( self , displaytext , name , networkofferingid , id , zoneid , driver , extra = None ) : self . displaytext = displaytext self . name = name self . networkofferingid = networkofferingid self . id = id self . zoneid = zoneid self . driver = driver self . extra = extra or { } def __repr__ ( self ) : return ( ( '' '' '' ) % ( self . displaytext , self . name , self . networkofferingid , self . id , self . zoneid , self . driver . name ) ) class CloudStackNetworkOffering ( object ) : \"\"\"\"\"\" def __init__ ( self , name , display_text , guest_ip_type , id , service_offering_id , for_vpc , driver , extra = None ) : self . display_text = display_text self . name = name self . guest_ip_type = guest_ip_type self . id = id self . service_offering_id = service_offering_id self . for_vpc = for_vpc self . driver = driver self . extra = extra or { } def __repr__ ( self ) : return ( ( '' '' '' ) % ( self . id , self . name , self . display_text , self . guest_ip_type , self . service_offering_id , self . for_vpc , self . driver . name ) ) class CloudStackNic ( object ) : \"\"\"\"\"\" def __init__ ( self , id , network_id , net_mask , gateway , ip_address , is_default , mac_address , driver , extra = None ) : self . id = id self . network_id = network_id self . net_mask = net_mask self . gateway = gateway self . ip_address = ip_address self . is_default = is_default self . mac_address = mac_address self . driver = driver self . extra = extra or { } def __repr__ ( self ) : return ( ( '' '' '' ) % ( self . id , self . network_id , self . net_mask , self . gateway , self . ip_address , self . is_default , self . mac_address , self . driver . name ) ) def __eq__ ( self , other ) : return self . __class__ is other . __class__ and self . id == other . id class CloudStackVPC ( object ) : \"\"\"\"\"\" def __init__ ( self , name , vpc_offering_id , id , cidr , driver , zone_id = None , display_text = None , extra = None ) : self . display_text = display_text self . name = name self . vpc_offering_id = vpc_offering_id self . id = id self . zone_id = zone_id self . cidr = cidr self . driver = driver self . extra = extra or { } def __repr__ ( self ) : return ( ( '' '' ) % ( self . name , self . vpc_offering_id , self . id , self . cidr , self . driver . name , self . zone_id , self . display_text ) ) class CloudStackVPCOffering ( object ) : \"\"\"\"\"\" def __init__ ( self , name , display_text , id , driver , extra = None ) : self . name = name self . display_text = display_text self . id = id self . driver = driver self . extra = extra or { } def __repr__ ( self ) : return ( ( '' '' '' ) % ( self . name , self . display_text , self . id , self . driver . name ) ) class CloudStackVpnGateway ( object ) : \"\"\"\"\"\" def __init__ ( self , id , account , domain , domain_id , public_ip , vpc_id , driver , extra = None ) : self . id = id self . account = account self . domain = domain self . domain_id = domain_id self . public_ip = public_ip self . vpc_id = vpc_id self . driver = driver self . extra = extra or { } @ property def vpc ( self ) : for vpc in self . driver . ex_list_vpcs ( ) : if self . vpc_id == vpc . id : return vpc raise LibcloudError ( '' % self . vpc_id ) def delete ( self ) : return self . driver . ex_delete_vpn_gateway ( vpn_gateway = self ) def __repr__ ( self ) : return ( ( '' '' '' ) % ( self . account , self . domain , self . domain_id , self . id , self . public_ip , self . vpc_id , self . driver . name ) ) class CloudStackVpnCustomerGateway ( object ) : \"\"\"\"\"\" def __init__ ( self , id , cidr_list , esp_policy , gateway , ike_policy , ipsec_psk , driver , extra = None ) : self . id = id self . cidr_list = cidr_list self . esp_policy = esp_policy self . gateway = gateway self . ike_policy = ike_policy self . ipsec_psk = ipsec_psk self . driver = driver self . extra = extra or { } def delete ( self ) : return self . driver . ex_delete_vpn_customer_gateway ( vpn_customer_gateway = self ) def __repr__ ( self ) : return ( ( '' '' '' ) % ( self . id , self . cidr_list , self . esp_policy , self . gateway , self . ike_policy , self . ipsec_psk , self . driver . name ) ) class CloudStackVpnConnection ( object ) : \"\"\"\"\"\" def __init__ ( self , id , passive , vpn_customer_gateway_id , vpn_gateway_id , state , driver , extra = None ) : self . id = id self . passive = passive self . vpn_customer_gateway_id = vpn_customer_gateway_id self . vpn_gateway_id = vpn_gateway_id self . state = state self . driver = driver self . extra = extra or { } @ property def vpn_customer_gateway ( self ) : try : return self . driver . ex_list_vpn_customer_gateways ( id = self . vpn_customer_gateway_id ) [ ] except IndexError : raise LibcloudError ( '' % self . vpn_customer_gateway_id ) @ property def vpn_gateway ( self ) : try : return self . driver . ex_list_vpn_gateways ( id = self . vpn_gateway_id ) [ ] except IndexError : raise LibcloudError ( '' % self . vpn_gateway_id ) def delete ( self ) : return self . driver . ex_delete_vpn_connection ( vpn_connection = self ) def __repr__ ( self ) : return ( ( '' '' '' ) % ( self . id , self . passive , self . vpn_customer_gateway_id , self . vpn_gateway_id , self . state , self . driver . name ) ) class CloudStackRouter ( object ) : \"\"\"\"\"\" def __init__ ( self , id , name , state , public_ip , vpc_id , driver ) : self . id = id self . name = name self . state = state self . public_ip = public_ip self . vpc_id = vpc_id self . driver = driver def __repr__ ( self ) : return ( ( '' '' ) % ( self . id , self . name , self . state , self . public_ip , self . vpc_id , self . driver . name ) ) class CloudStackProject ( object ) : \"\"\"\"\"\" def __init__ ( self , id , name , display_text , driver , extra = None ) : self . id = id self . name = name self . display_text = display_text self . driver = driver self . extra = extra or { } def __repr__ ( self ) : return ( ( '' '' ) % ( self . id , self . display_text , self . name , self . driver . name ) ) class CloudStackAffinityGroup ( object ) : \"\"\"\"\"\" def __init__ ( self , id , account , description , domain , domainid , name , group_type , virtualmachine_ids ) : \"\"\"\"\"\" self . id = id self . account = account self . description = description self . domain = domain self . domainid = domainid self . name = name self . type = group_type self . virtualmachine_ids = virtualmachine_ids def __repr__ ( self ) : return ( ( '' ) % ( self . id , self . name , self . type ) ) class CloudStackAffinityGroupType ( object ) : \"\"\"\"\"\" def __init__ ( self , type_name ) : \"\"\"\"\"\" self . type = type_name def __repr__ ( self ) : return ( ( '' ) % self . type ) class CloudStackNodeDriver ( CloudStackDriverMixIn , NodeDriver ) : \"\"\"\"\"\" name = '' api_name = '' website = '' type = Provider . CLOUDSTACK features = { '' : [ '' ] } NODE_STATE_MAP = { '' : NodeState . RUNNING , '' : NodeState . REBOOTING , '' : NodeState . STOPPED , '' : NodeState . PENDING , '' : NodeState . TERMINATED , '' : NodeState . PENDING , '' : NodeState . TERMINATED } VOLUME_STATE_MAP = { '' : StorageVolumeState . CREATING , '' : StorageVolumeState . DELETING , '' : StorageVolumeState . DELETING , '' : StorageVolumeState . DELETED , '' : StorageVolumeState . DELETED , '' : StorageVolumeState . AVAILABLE , '' : StorageVolumeState . AVAILABLE , '' : StorageVolumeState . BACKUP , '' : StorageVolumeState . ERROR } def __init__ ( self , key , secret = None , secure = True , host = None , path = None , port = None , url = None , * args , ** kwargs ) : \"\"\"\"\"\" if url : parsed = urlparse . urlparse ( url ) path = parsed . path scheme = parsed . scheme split = parsed . netloc . split ( '' ) if len ( split ) == : host = parsed . netloc port = if scheme == '' else else : host = split [ ] port = int ( split [ ] ) else : host = host if host else self . host path = path if path else self . path if path is not None : self . path = path if host is not None : self . host = host if ( self . type == Provider . CLOUDSTACK ) and ( not host or not path ) : raise Exception ( '' '' '' ) super ( CloudStackNodeDriver , self ) . __init__ ( key = key , secret = secret , secure = secure , host = host , port = port ) def list_images ( self , location = None ) : args = { '' : '' } if location is not None : args [ '' ] = location . id imgs = self . _sync_request ( command = '' , params = args , method = '' ) images = [ ] for img in imgs . get ( '' , [ ] ) : extra = { '' : img [ '' ] , '' : img [ '' ] , '' : img [ '' ] , '' : img [ '' ] } size = img . get ( '' , None ) if size is not None : extra . update ( { '' : img [ '' ] } ) images . append ( NodeImage ( id = img [ '' ] , name = img [ '' ] , driver = self . connection . driver , extra = extra ) ) return images def list_locations ( self ) : \"\"\"\"\"\" locs = self . _sync_request ( '' ) locations = [ ] for loc in locs [ '' ] : location = NodeLocation ( str ( loc [ '' ] ) , loc [ '' ] , '' , self ) locations . append ( location ) return locations def list_nodes ( self , project = None , location = None ) : \"\"\"\"\"\" args = { } if project : args [ '' ] = project . id if location is not None : args [ '' ] = location . id vms = self . _sync_request ( '' , params = args ) addrs = self . _sync_request ( '' , params = args ) port_forwarding_rules = self . _sync_request ( '' ) ip_forwarding_rules = self . _sync_request ( '' ) public_ips_map = { } for addr in addrs . get ( '' , [ ] ) : if '' not in addr : continue vm_id = str ( addr [ '' ] ) if vm_id not in public_ips_map : public_ips_map [ vm_id ] = { } public_ips_map [ vm_id ] [ addr [ '' ] ] = addr [ '' ] nodes = [ ] for vm in vms . get ( '' , [ ] ) : public_ips = public_ips_map . get ( str ( vm [ '' ] ) , { } ) . keys ( ) public_ips = list ( public_ips ) node = self . _to_node ( data = vm , public_ips = public_ips ) addresses = public_ips_map . get ( str ( vm [ '' ] ) , { } ) . items ( ) addresses = [ CloudStackAddress ( id = address_id , address = address , driver = node . driver ) for address , address_id in addresses ] node . extra [ '' ] = addresses rules = [ ] for addr in addresses : for r in ip_forwarding_rules . get ( '' , [ ] ) : if str ( r [ '' ] ) == node . id : rule = CloudStackIPForwardingRule ( node , r [ '' ] , addr , r [ '' ] . upper ( ) , r [ '' ] , r [ '' ] ) rules . append ( rule ) node . extra [ '' ] = rules rules = [ ] for r in port_forwarding_rules . get ( '' , [ ] ) : if str ( r [ '' ] ) == node . id : addr = [ CloudStackAddress ( id = a [ '' ] , address = a [ '' ] , driver = node . driver ) for a in addrs . get ( '' , [ ] ) if a [ '' ] == r [ '' ] ] rule = CloudStackPortForwardingRule ( node , r [ '' ] , addr [ ] , r [ '' ] . upper ( ) , r [ '' ] , r [ '' ] , r [ '' ] , r [ '' ] ) if not addr [ ] . address in node . public_ips : node . public_ips . append ( addr [ ] . address ) rules . append ( rule ) node . extra [ '' ] = rules nodes . append ( node ) return nodes def ex_get_node ( self , node_id , project = None ) : \"\"\"\"\"\" list_nodes_args = { '' : node_id } list_ips_args = { } if project : list_nodes_args [ '' ] = project . id list_ips_args [ '' ] = project . id vms = self . _sync_request ( '' , params = list_nodes_args ) if not vms : raise Exception ( \"\" % node_id ) vm = vms [ '' ] [ ] addrs = self . _sync_request ( '' , params = list_ips_args ) public_ips = { } for addr in addrs . get ( '' , [ ] ) : if '' not in addr : continue public_ips [ addr [ '' ] ] = addr [ '' ] node = self . _to_node ( data = vm , public_ips = list ( public_ips . keys ( ) ) ) addresses = [ CloudStackAddress ( id = address_id , address = address , driver = node . driver ) for address , address_id in public_ips . items ( ) ] node . extra [ '' ] = addresses rules = [ ] list_fw_rules = { '' : node_id } for addr in addresses : result = self . _sync_request ( '' , params = list_fw_rules ) for r in result . get ( '' , [ ] ) : if str ( r [ '' ] ) == node . id : rule = CloudStackIPForwardingRule ( node , r [ '' ] , addr , r [ '' ] . upper ( ) , r [ '' ] , r [ '' ] ) rules . append ( rule ) node . extra [ '' ] = rules rules = [ ] public_ips = self . ex_list_public_ips ( ) result = self . _sync_request ( '' , params = list_fw_rules ) for r in result . get ( '' , [ ] ) : if str ( r [ '' ] ) == node . id : addr = [ a for a in public_ips if a . address == r [ '' ] ] rule = CloudStackPortForwardingRule ( node , r [ '' ] , addr [ ] , r [ '' ] . upper ( ) , r [ '' ] , r [ '' ] , r [ '' ] , r [ '' ] ) if not addr [ ] . address in node . public_ips : node . public_ips . append ( addr [ ] . address ) rules . append ( rule ) node . extra [ '' ] = rules return node def list_sizes ( self , location = None ) : \"\"\"\"\"\" szs = self . _sync_request ( command = '' , method = '' ) sizes = [ ] for sz in szs [ '' ] : extra = { '' : sz [ '' ] } sizes . append ( NodeSize ( sz [ '' ] , sz [ '' ] , sz [ '' ] , , , , self , extra = extra ) ) return sizes def create_node ( self , ** kwargs ) : \"\"\"\"\"\" server_params = self . _create_args_to_params ( None , ** kwargs ) data = self . _async_request ( command = '' , params = server_params , method = '' ) [ '' ] node = self . _to_node ( data = data ) return node def _create_args_to_params ( self , node , ** kwargs ) : server_params = { } name = kwargs . get ( '' , None ) size = kwargs . get ( '' , None ) image = kwargs . get ( '' , None ) location = kwargs . get ( '' , None ) networks = kwargs . get ( '' , None ) project = kwargs . get ( '' , None ) diskoffering = kwargs . get ( '' , None ) ex_key_name = kwargs . get ( '' , None ) ex_user_data = kwargs . get ( '' , None ) ex_security_groups = kwargs . get ( '' , None ) ex_displayname = kwargs . get ( '' , None ) ex_ip_address = kwargs . get ( '' , None ) ex_start_vm = kwargs . get ( '' , None ) ex_rootdisksize = kwargs . get ( '' , None ) ex_affinity_groups = kwargs . get ( '' , None ) if name : server_params [ '' ] = name if ex_displayname : server_params [ '' ] = ex_displayname if size : server_params [ '' ] = size . id if image : server_params [ '' ] = image . id if location : server_params [ '' ] = location . id else : server_params [ '' ] = self . list_locations ( ) [ ] . id if networks : networks = '' . join ( [ str ( network . id ) for network in networks ] ) server_params [ '' ] = networks if project : server_params [ '' ] = project . id if diskoffering : server_params [ '' ] = diskoffering . id if ex_key_name : server_params [ '' ] = ex_key_name if ex_user_data : ex_user_data = base64 . b64encode ( b ( ex_user_data ) . decode ( '' ) ) server_params [ '' ] = ex_user_data if ex_security_groups : ex_security_groups = '' . join ( ex_security_groups ) server_params [ '' ] = ex_security_groups if ex_ip_address : server_params [ '' ] = ex_ip_address if ex_rootdisksize : server_params [ '' ] = ex_rootdisksize if ex_start_vm is not None : server_params [ '' ] = ex_start_vm if ex_affinity_groups : affinity_group_ids = '' . join ( ag . id for ag in ex_affinity_groups ) server_params [ '' ] = affinity_group_ids return server_params def destroy_node ( self , node , ex_expunge = False ) : \"\"\"\"\"\" args = { '' : node . id , } if ex_expunge : args [ '' ] = ex_expunge self . _async_request ( command = '' , params = args , method = '' ) return True def reboot_node ( self , node ) : \"\"\"\"\"\" self . _async_request ( command = '' , params = { '' : node . id } , method = '' ) return True def ex_start ( self , node ) : \"\"\"\"\"\" res = self . _async_request ( command = '' , params = { '' : node . id } , method = '' ) return res [ '' ] [ '' ] def ex_stop ( self , node ) : \"\"\"\"\"\" res = self . _async_request ( command = '' , params = { '' : node . id } , method = '' ) return res [ '' ] [ '' ] def ex_list_disk_offerings ( self ) : \"\"\"\"\"\" diskOfferings = [ ] diskOfferResponse = self . _sync_request ( command = '' , method = '' ) for diskOfferDict in diskOfferResponse . get ( '' , ( ) ) : diskOfferings . append ( CloudStackDiskOffering ( id = diskOfferDict [ '' ] , name = diskOfferDict [ '' ] , size = diskOfferDict [ '' ] , customizable = diskOfferDict [ '' ] ) ) return diskOfferings def ex_list_networks ( self , project = None ) : \"\"\"\"\"\" args = { } if project is not None : args [ '' ] = project . id res = self . _sync_request ( command = '' , params = args , method = '' ) nets = res . get ( '' , [ ] ) networks = [ ] extra_map = RESOURCE_EXTRA_ATTRIBUTES_MAP [ '' ] for net in nets : extra = self . _get_extra_dict ( net , extra_map ) if '' in net : extra [ '' ] = self . _get_resource_tags ( net [ '' ] ) networks . append ( CloudStackNetwork ( net [ '' ] , net [ '' ] , net [ '' ] , net [ '' ] , net [ '' ] , self , extra = extra ) ) return networks def ex_list_network_offerings ( self ) : \"\"\"\"\"\" res = self . _sync_request ( command = '' , method = '' ) netoffers = res . get ( '' , [ ] ) networkofferings = [ ] for netoffer in netoffers : networkofferings . append ( CloudStackNetworkOffering ( netoffer [ '' ] , netoffer [ '' ] , netoffer [ '' ] , netoffer [ '' ] , netoffer [ '' ] , netoffer [ '' ] , self ) ) return networkofferings def ex_create_network ( self , display_text , name , network_offering , location , gateway = None , netmask = None , network_domain = None , vpc_id = None , project_id = None ) : \"\"\"\"\"\" extra_map = RESOURCE_EXTRA_ATTRIBUTES_MAP [ '' ] args = { '' : display_text , '' : name , '' : network_offering . id , '' : location . id , } if gateway is not None : args [ '' ] = gateway if netmask is not None : args [ '' ] = netmask if network_domain is not None : args [ '' ] = network_domain if vpc_id is not None : args [ '' ] = vpc_id if project_id is not None : args [ '' ] = project_id \"\"\"\"\"\" result = self . _sync_request ( command = '' , params = args , method = '' ) result = result [ '' ] extra = self . _get_extra_dict ( result , extra_map ) network = CloudStackNetwork ( display_text , name , network_offering . id , result [ '' ] , location . id , self , extra = extra ) return network def ex_delete_network ( self , network , force = None ) : \"\"\"\"\"\" args = { '' : network . id , '' : force } self . _async_request ( command = '' , params = args , method = '' ) return True def ex_list_vpc_offerings ( self ) : \"\"\"\"\"\" res = self . _sync_request ( command = '' , method = '' ) vpcoffers = res . get ( '' , [ ] ) vpcofferings = [ ] for vpcoffer in vpcoffers : vpcofferings . append ( CloudStackVPCOffering ( vpcoffer [ '' ] , vpcoffer [ '' ] , vpcoffer [ '' ] , self ) ) return vpcofferings def ex_list_vpcs ( self , project = None ) : \"\"\"\"\"\" args = { } if project is not None : args [ '' ] = project . id res = self . _sync_request ( command = '' , params = args , method = '' ) vpcs = res . get ( '' , [ ] ) networks = [ ] for vpc in vpcs : networks . append ( CloudStackVPC ( vpc [ '' ] , vpc [ '' ] , vpc [ '' ] , vpc [ '' ] , self , vpc [ '' ] , vpc [ '' ] ) ) return networks def ex_list_routers ( self , vpc_id = None ) : \"\"\"\"\"\" args = { } if vpc_id is not None : args [ '' ] = vpc_id res = self . _sync_request ( command = '' , params = args , method = '' ) rts = res . get ( '' , [ ] ) routers = [ ] for router in rts : routers . append ( CloudStackRouter ( router [ '' ] , router [ '' ] , router [ '' ] , router [ '' ] , router [ '' ] , self ) ) return routers def ex_create_vpc ( self , cidr , display_text , name , vpc_offering , zone_id , network_domain = None ) : \"\"\"\"\"\" extra_map = RESOURCE_EXTRA_ATTRIBUTES_MAP [ '' ] args = { '' : cidr , '' : display_text , '' : name , '' : vpc_offering . id , '' : zone_id , } if network_domain is not None : args [ '' ] = network_domain result = self . _sync_request ( command = '' , params = args , method = '' ) extra = self . _get_extra_dict ( result , extra_map ) vpc = CloudStackVPC ( name , vpc_offering . id , result [ '' ] , cidr , self , zone_id , display_text , extra = extra ) return vpc def ex_delete_vpc ( self , vpc ) : \"\"\"\"\"\" args = { '' : vpc . id } self . _async_request ( command = '' , params = args , method = '' ) return True def ex_list_projects ( self ) : \"\"\"\"\"\" res = self . _sync_request ( command = '' , method = '' ) projs = res . get ( '' , [ ] ) projects = [ ] extra_map = RESOURCE_EXTRA_ATTRIBUTES_MAP [ '' ] for proj in projs : extra = self . _get_extra_dict ( proj , extra_map ) if '' in proj : extra [ '' ] = self . _get_resource_tags ( proj [ '' ] ) projects . append ( CloudStackProject ( id = proj [ '' ] , name = proj [ '' ] , display_text = proj [ '' ] , driver = self , extra = extra ) ) return projects def create_volume ( self , size , name , location = None , snapshot = None ) : \"\"\"\"\"\" for diskOffering in self . ex_list_disk_offerings ( ) : if diskOffering . size == size or diskOffering . customizable : break else : raise LibcloudError ( '' % size ) if location is None : location = self . list_locations ( ) [ ] params = { '' : name , '' : diskOffering . id , '' : location . id } if diskOffering . customizable : params [ '' ] = size requestResult = self . _async_request ( command = '' , params = params , method = '' ) volumeResponse = requestResult [ '' ] state = self . _to_volume_state ( volumeResponse ) return StorageVolume ( id = volumeResponse [ '' ] , name = name , size = size , state = state , driver = self , extra = dict ( name = volumeResponse [ '' ] ) ) def destroy_volume ( self , volume ) : \"\"\"\"\"\" self . _sync_request ( command = '' , params = { '' : volume . id } , method = '' ) return True def attach_volume ( self , node , volume , device = None ) : \"\"\"\"\"\" self . _async_request ( command = '' , params = { '' : volume . id , '' : node . id } , method = '' ) return True def detach_volume ( self , volume ) : \"\"\"\"\"\" self . _async_request ( command = '' , params = { '' : volume . id } , method = '' ) return True def list_volumes ( self , node = None ) : \"\"\"\"\"\" if node : volumes = self . _sync_request ( command = '' , params = { '' : node . id } , method = '' ) else : volumes = self . _sync_request ( command = '' , method = '' ) list_volumes = [ ] extra_map = RESOURCE_EXTRA_ATTRIBUTES_MAP [ '' ] for vol in volumes . get ( '' , [ ] ) : extra = self . _get_extra_dict ( vol , extra_map ) if '' in vol : extra [ '' ] = self . _get_resource_tags ( vol [ '' ] ) state = self . _to_volume_state ( vol ) list_volumes . append ( StorageVolume ( id = vol [ '' ] , name = vol [ '' ] , size = vol [ '' ] , state = state , driver = self , extra = extra ) ) return list_volumes def ex_get_volume ( self , volume_id , project = None ) : \"\"\"\"\"\" args = { '' : volume_id } if project : args [ '' ] = project . id volumes = self . _sync_request ( command = '' , params = args ) if not volumes : raise Exception ( \"\" % volume_id ) vol = volumes [ '' ] [ ] extra_map = RESOURCE_EXTRA_ATTRIBUTES_MAP [ '' ] extra = self . _get_extra_dict ( vol , extra_map ) if '' in vol : extra [ '' ] = self . _get_resource_tags ( vol [ '' ] ) state = self . _to_volume_state ( vol ) volume = StorageVolume ( id = vol [ '' ] , name = vol [ '' ] , state = state , size = vol [ '' ] , driver = self , extra = extra ) return volume def list_key_pairs ( self , ** kwargs ) : \"\"\"\"\"\" extra_args = kwargs . copy ( ) res = self . _sync_request ( command = '' , params = extra_args , method = '' ) key_pairs = res . get ( '' , [ ] ) key_pairs = self . _to_key_pairs ( data = key_pairs ) return key_pairs def get_key_pair ( self , name ) : \"\"\"\"\"\" params = { '' : name } res = self . _sync_request ( command = '' , params = params , method = '' ) key_pairs = res . get ( '' , [ ] ) if len ( key_pairs ) == : raise KeyPairDoesNotExistError ( name = name , driver = self ) key_pair = self . _to_key_pair ( data = key_pairs [ ] ) return key_pair def create_key_pair ( self , name , ** kwargs ) : \"\"\"\"\"\" extra_args = kwargs . copy ( ) params = { '' : name } params . update ( extra_args ) res = self . _sync_request ( command = '' , params = params , method = '' ) key_pair = self . _to_key_pair ( data = res [ '' ] ) return key_pair def import_key_pair_from_string ( self , name , key_material ) : \"\"\"\"\"\" res = self . _sync_request ( command = '' , params = { '' : name , '' : key_material } , method = '' ) key_pair = self . _to_key_pair ( data = res [ '' ] ) return key_pair def delete_key_pair ( self , key_pair , ** kwargs ) : \"\"\"\"\"\" extra_args = kwargs . copy ( ) params = { '' : key_pair . name } params . update ( extra_args ) res = self . _sync_request ( command = '' , params = params , method = '' ) return res [ '' ] == '' def ex_list_public_ips ( self ) : \"\"\"\"\"\" ips = [ ] res = self . _sync_request ( command = '' , method = '' ) if not res : return ips for ip in res [ '' ] : ips . append ( CloudStackAddress ( ip [ '' ] , ip [ '' ] , self , ip . get ( '' , [ ] ) , ip . get ( '' ) , ip . get ( '' ) ) ) return ips def ex_allocate_public_ip ( self , vpc_id = None , network_id = None , location = None ) : \"\"\"\"\"\" args = { } if location is not None : args [ '' ] = location . id else : args [ '' ] = self . list_locations ( ) [ ] . id if vpc_id is not None : args [ '' ] = vpc_id if network_id is not None : args [ '' ] = network_id addr = self . _async_request ( command = '' , params = args , method = '' ) addr = addr [ '' ] addr = CloudStackAddress ( addr [ '' ] , addr [ '' ] , self ) return addr def ex_release_public_ip ( self , address ) : \"\"\"\"\"\" res = self . _async_request ( command = '' , params = { '' : address . id } , method = '' ) return res [ '' ] def ex_list_firewall_rules ( self ) : \"\"\"\"\"\" rules = [ ] result = self . _sync_request ( command = '' , method = '' ) if result != { } : public_ips = self . ex_list_public_ips ( ) for rule in result [ '' ] : ", "answer": "addr = [ a for a in public_ips if"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import logging import os import runpy import shutil import sys import textwrap import argparse import config from path import path import utils if sys . platform == '' : GLOBAL_CONFIG_FILE = '' else : GLOBAL_CONFIG_FILE = '' MISSING_GAE_SDK_MSG = \"\" \"\" class Action ( object ) : \"\"\"\"\"\" name = None description = None epilog = None def __init__ ( self , manager , name ) : self . manager = manager self . name = name self . logger = logging . getLogger ( name ) def __call__ ( self , argv ) : raise NotImplementedError ( ) def get_config_section ( self ) : sections = [ self . manager . app , '' ] return [ '' % ( s , self . name ) for s in sections if s ] def error ( self , message , status = ) : \"\"\"\"\"\" self . logger . error ( message ) sys . exit ( status ) def run_hooks ( self , import_names , args ) : \"\"\"\"\"\" hooks = [ ] for import_name in import_names : hook = utils . import_string ( import_name , True ) if hook is None : ", "answer": "self . error ( '' % import_name )"}, {"prompt": " \"\"\"\"\"\" import collections import itertools import sys import warnings def is_iterable ( x ) : \"\" try : iter ( x ) except TypeError : ", "answer": "return False"}, {"prompt": " import DeepFried2 as df def net ( ) : model = df . Sequential ( ) model . add ( df . Linear ( * , ) ) model . add ( df . ReLU ( ) ) model . add ( df . Linear ( , ) ) model . add ( df . ReLU ( ) ) model . add ( df . Linear ( , ) ) model . add ( df . ReLU ( ) ) model . add ( df . Linear ( , ) ) model . add ( df . SoftMax ( ) ) return model def lenet_cudnn ( ) : model = df . Sequential ( ) model . add ( df . Reshape ( - , , , ) ) model . add ( df . SpatialConvolutionCUDNN ( , , ( , ) , border = '' , bias = False ) ) model . add ( df . BatchNormalization ( ) ) model . add ( df . ReLU ( ) ) model . add ( df . SpatialMaxPoolingCUDNN ( ( , ) ) ) model . add ( df . SpatialConvolutionCUDNN ( , , ( , ) , border = '' , bias = False ) ) model . add ( df . BatchNormalization ( ) ) model . add ( df . ReLU ( ) ) model . add ( df . SpatialMaxPoolingCUDNN ( ( , ) ) ) model . add ( df . Reshape ( - , * * ) ) model . add ( df . Linear ( * * , , bias = False ) ) model . add ( df . BatchNormalization ( ) ) model . add ( df . ReLU ( ) ) model . add ( df . Dropout ( ) ) model . add ( df . Linear ( , ) ) model . add ( df . SoftMax ( ) ) return model def lenet_same ( ) : model = df . Sequential ( ) model . add ( df . Reshape ( - , , , ) ) model . add ( df . SpatialConvolution ( , , ( , ) , border = '' , bias = False ) ) model . add ( df . BatchNormalization ( ) ) model . add ( df . ReLU ( ) ) model . add ( df . SpatialMaxPooling ( ( , ) ) ) model . add ( df . SpatialConvolution ( , , ( , ) , border = '' , bias = False ) ) model . add ( df . BatchNormalization ( ) ) model . add ( df . ReLU ( ) ) model . add ( df . SpatialMaxPooling ( ( , ) ) ) model . add ( df . Reshape ( - , * * ) ) model . add ( df . Linear ( * * , , bias = False ) ) model . add ( df . BatchNormalization ( ) ) model . add ( df . ReLU ( ) ) ", "answer": "model . add ( df . Dropout ( ) )"}, {"prompt": " from paramz import Param from . priorizable import Priorizable from paramz . transformations import __fixed__ import logging , numpy as np class Param ( Param , Priorizable ) : ", "answer": "pass "}, {"prompt": " \"\"\"\"\"\" import MySQLdb import MySQLdb . cursors import psycopg2 from . . config import Config from . . utils . exceptions import ETLConfigError from . . utils . helpers import exactly_one from . . utils . helpers import retry from . . utils . hook import hook config = Config ( ) CONNECTION_RETRIES = config . etl . get ( '' , ) def get_redshift_config ( ) : \"\"\"\"\"\" if not hasattr ( config , '' ) : raise ETLConfigError ( '' ) return config . redshift @ retry ( CONNECTION_RETRIES , ) @ hook ( '' ) def redshift_connection ( redshift_creds = None , autocommit = True , connect_timeout = , ** kwargs ) : \"\"\"\"\"\" if redshift_creds is None : redshift_creds = get_redshift_config ( ) connection = psycopg2 . connect ( host = redshift_creds [ '' ] , user = redshift_creds [ '' ] , password = redshift_creds [ '' ] , port = redshift_creds [ '' ] , database = redshift_creds [ '' ] , connect_timeout = connect_timeout , ** kwargs ) connection . autocommit = autocommit return connection def get_sql_config ( database_name ) : \"\"\"\"\"\" if not hasattr ( config , '' ) : raise ETLConfigError ( '' ) if database_name not in config . mysql : raise ETLConfigError ( '' % database_name ) sql_creds = config . mysql [ database_name ] sql_creds [ '' ] = database_name return sql_creds @ retry ( CONNECTION_RETRIES , ) @ hook ( '' ) def rds_connection ( database_name = None , sql_creds = None , cursorclass = MySQLdb . cursors . SSCursor , ** kwargs ) : \"\"\"\"\"\" assert exactly_one ( database_name , sql_creds ) , '' if sql_creds is None : sql_creds = get_sql_config ( database_name ) connection = MySQLdb . connect ( host = sql_creds [ '' ] , ", "answer": "user = sql_creds [ '' ] ,"}, {"prompt": " \"\"\"\"\"\" import commands import fnmatch import optparse import os import sys import checkers import scmhandlers class CommandError ( Exception ) : pass class CodeQuality ( object ) : def __init__ ( self , options ) : self . options = options def codequality ( self , paths ) : if self . options . list_checkers : self . _list_checkers ( ) return if not paths and not self . options . scmhandler : paths = [ '' ] if self . options . scmhandler and self . options . scmhandler not in scmhandlers . scmhandlers : raise CommandError ( '' % self . options . scmhandler ) paths = self . _resolve_paths ( * paths ) scmhandler = scmhandlers . scmhandlers . get ( self . options . scmhandler , scmhandlers . NoSCMHandler ) ( ) errors_exist = False checker_to_loc_to_filename = { } for filename , location in scmhandler . srcs_to_check ( paths , rev = self . options . rev , ignore_untracked = self . options . ignore_untracked ) : if self . _should_ignore ( filename ) : continue checker_classes = self . _relevant_checkers ( filename ) for checker_class in checker_classes : loc_to_filename = checker_to_loc_to_filename . setdefault ( checker_class , { } ) loc_to_filename [ location ] = filename for checker_class , loc_to_filename in checker_to_loc_to_filename . iteritems ( ) : locations = loc_to_filename . keys ( ) if self . options . verbose : for location , filename in loc_to_filename . iteritems ( ) : print '' % ( checker_class . __name__ , filename , '' if location == filename else ( '' % location ) ) try : errs = checker_class ( ) . check ( locations ) except OSError : continue for err in errs : errors_exist = True err [ '' ] = loc_to_filename [ err [ '' ] ] print self . out_fmt % err return errors_exist out_fmt = '' def _relevant_checkers ( self , path ) : \"\"\"\"\"\" _ , ext = os . path . splitext ( path ) ext = ext . lstrip ( '' ) return checkers . checkers . get ( ext , [ ] ) def _resolve_paths ( self , * paths ) : \"\"\"\"\"\" result = set ( ) for path in paths : if os . path . isdir ( path ) : for dirpath , _ , filenames in os . walk ( path ) : for filename in filenames : path = os . path . join ( dirpath , filename ) if path . startswith ( '' ) : path = path [ : ] . lstrip ( '' ) if not self . _should_ignore ( path ) : result . add ( path ) else : result . add ( path ) return result def _list_checkers ( self ) : \"\"\"\"\"\" classes = set ( ) for checker_group in checkers . checkers . itervalues ( ) : for checker in checker_group : classes . add ( checker ) max_width = for clazz in classes : max_width = max ( max_width , len ( clazz . tool ) , len ( clazz . __name__ ) ) for clazz in sorted ( classes ) : status , _ = commands . getstatusoutput ( '' % clazz . tool ) result = '' if status else '' version = '' if status else clazz . get_version ( ) print '' % ( clazz . __name__ . ljust ( max_width + ) , clazz . tool . ljust ( max_width + ) , result . ljust ( max_width + ) , version , ) def _should_ignore ( self , path ) : \"\"\"\"\"\" for ignore in self . options . ignores : if fnmatch . fnmatch ( path , ignore ) : return True return False def main ( ) : parser = optparse . OptionParser ( usage = \"\" % __doc__ . strip ( ) , ) parser . add_option ( '' , dest = '' , default = None , help = '' '' , ) ", "answer": "parser . add_option ("}, {"prompt": " from flask . ext . babel import lazy_gettext as _ import flask import wtforms import auth import config import i18n import model import util from main import app @ app . route ( '' ) @ auth . admin_required def admin ( ) : return flask . render_template ( '' , title = _ ( '' ) , html_class = '' , ) class ConfigUpdateForm ( i18n . Form ) : analytics_id = wtforms . StringField ( model . Config . analytics_id . _verbose_name , filters = [ util . strip_filter ] ) announcement_html = wtforms . TextAreaField ( model . Config . announcement_html . _verbose_name , filters = [ util . strip_filter ] ) ", "answer": "announcement_type = wtforms . SelectField ( model . Config . announcement_type . _verbose_name , choices = [ ( t , t . title ( ) ) for t in model . Config . announcement_type . _choices ] )"}, {"prompt": " __project__ = '' ", "answer": "__version__ = \"\" "}, {"prompt": " import functools import sys import unittest from test import test_support from weakref import proxy import pickle @ staticmethod def PythonPartial ( func , * args , ** keywords ) : '' def newfunc ( * fargs , ** fkeywords ) : newkeywords = keywords . copy ( ) newkeywords . update ( fkeywords ) return func ( * ( args + fargs ) , ** newkeywords ) newfunc . func = func newfunc . args = args newfunc . keywords = keywords return newfunc def capture ( * args , ** kw ) : \"\"\"\"\"\" return args , kw def signature ( part ) : \"\"\"\"\"\" return ( part . func , part . args , part . keywords , part . __dict__ ) class TestPartial ( unittest . TestCase ) : thetype = functools . partial def test_basic_examples ( self ) : p = self . thetype ( capture , , , a = , b = ) self . assertEqual ( p ( , , b = , c = ) , ( ( , , , ) , dict ( a = , b = , c = ) ) ) p = self . thetype ( map , lambda x : x * ) self . assertEqual ( p ( [ , , , ] ) , [ , , , ] ) def test_attributes ( self ) : p = self . thetype ( capture , , , a = , b = ) self . assertEqual ( p . func , capture ) self . assertEqual ( p . args , ( , ) ) self . assertEqual ( p . keywords , dict ( a = , b = ) ) self . assertRaises ( TypeError , setattr , p , '' , map ) self . assertRaises ( TypeError , setattr , p , '' , ( , ) ) self . assertRaises ( TypeError , setattr , p , '' , dict ( a = , b = ) ) p = self . thetype ( hex ) try : del p . __dict__ except TypeError : pass else : self . fail ( '' ) def test_argument_checking ( self ) : self . assertRaises ( TypeError , self . thetype ) try : self . thetype ( ) ( ) except TypeError : pass else : self . fail ( '' ) def test_protection_of_callers_dict_argument ( self ) : def func ( a = , b = ) : return a d = { '' : } p = self . thetype ( func , a = ) self . assertEqual ( p ( ** d ) , ) self . assertEqual ( d , { '' : } ) p ( b = ) self . assertEqual ( d , { '' : } ) def test_arg_combinations ( self ) : p = self . thetype ( capture ) self . assertEqual ( p ( ) , ( ( ) , { } ) ) self . assertEqual ( p ( , ) , ( ( , ) , { } ) ) p = self . thetype ( capture , , ) self . assertEqual ( p ( ) , ( ( , ) , { } ) ) self . assertEqual ( p ( , ) , ( ( , , , ) , { } ) ) def test_kw_combinations ( self ) : p = self . thetype ( capture ) self . assertEqual ( p ( ) , ( ( ) , { } ) ) self . assertEqual ( p ( a = ) , ( ( ) , { '' : } ) ) p = self . thetype ( capture , a = ) self . assertEqual ( p ( ) , ( ( ) , { '' : } ) ) self . assertEqual ( p ( b = ) , ( ( ) , { '' : , '' : } ) ) self . assertEqual ( p ( a = , b = ) , ( ( ) , { '' : , '' : } ) ) def test_positional ( self ) : for args in [ ( ) , ( , ) , ( , ) , ( , , ) , ( , , , ) ] : p = self . thetype ( capture , * args ) expected = args + ( '' , ) got , empty = p ( '' ) self . assertTrue ( expected == got and empty == { } ) def test_keyword ( self ) : for a in [ '' , , None , ] : p = self . thetype ( capture , a = a ) expected = { '' : a , '' : None } empty , got = p ( x = None ) self . assertTrue ( expected == got and empty == ( ) ) def test_no_side_effects ( self ) : p = self . thetype ( capture , , a = ) args1 , kw1 = p ( , b = ) self . assertTrue ( args1 == ( , ) and kw1 == { '' : , '' : } ) args2 , kw2 = p ( ) self . assertTrue ( args2 == ( , ) and kw2 == { '' : } ) def test_error_propagation ( self ) : def f ( x , y ) : x // y self . assertRaises ( ZeroDivisionError , self . thetype ( f , , ) ) self . assertRaises ( ZeroDivisionError , self . thetype ( f , ) , ) self . assertRaises ( ZeroDivisionError , self . thetype ( f ) , , ) self . assertRaises ( ZeroDivisionError , self . thetype ( f , y = ) , ) def test_weakref ( self ) : f = self . thetype ( int , base = ) p = proxy ( f ) self . assertEqual ( f . func , p . func ) f = None self . assertRaises ( ReferenceError , getattr , p , '' ) def test_with_bound_and_unbound_methods ( self ) : data = map ( str , range ( ) ) join = self . thetype ( str . join , '' ) self . assertEqual ( join ( data ) , '' ) join = self . thetype ( '' . join ) self . assertEqual ( join ( data ) , '' ) def test_pickle ( self ) : f = self . thetype ( signature , '' , bar = True ) f . add_something_to__dict__ = True for proto in range ( pickle . HIGHEST_PROTOCOL + ) : f_copy = pickle . loads ( pickle . dumps ( f , proto ) ) self . assertEqual ( signature ( f ) , signature ( f_copy ) ) def test_setstate_refcount ( self ) : class BadSequence : def __len__ ( self ) : return def __getitem__ ( self , key ) : if key == : return max elif key == : return tuple ( range ( ) ) elif key in ( , ) : return { } raise IndexError f = self . thetype ( object ) self . assertRaises ( SystemError , f . __setstate__ , BadSequence ( ) ) class PartialSubclass ( functools . partial ) : pass class TestPartialSubclass ( TestPartial ) : thetype = PartialSubclass class TestPythonPartial ( TestPartial ) : thetype = PythonPartial test_pickle = test_setstate_refcount = None test_attributes = None class TestUpdateWrapper ( unittest . TestCase ) : def check_wrapper ( self , wrapper , wrapped , assigned = functools . WRAPPER_ASSIGNMENTS , updated = functools . WRAPPER_UPDATES ) : for name in assigned : self . assertTrue ( getattr ( wrapper , name ) is getattr ( wrapped , name ) ) for name in updated : wrapper_attr = getattr ( wrapper , name ) wrapped_attr = getattr ( wrapped , name ) for key in wrapped_attr : self . assertTrue ( wrapped_attr [ key ] is wrapper_attr [ key ] ) def _default_update ( self ) : def f ( ) : \"\"\"\"\"\" pass f . attr = '' def wrapper ( ) : pass functools . update_wrapper ( wrapper , f ) return wrapper , f def test_default_update ( self ) : wrapper , f = self . _default_update ( ) self . check_wrapper ( wrapper , f ) self . assertEqual ( wrapper . __name__ , '' ) self . assertEqual ( wrapper . attr , '' ) @ unittest . skipIf ( sys . flags . optimize >= , \"\" ) def test_default_update_doc ( self ) : wrapper , f = self . _default_update ( ) self . assertEqual ( wrapper . __doc__ , '' ) def test_no_update ( self ) : def f ( ) : \"\"\"\"\"\" pass f . attr = '' def wrapper ( ) : pass functools . update_wrapper ( wrapper , f , ( ) , ( ) ) self . check_wrapper ( wrapper , f , ( ) , ( ) ) self . assertEqual ( wrapper . __name__ , '' ) self . assertEqual ( wrapper . __doc__ , None ) self . assertFalse ( hasattr ( wrapper , '' ) ) def test_selective_update ( self ) : def f ( ) : pass f . attr = '' f . dict_attr = dict ( a = , b = , c = ) def wrapper ( ) : pass wrapper . dict_attr = { } assign = ( '' , ) update = ( '' , ) functools . update_wrapper ( wrapper , f , assign , update ) self . check_wrapper ( wrapper , f , assign , update ) ", "answer": "self . assertEqual ( wrapper . __name__ , '' )"}, {"prompt": " import pytest from modules . level import Level , highest_display_priority from modules . monsters import Cockroach from modules . item import Item @ pytest . fixture def level ( ) : contents = [ ] item = Item ( \"\" , \"\" ) ", "answer": "item . place ( ( , ) )"}, {"prompt": " import sys from game . settings import * from game import color as clr __author__ = '' class Piece ( object ) : \"\"\"\"\"\" def __init__ ( self , x , y , colour ) : self . x = x self . y = y self . state = '' self . flipped = False ", "answer": "self . colour = colour"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Static ( )"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " import yaml ", "answer": "import os . path"}, {"prompt": " import json from libsaas . services import base from libsaas import http from . import resource class Fullcontact ( base . Resource ) : def __init__ ( self , api_key ) : \"\"\"\"\"\" self . apiroot = '' self . api_key = api_key self . add_filter ( self . use_json ) self . add_filter ( self . add_api_key ) def get_url ( self ) : return self . apiroot def add_api_key ( self , request ) : request . params . update ( { '' : self . api_key } ) def use_json ( self , request ) : request . uri += '' @ base . resource ( resource . Person ) def person ( self , email = None , emailMD5 = None , phone = None , twitter = None , facebookUsername = None ) : \"\"\"\"\"\" kwargs = list ( filter ( None , [ email , emailMD5 , phone , twitter , facebookUsername , ] ) ) if len ( kwargs ) != : raise TypeError ( '' '' ) return resource . Person ( self , email = email , emailMD5 = emailMD5 , phone = phone , twitter = twitter , facebookUsername = facebookUsername ) @ base . resource ( resource . Enhanced ) def enhanced ( self , email ) : \"\"\"\"\"\" return resource . Enhanced ( self , email ) ", "answer": "@ base . resource ( resource . Name )"}, {"prompt": " from invoke import task , Collection @ task ( aliases = [ '' ] ) def top_level ( ) : ", "answer": "pass"}, {"prompt": " \"\"\"\"\"\" from pygments . style import Style from pygments . token import Keyword , Name , Comment , String , Error , Number , Operator , Generic , Whitespace , Punctuation , Other , Literal class ComplexityStyle ( Style ) : default_style = \"\" styles = { Whitespace : \"\" , Error : \"\" , Other : \"\" , Comment : \"\" , Comment . Preproc : \"\" , Keyword : \"\" , Keyword . Constant : \"\" , ", "answer": "Keyword . Declaration : \"\" ,"}, {"prompt": " from django import forms from django . utils . translation import ugettext_lazy from onadata . apps . viewer . models . data_dictionary import DataDictionary class QuickConverter ( forms . Form ) : xls_file = forms . FileField ( label = ugettext_lazy ( \"\" ) ) def publish ( self , user ) : if self . is_valid ( ) : return DataDictionary . objects . create ( ", "answer": "user = user ,"}, {"prompt": " import logging def get_logger ( LOGFILE ) : logger = logging . getLogger ( '' ) logger . setLevel ( logging . DEBUG ) fh = logging . FileHandler ( LOGFILE ) fh . setLevel ( logging . DEBUG ) ch = logging . StreamHandler ( ) ch . setLevel ( logging . DEBUG ) formatter = logging . Formatter ( '' ) fh . setFormatter ( formatter ) ch . setFormatter ( formatter ) logger . addHandler ( fh ) logger . addHandler ( ch ) return logger ", "answer": "logger = get_logger ( '' ) "}, {"prompt": " from os . path import exists , join import glob import json from pythonforandroid . logger import ( info , info_notify , warning , Err_Style , Err_Fore ) from pythonforandroid . util import current_directory class Distribution ( object ) : '''''' ctx = None name = None needs_build = False url = None dist_dir = None archs = [ ] '''''' recipes = [ ] description = '' def __init__ ( self , ctx ) : self . ctx = ctx def __str__ ( self ) : return '' . format ( self . name , '' . join ( self . recipes ) ) def __repr__ ( self ) : return str ( self ) @ classmethod def get_distribution ( cls , ctx , name = None , recipes = [ ] , allow_download = True , force_build = False , allow_build = True , extra_dist_dirs = [ ] , require_perfect_match = False ) : '''''' existing_dists = Distribution . get_distributions ( ctx ) needs_build = True possible_dists = existing_dists if name is not None and name : possible_dists = [ d for d in possible_dists if d . name == name ] _possible_dists = [ ] for dist in possible_dists : for recipe in recipes : if recipe not in dist . recipes : break else : _possible_dists . append ( dist ) possible_dists = _possible_dists if possible_dists : info ( '' '' ) pretty_log_dists ( possible_dists ) else : info ( '' ) for dist in possible_dists : if force_build : continue if ( set ( dist . recipes ) == set ( recipes ) or ( set ( recipes ) . issubset ( set ( dist . recipes ) ) and not require_perfect_match ) ) : info_notify ( '' . format ( dist . name ) ) return dist assert len ( possible_dists ) < if not name and possible_dists : info ( '' '' '' . format ( name , '' . join ( recipes ) , '' . join ( possible_dists [ ] . recipes ) ) ) info ( '' ) exit ( ) dist = Distribution ( ctx ) dist . needs_build = True if not name : filen = '' i = while exists ( join ( ctx . dist_dir , filen . format ( i ) ) ) : i += name = filen . format ( i ) dist . name = name dist . dist_dir = join ( ctx . dist_dir , dist . name ) dist . recipes = recipes return dist @ classmethod def get_distributions ( cls , ctx , extra_dist_dirs = [ ] ) : '''''' if extra_dist_dirs : warning ( '' '' ) exit ( ) dist_dir = ctx . dist_dir folders = glob . glob ( join ( dist_dir , '' ) ) for dir in extra_dist_dirs : folders . extend ( glob . glob ( join ( dir , '' ) ) ) dists = [ ] for folder in folders : if exists ( join ( folder , '' ) ) : with open ( join ( folder , '' ) ) as fileh : ", "answer": "dist_info = json . load ( fileh )"}, {"prompt": " \"\"\"\"\"\" from django . template import loader , RequestContext from django . http import HttpResponse , Http404 ", "answer": "from django . http import HttpResponseRedirect , HttpResponsePermanentRedirect"}, {"prompt": " import pickle from cStringIO import StringIO from test import test_support from test . pickletester import ( AbstractPickleTests , AbstractPickleModuleTests , AbstractPersistentPicklerTests , AbstractPicklerUnpicklerObjectTests , BigmemPickleTests ) class PickleTests ( AbstractPickleTests , AbstractPickleModuleTests ) : def dumps ( self , arg , proto = , fast = ) : return pickle . dumps ( arg , proto ) def loads ( self , buf ) : return pickle . loads ( buf ) module = pickle error = KeyError class PicklerTests ( AbstractPickleTests ) : ", "answer": "error = KeyError"}, {"prompt": " from django import forms from django . utils . translation import ugettext as _ from projector . core . exceptions import ProjectorError class BaseExternalForkForm ( forms . Form ) : \"\"\"\"\"\" help_text = '' as_private = forms . BooleanField ( initial = False , label = _ ( '' ) , help_text = _ ( '' ) , required = False ) def is_public ( self ) : if not hasattr ( self , '' ) : raise ProjectorError ( \"\" ) ", "answer": "return not self . cleaned_data [ '' ]"}, {"prompt": " from fuel_dev_tools import command from fuel_dev_tools import docker from fuel_dev_tools import info class DockerNailgunMixin ( docker . DockerMixin ) : container = '' default_command = '' def get_log_directory ( self ) : return '' class NailgunInfo ( DockerNailgunMixin , info . BasicInfo ) : @ classmethod def get_info ( cls ) : return ( '' '' '' '' ) class Id ( DockerNailgunMixin , docker . IdCommand ) : \"\"\"\"\"\" class Config ( DockerNailgunMixin , docker . ConfigCommand ) : \"\"\"\"\"\" class DBReset ( DockerNailgunMixin , command . BaseCommand ) : \"\"\"\"\"\" def take_action ( self , parsed_args ) : from fuel_dev_tools . docker import postgres reset_sql = \"\"\"\"\"\" p = postgres . Shell ( self . app , self . app_args ) cmd = [ '' , '' . format ( reset_sql ) , '' . format ( p . get_container_directory ( ) ) , ] p . ssh_command ( * cmd ) cmd = p . container_command ( '' , '' , '' ) p . ssh_command ( * cmd ) ", "answer": "cmd = p . container_command ("}, {"prompt": " \"\"\"\"\"\" import base64 import unittest from cafe . drivers . unittest . decorators import tags from cloudcafe . common . tools . datagen import rand_name from cloudcafe . compute . common . types import ComputeHypervisors , NovaServerStatusTypes from cloudcafe . compute . config import ComputeConfig from cloudroast . compute . fixtures import ServerFromImageFixture from cloudcafe . compute . servers_api . config import ServersConfig compute_config = ComputeConfig ( ) hypervisor = compute_config . hypervisor . lower ( ) @ unittest . skipIf ( hypervisor in [ ComputeHypervisors . LXC_LIBVIRT , ComputeHypervisors . IRONIC ] , '' ) class RebuildServerTests ( object ) : compute_config = ComputeConfig ( ) hypervisor = compute_config . hypervisor . lower ( ) servers_config = ServersConfig ( ) file_injection_enabled = servers_config . personality_file_injection_enabled @ tags ( type = '' , net = '' ) def test_verify_rebuild_server_response ( self ) : \"\"\"\"\"\" rebuilt_server = self . rebuilt_server_response . entity self . assertEqual ( rebuilt_server . name , self . name , msg = \"\" ) self . assertEqual ( rebuilt_server . image . id , self . image_ref_alt , msg = \"\" ) self . assertEqual ( rebuilt_server . flavor . id , self . flavor_ref , msg = \"\" ) self . assertEqual ( rebuilt_server . id , self . server . id , msg = \"\" ) self . assertEqual ( rebuilt_server . links . bookmark , self . server . links . bookmark , msg = \"\" ) self . assertEqual ( rebuilt_server . metadata . get ( '' ) , '' ) self . assertEqual ( rebuilt_server . created , self . server . created , msg = \"\" ) self . assertTrue ( rebuilt_server . updated != self . server . updated , msg = \"\" ) self . assertEquals ( rebuilt_server . addresses , self . server . addresses , msg = \"\" ) @ tags ( type = '' , net = '' ) def test_rebuilt_server_addresses ( self ) : \"\"\"\"\"\" rebuilt_server = self . rebuilt_server_response . entity addresses = rebuilt_server . addresses for name , ip_addresses in self . expected_networks . iteritems ( ) : network = addresses . get_by_name ( name ) if ip_addresses . get ( '' ) : self . assertIsNotNone ( network . ipv4 , msg = '' . format ( name = name ) ) else : self . assertIsNone ( network . ipv4 , msg = '' . format ( name = name ) ) if ip_addresses . get ( '' ) : self . assertIsNotNone ( network . ipv6 , msg = '' . format ( name = name ) ) else : self . assertIsNone ( network . ipv6 , msg = '' . format ( name = name ) ) @ tags ( type = '' , net = '' ) def test_address_not_changed_on_rebuild ( self ) : \"\"\"\"\"\" rebuilt_server = self . rebuilt_server_response . entity addresses = rebuilt_server . addresses self . assertEqual ( addresses , self . server . addresses ) @ tags ( type = '' , net = '' ) def test_can_log_into_server_after_rebuild ( self ) : \"\"\"\"\"\" remote_instance = self . server_behaviors . get_remote_instance_client ( self . server , config = self . servers_config , password = self . password , key = self . key . private_key ) self . assertTrue ( remote_instance . can_authenticate ( ) ) @ tags ( type = '' , net = '' ) def test_rebuilt_server_vcpus ( self ) : \"\"\"\"\"\" remote_client = self . server_behaviors . get_remote_instance_client ( ", "answer": "self . server , config = self . servers_config , password = self . password ,"}, {"prompt": " import unittest from flask import current_app from flask . ext . testing import TestCase from project import app class TestTestingConfig ( TestCase ) : def create_app ( self ) : app . config . from_object ( '' ) return app def test_app_is_testing ( self ) : self . assertTrue ( current_app . config [ '' ] ) self . assertTrue ( app . config [ '' ] is True ) self . assertTrue ( app . config [ '' ] == ) self . assertTrue ( app . config [ '' ] is False ) def test_app_exists ( self ) : self . assertFalse ( current_app is None ) ", "answer": "if __name__ == '' :"}, {"prompt": " import numpy as np from layers import * from fast_layers import * conv_forward = conv_forward_fast conv_backward = conv_backward_fast avg_pool_forward = avg_pool_forward_fast avg_pool_backward = avg_pool_backward_fast max_pool_forward = max_pool_forward_fast max_pool_backward = max_pool_backward_fast def spatial_reflection_padding ( array , pad_width , pad_type = '' ) : '''''' return np . pad ( array , pad_width , '' , pad_type ) def spatial_replication_padding ( array , pad_width ) : '''''' return np . pad ( array , pad_width , '' ) def skip_forward ( x , n_out_channels ) : '''''' N , n_in_channels , H , W = x . shape assert ( n_in_channels == n_out_channels ) or ( n_out_channels == n_in_channels * ) , '' skip = np . array ( x , copy = True ) pool_cache , downsampled , skip_p = None , False , if n_out_channels > n_in_channels : pool_param = { '' : , '' : , '' : } skip , pool_cache = avg_pool_forward ( skip , pool_param ) p = skip_p = ( n_in_channels ) / skip = np . pad ( skip , ( ( , ) , ( p , p ) , ( , ) , ( , ) ) , mode = '' ) downsampled = True return skip , ( pool_cache , downsampled , skip_p ) def skip_backward ( dout , cache ) : '''''' pool_cache , downsampled , skip_p = cache dskip = np . array ( dout , copy = True ) if downsampled : dskip = dskip [ : , skip_p : - skip_p , : , : ] dskip = avg_pool_backward ( dskip , pool_cache ) return dskip def affine_relu_forward ( x , w , b ) : '''''' a , fc_cache = affine_forward ( x , w , b ) out , relu_cache = relu_forward ( a ) cache = ( fc_cache , relu_cache ) return out , cache def affine_relu_backward ( dout , cache ) : '''''' fc_cache , relu_cache = cache da = relu_backward ( dout , relu_cache ) dx , dw , db = affine_backward ( da , fc_cache ) return dx , dw , db def affine_bn_relu_forward ( x , w , b , gamma , beta , bn_param ) : '''''' h , h_cache = affine_forward ( x , w , b ) hnorm , hnorm_cache = batchnorm_forward ( h , gamma , beta , bn_param ) hnormrelu , relu_cache = relu_forward ( hnorm ) cache = ( h_cache , hnorm_cache , relu_cache ) return hnormrelu , cache def affine_bn_relu_backward ( dout , cache ) : '''''' h_cache , hnorm_cache , relu_cache = cache dhnormrelu = relu_backward ( dout , relu_cache ) dhnorm , dgamma , dbeta = batchnorm_backward ( dhnormrelu , hnorm_cache ) dx , dw , db = affine_backward ( dhnorm , h_cache ) return dx , dw , db , dgamma , dbeta def conv_relu_forward ( x , w , b , conv_param ) : '''''' a , conv_cache = conv_forward_fast ( x , w , b , conv_param ) out , relu_cache = relu_forward ( a ) cache = ( conv_cache , relu_cache ) return out , cache def conv_relu_backward ( dout , cache ) : '''''' conv_cache , relu_cache = cache da = relu_backward ( dout , relu_cache ) dx , dw , db = conv_backward_fast ( da , conv_cache ) return dx , dw , db def conv_relu_pool_forward ( x , w , b , conv_param , pool_param ) : '''''' a , conv_cache = conv_forward_fast ( x , w , b , conv_param ) s , relu_cache = relu_forward ( a ) out , pool_cache = max_pool_forward ( s , pool_param ) cache = ( conv_cache , relu_cache , pool_cache ) return out , cache def conv_relu_pool_backward ( dout , cache ) : '''''' conv_cache , relu_cache , pool_cache = cache ds = max_pool_backward ( dout , pool_cache ) da = relu_backward ( ds , relu_cache ) dx , dw , db = conv_backward_fast ( da , conv_cache ) return dx , dw , db def conv_bn_relu_forward ( x , w , b , conv_param , gamma , beta , bn_param ) : '''''' out , conv_cache = conv_forward_fast ( x , w , b , conv_param ) out , batchnorm_cache = spatial_batchnorm_forward ( out , gamma , beta , bn_param ) ", "answer": "out , relu_cache = relu_forward ( out )"}, {"prompt": " from djangoplugins . point import PluginMount class BeforeStoragePluginPoint ( object ) : __metaclass__ = PluginMount settings_field_name = '' class DatabaseStoragePluginPoint ( object ) : ", "answer": "__metaclass__ = PluginMount"}, {"prompt": " from botocore . model import DenormalizedStructureBuilder from boto3 . resources . model import ResourceModel , Action , Collection , Waiter from tests import BaseTestCase class TestModels ( BaseTestCase ) : def test_resource_name ( self ) : model = ResourceModel ( '' , { } , { } ) self . assertEqual ( model . name , '' ) def test_resource_shape ( self ) : model = ResourceModel ( '' , { '' : '' } , { } ) self . assertEqual ( model . shape , '' ) def test_resource_identifiers ( self ) : model = ResourceModel ( '' , { '' : [ { '' : '' } , { '' : '' , '' : '' } ] } , { } ) self . assertEqual ( model . identifiers [ ] . name , '' ) self . assertEqual ( model . identifiers [ ] . name , '' ) self . assertEqual ( model . identifiers [ ] . member_name , '' ) def test_resource_action_raw ( self ) : model = ResourceModel ( '' , { '' : { '' : { '' : { '' : '' , '' : [ { '' : '' , '' : '' , '' : '' } ] } , '' : '' } } } , { } ) self . assertIsInstance ( model . actions , list ) self . assertEqual ( len ( model . actions ) , ) action = model . actions [ ] self . assertIsInstance ( action , Action ) self . assertEqual ( action . request . operation , '' ) self . assertIsInstance ( action . request . params , list ) self . assertEqual ( len ( action . request . params ) , ) self . assertEqual ( action . request . params [ ] . target , '' ) self . assertEqual ( action . request . params [ ] . source , '' ) self . assertEqual ( action . request . params [ ] . name , '' ) self . assertEqual ( action . path , '' ) def test_resource_action_response_resource ( self ) : model = ResourceModel ( '' , { '' : { '' : { '' : { '' : '' , '' : '' } } } } , { '' : { } } ) action = model . actions [ ] self . assertEqual ( action . resource . type , '' ) self . assertEqual ( action . resource . path , '' ) self . assertIsInstance ( action . resource . model , ResourceModel ) self . assertEqual ( action . resource . model . name , '' ) def test_resource_load_action ( self ) : model = ResourceModel ( '' , { '' : { '' : { '' : '' } , '' : '' } } , { } ) self . assertIsInstance ( model . load , Action ) self . assertEqual ( model . load . request . operation , '' ) self . assertEqual ( model . load . path , '' ) def test_resource_batch_action ( self ) : model = ResourceModel ( '' , { '' : { '' : { '' : { '' : '' , '' : [ { '' : '' , '' : '' , '' : '' } ] } } } } , { } ) self . assertIsInstance ( model . batch_actions , list ) action = model . batch_actions [ ] self . assertIsInstance ( action , Action ) self . assertEqual ( action . request . operation , '' ) self . assertEqual ( action . request . params [ ] . target , '' ) def test_sub_resources ( self ) : model = ResourceModel ( '' , { '' : { '' : { '' : { '' : '' , '' : [ { '' : '' , '' : '' } ] } } , '' : { '' : { '' : '' , '' : [ { '' : '' , '' : '' } ] } } } } , { '' : { } } ) self . assertIsInstance ( model . subresources , list ) self . assertEqual ( len ( model . subresources ) , ) action = model . subresources [ ] resource = action . resource self . assertIn ( action . name , [ '' , '' ] ) self . assertEqual ( resource . identifiers [ ] . target , '' ) self . assertEqual ( resource . identifiers [ ] . source , '' ) self . assertEqual ( resource . type , '' ) def test_resource_references ( self ) : model_def = { '' : { '' : { '' : { '' : '' , '' : [ { '' : '' , '' : '' , '' : '' } ] } } } } resource_defs = { '' : { } } model = ResourceModel ( '' , model_def , resource_defs ) self . assertIsInstance ( model . references , list ) self . assertEqual ( len ( model . references ) , ) ref = model . references [ ] self . assertEqual ( ref . name , '' ) self . assertEqual ( ref . resource . type , '' ) self . assertEqual ( ref . resource . identifiers [ ] . target , '' ) self . assertEqual ( ref . resource . identifiers [ ] . source , '' ) self . assertEqual ( ref . resource . identifiers [ ] . path , '' ) def test_resource_collections ( self ) : model = ResourceModel ( '' , { '' : { '' : { '' : { '' : '' } , '' : { '' : '' , '' : '' } } } } , { '' : { } } ) self . assertIsInstance ( model . collections , list ) self . assertEqual ( len ( model . collections ) , ) self . assertIsInstance ( model . collections [ ] , Collection ) self . assertEqual ( model . collections [ ] . request . operation , '' ) self . assertEqual ( model . collections [ ] . resource . type , '' ) self . assertEqual ( model . collections [ ] . resource . model . name , '' ) self . assertEqual ( model . collections [ ] . resource . path , '' ) def test_waiter ( self ) : model = ResourceModel ( '' , { '' : { '' : { '' : '' , '' : [ { '' : '' , '' : '' , '' : '' } ] } } } , { } ) self . assertIsInstance ( model . waiters , list ) waiter = model . waiters [ ] self . assertIsInstance ( waiter , Waiter ) self . assertEqual ( waiter . name , '' ) self . assertEqual ( waiter . waiter_name , '' ) self . assertEqual ( waiter . params [ ] . target , '' ) class TestRenaming ( BaseTestCase ) : def test_multiple ( self ) : model = ResourceModel ( '' , { '' : [ { '' : '' } ] , '' : { '' : { } } , '' : { '' : { '' : { '' : '' , '' : [ { '' : '' , '' : '' , '' : '' } ] } } } , '' : { '' : { } } , '' : { '' : { } } } , { '' : { } } ) shape = DenormalizedStructureBuilder ( ) . with_members ( { '' : { '' : '' , } , '' : { '' : '' } } ) . build_model ( ) model . load_rename_map ( shape ) self . assertEqual ( model . identifiers [ ] . name , '' ) self . assertEqual ( model . actions [ ] . name , '' ) self . assertEqual ( model . references [ ] . name , '' ) self . assertEqual ( model . collections [ ] . name , '' ) self . assertEqual ( model . waiters [ ] . name , '' ) self . assertNotIn ( '' , model . get_attributes ( shape ) ) self . assertIn ( '' , model . get_attributes ( shape ) ) def test_meta_beats_identifier ( self ) : model = ResourceModel ( '' , { '' : [ { '' : '' } ] } , { } ) model . load_rename_map ( ) self . assertEqual ( model . identifiers [ ] . name , '' ) def test_load_beats_identifier ( self ) : model = ResourceModel ( '' , { '' : [ { '' : '' } ] , '' : { '' : { '' : '' } } } , { } ) model . load_rename_map ( ) self . assertTrue ( model . load ) self . assertEqual ( model . identifiers [ ] . name , '' ) def test_identifier_beats_action ( self ) : model = ResourceModel ( '' , { '' : [ { '' : '' } ] , '' : { '' : { '' : { '' : '' } } } } , { } ) model . load_rename_map ( ) self . assertEqual ( model . identifiers [ ] . name , '' ) self . assertEqual ( model . actions [ ] . name , '' ) def test_action_beats_reference ( self ) : model = ResourceModel ( '' , { '' : { '' : { '' : { '' : '' } } } , '' : { '' : { '' : { '' : '' , '' : [ { '' : '' , '' : '' , '' : '' } ] } } } } , { '' : { } } ) ", "answer": "model . load_rename_map ( )"}, {"prompt": " \"\"\"\"\"\" import os import tempfile import unittest from ganeti import constants from ganeti import uidpool ", "answer": "from ganeti import errors"}, {"prompt": " from django import template register = template . Library ( ) @ register . inclusion_tag ( '' ) def unsubscribe_instructions ( watch ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" import numpy as np ", "answer": "import scipy as sp"}, {"prompt": " class node : pass class DequeDict ( object ) : \"\"\"\"\"\" def __init__ ( self , i = [ ] ) : self . l = node ( ) self . l . next = self . l self . l . prev = self . l self . l . key = None self . l . value = None self . d = { } if i : self . extend ( i ) def extend ( self , l ) : \"\"\"\"\"\" for key , value in l : self . append ( key , value ) def append ( self , key , value ) : \"\"\"\"\"\" n = node ( ) n . key = key n . value = value self . l . prev . next = n n . prev = self . l . prev n . next = self . l self . l . prev = n self . d [ key ] = n def appendleft ( self , key , value ) : \"\"\"\"\"\" n = node ( ) n . key = key n . value = value self . l . next . prev = n n . next = self . l . next n . prev = self . l self . l . next = n self . d [ key ] = n def pop ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from sellmo . core import chaining from sellmo . apps . customer . routines import customer_from_request from sellmo . apps . customer . models import Contactable , Customer from . routines import completed_order_from_request @ chaining . link ( customer_from_request , takes_result = True ) def _customer_from_request ( customer , request , ** kwargs ) : order = completed_order_from_request ( request ) ", "answer": "if order is not None :"}, {"prompt": " \"\"\"\"\"\" import logging __version__ = '' logging . addLevelName ( , \"\" ) logging . addLevelName ( , \"\" ) try : _ ( '' ) except NameError : import gettext ", "answer": "gettext . NullTranslations ( ) . install ( ) "}, {"prompt": " \"\"\"\"\"\" ", "answer": "_init_admin_code = '''''' "}, {"prompt": " \"\"\"\"\"\" revision = '' down_revision = '' from alembic import op import sqlalchemy as sa def upgrade ( active_plugins = None , options = None ) : op . create_table ( '' , sa . Column ( '' , sa . String ( length = ) , nullable = False ) , sa . Column ( '' , sa . String ( length = ) , nullable = False ) , sa . ForeignKeyConstraint ( [ '' ] , [ '' ] ) , sa . ForeignKeyConstraint ( [ '' ] , ", "answer": "[ '' ] ,"}, {"prompt": " \"\"\"\"\"\" from nose . tools import assert_equal , assert_raises , assert_not_equal import io import tempfile import os import networkx as nx from networkx . testing import ( assert_edges_equal , assert_nodes_equal , assert_graphs_equal ) class TestEdgelist : def setUp ( self ) : self . G = nx . Graph ( name = \"\" ) e = [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] self . G . add_edges_from ( e ) self . G . add_node ( '' ) ", "answer": "self . DG = nx . DiGraph ( self . G )"}, {"prompt": " try : from sys import version_info except ImportError : version_info = ( , ) from operator import getslice from types import SliceType from string import join from pyasn1 import error tagClassUniversal = tagClassApplication = tagClassContext = tagClassPrivate = tagFormatSimple = tagFormatConstructed = tagCategoryImplicit = tagCategoryExplicit = tagCategoryUntagged = class Tag : def __init__ ( self , tagClass , tagFormat , tagId ) : if tagId < : raise error . PyAsn1Error ( '' % tagId ) self . __tag = ( tagClass , tagFormat , tagId ) self . __uniqTag = ( tagClass , tagId ) self . __hashedUniqTag = hash ( self . __uniqTag ) def __repr__ ( self ) : return '' % ( ( self . __class__ . __name__ , ) + self . __tag ) def __cmp__ ( self , other ) : return cmp ( self . __uniqTag , other ) def __eq__ ( self , other ) : return self is other or self . __hashedUniqTag == other def __ne__ ( self , other ) : return not ( self is other ) and self . __hashedUniqTag != other def __hash__ ( self ) : return self . __hashedUniqTag def __getitem__ ( self , idx ) : return self . __tag [ idx ] def __and__ ( self , ( tagClass , tagFormat , tagId ) ) : return self . __class__ ( self . __tag & tagClass , self . __tag & tagFormat , self . __tag & tagId ) def __or__ ( self , ( tagClass , tagFormat , tagId ) ) : return self . __class__ ( self . __tag [ ] | tagClass , self . __tag [ ] | tagFormat , self . __tag [ ] | tagId ) class TagSet : def __init__ ( self , baseTag = ( ) , * superTags ) : ", "answer": "self . __baseTag = baseTag"}, {"prompt": " from setuptools import setup , find_packages setup ( name = '' , version = '' , description = '' , author = '' , author_email = '' , url = '' , packages = find_packages ( exclude = [ '' ] ) , scripts = [ '' ] , data_files = [ ( '' , [ '' ] ) ] , ", "answer": "install_requires = [ '' ] ,"}, {"prompt": " '''''' import unittest ", "answer": "from nose . plugins . attrib import attr"}, {"prompt": " from django . http import HttpResponseRedirect from neurovault . apps . statmaps . utils import HttpRedirectException ", "answer": "class CollectionRedirectMiddleware :"}, {"prompt": " from . . excel_comparsion_test import ExcelComparisonTest from ... workbook import Workbook class TestCompareXLSXFiles ( ExcelComparisonTest ) : \"\"\"\"\"\" def setUp ( self ) : ", "answer": "self . maxDiff = None"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import abc import os import logging from . utils import print_info import six try : from dateutil . parser import parse as dtparse except ImportError : print_info ( \"\"\"\"\"\" ) from datetime import datetime def dtparse ( dtstring ) : \"\"\"\"\"\" return datetime . strptime ( dtstring , '' ) try : import simplejson as json except ImportError : import json try : import yaml except ImportError : def load ( self , filename ) : raise Exception ( \"\" . format ( filename ) ) yaml = type ( '' , ( object , ) , { '' : load } ) ( ) log = logging . getLogger ( __name__ ) class FixtureLoader ( six . with_metaclass ( abc . ABCMeta , object ) ) : @ abc . abstractmethod def load ( self ) : pass class JSONLoader ( FixtureLoader ) : extensions = ( '' , '' ) def load ( self , filename ) : def _datetime_parser ( dct ) : ", "answer": "for key , value in list ( dct . items ( ) ) :"}, {"prompt": " \"\"\"\"\"\" from django . core . urlresolvers import reverse from django import forms from django . core . mail import send_mail from django . conf import settings from django . http import HttpResponseRedirect import logging STATUS_UPDATES = False def create_user ( username , password , name = None ) : from helios_auth . models import User user = User . get_by_type_and_id ( '' , username ) if user : raise Exception ( '' ) info = { '' : password , '' : name } user = User . update_or_create ( user_type = '' , user_id = username , info = info ) user . save ( ) class LoginForm ( forms . Form ) : username = forms . CharField ( max_length = ) password = forms . CharField ( widget = forms . PasswordInput ( ) , max_length = ) def password_check ( user , password ) : return ( user and user . info [ '' ] == password ) def password_login_view ( request ) : from helios_auth . view_utils import render_template from helios_auth . views import after from helios_auth . models import User error = None if request . method == \"\" : form = LoginForm ( ) else : form = LoginForm ( request . POST ) request . session [ '' ] = '' if request . POST . has_key ( '' ) : request . session [ '' ] = request . POST . get ( '' ) if form . is_valid ( ) : username = form . cleaned_data [ '' ] . strip ( ) password = form . cleaned_data [ '' ] . strip ( ) try : user = User . get_by_type_and_id ( '' , username ) if password_check ( user , password ) : request . session [ '' ] = user . user_id return HttpResponseRedirect ( reverse ( after ) ) except User . DoesNotExist : pass error = '' return render_template ( request , '' , { '' : form , '' : error } ) def password_forgotten_view ( request ) : \"\"\"\"\"\" from helios_auth . view_utils import render_template from helios_auth . models import User if request . method == \"\" : ", "answer": "return render_template ( request , '' , { '' : request . GET . get ( '' , '' ) } )"}, {"prompt": " import unittest import redisco from distutils . version import LooseVersion as Version class ConnectionTestCase ( unittest . TestCase ) : def test_redis_version ( self ) : ", "answer": "self . assertTrue ( Version ( redisco . redis . __version__ ) >= '' )"}, {"prompt": " '''''' LOGGING_LEVELS = [ ( \"\" , ) , ( \"\" , ) , ] ", "answer": "'''''' "}, {"prompt": " from __future__ import absolute_import , unicode_literals from django . conf import settings from dbaas import features import logging LOG = logging . getLogger ( __name__ ) def get_ldap_connection ( ) : import ldap server = settings . AUTH_LDAP_SERVER_URI user_pw = settings . AUTH_LDAP_BIND_PASSWORD dn = settings . AUTH_LDAP_BIND_DN conn = None LOG . debug ( \"\" ) conn = ldap . initialize ( server ) conn . bind_s ( dn , user_pw ) LOG . debug ( \"\" ) return conn def find_ldap_groups_from_user ( username = None ) : groups = [ ] if features . LDAP_ENABLED and username : import ldap user_search = settings . AUTH_LDAP_USER_SEARCH_STR group_search = settings . AUTH_LDAP_GROUP_SEARCH_STR LOG . debug ( \"\" % group_search ) LOG . debug ( \"\" % username ) try : conn = get_ldap_connection ( ) group_result = conn . search_s ( group_search , ldap . SCOPE_SUBTREE , \"\" % username , None ) for entry in group_result : group_name = entry [ ] . split ( '' ) [ ] . split ( '' ) [ ] . strip ( ) if group_name != username : groups . append ( \"\" + group_name ) except Exception , e : LOG . error ( \"\" % e ) ", "answer": "finally :"}, {"prompt": " \"\"\"\"\"\" import os import re import sys import json import locale import zipfile import logging import textwrap import validictory from . sharedtypes import JSONEncoder from ilorest . rest . v1_helper import ( RisObject ) LOGGER = logging . getLogger ( __name__ ) class ValidationError ( Exception ) : \"\"\"\"\"\" pass class SchemaValidationError ( ValidationError ) : \"\"\"\"\"\" pass class RegistryValidationError ( ValidationError ) : \"\"\"\"\"\" def __init__ ( self , msg , regentry = None , selector = None ) : super ( RegistryValidationError , self ) . __init__ ( msg ) self . reg = regentry self . sel = selector class UnknownValidatorError ( Exception ) : \"\"\"\"\"\" \"\"\"\"\"\" class ValidationManager ( object ) : \"\"\"\"\"\" \"\"\"\"\"\" def __init__ ( self , local_path , bios_local_path , romfamily = None , biosversion = None , iloversion = None , monolith = None ) : super ( ValidationManager , self ) . __init__ ( ) defaultilopath = None defaultbiospath = None schemamainfolder = None if float ( iloversion ) < : if os . name == '' : defaultilopath = r\"\" defaultbiospath = r\"\" schemamainfolder = os . path . dirname ( sys . executable ) else : defaultilopath = \"\" defaultbiospath = \"\" schemamainfolder = \"\" if not local_path : if not os . path . isdir ( defaultilopath ) : ilozip = self . getiloziplocation ( schemamainfolder , iloversion ) if ilozip and os . path . exists ( ilozip ) : with zipfile . ZipFile ( os . path . join ( schemamainfolder , ilozip ) , \"\" ) as zfile : zfile . extractall ( os . path . join ( schemamainfolder , \"\" ) ) local_path = os . path . join ( schemamainfolder , u'' ) else : raise SchemaValidationError ( u'' '' '' '' ) else : local_path = defaultilopath else : if not os . path . isdir ( local_path ) : raise SchemaValidationError ( u\"\" \"\" % local_path ) if not bios_local_path : if not os . path . isdir ( defaultbiospath ) : bioszip = self . getbiosziplocation ( romfamily , schemamainfolder , biosversion ) if bioszip and os . path . exists ( bioszip ) : with zipfile . ZipFile ( os . path . join ( schemamainfolder , bioszip ) , \"\" ) as zfile : zfile . extractall ( os . path . join ( schemamainfolder , \"\" ) ) bios_local_path = os . path . join ( schemamainfolder , u'' ) else : raise SchemaValidationError ( u'' '' '' '' ) else : bios_local_path = defaultbiospath else : if not os . path . isdir ( bios_local_path ) : raise SchemaValidationError ( u\"\" \"\" % bios_local_path ) else : if monolith . is_redfish : local_path = \"\" bios_local_path = \"\" else : local_path = \"\" bios_local_path = \"\" self . _schema_locations = list ( ) self . _classes = list ( ) self . _registry_locations = list ( ) self . _classes_registry = list ( ) self . _bios_schema_locations = list ( ) self . _bios_classes = list ( ) self . _bios_registry_locations = list ( ) self . _bios_classes_registry = list ( ) self . _ilo_messages = list ( ) self . _base_messages = list ( ) self . _hpcommon_messages = list ( ) self . _iloevents_messages = list ( ) self . _errors = list ( ) if monolith . is_redfish : self . _schemaid = [ \"\" , \"\" ] self . _regid = [ \"\" , \"\" ] else : self . _schemaid = [ \"\" , \"\" ] self . _regid = [ \"\" , \"\" ] if local_path : self . add_location ( schema_path = local_path , monolith = monolith ) self . add_location ( registry_path = local_path , monolith = monolith ) if bios_local_path : self . add_location ( schema_path = bios_local_path , biossection = True , monolith = monolith ) self . add_location ( registry_path = bios_local_path , biossection = True , monolith = monolith ) def getbiosziplocation ( self , romfamily , schemadir , biosversion ) : \"\"\"\"\"\" foundfile = None currentver = None tempstr = \"\" + romfamily + \"\" + biosversion for _ , _ , filenames in os . walk ( schemadir ) : for filename in filenames : if tempstr in filename : regentry = re . compile ( '' % tempstr ) mentry = regentry . search ( filename ) if mentry and currentver : if currentver < mentry . group ( ) : foundfile = filename currentver = mentry . group ( ) elif mentry and not currentver : foundfile = filename currentver = mentry . group ( ) if foundfile : return os . path . join ( schemadir , foundfile ) else : return None def getiloziplocation ( self , schemadir , iloversion ) : \"\"\"\"\"\" if float ( iloversion ) < : iloversion = u'' tempstr = \"\" + iloversion . replace ( \"\" , \"\" ) for _ , _ , filenames in os . walk ( schemadir ) : for filename in filenames : if tempstr in filename : return os . path . join ( schemadir , filename ) return None def add_location ( self , schema_path = None , registry_path = None , biossection = False , monolith = None ) : \"\"\"\"\"\" \"\"\"\"\"\" if schema_path : if not biossection : self . _schema_locations . append ( schema_path ) self . _update_location_map ( monolith = monolith ) else : self . _bios_schema_locations . append ( schema_path ) self . _update_location_map ( biossection = True , monolith = monolith ) elif registry_path : if not biossection : self . _registry_locations . append ( registry_path ) self . _update_location_map ( registries = True , monolith = monolith ) else : self . _bios_registry_locations . append ( registry_path ) self . _update_location_map ( biossection = True , registries = True , monolith = monolith ) else : raise ValueError ( u\"\" \"\" ) def _update_location_map ( self , biossection = False , registries = False , monolith = None ) : \"\"\"\"\"\" locationslist = list ( ) pathjoinstr = None if not registries : pathjoinstr = \"\" if not biossection : locationslist = self . _schema_locations else : locationslist = self . _bios_schema_locations else : pathjoinstr = \"\" if not biossection : locationslist = self . _registry_locations else : locationslist = self . _bios_registry_locations for location in locationslist : if monolith : self . new_load_file ( monolith , root = location , biossection = biossection , registries = registries ) elif self . _is_local ( location ) : for root , _ , filenames in os . walk ( os . path . join ( location , pathjoinstr ) ) : for filename in filenames : fqpath = os . path . abspath ( os . path . join ( os . path . normpath ( root ) , filename ) ) if self . load_file ( fqpath , root = location , biossection = biossection , registries = registries ) : LOGGER . info ( \"\" , fqpath ) def new_load_file ( self , monolith , root = None , biossection = False , registries = False ) : \"\"\"\"\"\" classesdataholder = [ ] for itemtype in monolith . types : if itemtype . startswith ( \"\" ) or itemtype . startswith ( \"\" ) and u'' in monolith . types [ itemtype ] : for instance in monolith . types [ itemtype ] [ u'' ] : if self . _schemaid [ ] in instance . resp . request . path . lower ( ) or self . _regid [ ] in instance . resp . request . path . lower ( ) : if not registries and self . _schemaid [ ] in instance . resp . request . path . lower ( ) : if classesdataholder : if self . _schemaid [ ] in instance . resp . dict : classesdataholder [ ] [ self . _schemaid [ ] ] . extend ( instance . resp . dict [ self . _schemaid [ ] ] ) else : classesdataholder . append ( instance . resp . dict ) elif registries and self . _regid [ ] in instance . resp . request . path . lower ( ) : if classesdataholder : if monolith . is_redfish : classesdataholder [ ] [ self . _regid [ ] ] . extend ( instance . resp . dict [ self . _regid [ ] ] ) else : classesdataholder . append ( instance . resp . dict ) if classesdataholder : classesdataholder = classesdataholder [ ] try : if monolith . _typestring in classesdataholder and ( '' in classesdataholder [ monolith . _typestring ] or ( '' in classesdataholder [ monolith . _typestring ] and monolith . is_redfish ) ) : newclass = Classes . parse ( classesdataholder ) newclass . set_root ( root ) if not registries : if not biossection : self . _classes . append ( newclass ) else : self . _bios_classes . append ( newclass ) else : if not biossection : self . _classes_registry . append ( newclass ) else : self . _bios_classes_registry . append ( newclass ) except BaseException : pass else : pass def load_file ( self , filepath , root = None , biossection = False , registries = False , datareturn = False ) : \"\"\"\"\"\" result = False if os . path . isfile ( filepath ) : try : filehand = open ( filepath , '' ) data = json . load ( filehand ) if datareturn : return data if u'' in data and data [ u'' ] == '' : if biossection and registries : itemsreturn = self . bios_helper_function ( data , root ) data [ \"\" ] = itemsreturn newclass = Classes . parse ( data ) newclass . set_root ( root ) if not registries : if not biossection : self . _classes . append ( newclass ) else : self . _bios_classes . append ( newclass ) else : if not biossection : self . _classes_registry . append ( newclass ) else : self . _bios_classes_registry . append ( newclass ) result = True except BaseException : pass else : pass finally : filehand . close ( ) return result def bios_helper_function ( self , data , root ) : \"\"\"\"\"\" folderentries = data [ \"\" ] datareturn = list ( ) for entry in folderentries [ \"\" ] : joinstr = entry [ \"\" ] if os . name == '' and joinstr [ ] == \"\" : joinstr = joinstr . replace ( \"\" , \"\" ) [ : ] elif joinstr [ ] == \"\" : joinstr = joinstr [ : ] for root , _ , filenames in os . walk ( os . path . join ( root , joinstr ) ) : for filename in filenames : fqpath = os . path . abspath ( os . path . join ( os . path . normpath ( root ) , filename ) ) datareturn . append ( self . load_file ( fqpath , root = root , biossection = True , registries = True , datareturn = True ) ) LOGGER . info ( \"\" , fqpath ) return datareturn def validate ( self , item , selector = None , currdict = None , monolith = None , newarg = None , checkall = False , regloc = None ) : \"\"\"\"\"\" \"\"\"\"\"\" if regloc : attrreg = RepoRegistryEntry ( regloc ) else : attrreg = self . find_schema ( schname = item [ monolith . _typestring ] ) if attrreg : tempvalue = attrreg . validate ( item , self . _errors , selector = selector , currdict = currdict , monolith = monolith , newarg = newarg , checkall = checkall ) if tempvalue is True : return False elif tempvalue : self . _errors = tempvalue return True def bios_validate ( self , item , regname , selector = None , currdict = None , checkall = False , monolith = None ) : \"\"\"\"\"\" \"\"\"\"\"\" attrreg = self . find_bios_registry ( regname = regname ) if attrreg : tempvalue = attrreg . validate_bios_version ( item , self . _errors , selector = selector , currdict = currdict , checkall = checkall , monolith = monolith ) if tempvalue == '' : return tempvalue elif tempvalue == '' : return tempvalue elif tempvalue : self . _errors = tempvalue return True def bios_info ( self , item , regname , selector ) : \"\"\"\"\"\" \"\"\"\"\"\" attrreg = self . find_bios_registry ( regname = regname ) if attrreg : if attrreg . validate_bios_version ( item , self . _errors , selector = selector ) : return False return True def find_schema ( self , schname ) : \"\"\"\"\"\" \"\"\"\"\"\" for cls in self . _classes : found = cls . find_schema ( schname = schname ) if found : return found return None def find_registry ( self , regname ) : \"\"\"\"\"\" \"\"\"\"\"\" for cls in self . _classes_registry : found = cls . find_registry ( regname = regname ) if found : return found return None def find_bios_registry ( self , regname ) : \"\"\"\"\"\" \"\"\"\"\"\" for cls in self . _bios_classes_registry : found = cls . find_bios_registry ( regname = regname ) if found : return found return None def get_errors ( self ) : \"\"\"\"\"\" return self . _errors def _is_local ( self , path ) : \"\"\"\"\"\" if u'' in path : return False return True class Classes ( RisObject ) : \"\"\"\"\"\" def __init__ ( self , item ) : super ( Classes , self ) . __init__ ( item ) self . _root = None def set_root ( self , newroot ) : \"\"\"\"\"\" self . _root = newroot def find_schema ( self , schname ) : \"\"\"\"\"\" result = None if hasattr ( self , '' ) and isinstance ( self . Items , list ) : for entry in self . Items : if entry and u'' in entry and entry [ u'' ] . lower ( ) == schname . lower ( ) : regentry = RepoRegistryEntry . parse ( entry ) regentry . set_root ( self . _root ) result = regentry break elif hasattr ( self , '' ) and isinstance ( self . Members , list ) : schname = schname . split ( '' ) [ - ] for entry in self . Members : schlink = entry [ u'' ] . split ( '' ) schlink = schlink [ len ( schlink ) - ] if schname . lower ( ) == schlink . lower ( ) : result = entry break return result def find_registry ( self , regname ) : \"\"\"\"\"\" result = None if hasattr ( self , '' ) and isinstance ( self . Items , list ) : for entry in self . Items : if entry and ( u'' in entry and entry [ u'' ] . lower ( ) . startswith ( regname . lower ( ) ) ) : regentry = RepoRegistryEntry . parse ( entry ) regentry . set_root ( self . _root ) result = regentry break elif hasattr ( self , '' ) and isinstance ( self . Members , list ) : regname = regname . split ( '' ) [ - ] for entry in self . Members : reglink = entry [ u'' ] . split ( '' ) reglink = reglink [ len ( reglink ) - ] if regname . lower ( ) == reglink . lower ( ) : result = entry break return result def find_bios_schema ( self , schname ) : \"\"\"\"\"\" result = None if hasattr ( self , '' ) and isinstance ( self . Items , list ) : for entry in self . Items : if ( u'' in entry and entry [ u'' ] . lower ( ) == schname . lower ( ) ) : regentry = RepoRegistryEntry . parse ( entry ) regentry . set_root ( self . _root ) result = regentry break return result def find_bios_registry ( self , regname ) : \"\"\"\"\"\" result = None if hasattr ( self , '' ) and isinstance ( self . Items , list ) : for entry in self . Items : if entry and ( u'' in entry and regname . lower ( ) in entry [ u'' ] . lower ( ) ) : regentry = RepoRegistryEntry . parse ( entry ) regentry . set_root ( self . _root ) result = regentry break return result class RepoBaseEntry ( RisObject ) : \"\"\"\"\"\" def __init__ ( self , d ) : super ( RepoBaseEntry , self ) . __init__ ( d ) self . _root = None def set_root ( self , newroot ) : \"\"\"\"\"\" self . _root = newroot def _read_location_file ( self , currloc , errlist ) : \"\"\"\"\"\" result = None if u'' in currloc : root = os . path . normpath ( self . _root ) xref = os . path . normpath ( currloc . Uri . extref ) . lstrip ( os . path . sep ) fqpath = os . path . join ( root , xref ) if not os . path . isfile ( fqpath ) : errlist . append ( SchemaValidationError ( u\"\" % fqpath ) ) else : result = None if fqpath . endswith ( '' ) : result = open ( fqpath ) . read ( ) return result class RepoRegistryEntry ( RepoBaseEntry ) : \"\"\"\"\"\" def __init__ ( self , d ) : super ( RepoRegistryEntry , self ) . __init__ ( d ) def validate ( self , tdict , errlist = None , selector = None , currdict = None , checkall = False , monolith = None , newarg = None ) : \"\"\"\"\"\" if not errlist : errlist = list ( ) reg = self . get_registry_model ( errlist = errlist , currdict = currdict , monolith = monolith , newarg = newarg ) if reg and not checkall : try : if reg [ selector ] . readonly : return True except BaseException : pass else : pass results = reg . validate_attribute_values ( tdict ) errlist . extend ( results ) elif checkall and selector is None : results = reg . validate_attribute_values ( tdict ) errlist . extend ( results ) else : errlist . append ( RegistryValidationError ( u'' '' ) ) if errlist : return errlist def validate_bios_version ( self , tdict , errlist = None , selector = None , checkall = False , currdict = None , monolith = None ) : \"\"\"\"\"\" if not errlist : errlist = list ( ) reg = self . get_registry_model_bios_version ( errlist = errlist , currdict = currdict , monolith = monolith ) if reg and not checkall : for item in reg . Attributes : if not item [ \"\" ] == selector : continue if item [ \"\" ] is True : return '' try : if item [ \"\" ] is True : return '' except BaseException : continue else : continue results = reg . validate_att_val_bios ( tdict ) errlist . extend ( results ) elif checkall and selector is None : results = reg . validate_att_val_bios ( tdict ) errlist . extend ( results ) else : errlist . append ( RegistryValidationError ( u'' '' ) ) if errlist : return errlist def validate_deprecated ( self , tdict , errlist = None ) : \"\"\"\"\"\" if not errlist : errlist = list ( ) if not hasattr ( self , u'' ) : errlist . append ( RegistryValidationError ( u'' '' ) ) return errlist currloc = None defloc = None langcode = '' for loc in self . Location : for loclang in loc . keys ( ) : if loclang . lower ( ) == langcode . lower ( ) : currloc = loc [ loclang ] break elif loclang . lower ( ) == u'' : defloc = loc [ loclang ] if not currloc : currloc = defloc if not currloc : errlist . append ( RegistryValidationError ( u'' '' ) ) return location_file = self . _read_location_file ( currloc , errlist = errlist ) if not location_file : errlist . append ( RegistryValidationError ( u'' ) ) else : jsonreg = json . loads ( location_file ) if u'' in jsonreg : if u'' in jsonreg and jsonreg [ u'' ] == u'' : reg = HpPropertiesRegistry . parse ( jsonreg [ u'' ] ) results = reg . validate_attribute_values ( tdict ) errlist . extend ( results ) def get_registry_model ( self , currdict = None , monolith = None , errlist = None , skipcommit = False , searchtype = None , newarg = None , latestschema = None ) : \"\"\"\"\"\" if not errlist : errlist = list ( ) if not hasattr ( self , u'' ) : errlist . append ( RegistryValidationError ( u'' ) ) return None currloc = None defloc = \"\" langcode = list ( locale . getdefaultlocale ( ) ) if not langcode [ ] : langcode [ ] = \"\" for loc in self . Location : locationlanguage = loc [ \"\" ] . lower ( ) locationlanguage = locationlanguage . replace ( \"\" , \"\" ) if locationlanguage in langcode [ ] . lower ( ) : currloc = loc break if not currloc : currloc = defloc if not currloc : errlist . append ( RegistryValidationError ( u'' '' ) ) return None if not searchtype : searchtype = \"\" location_file = None if currdict and monolith : for itemtype in monolith . types : if itemtype . lower ( ) . startswith ( searchtype . lower ( ) ) and u'' in monolith . types [ itemtype ] : for instance in monolith . types [ itemtype ] [ u'' ] : try : if monolith . is_redfish : currtype = currdict [ instance . _typestring ] . split ( '' ) [ - ] currtype = currtype . split ( '' ) [ ] + '' else : currtype = currdict [ instance . _typestring ] if latestschema : currtype = currdict [ instance . _typestring ] . split ( '' ) [ : ] insttype = instance . resp . dict [ \"\" ] . split ( '' ) [ : ] if currtype == insttype or currtype == instance . resp . dict [ \"\" ] . split ( '' ) [ : ] : location_file = instance . resp . dict break elif searchtype == \"\" and instance . resp . dict [ \"\" ] . startswith ( currtype ) or \"\" in instance . resp . dict . keys ( ) and currdict [ instance . _typestring ] == instance . resp . dict [ \"\" ] : location_file = instance . resp . dict break elif searchtype != \"\" and currdict [ instance . _typestring ] in instance . resp . dict [ \"\" ] : location_file = instance . resp . dict break except BaseException : pass else : pass if location_file : break else : location_file = self . _read_location_file ( currloc , errlist = errlist ) if not location_file : errlist . append ( RegistryValidationError ( u'' ) ) else : if currdict and monolith : jsonreg = json . loads ( json . dumps ( location_file , indent = , cls = JSONEncoder ) ) else : jsonreg = json . loads ( location_file ) if skipcommit : return jsonreg [ \"\" ] if u'' in jsonreg : regitem = jsonreg [ u'' ] reg = HpPropertiesRegistry . parse ( regitem ) if newarg : regcopy = reg for arg in newarg [ : - ] : try : if '' in regcopy [ arg ] . iterkeys ( ) and ( '' in regcopy [ arg ] . iterkeys ( ) ) : regcopy [ arg ] [ '' ] . update ( regcopy [ arg ] [ '' ] ) regcopy = regcopy [ arg ] [ \"\" ] for pattern in regcopy . iterkeys ( ) : test = re . compile ( pattern ) nextarg = newarg [ newarg . index ( arg ) + ] match = test . match ( nextarg ) if match : regcopy [ nextarg ] = regcopy . pop ( pattern ) break elif '' in regcopy [ arg ] : oneof = regcopy [ arg ] [ '' ] for item in oneof : regcopy = item [ '' ] if not arg == newarg [ - ] : try : nextitem = newarg [ newarg . index ( arg ) + ] regcopy [ nextitem ] break except Exception : continue else : regcopy = regcopy [ arg ] [ \"\" ] except Exception : try : regcopy = regcopy [ arg ] [ '' ] for pattern in regcopy . iterkeys ( ) : test = re . compile ( pattern ) nextarg = newarg [ newarg . index ( arg ) + ] match = test . match ( nextarg ) if match : patterninfo = regcopy . pop ( pattern ) regcopy [ nextarg ] = patterninfo except BaseException : return None reg = regcopy return reg return None def get_registry_model_bios_version ( self , currdict = None , monolith = None , errlist = None ) : \"\"\"\"\"\" \"\"\"\"\"\" if not errlist : errlist = list ( ) if not hasattr ( self , u'' ) : errlist . append ( RegistryValidationError ( u'' ) ) return None currloc = None defloc = \"\" langcode = list ( locale . getdefaultlocale ( ) ) if not langcode [ ] : langcode [ ] = \"\" for loc in self . Location : locationlanguage = loc [ \"\" ] . lower ( ) locationlanguage = locationlanguage . replace ( \"\" , \"\" ) if locationlanguage in langcode [ ] . lower ( ) : currloc = loc break if not currloc : currloc = defloc if not currloc : errlist . append ( RegistryValidationError ( u'' ) ) return None location_file = None if currdict and monolith : for itemtype in monolith . types : if \"\" in itemtype and u'' in monolith . types [ itemtype ] : for instance in monolith . types [ itemtype ] [ u'' ] : location_file = instance . resp . dict break if location_file : break else : location_file = self . _read_location_file ( currloc , errlist = errlist ) if not location_file : errlist . append ( RegistryValidationError ( u'' ) ) else : if currdict and monolith : jsonreg = json . loads ( json . dumps ( location_file , indent = , cls = JSONEncoder ) ) else : jsonreg = json . loads ( location_file ) if u'' in jsonreg : regitem = jsonreg [ u'' ] reg = HpPropertiesRegistry . parse ( regitem ) return reg return None class RepoSchemaEntry ( RepoBaseEntry ) : \"\"\"\"\"\" def __init__ ( self , item ) : super ( RepoSchemaEntry , self ) . __init__ ( item ) self . _root = None def set_root ( self , newroot ) : \"\"\"\"\"\" self . _root = newroot def _read_location_file ( self , currloc , errlist ) : \"\"\"\"\"\" if u'' in currloc and u'' in currloc : fqpath = os . path . join ( self . _root , currloc . ArchiveUri . xref . lstrip ( os . path . sep ) ) if not os . path . isfile ( fqpath ) : errlist . append ( SchemaValidationError ( u\"\" \"\" % fqpath ) ) else : archive_file = currloc . ArchiveFile archive_fh = None result = None if fqpath . endswith ( '' ) : archive_fh = zipfile . ZipFile ( fqpath ) infolist = archive_fh . infolist ( ) for i in infolist : if i . filename . lower ( ) == archive_file . lower ( ) : jsonsch_fh = archive_fh . open ( i ) result = jsonsch_fh . read ( ) jsonsch_fh . close ( ) archive_fh . close ( ) return result def validate ( self , tdict , errlist = None ) : \"\"\"\"\"\" if not errlist : errlist = list ( ) result = list ( ) if not hasattr ( self , u'' ) : result . append ( SchemaValidationError ( u'' '' ) ) return result currloc = None defloc = None langcode = '' for loc in self . Location : for loclang in loc . keys ( ) : if loclang . lower ( ) == langcode . lower ( ) : currloc = loc [ loclang ] break elif loclang . lower ( ) == u'' : defloc = loc [ loclang ] if not currloc : currloc = defloc if not currloc : result . append ( SchemaValidationError ( u'' ) ) return location_file = self . _read_location_file ( currloc , errlist = result ) if not location_file : result . append ( SchemaValidationError ( u'' ) ) else : jsonsch = json . loads ( location_file ) validictory . validate ( tdict , jsonsch ) class HpPropertiesRegistry ( RisObject ) : \"\"\"\"\"\" def __init__ ( self , d ) : super ( HpPropertiesRegistry , self ) . __init__ ( d ) def validate_attribute_values ( self , tdict ) : \"\"\"\"\"\" result = list ( ) for tkey in tdict : try : if self [ tkey ] and hasattr ( self [ tkey ] , \"\" ) : temp = self . validate_attribute ( self [ tkey ] , tdict [ tkey ] , tkey ) for err in temp : if isinstance ( err , RegistryValidationError ) : if err . reg : err . sel = tkey result . extend ( temp ) except Exception : pass return result def validate_att_val_bios ( self , tdict ) : \"\"\"\"\"\" result = list ( ) for tkey in tdict : for item in self . Attributes : try : if item [ \"\" ] == tkey and hasattr ( item , \"\" ) : temp = self . validate_attribute ( item , tdict [ tkey ] , tkey ) for err in temp : if isinstance ( err , RegistryValidationError ) : if err . reg : err . sel = tkey result . extend ( temp ) break except Exception : pass return result def get_validator ( self , attrname , newargs = None , oneof = None ) : \"\"\"\"\"\" if oneof : self = oneof if newargs : for arg in newargs : try : self = self [ '' ] except Exception : pass if not hasattr ( self , arg ) : return None elif not arg == newargs [ - ] : self = self [ arg ] if not hasattr ( self , attrname ) : return None validator = None if EnumValidator . is_type ( self [ attrname ] ) : validator = EnumValidator . parse ( self [ attrname ] ) elif StringValidator . is_type ( self [ attrname ] ) : validator = StringValidator . parse ( self [ attrname ] ) elif ObjectValidator . is_type ( self [ attrname ] ) : validator = ObjectValidator . parse ( self [ attrname ] ) elif IntegerValidator . is_type ( self [ attrname ] ) : validator = IntegerValidator . parse ( self [ attrname ] ) elif BoolValidator . is_type ( self [ attrname ] ) : validator = BoolValidator . parse ( self [ attrname ] ) elif PasswordValidator . is_type ( self [ attrname ] ) : validator = PasswordValidator . parse ( self [ attrname ] ) elif u'' in self [ attrname ] . keys ( ) : for item in self [ attrname ] [ '' ] : validator = self . get_validator ( attrname , newargs , HpPropertiesRegistry ( { attrname : item } ) ) if validator : break return validator def get_validator_bios ( self , attrname ) : \"\"\"\"\"\" for item in self . Attributes : if item [ \"\" ] == attrname : validator = None if EnumValidator . is_type ( item ) : validator = EnumValidator . parse ( item ) elif StringValidator . is_type ( item ) : validator = StringValidator . parse ( item ) elif IntegerValidator . is_type ( item ) : validator = IntegerValidator . parse ( item ) elif BoolValidator . is_type ( item ) : validator = BoolValidator . parse ( item ) elif ObjectValidator . is_type ( item ) : validator = ObjectValidator . parse ( item ) elif PasswordValidator . is_type ( item ) : validator = PasswordValidator . parse ( item ) return validator return None def validate_attribute ( self , attrentry , attrval , name ) : \"\"\"\"\"\" result = list ( ) validator = None if EnumValidator . is_type ( attrentry ) : validator = EnumValidator . parse ( attrentry ) elif StringValidator . is_type ( attrentry ) : validator = StringValidator . parse ( attrentry ) elif IntegerValidator . is_type ( attrentry ) : validator = IntegerValidator . parse ( attrentry ) elif BoolValidator . is_type ( attrentry ) : validator = BoolValidator . parse ( attrentry ) elif ObjectValidator . is_type ( attrentry ) : validator = ObjectValidator . parse ( attrentry ) elif PasswordValidator . is_type ( attrentry ) : validator = PasswordValidator . parse ( attrentry ) else : raise UnknownValidatorError ( attrentry ) if validator : result . extend ( validator . validate ( attrval , name ) ) return result class BaseValidator ( RisObject ) : \"\"\"\"\"\" def __init__ ( self , d ) : super ( BaseValidator , self ) . __init__ ( d ) def validate ( self ) : \"\"\"\"\"\" raise RuntimeError ( u'' '' ) class EnumValidator ( BaseValidator ) : \"\"\"\"\"\" def __init__ ( self , d ) : super ( EnumValidator , self ) . __init__ ( d ) @ staticmethod def is_type ( attrentry ) : \"\"\"\"\"\" if u'' in attrentry : if isinstance ( attrentry [ u'' ] , list ) : for item in attrentry [ u'' ] : if item . lower ( ) == u'' : return True elif u'' in attrentry and item . lower ( ) == u'' : return True elif u'' in attrentry and attrentry [ u'' ] == \"\" : for key , value in attrentry [ u'' ] . iteritems ( ) : if key . lower ( ) == \"\" and value . lower ( ) == u'' : return True else : if attrentry [ u'' ] . lower ( ) == u'' : return True elif u'' in attrentry and attrentry [ u'' ] . lower ( ) == u'' : return True elif u'' in attrentry : if attrentry [ u'' ] . lower ( ) == u'' : return True return False def validate ( self , newval , name ) : \"\"\"\"\"\" result = list ( ) try : for possibleval in self . enum : if possibleval . lower ( ) == newval . lower ( ) : return result except Exception : for possibleval in self . Value : if possibleval . ValueName . lower ( ) == str ( newval ) . lower ( ) : return result result . append ( RegistryValidationError ( u\"\" \"\" % ( newval , name ) , regentry = self ) ) return result def print_help ( self , name , out = sys . stdout ) : \"\"\"\"\"\" wrapper = textwrap . TextWrapper ( ) wrapper . initial_indent = '' * wrapper . subsequent_indent = '' * out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % name ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( u'' ) out . write ( '' ) if u'' in self and isinstance ( self [ u'' ] , list ) : out . write ( u'' ) for item in self [ u'' ] : out . write ( '' % wrapper . fill ( '' % item ) ) out . write ( '' ) elif u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) elif u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) elif u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) out . write ( u'' ) try : for possibleval in self . enum : out . write ( '' % possibleval ) except Exception : for possibleval in self . Value : out . write ( '' % possibleval ) out . write ( '' ) class BoolValidator ( BaseValidator ) : \"\"\"\"\"\" def __init__ ( self , d ) : super ( BoolValidator , self ) . __init__ ( d ) @ staticmethod def is_type ( attrentry ) : \"\"\"\"\"\" if u'' in attrentry : if isinstance ( attrentry [ u'' ] , list ) : for item in attrentry [ u'' ] : if item . lower ( ) == u'' : return True elif attrentry [ u'' ] == \"\" : for key , value in attrentry [ u'' ] . iteritems ( ) : if key . lower ( ) == \"\" and value . lower ( ) == u'' : return True else : if attrentry [ u'' ] . lower ( ) == u'' : return True elif u'' in attrentry : if attrentry [ u'' ] . lower ( ) == u'' : return True return False def validate ( self , newval , name ) : \"\"\"\"\"\" result = list ( ) if newval is False or newval is True : return result result . append ( RegistryValidationError ( u\"\" % ( newval , name ) , regentry = self ) ) return result def print_help ( self , name , out = sys . stdout ) : \"\"\"\"\"\" wrapper = textwrap . TextWrapper ( ) wrapper . initial_indent = '' * wrapper . subsequent_indent = '' * out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % name ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( u'' ) out . write ( '' ) if u'' in self and isinstance ( self [ u'' ] , list ) : out . write ( u'' ) for item in self [ u'' ] : out . write ( '' % wrapper . fill ( '' % item ) ) out . write ( '' ) elif u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) elif u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) elif u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) out . write ( u'' ) out . write ( '' ) out . write ( '' ) class StringValidator ( BaseValidator ) : \"\"\"\"\"\" def __init__ ( self , d ) : super ( StringValidator , self ) . __init__ ( d ) @ staticmethod def is_type ( attrentry ) : \"\"\"\"\"\" if u'' in attrentry : if isinstance ( attrentry [ u'' ] , list ) : for item in attrentry [ u'' ] : if item . lower ( ) == u'' : return True elif attrentry [ u'' ] == \"\" : for key , value in attrentry [ u'' ] . iteritems ( ) : if key . lower ( ) == \"\" and u'' in value : return True else : if attrentry [ u'' ] . lower ( ) == u'' : return True elif u'' in attrentry : if attrentry [ u'' ] . lower ( ) == u'' : return True return False def validate ( self , newval , name ) : \"\"\"\"\"\" result = list ( ) if u'' in self : if len ( newval ) < int ( self [ u'' ] ) : result . append ( RegistryValidationError ( u\"\" % ( self . Name , int ( self [ u'' ] ) ) , regentry = self ) ) if u'' in self : if len ( newval ) > int ( self [ u'' ] ) : result . append ( RegistryValidationError ( u\"\" % ( self . Name , int ( self [ u'' ] ) ) , regentry = self ) ) if u'' in self : if self [ u'' ] : pat = re . compile ( self [ u'' ] ) if newval and not pat . match ( newval ) : result . append ( RegistryValidationError ( u\"\" \"\" % ( self ) , regentry = self ) ) return result def print_help ( self , name , out = sys . stdout ) : \"\"\"\"\"\" wrapper = textwrap . TextWrapper ( ) wrapper . initial_indent = '' * wrapper . subsequent_indent = '' * out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % name ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( u'' ) out . write ( '' ) if u'' in self and isinstance ( self [ u'' ] , list ) : out . write ( u'' ) for item in self [ u'' ] : out . write ( '' % wrapper . fill ( '' % item ) ) out . write ( '' ) elif u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) elif u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) if u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) elif u'' in self : out . write ( u'' ) out . write ( '' % wrapper . fill ( '' % self ) ) out . write ( '' ) class IntegerValidator ( BaseValidator ) : \"\"\"\"\"\" def __init__ ( self , d ) : super ( IntegerValidator , self ) . __init__ ( d ) @ staticmethod def is_type ( attrentry ) : \"\"\"\"\"\" if u'' in attrentry : if isinstance ( attrentry [ u'' ] , list ) : for item in attrentry [ u'' ] : if item . lower ( ) == u'' or item . lower ( ) == u'' : return True elif attrentry [ u'' ] == \"\" : for key , value in attrentry [ u'' ] . iteritems ( ) : if key . lower ( ) == \"\" : if value . lower ( ) == u'' or value . lower ( ) == u'' : return True else : if attrentry [ u'' ] . lower ( ) == u'' or attrentry [ u'' ] . lower ( ) . lower ( ) == u'' : return True elif u'' in attrentry : if attrentry [ u'' ] . lower ( ) == u'' : return True return False def validate ( self , newval , name ) : \"\"\"\"\"\" result = list ( ) intval = int ( newval ) ", "answer": "pat = re . compile ( r'' )"}, {"prompt": " import asyncio from datetime import datetime import contexts import asynqp from asynqp import message from asynqp import frames from asynqp import spec from asynqp import exceptions from . base_contexts import OpenChannelContext , QueueContext , ExchangeContext , BoundQueueContext , ConsumerContext from . util import testing_exception_handler class WhenDeclaringAQueue ( OpenChannelContext ) : def when_I_declare_a_queue ( self ) : self . async_partial ( self . channel . declare_queue ( '' , durable = True , exclusive = True , auto_delete = True , arguments = { '' : , '' : } ) ) def it_should_send_a_QueueDeclare_method ( self ) : expected_method = spec . QueueDeclare ( , '' , False , True , True , True , False , { '' : , '' : } ) self . server . should_have_received_method ( self . channel . id , expected_method ) class WhenQueueDeclareOKArrives ( OpenChannelContext ) : def given_I_declared_a_queue ( self ) : self . queue_name = '' self . task = asyncio . async ( self . channel . declare_queue ( self . queue_name , durable = True , exclusive = True , auto_delete = True , arguments = { '' : , '' : } ) ) self . tick ( ) def when_QueueDeclareOK_arrives ( self ) : self . server . send_method ( self . channel . id , spec . QueueDeclareOK ( self . queue_name , , ) ) self . result = self . task . result ( ) def it_should_have_the_correct_queue_name ( self ) : assert self . result . name == self . queue_name def it_should_be_durable ( self ) : assert self . result . durable def it_should_be_exclusive ( self ) : assert self . result . exclusive def it_should_auto_delete ( self ) : assert self . result . auto_delete class WhenILetTheServerPickTheQueueName ( OpenChannelContext ) : def given_I_declared_a_queue ( self ) : self . task = asyncio . async ( self . channel . declare_queue ( '' , durable = True , exclusive = True , auto_delete = True ) , loop = self . loop ) self . tick ( ) self . queue_name = '' def when_QueueDeclareOK_arrives ( self ) : self . server . send_method ( self . channel . id , spec . QueueDeclareOK ( self . queue_name , , ) ) self . result = self . task . result ( ) def it_should_return_a_queue_with_the_correct_name ( self ) : assert self . result . name == self . queue_name class WhenIUseAnIllegalNameForAQueue ( OpenChannelContext ) : @ classmethod def examples_of_bad_names ( cls ) : yield '' yield '' def when_I_declare_the_queue ( self , queue_name ) : self . task = asyncio . async ( self . channel . declare_queue ( queue_name , durable = True , exclusive = True , auto_delete = True ) , loop = self . loop ) self . tick ( ) def it_should_throw_ValueError ( self ) : assert isinstance ( self . task . exception ( ) , ValueError ) class WhenBindingAQueueToAnExchange ( QueueContext , ExchangeContext ) : def when_I_bind_the_queue ( self ) : self . async_partial ( self . queue . bind ( self . exchange , '' , arguments = { '' : '' } ) ) def it_should_send_QueueBind ( self ) : expected_method = spec . QueueBind ( , self . queue . name , self . exchange . name , '' , False , { '' : '' } ) self . server . should_have_received_method ( self . channel . id , expected_method ) class WhenQueueBindOKArrives ( QueueContext , ExchangeContext ) : def given_I_sent_QueueBind ( self ) : self . task = asyncio . async ( self . queue . bind ( self . exchange , '' ) ) self . tick ( ) def when_QueueBindOK_arrives ( self ) : self . server . send_method ( self . channel . id , spec . QueueBindOK ( ) ) self . binding = self . task . result ( ) def then_the_returned_binding_should_have_the_correct_queue ( self ) : assert self . binding . queue is self . queue def and_the_returned_binding_should_have_the_correct_exchange ( self ) : assert self . binding . exchange is self . exchange class WhenUnbindingAQueue ( BoundQueueContext ) : def when_I_unbind_the_queue ( self ) : self . async_partial ( self . binding . unbind ( arguments = { '' : '' } ) ) def it_should_send_QueueUnbind ( self ) : expected_method = spec . QueueUnbind ( , self . queue . name , self . exchange . name , '' , { '' : '' } ) self . server . should_have_received_method ( self . channel . id , expected_method ) class WhenQueueUnbindOKArrives ( BoundQueueContext ) : def given_I_unbound_the_queue ( self ) : self . task = asyncio . async ( self . binding . unbind ( ) ) self . tick ( ) def when_QueueUnbindOK_arrives ( self ) : self . server . send_method ( self . channel . id , spec . QueueUnbindOK ( ) ) def it_should_be_ok ( self ) : assert self . task . result ( ) is None class WhenIUnbindAQueueTwice ( BoundQueueContext ) : def given_an_unbound_queue ( self ) : asyncio . async ( self . binding . unbind ( ) ) self . tick ( ) self . server . send_method ( self . channel . id , spec . QueueUnbindOK ( ) ) def when_I_unbind_the_queue_again ( self ) : self . task = asyncio . async ( self . binding . unbind ( ) ) self . tick ( ) def it_should_throw_Deleted ( self ) : assert isinstance ( self . task . exception ( ) , asynqp . Deleted ) class WhenIAskForAMessage ( QueueContext ) : def when_I_get_a_message ( self ) : self . async_partial ( self . queue . get ( no_ack = False ) ) def it_should_send_BasicGet ( self ) : self . server . should_have_received_method ( self . channel . id , spec . BasicGet ( , self . queue . name , False ) ) class WhenBasicGetEmptyArrives ( QueueContext ) : def given_I_asked_for_a_message ( self ) : self . task = asyncio . async ( self . queue . get ( no_ack = False ) ) self . tick ( ) def when_BasicGetEmpty_arrives ( self ) : self . server . send_method ( self . channel . id , spec . BasicGetEmpty ( '' ) ) def it_should_return_None ( self ) : assert self . task . result ( ) is None class WhenBasicGetOKArrives ( QueueContext ) : def given_I_asked_for_a_message ( self ) : self . expected_message = asynqp . Message ( '' , timestamp = datetime ( , , ) ) self . task = asyncio . async ( self . queue . get ( no_ack = False ) ) self . tick ( ) def when_BasicGetOK_arrives_with_content ( self ) : method = spec . BasicGetOK ( , False , '' , '' , ) self . server . send_method ( self . channel . id , method ) header = message . get_header_payload ( self . expected_message , spec . BasicGet . method_type [ ] ) self . server . send_frame ( frames . ContentHeaderFrame ( self . channel . id , header ) ) body = message . get_frame_payloads ( self . expected_message , ) [ ] self . server . send_frame ( frames . ContentBodyFrame ( self . channel . id , body ) ) self . tick ( ) def it_should_return_the_expected_message ( self ) : assert self . task . result ( ) == self . expected_message def it_should_put_the_exchange_name_on_the_msg ( self ) : assert self . task . result ( ) . exchange_name == '' def it_should_put_the_routing_key_on_the_msg ( self ) : assert self . task . result ( ) . routing_key == '' class WhenConnectionClosedOnGet ( QueueContext ) : def given_I_asked_for_a_message ( self ) : self . task = asyncio . async ( self . queue . get ( no_ack = False ) ) self . tick ( ) def when_connection_is_closed ( self ) : try : self . server . protocol . connection_lost ( Exception ( ) ) except Exception : pass self . tick ( ) def it_should_raise_exception ( self ) : assert self . task . exception ( ) is not None class WhenISubscribeToAQueue ( QueueContext ) : def when_I_start_a_consumer ( self ) : self . async_partial ( self . queue . consume ( lambda msg : None , no_local = False , no_ack = False , exclusive = False , arguments = { '' : } ) ) def it_should_send_BasicConsume ( self ) : self . server . should_have_received_method ( self . channel . id , spec . BasicConsume ( , self . queue . name , '' , False , False , False , False , { '' : } ) ) class WhenConsumeOKArrives ( QueueContext ) : def given_I_started_a_consumer ( self ) : self . task = asyncio . async ( self . queue . consume ( lambda msg : None , no_local = False , no_ack = False , exclusive = False , arguments = { '' : } ) ) self . tick ( ) def when_BasicConsumeOK_arrives ( self ) : method = spec . BasicConsumeOK ( '' ) self . server . send_method ( self . channel . id , method ) def it_should_return_a_consumer_with_the_correct_consumer_tag ( self ) : assert self . task . result ( ) . tag == '' class WhenBasicDeliverArrives ( ConsumerContext ) : def given_a_message ( self ) : self . expected_message = asynqp . Message ( '' , timestamp = datetime ( , , ) ) def when_BasicDeliver_arrives_with_content ( self ) : method = spec . BasicDeliver ( self . consumer . tag , , False , '' , '' ) self . server . send_method ( self . channel . id , method ) header = message . get_header_payload ( self . expected_message , spec . BasicGet . method_type [ ] ) self . server . send_frame ( frames . ContentHeaderFrame ( self . channel . id , header ) ) body = message . get_frame_payloads ( self . expected_message , ) [ ] self . server . send_frame ( frames . ContentBodyFrame ( self . channel . id , body ) ) self . tick ( ) def it_should_send_the_message_to_the_callback ( self ) : self . callback . assert_called_once_with ( self . expected_message ) class WhenAConsumerThrowsAnExceptionAndAnotherMessageArrives ( ConsumerContext ) : def given_a_consumer_has_thrown_an_exception ( self ) : self . loop . set_exception_handler ( lambda l , c : None ) self . expected_message = asynqp . Message ( '' , timestamp = datetime ( , , ) ) self . consumer . callback . side_effect = Exception self . deliver_msg ( ) def when_another_message_arrives ( self ) : self . deliver_msg ( ) def it_should_correctly_call_the_consumer_again ( self ) : assert self . callback . call_count == def deliver_msg ( self ) : method = spec . BasicDeliver ( self . consumer . tag , , False , '' , '' ) self . server . send_method ( self . channel . id , method ) header = message . get_header_payload ( self . expected_message , spec . BasicGet . method_type [ ] ) self . server . send_frame ( frames . ContentHeaderFrame ( self . channel . id , header ) ) body = message . get_frame_payloads ( self . expected_message , ) [ ] self . server . send_frame ( frames . ContentBodyFrame ( self . channel . id , body ) ) self . tick ( ) def cleanup_the_exception_handler ( self ) : self . loop . set_exception_handler ( testing_exception_handler ) class WhenICancelAConsumer ( ConsumerContext ) : def when_I_cancel_the_consumer ( self ) : self . async_partial ( self . consumer . cancel ( ) ) def it_should_send_a_BasicCancel_method ( self ) : self . server . should_have_received_method ( self . channel . id , spec . BasicCancel ( self . consumer . tag , False ) ) class WhenCancelOKArrives ( ConsumerContext ) : def given_I_cancelled_a_consumer ( self ) : asyncio . async ( self . consumer . cancel ( ) ) self . tick ( ) def when_BasicCancelOK_arrives ( self ) : self . server . send_method ( self . channel . id , spec . BasicCancelOK ( self . consumer . tag ) ) def it_should_be_cancelled ( self ) : assert self . consumer . cancelled class WhenCancelOKArrivesForAConsumerWithAnOnCancelMethod ( QueueContext ) : def given_I_started_and_cancelled_a_consumer ( self ) : self . consumer = self . ConsumerWithOnCancel ( ) task = asyncio . async ( self . queue . consume ( self . consumer , no_local = False , no_ack = False , exclusive = False , arguments = { '' : } ) ) self . tick ( ) self . server . send_method ( self . channel . id , spec . BasicConsumeOK ( '' ) ) self . tick ( ) asyncio . async ( task . result ( ) . cancel ( ) ) ", "answer": "self . tick ( )"}, {"prompt": " from paasta_tools . cli . utils import execute_paasta_serviceinit_on_remote_master from paasta_tools . cli . utils import figure_out_service_name from paasta_tools . cli . utils import lazy_choices_completer from paasta_tools . cli . utils import list_instances from paasta_tools . cli . utils import list_services from paasta_tools . utils import compose_job_id from paasta_tools . utils import DEFAULT_SOA_DIR from paasta_tools . utils import list_clusters def add_subparser ( subparsers ) : status_parser = subparsers . add_parser ( '' , help = \"\" , description = ( \"\" \"\" \"\" \"\" ) , epilog = ( \"\" \"\" ) , ) status_parser . add_argument ( '' , '' , help = \"\" , ) . completer = lazy_choices_completer ( list_services ) status_parser . add_argument ( '' , '' , help = \"\" , required = True , ) . completer = lazy_choices_completer ( list_instances ) status_parser . add_argument ( '' , '' , help = \"\" , required = True , ) . completer = lazy_choices_completer ( list_clusters ) status_parser . add_argument ( '' , '' , help = \"\" , required = False , ) status_parser . add_argument ( ", "answer": "'' , '' ,"}, {"prompt": " from jug import TaskGenerator from time import sleep @ TaskGenerator def double ( x ) : sleep ( ) return * x @ TaskGenerator def add ( a , b ) : return a + b @ TaskGenerator ", "answer": "def print_final_result ( oname , value ) :"}, {"prompt": " import cassiopeia . type . dto . common import cassiopeia . type . core . common if cassiopeia . type . dto . common . sqlalchemy_imported : import sqlalchemy import sqlalchemy . orm @ cassiopeia . type . core . common . inheritdocs class TournamentCodeParameters ( cassiopeia . type . dto . common . CassiopeiaParametersDto ) : \"\"\"\"\"\" def __init__ ( self , teamSize , spectatorType , pickType , mapType , allowedSummonerIds = None , metadata = \"\" ) : ", "answer": "self . teamSize = teamSize"}, {"prompt": " from __future__ import unicode_literals import time import pexpect from behave import given , when , then def expect_exact ( context , expected ) : context . cli . expect_exact ( expected , timeout = ) @ given ( u\"\" ) def step_start_cycli ( context ) : context . cli = pexpect . spawnu ( \"\" ) @ given ( u\"\" ) ", "answer": "def step_prompt_visible ( context ) :"}, {"prompt": " import smtplib from email . mime . text import MIMEText import socket from . parser import load_task_graph def notify ( * contact_list ) : \"\"\"\"\"\" task_graph = load_task_graph ( ) status = '' if task_graph . successful : ", "answer": "status = ''"}, {"prompt": " from setuptools import setup , find_packages ", "answer": "setup ( name = '' ,"}, {"prompt": " import sys ", "answer": "from base_django import DjangoHgBuild"}, {"prompt": " import SCons . compat import builtins import os import pickle import shutil import time keep_all_files = ignore_corrupt_dbfiles = def corruption_warning ( filename ) : print \"\" , filename try : unicode ", "answer": "except NameError :"}, {"prompt": " \"\"\"\"\"\" import logging import threading from django . core . handlers . wsgi import WSGIRequest from perftools . middleware import Base from perftools . patcher import Patcher class State ( threading . local ) : def __init__ ( self ) : self . count = self . queries = [ ] class CursorWrapper ( object ) : def __init__ ( self , cursor , connection , state , queries = False ) : self . cursor = cursor self . connection = connection self . _state = state self . _queries = queries ", "answer": "def _incr ( self , sql , params ) :"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import atom . http_core class Error ( Exception ) : pass ", "answer": "class MissingHost ( Error ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Building ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " class _Getch : \"\"\"\"\"\" def __init__ ( self ) : try : self . impl = _GetchWindows ( ) except ImportError : self . impl = _GetchUnix ( ) def __call__ ( self ) : return self . impl ( ) class _GetchUnix : def __init__ ( self ) : import tty , sys def __call__ ( self ) : import sys , tty , termios fd = sys . stdin . fileno ( ) old_settings = termios . tcgetattr ( fd ) try : tty . setraw ( sys . stdin . fileno ( ) ) ch = sys . stdin . read ( ) finally : termios . tcsetattr ( fd , termios . TCSADRAIN , old_settings ) ", "answer": "return ch"}, {"prompt": " \"\"\"\"\"\" __all__ = [ '' ", "answer": "]"}, {"prompt": " from oslo_config import cfg from oslo_log import versionutils _DEFAULT_LOG_DATE_FORMAT = \"\" DEFAULT_LOG_LEVELS = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] _IGNORE_MESSAGE = \"\" common_cli_opts = [ cfg . BoolOpt ( '' , short = '' , default = False , help = '' '' ) , cfg . BoolOpt ( '' , short = '' , default = True , help = '' '' , deprecated_for_removal = True ) , ] logging_cli_opts = [ cfg . StrOpt ( '' , metavar = '' , deprecated_name = '' , help = '' '' '' '' '' '' '' '' ) , cfg . StrOpt ( '' , default = _DEFAULT_LOG_DATE_FORMAT , metavar = '' , help = '' '' + _IGNORE_MESSAGE ) , cfg . StrOpt ( '' , metavar = '' , deprecated_name = '' , help = '' '' '' + _IGNORE_MESSAGE ) , cfg . StrOpt ( '' , deprecated_name = '' , help = '' '' + _IGNORE_MESSAGE ) , cfg . BoolOpt ( '' , default = False , help = '' '' '' '' '' + _IGNORE_MESSAGE ) , cfg . BoolOpt ( '' , default = False , help = '' '' '' + _IGNORE_MESSAGE ) , cfg . StrOpt ( '' , default = '' , help = '' + _IGNORE_MESSAGE ) , ] generic_log_opts = [ cfg . BoolOpt ( '' , default = True , help = '' + _IGNORE_MESSAGE ) , ] log_opts = [ cfg . StrOpt ( '' , default = '' '' '' , help = '' ) , cfg . StrOpt ( '' , default = '' '' , help = '' '' ) , cfg . StrOpt ( '' , default = '' , help = '' '' ) , cfg . StrOpt ( '' , default = '' '' , help = '' ) , cfg . StrOpt ( '' , default = '' '' , help = '' '' ) , ", "answer": "cfg . ListOpt ( '' ,"}, {"prompt": " from paste . fixture import * try : from paste . debug . profile import * disable = False except ImportError : disable = True if not disable : ", "answer": "def simple_app ( environ , start_response ) :"}, {"prompt": " from __future__ import unicode_literals ", "answer": "import timeit"}, {"prompt": " __author__ = '' import argparse import msgpack import os from interface . services . icontainer_agent import IContainerAgent , ContainerAgentClient from pyon . net . messaging import make_node from pyon . core . bootstrap import CFG , bootstrap_pyon def main ( ) : parser = argparse . ArgumentParser ( description = \"\" ) parser . add_argument ( \"\" , help = \"\" ) parser . add_argument ( \"\" , help = \"\" , choices = IContainerAgent . names ( ) ) parser . add_argument ( \"\" , metavar = \"\" , nargs = \"\" , help = \"\" ) opts = parser . parse_args ( ) pidfile = opts . pidfile if not pidfile : raise Exception ( \"\" ) parms = { } with open ( pidfile , '' ) as pf : parms = msgpack . loads ( pf . read ( ) ) assert parms , \"\" bootstrap_pyon ( ) node , ioloop = make_node ( parms [ '' ] ) node . setup_interceptors ( CFG . interceptor ) cc = ContainerAgentClient ( node = node , to_name = ( parms [ '' ] , parms [ '' ] ) ) methdefs = [ x [ ] for x in IContainerAgent . namesAndDescriptions ( ) if x [ ] == opts . command ] assert len ( methdefs ) == arg_names = methdefs [ ] . positional msg_args = dict ( zip ( arg_names , opts . commandargs ) ) retval = cc . request ( msg_args , op = opts . command ) ", "answer": "if opts . command == \"\" :"}, {"prompt": " from oslo_log import log as logging import sahara . plugins . mapr . domain . configuration_file as bcf import sahara . plugins . mapr . domain . node_process as np import sahara . plugins . mapr . domain . service as s import sahara . plugins . mapr . util . validation_utils as vu import sahara . utils . files as files LOG = logging . getLogger ( __name__ ) HIVE_METASTORE = np . NodeProcess ( name = '' , ", "answer": "ui_name = '' ,"}, {"prompt": " import unittest import utils import sdk change_file_permissions = [ '' ] change_folder_permissions = [ '' , '' ] list_permissions = [ '' , '' , '' , '' ] readonly_permissions = [ '' , '' ] class Permissions ( unittest . TestCase ) : new_roles = { } @ utils . allow ( services = list_permissions ) def setUp ( self ) : acc = self . account if acc . service in list_permissions : self . test_folder = utils . create_or_get_test_folder ( acc ) self . test_file = utils . create_test_file ( acc ) new_roles = { \"\" : \"\" , \"\" : \"\" } if acc . service in change_folder_permissions : self . new_roles = new_roles self . test_folder . permissions . create ( data = self . new_roles ) if acc . service in change_file_permissions : self . new_roles = new_roles self . test_file . permissions . create ( data = self . new_roles ) def list_helper ( self , data ) : result = data . permissions . all ( ) self . assertIsInstance ( result , sdk . resources . AnnotatedList ) owner_exists = False for perm in result : self . assertIsInstance ( perm , sdk . resources . Permission ) if self . account . service not in readonly_permissions : if perm . role == \"\" : owner_exists = True else : self . assertIn ( perm . email , self . new_roles ) self . assertEqual ( perm . role , self . new_roles . get ( perm . email ) ) self . assertTrue ( owner_exists ) def test_folder_permissions_list ( self ) : if self . account . service in list_permissions : self . list_helper ( self . test_folder ) def test_folder_permissions_set ( self ) : if self . account . service in change_folder_permissions : self . new_roles = { \"\" : \"\" , \"\" : \"\" } result = self . test_folder . permissions . create ( data = self . new_roles ) self . assertIsInstance ( result . permissions , list ) self . list_helper ( self . test_folder ) def test_folder_permissions_update ( self ) : if self . account . service in change_folder_permissions : self . new_roles . update ( { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } ) result = self . test_folder . permissions . update ( data = self . new_roles ) self . assertIsInstance ( result . permissions , list ) self . list_helper ( self . test_folder ) def test_file_permissions_list ( self ) : if self . account . service in list_permissions : self . list_helper ( self . test_file ) def test_file_permissions_set ( self ) : if self . account . service in change_file_permissions : self . new_roles = { \"\" : \"\" , \"\" : \"\" } result = self . test_file . permissions . create ( data = self . new_roles ) self . assertIsInstance ( result . permissions , list ) self . list_helper ( self . test_file ) def test_file_permissions_update ( self ) : if self . account . service in change_file_permissions : self . new_roles . update ( { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } ) result = self . test_file . permissions . update ( data = self . new_roles ) self . assertIsInstance ( result . permissions , list ) self . list_helper ( self . test_file ) def test_cases ( ) : return [ utils . create_test_case ( acc , Permissions ) for acc in utils . accounts ] if __name__ == '' : ", "answer": "suite = utils . create_suite ( test_cases ( ) )"}, {"prompt": " import pytest import sys from . test_base_class import TestBaseClass from aerospike import exception as e aerospike = pytest . importorskip ( \"\" ) try : import aerospike except : print ( \"\" ) sys . exit ( ) class TestSetPassword ( TestBaseClass ) : pytestmark = pytest . mark . skipif ( TestBaseClass ( ) . get_hosts ( ) [ ] == None , reason = \"\" ) def setup_method ( self , method ) : \"\"\"\"\"\" hostlist , user , password = TestBaseClass ( ) . get_hosts ( ) config = { \"\" : hostlist } TestSetPassword . Me = self self . client = aerospike . client ( config ) . connect ( user , password ) try : self . client . admin_drop_user ( \"\" ) except : pass self . client . admin_create_user ( \"\" , \"\" , [ \"\" ] , { } ) self . delete_users = [ ] def teardown_method ( self , method ) : \"\"\"\"\"\" self . client . admin_drop_user ( \"\" ) self . client . close ( ) def test_set_password_without_any_parameters ( self ) : with pytest . raises ( TypeError ) as typeError : self . client . admin_set_password ( ) assert \"\" in str ( typeError . value ) def test_set_password_with_proper_parameters ( self ) : user = \"\" password = \"\" status = self . client . admin_set_password ( user , password ) assert status == def test_set_password_with_invalid_timeout_policy_value ( self ) : policy = { '' : } user = \"\" password = \"\" try : self . client . admin_set_password ( user , password , policy ) except e . ParamError as exception : assert exception . code == - assert exception . msg == \"\" def test_set_password_with_proper_timeout_policy_value ( self ) : policy = { '' : } user = \"\" password = \"\" status = self . client . admin_set_password ( user , password , policy ) ", "answer": "assert status == "}, {"prompt": " \"\"\"\"\"\" from datetime import timedelta import logging import sys from homeassistant . components import ( zone as zone_cmp , sun as sun_cmp ) from homeassistant . const import ( ATTR_GPS_ACCURACY , ATTR_LATITUDE , ATTR_LONGITUDE , CONF_ENTITY_ID , CONF_VALUE_TEMPLATE , CONF_CONDITION , WEEKDAYS ) from homeassistant . exceptions import TemplateError , HomeAssistantError import homeassistant . helpers . config_validation as cv from homeassistant . helpers . template import render import homeassistant . util . dt as dt_util FROM_CONFIG_FORMAT = '' CONF_BELOW = '' CONF_ABOVE = '' CONF_STATE = '' CONF_ZONE = '' EVENT_SUNRISE = '' EVENT_SUNSET = '' _LOGGER = logging . getLogger ( __name__ ) def from_config ( config , config_validation = True ) : \"\"\"\"\"\" factory = getattr ( sys . modules [ __name__ ] , FROM_CONFIG_FORMAT . format ( config . get ( CONF_CONDITION ) ) , None ) if factory is None : raise HomeAssistantError ( '' . format ( config . get ( CONF_CONDITION ) , config ) ) return factory ( config , config_validation ) def and_from_config ( config , config_validation = True ) : \"\"\"\"\"\" if config_validation : config = cv . AND_CONDITION_SCHEMA ( config ) checks = [ from_config ( entry ) for entry in config [ '' ] ] def if_and_condition ( hass , variables = None ) : \"\"\"\"\"\" return all ( check ( hass , variables ) for check in checks ) return if_and_condition def or_from_config ( config , config_validation = True ) : \"\"\"\"\"\" if config_validation : config = cv . OR_CONDITION_SCHEMA ( config ) checks = [ from_config ( entry ) for entry in config [ '' ] ] def if_or_condition ( hass , variables = None ) : \"\"\"\"\"\" return any ( check ( hass , variables ) for check in checks ) return if_or_condition def numeric_state ( hass , entity , below = None , above = None , value_template = None , variables = None ) : \"\"\"\"\"\" if isinstance ( entity , str ) : entity = hass . states . get ( entity ) if entity is None : return False if value_template is None : ", "answer": "value = entity . state"}, {"prompt": " from zipa import api_github_com as github repos = github . orgs . django . repos ", "answer": "for repo in repos [ { '' : '' , '' : '' } ] :"}, {"prompt": " import mock import unittest from networking_cisco . plugins . cisco . cpnr . netns import iflist from networking_cisco . plugins . cisco . cpnr . netns import nslist class TestNetNs ( unittest . TestCase ) : @ mock . patch ( '' ) @ mock . patch ( '' ) def test_nslist ( self , mock_listdir , mock_path ) : mock_path . exists . return_value = True mock_listdir . return_value = [ ] mock_listdir . return_value . append ( ( '' ) ) mock_listdir . return_value . append ( ( '' ) ) nsdirs = nslist ( ) self . assertEqual ( '' , nsdirs [ ] ) self . assertEqual ( '' , nsdirs [ ] ) mock_path . exists . return_value = False nsdirs = nslist ( ) self . assertEqual ( [ ] , nsdirs ) @ mock . patch ( '' ) def test_iflist ( self , mock_check_output ) : ip_addr_str = ( b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' b'' ) mock_check_output . return_value = ip_addr_str interfaces = iflist ( ) ", "answer": "name , addr , mask = interfaces [ ]"}, {"prompt": " from flask import Flask from requests import JSONRPCRequest from views import json_echo , echo from method_views import JSONEchoView ", "answer": "Flask . request_class = JSONRPCRequest"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from moztrap . settings . default import *"}, {"prompt": " import urllib from StringIO import StringIO from base64 import b32encode from flask import abort from flask import flash from flask import make_response from flask import render_template from flask import redirect from flask import request from flask import send_file from flask import url_for from flask . views import View from flaskwallet import session from settingsapp . models import Setting import qrcode from Crypto . Random import get_random_bytes class OTPSetupView ( View ) : def dispatch_request ( self ) : return render_template ( '' ) class QRView ( View ) : \"\"\"\"\"\" def dispatch_request ( self ) : secret = self . get_secret ( ) if secret : return send_file ( self . get_qr ( secret ) , mimetype = '' ) else : abort ( ) def get_secret ( self ) : \"\"\"\"\"\" name = '' setting = session . query ( Setting ) . get ( name ) if setting : ret = False else : secret = get_random_bytes ( ) code = b32encode ( secret ) setting = Setting ( name , code ) session . add ( setting ) session . commit ( ) ret = code return ret def get_qr ( self , secret ) : img_io = StringIO ( ) qr = self . build_qr_image ( secret ) qr . save ( img_io , '' ) img_io . seek ( ) return img_io def build_qr_image ( self , secret ) : qr = qrcode . QRCode ( ", "answer": "version = ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Weapon ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import unittest import tempfile import shutil import dulwich from support import setup_logger from spaghettifs . easygit import EasyGit , EasyTree , EasyBlob from spaghettifs . treetree import TreeTree class BasicTestCase ( unittest . TestCase ) : def setUp ( self ) : self . repo_path = tempfile . mkdtemp ( ) self . eg = EasyGit . new_repo ( self . repo_path , bare = True ) self . tt = TreeTree ( self . eg . root . new_tree ( '' ) ) def tearDown ( self ) : shutil . rmtree ( self . repo_path ) def commit ( self ) : self . eg . commit ( author = \"\" , message = \"\" ) def test_valid_ids ( self ) : self . assertRaises ( ValueError , self . tt . new_blob , '' ) self . assertRaises ( ValueError , self . tt . new_blob , ) try : ", "answer": "self . tt . new_blob ( '' )"}, {"prompt": " import sys , re import numpy import threading import math from io import BytesIO from bokeh . plotting import figure , show , curdoc from bokeh . models import BoxSelectTool , TapTool , PanTool from ginga import ImageView from ginga import Mixins , Bindings , colors from ginga . web . bokehw . CanvasRenderBokeh import CanvasRenderer from ginga . util . heaptimer import TimerHeap try : from ginga . aggw . ImageViewAgg import ImageViewAgg as ImageViewSS , ImageViewAggError as ImageViewError except ImportError : try : from ginga . cvw . ImageViewCv import ImageViewCv as ImageViewSS , ImageViewCvError as ImageViewError except ImportError : try : from ginga . pilw . ImageViewPil import ImageViewPil as ImageViewSS , ImageViewPilError as ImageViewError except ImportError : from ginga . mockw . ImageViewMock import ImageViewMock as ImageViewSS , ImageViewMockError as ImageViewError class ImageViewBokehError ( ImageViewError ) : pass class ImageViewBokeh2 ( ImageViewSS ) : \"\"\"\"\"\" def __init__ ( self , logger = None , rgbmap = None , settings = None ) : ImageViewSS . __init__ ( self , logger = logger , rgbmap = rgbmap , settings = settings ) self . figure = None self . bkimage = None self . _push_server = False self . _originUpper = False self . msgtask = None self . _defer_task = None def set_figure ( self , figure ) : \"\"\"\"\"\" self . figure = figure self . bkimage = None wd = figure . plot_width ht = figure . plot_height self . configure_window ( wd , ht ) def get_figure ( self ) : return self . figure def update_image ( self ) : if self . figure is None : return wd , ht = self . get_window_size ( ) surface = self . get_surface ( ) if isinstance ( surface , numpy . ndarray ) : arr8 = surface else : arr8 = numpy . fromstring ( surface . tostring ( ) , dtype = numpy . uint8 ) arr8 = arr8 . reshape ( ( ht , wd , ) ) view = arr8 . view ( dtype = numpy . uint32 ) . reshape ( ( ht , wd ) ) dst_x = dst_y = if self . bkimage is None : self . bkimage = self . figure . image_rgba ( image = [ view ] , x = [ dst_x ] , y = [ dst_y ] , dw = [ wd ] , dh = [ ht ] ) d_src = self . bkimage . data_source self . _setup_handlers ( d_src ) else : d_src = self . bkimage . data_source d_src . data [ \"\" ] = [ view ] d_src . data [ \"\" ] = [ dst_x ] d_src . data [ \"\" ] = [ dst_y ] d_src . data [ \"\" ] = [ wd ] d_src . data [ \"\" ] = [ ht ] if self . _push_server : try : cursession ( ) . store_objects ( d_src ) except Exception as e : self . logger . warning ( \"\" % ( str ( e ) ) ) def reschedule_redraw ( self , time_sec ) : if self . figure is not None : time_ms = int ( time_sec * ) def configure_window ( self , width , height ) : self . configure_surface ( width , height ) def _setup_handlers ( self , source ) : pass def set_cursor ( self , cursor ) : if self . figure is None : return def onscreen_message ( self , text , delay = None ) : if self . figure is None : return self . message = text self . redraw ( whence = ) if delay : ms = int ( delay * ) class ImageViewBokeh ( ImageView . ImageViewBase ) : \"\"\"\"\"\" def __init__ ( self , logger = None , rgbmap = None , settings = None ) : ImageView . ImageViewBase . __init__ ( self , logger = logger , rgbmap = rgbmap , settings = settings ) self . figure = None self . bkimage = None self . _push_server = False self . defer_redraw = False self . _originUpper = False self . img_fg = ( , , ) self . img_bg = ( , , ) self . message = None self . _rgb_order = '' self . renderer = CanvasRenderer ( self ) self . cursor = { } self . _msg_timer = None self . _defer_timer = None self . t_ . setDefaults ( show_pan_position = False , onscreen_ff = '' ) def set_figure ( self , figure ) : \"\"\"\"\"\" self . figure = figure self . bkimage = None wd = figure . plot_width ht = figure . plot_height self . configure_window ( wd , ht ) def get_figure ( self ) : return self . figure def get_rgb_order ( self ) : return self . _rgb_order def render_image ( self , rgbobj , dst_x , dst_y ) : \"\"\"\"\"\" self . logger . debug ( \"\" ) if self . figure is None : return data = self . getwin_array ( order = self . _rgb_order ) ht , wd = data . shape [ : ] view = data . view ( dtype = numpy . uint32 ) . reshape ( ( ht , wd ) ) dst_x = dst_y = if self . bkimage is None : self . bkimage = self . figure . image_rgba ( image = [ view ] , x = [ dst_x ] , y = [ dst_y ] , dw = [ wd ] , dh = [ ht ] ) d_src = self . bkimage . data_source self . _setup_handlers ( d_src ) else : d_src = self . bkimage . data_source d_src . data [ \"\" ] = [ view ] d_src . data [ \"\" ] = [ dst_x ] d_src . data [ \"\" ] = [ dst_y ] d_src . data [ \"\" ] = [ wd ] d_src . data [ \"\" ] = [ ht ] if self . t_ [ '' ] : size = int ( max ( ht , wd ) * ) ctr_x , ctr_y = self . get_center ( ) self . figure . cross ( x = [ ctr_x ] , y = [ ctr_y ] , size = size , color = '' , line_width = ) if self . message : y = ( ht // ) * x = ( wd // ) self . figure . text ( x = [ x ] , y = [ y ] , text = [ self . message ] , text_font_size = '' , text_baseline = '' , text_color = '' , text_align = '' ) if self . _push_server : try : cursession ( ) . store_objects ( d_src ) except Exception as e : self . logger . warning ( \"\" % ( str ( e ) ) ) def configure_window ( self , width , height ) : self . configure ( width , height ) def _setup_handlers ( self , source ) : pass def _resize_cb ( self , event ) : wd , ht = event . width , event . height self . logger . debug ( \"\" % ( wd , ht ) ) self . configure_window ( wd , ht ) def get_png_image_as_buffer ( self , output = None ) : ibuf = output if ibuf is None : ibuf = BytesIO ( ) qimg = self . figure . write_to_png ( ibuf ) return ibuf def update_image ( self ) : pass def set_cursor ( self , cursor ) : pass def define_cursor ( self , ctype , cursor ) : self . cursor [ ctype ] = cursor def get_cursor ( self , ctype ) : return self . cursor [ ctype ] def switch_cursor ( self , ctype ) : self . set_cursor ( self . cursor [ ctype ] ) def set_fg ( self , r , g , b ) : self . img_fg = ( r , g , b ) self . redraw ( whence = ) def onscreen_message ( self , text , delay = None ) : self . message = text self . redraw ( whence = ) if delay : time_ms = int ( delay * ) def onscreen_message_off ( self ) : return self . onscreen_message ( None ) def reschedule_redraw ( self , time_sec ) : if self . _defer_timer is None : self . delayed_redraw ( ) return time_ms = int ( time_sec * ) try : self . _defer_timer . interval = time_ms self . _defer_timer . start ( ) except Exception as e : self . logger . warning ( \"\" \"\" % ( str ( e ) ) ) self . delayed_redraw ( ) def show_pan_mark ( self , tf ) : self . t_ . set ( show_pan_position = tf ) self . redraw ( whence = ) def timer_cb ( self , * args ) : self . logger . info ( \"\" ) class ImageViewEvent ( ImageViewBokeh ) : def __init__ ( self , logger = None , rgbmap = None , settings = None ) : ImageViewBokeh . __init__ ( self , logger = logger , rgbmap = rgbmap , settings = settings ) self . last_win_x = self . last_win_y = self . last_data_x = self . last_data_y = self . enter_focus = self . t_ . get ( '' , True ) self . _keytbl = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , \"\" : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } hand = self . define_cursor ( '' , hand ) cross = self . define_cursor ( '' , cross ) for name in ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ) : self . enable_callback ( name ) def set_figure ( self , figure ) : super ( ImageViewEvent , self ) . set_figure ( figure ) def _setup_handlers ( self , source ) : source . on_change ( '' , self . select_event_cb ) self . _pan_tool = self . figure . select ( dict ( type = PanTool ) ) pass def transkey ( self , keyname ) : self . logger . debug ( \"\" % ( keyname ) ) if keyname is None : return keyname try : return self . _keytbl [ keyname . lower ( ) ] except KeyError : return keyname def get_keyTable ( self ) : return self . _keytbl def set_enter_focus ( self , tf ) : self . enter_focus = tf def focus_event ( self , event , hasFocus ) : return self . make_callback ( '' , hasFocus ) def enter_notify_event ( self , event ) : if self . enter_focus : self . focus_event ( event , True ) return self . make_callback ( '' ) def leave_notify_event ( self , event ) : self . logger . debug ( \"\" ) if self . enter_focus : self . focus_event ( event , False ) return self . make_callback ( '' ) def key_press_event ( self , event ) : keyname = event . key keyname = self . transkey ( keyname ) if keyname is not None : self . logger . debug ( \"\" % ( keyname ) ) return self . make_ui_callback ( '' , keyname ) def key_release_event ( self , event ) : keyname = event . key keyname = self . transkey ( keyname ) if keyname is not None : self . logger . debug ( \"\" % ( keyname ) ) return self . make_ui_callback ( '' , keyname ) def button_press_event ( self , event ) : x , y = event . x , event . y button = if event . button in ( , , ) : button |= << ( event . button - ) self . logger . debug ( \"\" % ( x , y , button ) ) data_x , data_y = self . get_data_xy ( x , y ) return self . make_ui_callback ( '' , button , data_x , data_y ) def button_release_event ( self , event ) : x , y = event . x , event . y button = if event . button in ( , , ) : button |= << ( event . button - ) self . logger . debug ( \"\" % ( x , y , button ) ) data_x , data_y = self . get_data_xy ( x , y ) return self . make_ui_callback ( '' , button , data_x , data_y ) def select_event_cb ( self , attrname , old_val , new_val ) : print ( \"\" % ( attrname , str ( new_val ) ) ) self . logger . info ( \"\" % ( attrname , str ( new_val ) ) ) def get_last_win_xy ( self ) : return ( self . last_win_x , self . last_win_y ) def get_last_data_xy ( self ) : return ( self . last_data_x , self . last_data_y ) def motion_notify_event ( self , event ) : button = x , y = event . x , event . y self . last_win_x , self . last_win_y = x , y if event . button in ( , , ) : button |= << ( event . button - ) self . logger . debug ( \"\" % ( x , y , button ) ) data_x , data_y = self . get_data_xy ( x , y ) self . last_data_x , self . last_data_y = data_x , data_y self . logger . debug ( \"\" % ( data_x , data_y ) ) return self . make_ui_callback ( '' , button , data_x , data_y ) def scroll_event ( self , event ) : x , y = event . x , event . y direction = None if event . step > : direction = elif event . step < : direction = amount = abs ( event . step ) * self . logger . debug ( \"\" % ( amount , direction ) ) data_x , data_y = self . get_data_xy ( x , y ) self . last_data_x , self . last_data_y = data_x , data_y return self . make_ui_callback ( '' , direction , amount , data_x , data_y ) ", "answer": "class ImageViewZoom ( Mixins . UIMixin , ImageViewEvent ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function from string import Template import pycuda . autoinit import pycuda . gpuarray as gpuarray from pycuda . compiler import SourceModule import numpy as np import skcuda . misc as misc A = B = C = N = A * B * C x_orig = np . asarray ( np . random . rand ( N ) , np . float64 ) x = x_orig . reshape ( ( A , B , C ) ) a = lambda i : i / ( B * C ) b = lambda i : np . mod ( i , B * C ) / C c = lambda i : np . mod ( np . mod ( i , B * C ) , C ) subscript = lambda i : ( a ( i ) , b ( i ) , c ( i ) ) for i in range ( x . size ) : assert x . flat [ i ] == x [ subscript ( i ) ] index = lambda i , j , k : i * B * C + j * C + k for i in range ( A ) : for j in range ( B ) : for k in range ( C ) : assert x [ i , j , k ] == x . flat [ index ( i , j , k ) ] func_mod_template = Template ( \"\"\"\"\"\" ) max_threads_per_block , max_block_dim , max_grid_dim = misc . get_dev_attrs ( pycuda . autoinit . device ) block_dim , grid_dim = misc . select_block_grid_sizes ( pycuda . autoinit . device , x . shape ) max_blocks_per_grid = max ( max_grid_dim ) func_mod = SourceModule ( func_mod_template . substitute ( max_threads_per_block = max_threads_per_block , max_blocks_per_grid = max_blocks_per_grid , A = A , B = B , C = C ) ) func = func_mod . get_function ( '' ) x_gpu = gpuarray . to_gpu ( x ) func ( x_gpu . gpudata , np . uint32 ( x_gpu . size ) , ", "answer": "block = block_dim ,"}, {"prompt": " '''''' __author__ = \"\" __date__ = \"\" __version__ = \"\" version_date = \"\" database_version = \"\" import httpserver import time import os import sys import getopt import yaml import nfvo_db from jsonschema import validate as js_v , exceptions as js_e from utils import auxiliary_functions as af from openmano_schemas import config_schema import nfvo global global_config def load_configuration ( configuration_file ) : default_tokens = { '' : , '' : '' } try : if not os . path . isfile ( configuration_file ) : return ( False , \"\" + configuration_file + \"\" ) ( return_status , code ) = af . read_file ( configuration_file ) if not return_status : return ( return_status , \"\" + configuration_file + \"\" + code ) try : config = yaml . load ( code ) except yaml . YAMLError , exc : error_pos = \"\" ", "answer": "if hasattr ( exc , '' ) :"}, {"prompt": " from django . contrib import admin from django . db import models from . models import Text from . widgets import HTMLEditorWidget class TextAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' , '' , ) search_fields = ( '' , ) formfield_overrides = { models . TextField : { '' : HTMLEditorWidget } , } ", "answer": "admin . site . register ( Text , TextAdmin ) "}, {"prompt": " import os import pytest from webtest import TestApp TEST_SETTINGS = { '' : os . environ . get ( '' , '' ) , '' : '' , '' : '' , '' : True , '' : True , '' : True , '' : os . environ . get ( '' , '' ) } ", "answer": "@ pytest . fixture"}, {"prompt": " from setuptools import setup , find_packages setup ( name = '' , version = '' , description = '' , author = '' , author_email = '' , url = '' , namespace_packages = [ '' ] , ", "answer": "packages = find_packages ( ) ,"}, {"prompt": " import os ", "answer": "DEBUG = False"}, {"prompt": " def stat_compute ( vuln_to_hosts , host_to_vulns ) : stat_vuln_count = len ( vuln_to_hosts ) stat_host_count = len ( host_to_vulns ) host_counts = { } most_pop_vuln = ( None , ) ", "answer": "for vuln , hosts in vuln_to_hosts . iteritems ( ) :"}, {"prompt": " \"\"\"\"\"\" __docformat__ = '' from os import curdir from os . path import exists , join as opj from . base import Interface from . . support . param import Parameter from . . support . constraints import EnsureStr , EnsureChoice from . . support . collectionrepo import CollectionRepo from datalad . support . collection_backends import CollectionRepoBackend from . . support . collection import MetaCollection , Collection from . . support . metadatahandler import CustomImporter , URIRef , Literal , DLNS , EMP , RDF , PAV , PROV , FOAF , DCTERMS from . . cmdline . helpers import get_repo_instance from . . log import lgr from datalad . cmdline . helpers import get_datalad_master from six . moves . urllib . parse import urlparse _OUTPUTS = ( '' , '' , '' ) ", "answer": "class SearchCollection ( Interface ) :"}, {"prompt": " from pig_util import outputSchema @ outputSchema ( '' ) def reverse ( word ) : \"\"\"\"\"\" return word [ : : - ] @ outputSchema ( '' ) def num_chars ( word ) : \"\"\"\"\"\" ", "answer": "return len ( word ) "}, {"prompt": " from __future__ import print_function import numpy import theano import theano . tensor as tt theano . config . floatX = '' rng = numpy . random N = feats = D = ( rng . randn ( N , feats ) . astype ( theano . config . floatX ) , rng . randint ( size = N , low = , high = ) . astype ( theano . config . floatX ) ) training_steps = x = tt . matrix ( \"\" ) y = tt . vector ( \"\" ) w = theano . shared ( rng . randn ( feats ) . astype ( theano . config . floatX ) , name = \"\" ) b = theano . shared ( numpy . asarray ( , dtype = theano . config . floatX ) , name = \"\" ) x . tag . test_value = D [ ] y . tag . test_value = D [ ] p_1 = / ( + tt . exp ( - tt . dot ( x , w ) - b ) ) prediction = p_1 > xent = - y * tt . log ( p_1 ) - ( - y ) * tt . log ( - p_1 ) cost = tt . cast ( xent . mean ( ) , '' ) + * ( w ** ) . sum ( ) gw , gb = tt . grad ( cost , [ w , b ] ) train = theano . function ( inputs = [ x , y ] , outputs = [ prediction , xent ] , updates = { w : w - * gw , b : b - * gb } , name = \"\" ) predict = theano . function ( inputs = [ x ] , outputs = prediction , name = \"\" ) if any ( [ x . op . __class__ . __name__ in [ '' , '' , '' , '' ] for x in train . maker . fgraph . toposort ( ) ] ) : print ( '' ) elif any ( [ x . op . __class__ . __name__ in [ '' , '' ] for x in train . maker . fgraph . toposort ( ) ] ) : print ( '' ) else : print ( '' ) print ( train . maker . fgraph . toposort ( ) ) for i in range ( training_steps ) : pred , err = train ( D [ ] , D [ ] ) print ( \"\" ) print ( D [ ] ) ", "answer": "print ( \"\" )"}, {"prompt": " \"\"\"\"\"\" import copy import gettext import locale from logging import handlers import os from babel import localedata import six _AVAILABLE_LANGUAGES = { } USE_LAZY = False class TranslatorFactory ( object ) : \"\"\"\"\"\" def __init__ ( self , domain , localedir = None ) : \"\"\"\"\"\" self . domain = domain if localedir is None : localedir = os . environ . get ( domain . upper ( ) + '' ) self . localedir = localedir def _make_translation_func ( self , domain = None ) : \"\"\"\"\"\" if domain is None : domain = self . domain t = gettext . translation ( domain , localedir = self . localedir , fallback = True ) m = t . gettext if six . PY3 else t . ugettext def f ( msg ) : \"\"\"\"\"\" if USE_LAZY : return Message ( msg , domain = domain ) return m ( msg ) return f @ property def primary ( self ) : \"\" return self . _make_translation_func ( ) def _make_log_translation_func ( self , level ) : return self . _make_translation_func ( self . domain + '' + level ) @ property def log_info ( self ) : \"\" return self . _make_log_translation_func ( '' ) @ property def log_warning ( self ) : \"\" return self . _make_log_translation_func ( '' ) @ property def log_error ( self ) : \"\" return self . _make_log_translation_func ( '' ) @ property def log_critical ( self ) : \"\" return self . _make_log_translation_func ( '' ) _translators = TranslatorFactory ( '' ) _ = _translators . primary _LI = _translators . log_info _LW = _translators . log_warning _LE = _translators . log_error _LC = _translators . log_critical def enable_lazy ( ) : \"\"\"\"\"\" global USE_LAZY USE_LAZY = True def install ( domain ) : \"\"\"\"\"\" from six import moves tf = TranslatorFactory ( domain ) moves . builtins . __dict__ [ '' ] = tf . primary class Message ( six . text_type ) : \"\"\"\"\"\" def __new__ ( cls , msgid , msgtext = None , params = None , domain = '' , * args ) : \"\"\"\"\"\" if not msgtext : msgtext = Message . _translate_msgid ( msgid , domain ) msg = super ( Message , cls ) . __new__ ( cls , msgtext ) msg . msgid = msgid msg . domain = domain msg . params = params return msg def translate ( self , desired_locale = None ) : \"\"\"\"\"\" translated_message = Message . _translate_msgid ( self . msgid , self . domain , desired_locale ) if self . params is None : return translated_message translated_params = _translate_args ( self . params , desired_locale ) translated_message = translated_message % translated_params return translated_message @ staticmethod def _translate_msgid ( msgid , domain , desired_locale = None ) : if not desired_locale : system_locale = locale . getdefaultlocale ( ) if not system_locale [ ] : desired_locale = '' ", "answer": "else :"}, {"prompt": " __author__ = \"\" \"\"\"\"\"\" from mock import Mock import os import unittest2 os . environ [ '' ] = '' from compass . utils import setting_wrapper as compass_setting reload ( compass_setting ) import config_data from compass . deployment . installers . config_manager import BaseConfigManager from compass . utils import flags from compass . utils import logsetting from plugins . chef_installer . implementation . chef_installer import ChefInstaller class TestChefInstaller ( unittest2 . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : super ( TestChefInstaller , self ) . setUp ( ) self . test_chef = self . _get_chef_installer ( ) def tearDown ( self ) : super ( TestChefInstaller , self ) . tearDown ( ) def _get_chef_installer ( self ) : adapter_info = config_data . adapter_test_config cluster_info = config_data . cluster_test_config hosts_info = config_data . hosts_test_config config_manager = BaseConfigManager ( adapter_info , cluster_info , hosts_info ) ChefInstaller . get_tmpl_path = Mock ( ) test_tmpl_dir = os . path . join ( os . path . join ( config_data . test_plugins_dir , '' ) , '' ) ChefInstaller . get_tmpl_path . return_value = test_tmpl_dir ChefInstaller . _get_chef_api = Mock ( ) ChefInstaller . _get_chef_api . return_value = '' ChefInstaller . get_all_roles = Mock ( ) ChefInstaller . get_all_roles . return_value = [ ] ChefInstaller . validate_roles = Mock ( ) ChefInstaller . validate_roles . return_value = True chef_installer = ChefInstaller ( config_manager ) return chef_installer def test_get_tmpl_vars ( self ) : pass def test_get_node_attributes ( self ) : cluster_dict = self . test_chef . _get_cluster_tmpl_vars ( ) vars_dict = self . test_chef . _get_host_tmpl_vars ( , cluster_dict ) expected_node_attr = { \"\" : { \"\" : { \"\" : { \"\" : { \"\" : \"\" } } } } } output = self . test_chef . _generate_node_attributes ( [ '' ] , vars_dict ) self . maxDiff = None self . assertDictEqual ( expected_node_attr , output ) def test_get_env_attributes ( self ) : expected_env = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : { } , \"\" : \"\" , \"\" : { \"\" : { \"\" : \"\" } } , \"\" : { \"\" : \"\" , \"\" : { \"\" : \"\" } , \"\" : { \"\" : { \"\" : \"\" } , \"\" : { \"\" : False } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } } , \"\" : { \"\" : { \"\" : \"\" } } , \"\" : { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : True , \"\" : \"\" } , \"\" : { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : { \"\" : \"\" } } , \"\" : { \"\" : { \"\" : [ \"\" ] , \"\" : { \"\" : False } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : True , \"\" : { \"\" : \"\" \"\" } } , \"\" : { \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : \"\" , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } } , \"\" : { \"\" : False } , \"\" : False , \"\" : True , \"\" : { \"\" : True , \"\" : { \"\" : False } , \"\" : { \"\" : \"\" } } , \"\" : { \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : False } , \"\" : { \"\" : { \"\" : False ", "answer": "} ,"}, {"prompt": " import pytz import numbers from hashlib import md5 from datetime import datetime from zipline . protocol import DATASOURCE_TYPE from six import iteritems , b def hash_args ( * args , ** kwargs ) : \"\"\"\"\"\" arg_string = '' . join ( [ str ( arg ) for arg in args ] ) kwarg_string = '' . join ( [ str ( key ) + '' + str ( value ) for key , value in iteritems ( kwargs ) ] ) combined = '' . join ( [ arg_string , kwarg_string ] ) hasher = md5 ( ) hasher . update ( b ( combined ) ) return hasher . hexdigest ( ) def assert_datasource_protocol ( event ) : \"\"\"\"\"\" assert event . type in DATASOURCE_TYPE if not event . type == DATASOURCE_TYPE . DONE : assert isinstance ( event . dt , datetime ) assert event . dt . tzinfo == pytz . utc def assert_trade_protocol ( event ) : \"\"\"\"\"\" assert_datasource_protocol ( event ) assert event . type == DATASOURCE_TYPE . TRADE ", "answer": "assert isinstance ( event . price , numbers . Real )"}, {"prompt": " import unittest import sys from os . path import realpath , dirname __usage__ = '''''' def show_detail ( items ) : for i in items : print repr ( i ) def show_test_result ( result ) : print print \"\" print result print print \"\" print show_detail ( result . errors ) print print \"\" print show_detail ( result . failures ) print ", "answer": "print \"\""}, {"prompt": " from gevent . event import Event , AsyncResult , Timeout from six . moves import xrange __all__ = [ '' , '' , '' ] class AsyncResultWrapper ( object ) : def __init__ ( self ) : self . async_result = None def create ( self ) : if self . async_result is not None : assert False , '' self . async_result = AsyncResult ( ) def get ( self , * args , ** kwargs ) : try : result = self . async_result . get ( * args , ** kwargs ) except Timeout : result = None self . async_result = None return result def set ( self , * args , ** kwargs ) : ", "answer": "if self . async_result is not None :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ", "answer": "( '' , '' ) ,"}, {"prompt": " import os ", "answer": "import re"}, {"prompt": " import gc import os import time from datetime import datetime , date , timedelta from optparse import make_option from django . core . files . storage import get_storage_class from django . core . management . base import BaseCommand from easy_thumbnails . conf import settings from easy_thumbnails . models import Source class ThumbnailCollectionCleaner ( object ) : \"\"\"\"\"\" sources = thumbnails = thumbnails_deleted = source_refs_deleted = execution_time = def _get_absolute_path ( self , path ) : return os . path . join ( settings . MEDIA_ROOT , path ) def _get_relative_path ( self , path ) : return os . path . relpath ( path , settings . MEDIA_ROOT ) def _check_if_exists ( self , storage , path ) : try : return storage . exists ( path ) except Exception as e : print ( \"\" % path ) print ( str ( e ) ) def _delete_sources_by_id ( self , ids ) : Source . objects . all ( ) . filter ( id__in = ids ) . delete ( ) def clean_up ( self , dry_run = False , verbosity = , last_n_days = , cleanup_path = None , storage = None ) : \"\"\"\"\"\" if dry_run : print ( \"\" ) if not storage : storage = get_storage_class ( settings . THUMBNAIL_DEFAULT_STORAGE ) ( ) sources_to_delete = [ ] time_start = time . time ( ) query = Source . objects . all ( ) if last_n_days > : today = date . today ( ) query = query . filter ( modified__range = ( today - timedelta ( days = last_n_days ) , today ) ) if cleanup_path : query = query . filter ( name__startswith = cleanup_path ) for source in queryset_iterator ( query ) : self . sources += abs_source_path = self . _get_absolute_path ( source . name ) if not self . _check_if_exists ( storage , abs_source_path ) : if verbosity > : print ( \"\" , abs_source_path ) self . source_refs_deleted += sources_to_delete . append ( source . id ) for thumb in source . thumbnails . all ( ) : self . thumbnails_deleted += abs_thumbnail_path = self . _get_absolute_path ( thumb . name ) if self . _check_if_exists ( storage , abs_thumbnail_path ) : if not dry_run : storage . delete ( abs_thumbnail_path ) if verbosity > : print ( \"\" , abs_thumbnail_path ) if len ( sources_to_delete ) >= and not dry_run : self . _delete_sources_by_id ( sources_to_delete ) sources_to_delete = [ ] if not dry_run : self . _delete_sources_by_id ( sources_to_delete ) self . execution_time = round ( time . time ( ) - time_start ) def print_stats ( self ) : \"\"\"\"\"\" print ( \"\" . format ( str ( datetime . now ( ) . strftime ( '' ) ) ) ) print ( \"\" . format ( \"\" , self . sources ) ) print ( \"\" . format ( \"\" , self . source_refs_deleted ) ) print ( \"\" . format ( \"\" , self . thumbnails_deleted ) ) print ( \"\" % self . execution_time ) def queryset_iterator ( queryset , chunksize = ) : \"\"\"\"\"\" primary_key = last_pk = queryset . order_by ( '' ) [ ] . pk queryset = queryset . order_by ( '' ) while primary_key < last_pk : for row in queryset . filter ( pk__gt = primary_key ) [ : chunksize ] : primary_key = row . pk yield row gc . collect ( ) class Command ( BaseCommand ) : ", "answer": "help = \"\"\"\"\"\""}, {"prompt": " from django . db import models from django . utils . translation import ugettext_lazy as _ from sellmo . core . loading import load import sellmo . contrib . checkout . mailing as _checkout_mailing @ load ( action = '' ) def finalize_model ( ) : class OrderMailMessage ( _checkout_mailing . models . OrderMailMessage ) : objects = ( _checkout_mailing . models . OrderMailMessageManager . from_queryset ( _checkout_mailing . models . OrderMailMessageQuerySet ) ) ( ) class Meta ( _checkout_mailing . models . OrderMailMessage . Meta ) : ", "answer": "app_label = ''"}, {"prompt": " import os import sys import urllib2 import argparse import time import multiprocessing as mp import glob from sets import Set \"\"\"\"\"\" def main ( ) : parser = argparse . ArgumentParser ( description = \"\" ) parser . add_argument ( '' , action = \"\" , help = \"\" ) result = parser . parse_args ( ) fileList = glob . glob ( result . path + '' ) newFileList = Set ( [ ] ) keyFileList = Set ( range ( , ) ) for name in fileList : fileNumber = int ( name . split ( '' ) [ ] . split ( '' ) [ ] ) newFileList . add ( fileNumber ) print keyFileList . difference ( newFileList ) if __name__ == \"\" : ", "answer": "main ( ) "}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from django . conf import settings from django . db import models from django . utils import timezone from sentry . db . models import ( BoundedBigIntegerField , FlexibleForeignKey , Model , BaseManager , sane_repr ) class ProjectBookmark ( Model ) : \"\"\"\"\"\" __core__ = True project_id = BoundedBigIntegerField ( blank = True , null = True ) user = FlexibleForeignKey ( settings . AUTH_USER_MODEL ) date_added = models . DateTimeField ( default = timezone . now , null = True ) objects = BaseManager ( ) class Meta : ", "answer": "app_label = ''"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) from collections import namedtuple class ScopeInfo ( namedtuple ( '' , [ '' , '' , '' ] ) ) : \"\"\"\"\"\" GLOBAL = '' TASK = '' SUBSYSTEM = '' INTERMEDIATE = '' @ property ", "answer": "def description ( self ) :"}, {"prompt": " import os import ast import sys import math import time import string import hashlib import tempfile import subprocess from operator import itemgetter from contextlib import contextmanager from getpass import getpass import random ; random = random . SystemRandom ( ) import sdb . subprocess_compat as subprocess from sdb . util import force_bytes from sdb . clipboard import set_clipboard_once , ClipboardException from sdb . diceware import WORDS from sdb import gpg_agent def encode ( records ) : res = [ ] for record in records : res . append ( repr ( record ) ) return ( '' . join ( res ) + '' ) . encode ( '' ) def decode ( str ) : records = [ ] for line in str . decode ( '' ) . split ( '' ) : if line : records . append ( ast . literal_eval ( line ) ) return records CASE_ALPHABET = string . ascii_letters ALPHANUMERIC = CASE_ALPHABET + string . digits EVERYTHING = ALPHANUMERIC + string . punctuation def gen_password ( choices = ALPHANUMERIC , length = ) : return '' . join ( random . choice ( choices ) for i in range ( length ) ) def requirements_satisfied ( requirements , str ) : return all ( [ i in str for i in requirements ] ) def gen_password_require ( requirements , choices = ALPHANUMERIC , length = ) : \"\"\"\"\"\" if len ( requirements ) > length or not requirements_satisfied ( requirements , choices ) : raise Exception ( \"\" % ( requirements , choices ) ) while True : pw = gen_password ( choices , length ) if requirements_satisfied ( requirements , pw ) : return pw def gen_password_entropy ( entropy , choices = ALPHANUMERIC ) : \"\"\"\"\"\" required_length = int ( math . ceil ( entropy / math . log ( len ( choices ) , ) ) ) return gen_password ( choices = choices , length = required_length ) def match ( needle , haystack ) : score = j = last_match = for c in needle : while j < len ( haystack ) and haystack [ j ] != c : j += if j >= len ( haystack ) : return score += / ( last_match + ) last_match = j j += return score def record_score ( term , records ) : return match ( term , records [ ] + records [ ] + records [ ] ) def search ( term , records ) : records = [ ( record_score ( term , i ) , i ) for i in records ] records = list ( filter ( itemgetter ( ) , records ) ) records . sort ( key = itemgetter ( ) , reverse = True ) return [ i [ ] for i in records ] def is_unique_list ( lst ) : return len ( lst ) == len ( set ( lst ) ) def disambiguate ( records ) : choices = [ itemgetter ( ) , itemgetter ( , ) , itemgetter ( , , ) ] for choice in choices : result = list ( map ( choice , records ) ) if is_unique_list ( result ) : return result return records class GPGException ( Exception ) : pass class IncorrectPasswordException ( GPGException ) : pass class InvalidEncryptedFileException ( GPGException ) : pass class FileCorruptionException ( GPGException ) : pass def gpg_exception_factory ( returncode , message ) : if returncode == : if b'' in message : return IncorrectPasswordException ( message ) if b'' in message : return FileCorruptionException ( message ) ", "answer": "if b'' in message :"}, {"prompt": " import io from unittest import TestCase , main import numpy as np from skbio import TreeNode from skbio . tree import majority_rule from skbio . tree . _majority_rule import ( _walk_clades , _filter_clades , _build_trees ) class MajorityRuleTests ( TestCase ) : def test_majority_rule ( self ) : trees = [ TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) ] exp = TreeNode . read ( io . StringIO ( \"\" ) ) obs = majority_rule ( trees ) self . assertEqual ( exp . compare_subsets ( obs [ ] ) , ) self . assertEqual ( len ( obs ) , ) tree = obs [ ] exp_supports = sorted ( [ , , , , , ] ) obs_supports = sorted ( [ n . support for n in tree . non_tips ( ) ] ) self . assertEqual ( obs_supports , exp_supports ) obs = majority_rule ( trees , weights = np . ones ( len ( trees ) ) * ) self . assertEqual ( exp . compare_subsets ( obs [ ] ) , ) self . assertEqual ( len ( obs ) , ) tree = obs [ ] exp_supports = sorted ( [ , , , , , ] ) obs_supports = sorted ( [ n . support for n in tree . non_tips ( ) ] ) with self . assertRaises ( ValueError ) : majority_rule ( trees , weights = [ , ] ) def test_majority_rule_multiple_trees ( self ) : trees = [ TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) ] trees = majority_rule ( trees ) self . assertEqual ( len ( trees ) , ) exp = set ( [ frozenset ( [ '' ] ) , frozenset ( [ '' ] ) , frozenset ( [ None , '' , '' ] ) , frozenset ( [ None , '' , '' ] ) ] ) obs = set ( [ frozenset ( [ n . name for n in t . traverse ( ) ] ) for t in trees ] ) self . assertEqual ( obs , exp ) def test_walk_clades ( self ) : trees = [ TreeNode . read ( io . StringIO ( \"\" ) ) , TreeNode . read ( io . StringIO ( \"\" ) ) ] exp_clades = [ ( frozenset ( [ '' ] ) , ) , ( frozenset ( [ '' ] ) , ) , ( frozenset ( [ '' , '' ] ) , ) , ( frozenset ( [ '' , '' ] ) , ) , ( frozenset ( [ '' , '' , '' , '' ] ) , ) , ( frozenset ( [ '' ] ) , ) , ( frozenset ( [ '' ] ) , ) , ( frozenset ( [ '' ] ) , ) , ( frozenset ( [ '' , '' ] ) , ) , ( frozenset ( [ '' , '' , '' ] ) , ) , ( frozenset ( [ '' , '' , '' , '' , '' ] ) , ) ] exp_lengths_nolength = { frozenset ( [ '' ] ) : None , frozenset ( [ '' ] ) : None , frozenset ( [ '' , '' ] ) : None , frozenset ( [ '' , '' ] ) : None , frozenset ( [ '' , '' , '' , '' ] ) : None , ", "answer": "frozenset ( [ '' ] ) : None ,"}, {"prompt": " import datetime import os . path import unittest import json import logging import esbench . analyze import esbench . api import esbench . test . test_api class ApiCallsTest ( unittest . TestCase ) : def test_get_benchmarks ( self ) : conn = esbench . api . Conn ( conn_cls = esbench . test . test_api . MockHTTPConnection ) resp = esbench . analyze . _get_benchmarks ( conn ) self . assertEqual ( resp . curl , '' % esbench . STATS_INDEX_NAME ) def test_get_observations ( self ) : conn = esbench . api . Conn ( conn_cls = esbench . test . test_api . MockHTTPConnection ) resp = esbench . analyze . _get_observations ( conn = conn , benchmark_id = '' ) self . assertEqual ( resp . curl , '' % ( esbench . STATS_INDEX_NAME , ) ) class DataTest ( unittest . TestCase ) : def setUp ( self ) : self . tmp_get_benchmarks = esbench . analyze . _get_benchmarks esbench . analyze . _get_benchmarks = lambda ** kwargs : esbench . api . ApiResponse ( status = , reason = '' , data = r\"\"\"\"\"\" , curl = '' , ) self . tmp_get_observations = esbench . analyze . _get_observations esbench . analyze . _get_observations = lambda ** kwargs : esbench . api . ApiResponse ( status = , reason = '' , data = r\"\"\"\"\"\" , curl = '' ) def tearDown ( self ) : esbench . analyze . _get_benchmarks = self . tmp_get_benchmarks esbench . analyze . _get_observations = self . tmp_get_observations def test_benchmarks ( self ) : self . assertEqual ( , len ( list ( esbench . analyze . _benchmarks ( resp = esbench . analyze . _get_benchmarks ( ) ) ) ) ) self . assertEqual ( , len ( list ( esbench . analyze . _benchmarks ( resp = esbench . analyze . _get_benchmarks ( ) , benchmark_ids = [ '' , '' ] ) ) ) ) self . assertEqual ( , len ( list ( esbench . analyze . _benchmarks ( resp = esbench . analyze . _get_benchmarks ( ) , benchmark_ids = [ '' ] ) ) ) ) resp = esbench . api . ApiResponse ( status = , reason = '' , data = '' , curl = '' ) ", "answer": "self . assertEqual ( , len ( list ( esbench . analyze . _benchmarks ( resp = resp ) ) ) )"}, {"prompt": " from flask . ext . wtf import Form from wtforms . fields import StringField , SubmitField from wtforms . validators import Required class LoginForm ( Form ) : \"\"\"\"\"\" ", "answer": "name = StringField ( '' , validators = [ Required ( ) ] )"}, {"prompt": " '''''' __all__ = ( '' , '' , '' ) from kivy . event import EventDispatcher from kivy . properties import StringProperty , ObjectProperty , AliasProperty knspace = None '''''' class KNSpace ( EventDispatcher ) : '''''' parent = None '''''' __has_applied = None def __init__ ( self , parent = None , ** kwargs ) : super ( KNSpace , self ) . __init__ ( ** kwargs ) self . parent = parent self . __has_applied = set ( self . properties ( ) . keys ( ) ) def __setattr__ ( self , name , value ) : prop = super ( KNSpace , self ) . property ( name , quiet = True ) has_applied = self . __has_applied if prop is None : ", "answer": "if hasattr ( self , name ) :"}, {"prompt": " import logging from abc import ABCMeta , abstractmethod , abstractproperty import six as six from couchdbkit import ResourceNotFound from dimagi . utils . decorators . memoized import memoized from couchforms import const class AbstractXFormInstance ( object ) : user_id = None @ property def attachments ( self ) : \"\"\"\"\"\" raise NotImplementedError @ property def form_data ( self ) : raise NotImplementedError ( ) @ property def metadata ( self ) : raise NotImplementedError ( ) @ property def is_normal ( self ) : raise NotImplementedError ( ) @ property def is_archived ( self ) : raise NotImplementedError ( ) @ property def is_deprecated ( self ) : raise NotImplementedError ( ) @ property def is_duplicate ( self ) : raise NotImplementedError ( ) @ property def is_error ( self ) : raise NotImplementedError ( ) @ property def is_submission_error_log ( self ) : raise NotImplementedError ( ) @ property def is_deleted ( self ) : raise NotImplementedError ( ) def auth_context ( self ) : raise NotImplementedError ( ) def get_data ( self , xpath ) : raise NotImplementedError ( ) def get_attachment ( self , attachment_name ) : raise NotImplementedError ( ) def archive ( self , user_id = None ) : raise NotImplementedError ( ) def unarchive ( self , user_id = None ) : raise NotImplementedError ( ) def get_xml_element ( self ) : raise NotImplementedError ( ) def get_xml ( self ) : raise NotImplementedError ( ) def save ( self , * args , ** kwargs ) : raise NotImplementedError ( ) def set_submission_properties ( self , submission_post ) : raise NotImplementedError ( ) def soft_delete ( self ) : raise NotImplementedError ( ) def to_json ( self ) : raise NotImplementedError ( ) @ classmethod def get ( self , xform_id ) : raise NotImplementedError ( ) @ property def xml_md5 ( self ) : raise NotImplementedError ( ) @ property def version ( self ) : return self . form_data . get ( const . TAG_VERSION , \"\" ) @ property def uiversion ( self ) : return self . form_data . get ( const . TAG_UIVERSION , \"\" ) @ property def type ( self ) : return self . form_data . get ( const . TAG_TYPE , \"\" ) @ memoized def get_sync_token ( self ) : from casexml . apps . phone . models import get_properly_wrapped_sync_log if self . last_sync_token : try : return get_properly_wrapped_sync_log ( self . last_sync_token ) except ResourceNotFound : logging . exception ( '' . format ( self . last_sync_token , self . form_id , self . domain , ) ) raise return None class AbstractCommCareCase ( object ) : @ property def case_name ( self ) : raise NotImplementedError ( ) @ property def parent ( self ) : raise NotImplementedError ( ) def soft_delete ( self ) : raise NotImplementedError ( ) def get_attachment ( self , attachment_name ) : raise NotImplementedError ( ) def is_deleted ( self ) : raise NotImplementedError ( ) def dynamic_case_properties ( self ) : raise NotImplementedError ( ) def get_actions_for_form ( self , xform ) : raise NotImplementedError def modified_since_sync ( self , sync_log ) : raise NotImplementedError def get_subcases ( self ) : raise NotImplementedError def get_case_property ( self , property ) : raise NotImplementedError def to_json ( self ) : raise NotImplementedError ( ) def to_api_json ( self ) : raise NotImplementedError ( ) @ memoized def get_index_map ( self , reversed = False ) : return dict ( [ ( index . identifier , { \"\" : index . referenced_type , \"\" : index . referenced_id , \"\" : index . relationship , } ) for index in ( self . indices if not reversed else self . reverse_indices ) ] ) def get_properties_in_api_format ( self ) : return dict ( self . dynamic_case_properties ( ) . items ( ) + { \"\" : self . external_id , \"\" : self . owner_id , \"\" : self . name , \"\" : self . type , \"\" : self . opened_on , } . items ( ) ) @ memoized def get_attachment_map ( self ) : return dict ( [ ( name , { '' : self . get_attachment_server_url ( att . identifier ) , '' : att . attachment_from } ) for name , att in self . case_attachments . items ( ) ] ) def to_xml ( self , version , include_case_on_closed = False ) : from xml . etree import ElementTree from casexml . apps . phone . xml import get_case_element if self . closed : if include_case_on_closed : elem = get_case_element ( self , ( '' , '' , '' ) , version ) else : elem = get_case_element ( self , ( '' ) , version ) else : elem = get_case_element ( self , ( '' , '' ) , version ) return ElementTree . tostring ( elem ) def get_attachment_server_url ( self , identifier ) : \"\"\"\"\"\" if identifier in self . case_attachments : from dimagi . utils import web from django . core . urlresolvers import reverse return \"\" % ( web . get_url_base ( ) , reverse ( \"\" , kwargs = { \"\" : self . domain , \"\" : self . case_id , ", "answer": "\"\" : identifier ,"}, {"prompt": " from shakespeare . tests import * import shakespeare . model as model import shakespeare . tests . test_stats class TestStatsController ( TestController ) : def setUp ( self ) : self . text = make_fixture ( ) self . text2 = make_fixture2 ( ) shakespeare . tests . test_stats . stats_fixture ( self . text ) def tearDown ( self ) : model . metadata . drop_all ( ) model . metadata . create_all ( ) def test_index ( self ) : url = url_for ( controller = '' , action = '' ) ", "answer": "res = self . app . get ( url )"}, {"prompt": " from django . apps import AppConfig from . import monkey_patch_user from guardian . conf import settings class GuardianConfig ( AppConfig ) : name = '' def ready ( self ) : ", "answer": "if settings . MONKEY_PATCH :"}, {"prompt": " '''''' from docpie import docpie if __name__ == '' : ", "answer": "print ( docpie ( __doc__ , name = '' ) ) "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " \"\"\"\"\"\" import os os . environ . setdefault ( \"\" , \"\" ) ", "answer": "from django . core . wsgi import get_wsgi_application"}, {"prompt": " \"\"\"\"\"\" from traits . has_traits import HasTraits from traits . trait_types import List , Int , Str from traitsui . item import Item from traitsui . view import View from traitsui . editors . list_str_editor import ListStrEditor from traitsui . tests . _tools import ( press_ok_button , skip_if_not_qt4 , skip_if_not_wx , store_exceptions_on_all_threads ) class ListStrEditorWithSelectedIndex ( HasTraits ) : values = List ( Str ( ) ) selected_index = Int ( ) selected_indices = List ( Int ( ) ) selected = Str ( ) single_select_view = View ( Item ( '' , show_label = False , editor = ListStrEditor ( selected_index = '' , editable = False ) , ) , buttons = [ '' ] ) multi_select_view = View ( Item ( '' , show_label = False , editor = ListStrEditor ( multi_select = True , selected_index = '' , editable = False ) , ) , ", "answer": "buttons = [ '' ] )"}, {"prompt": " from __future__ import absolute_import , unicode_literals from django . test . client import RequestFactory from drf_toolbox import serializers from drf_toolbox . compat import django_pgfields_installed , models from drf_toolbox . viewsets import ModelViewSet from rest_framework . request import Request from rest_framework . decorators import link from tests import models as test_models from tests . compat import mock from tests . views import * import unittest import uuid NO_DJANGOPG = '' class ModelViewSetTests ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . request = Request ( RequestFactory ( ) . get ( '' ) ) def test_get_queryset ( self ) : \"\"\"\"\"\" mvs = ModelViewSet ( ) with mock . patch . object ( ModelViewSet . mro ( ) [ ] , '' ) as m : qs = mvs . get_queryset ( ) self . assertEqual ( qs , m . return_value ) def test_get_queryset_with_kwargs ( self ) : \"\"\"\"\"\" mvs = ModelViewSet ( kwargs = { '' : } ) with mock . patch . object ( ModelViewSet . mro ( ) [ ] , '' ) as m : m . return_value = mock . MagicMock ( ) qs = mvs . get_queryset ( ) self . assertEqual ( m . return_value . mock_calls , [ mock . call . filter ( foo__pk = ) ] ) def test_get_serializer ( self ) : \"\"\"\"\"\" class ViewSet ( ModelViewSet ) : model = test_models . NormalModel @ link ( ) def foo ( self , request , pk ) : return '' vs = ViewSet ( request = self . request , kwargs = { } , format_kwarg = '' ) serializer = vs . get_serializer ( ) self . assertIsInstance ( serializer , serializers . ModelSerializer ) self . assertEqual ( serializer . context [ '' ] , [ '' ] ) def test_parser_classes_standard ( self ) : \"\"\"\"\"\" vs = NormalViewSet ( request = RequestFactory ( ) . options ( '' , HTTP_ACCEPT = '' ) , format_kwarg = '' , ) result = vs . options ( self . request ) self . assertEqual ( result . data [ '' ] , [ '' , '' , '' , ] ) @ unittest . skipUnless ( django_pgfields_installed , NO_DJANGOPG ) def test_parser_classes_with_composite_field ( self ) : \"\"\"\"\"\" class CompositeModel ( models . Model ) : foo = test_models . CoordsField ( ) class Meta : app_label = '' class CompositeViewSet ( ModelViewSet ) : model = CompositeModel cvs = CompositeViewSet ( request = RequestFactory ( ) . options ( '' , HTTP_ACCEPT = '' ) , format_kwarg = '' , ) result = cvs . options ( self . request ) self . assertEqual ( result . data [ '' ] , [ '' ] ) @ unittest . skipUnless ( django_pgfields_installed , NO_DJANGOPG ) def test_parser_classes_with_special_composite_field ( self ) : \"\"\"\"\"\" class CompositeModel ( models . Model ) : foo = test_models . SizeField ( ) class Meta : app_label = '' class CompositeViewSet ( ModelViewSet ) : model = CompositeModel cvs = CompositeViewSet ( request = RequestFactory ( ) . options ( '' , HTTP_ACCEPT = '' ) , format_kwarg = '' , ) result = cvs . options ( self . request ) self . assertEqual ( result . data [ '' ] , [ '' ] ) @ unittest . skipUnless ( django_pgfields_installed , NO_DJANGOPG ) def test_parser_classes_with_special_composite_field_passthrough ( self ) : \"\"\"\"\"\" ", "answer": "class CompositeModel ( models . Model ) :"}, {"prompt": " from tests . functional import browser , testcase from tests . pages . base import Page from tests . pages . admin import Signup @ testcase ( ) def test_signup ( ) : browser . open ( '' ) page = Page ( ) assert page . offers_signup_link page . click_signup_link ( ) page = Signup ( ) assert page . offers_signup_form foo = page . signup_form foo . fill ( dict ( username = '' , password = '' ) ) ", "answer": "foo . submit ( )"}, {"prompt": " from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from builtins import range from future import standard_library standard_library . install_aliases ( ) import sys PYTHON_VERSION = sys . version_info [ : ] PY2 = ( PYTHON_VERSION [ ] == ) if PY2 : if PYTHON_VERSION < ( , , ) : raise Exception ( '' ) elif PYTHON_VERSION < ( , ) : raise Exception ( '' ) import hpOneView as hpov from pprint import pprint def acceptEULA ( con ) : con . get_eula_status ( ) try : if con . get_eula_status ( ) is True : print ( '' ) con . set_eula ( '' ) except Exception as e : print ( '' ) print ( e ) def login ( con , credential ) : try : con . login ( credential ) except : print ( '' ) def getpolicy ( sts ) : policy = sts . get_storage_vol_template_policy ( ) print ( policy [ '' ] ) def main ( ) : ", "answer": "parser = argparse . ArgumentParser ( add_help = True ,"}, {"prompt": " import argparse import empaths import numpy as np import urllib , urllib2 import cStringIO import zlib import sys import tempfile import h5py def main ( ) : parser = argparse . ArgumentParser ( description = '' ) parser . add_argument ( '' , action = \"\" ) parser . add_argument ( '' , action = \"\" ) parser . add_argument ( '' , action = \"\" , type = int ) parser . add_argument ( '' , action = \"\" , type = int ) parser . add_argument ( '' , action = \"\" , type = int ) parser . add_argument ( '' , action = \"\" , type = int ) parser . add_argument ( '' , action = \"\" , type = int ) parser . add_argument ( '' , action = \"\" , type = int ) parser . add_argument ( '' , action = \"\" , type = int ) parser . add_argument ( '' , action = \"\" , type = int , help = '' , default = ) parser . add_argument ( '' , action = '' ) parser . add_argument ( '' , action = '' ) parser . add_argument ( '' , action = '' ) parser . add_argument ( '' , action = '' , help = '' ) parser . add_argument ( '' , action = '' , help = '' ) result = parser . parse_args ( ) anndata = np . ones ( [ result . zhigh - result . zlow , result . yhigh - result . ylow , result . xhigh - result . xlow ] ) tmpfile = tempfile . NamedTemporaryFile ( ) h5fh = h5py . File ( tmpfile . name ) idgrp = h5fh . create_group ( str ( result . annid ) ) idgrp . create_dataset ( \"\" , ( , ) , np . uint32 , data = result . resolution ) idgrp . create_dataset ( \"\" , ( , ) , np . uint32 , data = [ result . xlow , result . ylow , result . zlow ] ) idgrp . create_dataset ( \"\" , anndata . shape , np . uint32 , data = anndata ) if result . preserve : url = '' % ( result . baseurl , result . token ) elif result . exception : url = '' % ( result . baseurl , result . token ) elif result . reduce : url = '' % ( result . baseurl , result . token ) else : url = '' % ( result . baseurl , result . token ) if result . update : url += '' if result . dataonly : url += '' print url try : h5fh . flush ( ) tmpfile . seek ( ) req = urllib2 . Request ( url , tmpfile . read ( ) ) response = urllib2 . urlopen ( req ) except urllib2 . URLError , e : ", "answer": "print \"\" , url"}, {"prompt": " import win32gui import win32con import win32api import time import math import os import sys import re if sys . version_info . major == : from urllib import pathname2url as urllib_pathname2url else : from urllib . request import pathname2url as urllib_pathname2url g_debug = False g_windows = { } g_registeredClasses = { } def Debug ( msg ) : if not g_debug : return msg = \"\" + str ( msg ) print ( msg ) with open ( GetRealPath ( \"\" ) , \"\" ) as file : file . write ( msg + \"\" ) def GetRealPath ( file = None , encodeURL = False ) : if file is None : file = \"\" ", "answer": "if file . find ( \"\" ) != and file . find ( \"\" ) != and not re . search ( r\"\" , file ) :"}, {"prompt": " import time from . . azurectl_exceptions import ( AzureRequestStatusError , AzureRequestTimeout , AzureRequestError ) class RequestResult ( object ) : \"\"\"\"\"\" def __init__ ( self , request_id ) : self . request_id = request_id self . request_timeout_count = self . request_timeout = def status ( self , service ) : \"\"\"\"\"\" try : return service . get_operation_status ( self . request_id ) except Exception as e : raise AzureRequestStatusError ( '' % ( type ( e ) . __name__ , format ( e ) ) ) def wait_for_request_completion ( self , service ) : \"\"\"\"\"\" count = result = self . status ( service ) while result . status == '' : count = count + if count > self . request_timeout_count : raise AzureRequestTimeout ( '' % self . request_id ) ", "answer": "time . sleep ( self . request_timeout )"}, {"prompt": " from djangocms_blog . models import thumbnail_model from south . utils import datetime_utils as datetime from south . db import db from south . v2 import SchemaMigration from django . db import models from djangocms_blog . settings import get_setting class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( default = get_setting ( '' ) , max_length = ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( '' , '' ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' } ) } , '' : { '' : { '' : '' , '' : \"\" , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' , '' : '' } ) ,"}, {"prompt": " \"\"\"\"\"\" try : import sqlalchemy as sql HAS_SQLALCHEMY = True except ImportError : HAS_SQLALCHEMY = False try : import psycopg2 HAS_POSTGRES = True except ImportError : HAS_POSTGRES = False try : import _mysql HAS_MYSQL = True except ImportError : HAS_MYSQL = False import datetime import unittest from flask import Blueprint from test import FlaskTrackUsageTestCase from flask_track_usage import TrackUsage from flask_track_usage . storage . sql import SQLStorage @ unittest . skipUnless ( HAS_SQLALCHEMY , \"\" ) class TestSQLiteStorage ( FlaskTrackUsageTestCase ) : def _create_storage ( self ) : engine = sql . create_engine ( \"\" ) metadata = sql . MetaData ( bind = engine ) self . storage = SQLStorage ( engine = engine , metadata = metadata , table_name = self . given_table_name ) metadata . create_all ( ) def tearDown ( self ) : meta = sql . MetaData ( ) meta . reflect ( bind = self . storage . _eng ) for table in reversed ( meta . sorted_tables ) : self . storage . _eng . execute ( table . delete ( ) ) def setUp ( self ) : self . given_table_name = '' FlaskTrackUsageTestCase . setUp ( self ) self . blueprint = Blueprint ( '' , __name__ ) @ self . blueprint . route ( '' ) def blueprint ( ) : return \"\" self . app . register_blueprint ( self . blueprint ) self . _create_storage ( ) self . track_usage = TrackUsage ( self . app , self . storage ) self . track_usage . include_blueprint ( self . blueprint ) def test_table_name ( self ) : meta = sql . MetaData ( ) meta . reflect ( bind = self . storage . _eng ) assert self . given_table_name == meta . tables . keys ( ) [ ] def test_storage_data_basic ( self ) : self . client . get ( '' ) con = self . storage . _eng . connect ( ) s = sql . select ( [ self . storage . track_table ] ) result = con . execute ( s ) . fetchone ( ) assert result [ ] == u'' assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] == assert result [ ] is None assert result [ ] == None assert result [ ] == False assert result [ ] is None assert result [ ] == '' assert result [ ] . __class__ is float assert type ( result [ ] ) is datetime . datetime def test_storage_data_blueprint ( self ) : self . client . get ( '' ) con = self . storage . _eng . connect ( ) s = sql . select ( [ self . storage . track_table ] ) result = con . execute ( s ) . fetchone ( ) assert result [ ] == u'' assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] == '' assert result [ ] == assert result [ ] is None assert result [ ] is None assert result [ ] == False assert result [ ] is None assert result [ ] == '' assert result [ ] . __class__ is float assert type ( result [ ] ) is datetime . datetime def test_storage__get_raw ( self ) : self . client . get ( '' ) result = self . storage . _get_raw ( ) [ ] assert result [ ] == u'' assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] == assert result [ ] is None assert result [ ] is None assert result [ ] == False assert result [ ] is None assert result [ ] == '' assert result [ ] . __class__ is float assert type ( result [ ] ) is datetime . datetime self . client . get ( '' ) rows = self . storage . _get_raw ( ) print rows [ ] result = rows [ ] assert result [ ] == u'' assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] is None assert result [ ] == '' assert result [ ] == assert result [ ] is None assert result [ ] is None assert result [ ] == False ", "answer": "assert result [ ] is None"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import os from pandas . compat import StringIO import numpy as np _int64_max = np . iinfo ( np . int64 ) . max warning_to_new_contributors = \"\"\"\"\"\" header = \"\"\"\"\"\" inner_take_1d_template = \"\"\"\"\"\" take_1d_template = \"\"\"\"\"\" + inner_take_1d_template + \"\"\"\"\"\" + inner_take_1d_template inner_take_2d_axis0_template = \"\"\"\"\"\" take_2d_axis0_template = \"\"\"\"\"\" + inner_take_2d_axis0_template + \"\"\"\"\"\" + inner_take_2d_axis0_template inner_take_2d_axis1_template = \"\"\"\"\"\" take_2d_axis1_template = \"\"\"\"\"\" + inner_take_2d_axis1_template + \"\"\"\"\"\" + inner_take_2d_axis1_template take_2d_multi_template = \"\"\"\"\"\" \"\"\"\"\"\" backfill_template = \"\"\"\"\"\" pad_template = \"\"\"\"\"\" pad_1d_template = \"\"\"\"\"\" pad_2d_template = \"\"\"\"\"\" backfill_2d_template = \"\"\"\"\"\" backfill_1d_template = \"\"\"\"\"\" diff_2d_template = \"\"\"\"\"\" is_monotonic_template = '''''' map_indices_template = '''''' groupby_template = '''''' group_last_template = '''''' group_nth_template = '''''' group_add_template = '''''' group_prod_template = '''''' group_var_template = '''''' group_max_template = '''''' group_min_template = '''''' group_mean_template = '''''' group_ohlc_template = '''''' arrmap_template = '''''' left_join_unique_template = '''''' left_join_template = '''''' inner_join_template = '''''' outer_join_template2 = '''''' outer_join_template = '''''' ensure_dtype_template = \"\"\"\"\"\" ensure_functions = [ ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ] def generate_ensure_dtypes ( ) : output = StringIO ( ) for name , ctype , dtype in ensure_functions : filled = ensure_dtype_template % locals ( ) output . write ( filled ) return output . getvalue ( ) put2d_template = \"\"\"\"\"\" grouping_no_template = '''''' def generate_put_template ( template , use_ints = True , use_floats = True , use_objects = False , use_datelikes = False ) : floats_list = [ ( '' , '' , '' , '' , True ) , ( '' , '' , '' , '' , True ) , ] ints_list = [ ( '' , '' , '' , '' , True ) , ( '' , '' , '' , '' , True ) , ( '' , '' , '' , '' , True ) , ( '' , '' , '' , '' , True ) , ] date_like_list = [ ( '' , '' , '' , '' , True ) , ] object_list = [ ( '' , '' , '' , '' , False ) ] function_list = [ ] if use_floats : function_list . extend ( floats_list ) if use_ints : function_list . extend ( ints_list ) if use_objects : function_list . extend ( object_list ) if use_datelikes : function_list . extend ( date_like_list ) output = StringIO ( ) for name , c_type , dest_type , dest_dtype , nogil in function_list : func = template % { '' : name , '' : c_type , '' : dest_type . replace ( '' , '' ) , '' : dest_type , '' : dest_dtype , '' : '' if nogil else '' , '' : '' if nogil else '' } output . write ( func ) output . write ( \"\" ) return output . getvalue ( ) def generate_put_min_max_template ( template , use_ints = True , use_floats = True , use_objects = False , use_datelikes = False ) : floats_list = [ ( '' , '' , '' , '' , True ) , ( '' , '' , '' , '' , True ) , ] ints_list = [ ( '' , '' , '' , _int64_max , True ) , ] date_like_list = [ ( '' , '' , '' , _int64_max , True ) , ] object_list = [ ( '' , '' , '' , '' , False ) ] function_list = [ ] if use_floats : function_list . extend ( floats_list ) if use_ints : function_list . extend ( ints_list ) if use_objects : function_list . extend ( object_list ) if use_datelikes : function_list . extend ( date_like_list ) output = StringIO ( ) for name , dest_type , nan_val , inf_val , nogil in function_list : func = template % { '' : name , '' : dest_type , '' : nan_val , '' : inf_val , '' : \"\" if nogil else '' , '' : '' if nogil else '' } output . write ( func ) output . write ( \"\" ) return output . getvalue ( ) def generate_put_selection_template ( template , use_ints = True , use_floats = True , use_objects = False , use_datelikes = False ) : floats_list = [ ( '' , '' , '' , '' , True ) , ( '' , '' , '' , '' , True ) , ] ints_list = [ ( '' , '' , '' , '' , True ) , ] date_like_list = [ ( '' , '' , '' , '' , True ) , ] object_list = [ ( '' , '' , '' , '' , False ) ] function_list = [ ] if use_floats : function_list . extend ( floats_list ) if use_ints : function_list . extend ( ints_list ) if use_objects : function_list . extend ( object_list ) if use_datelikes : function_list . extend ( date_like_list ) output = StringIO ( ) for name , c_type , dest_type , nan_val , nogil in function_list : if nogil : nogil = \"\" tab = '' else : nogil = '' tab = '' func = template % { '' : name , '' : c_type , '' : dest_type , '' : nan_val , '' : nogil , '' : tab } output . write ( func ) output . write ( \"\" ) return output . getvalue ( ) def generate_take_template ( template , exclude = None ) : function_list = [ ( '' , '' , '' , '' , '' , '' , True , True ) , ( '' , '' , '' , '' , '' , '' , False , False ) , ( '' , '' , '' , '' , '' , '' , True , False ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , True , True ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , True , True ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , True , True ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , True , True ) , ( '' , '' , '' , '' , '' , '' , False , True ) , ( '' , '' , '' , '' , '' , '' , True , True ) , ( '' , '' , '' , '' , '' , '' , False , False ) , ] output = StringIO ( ) for ( name , dest , c_type_in , c_type_out , preval , postval , can_copy , nogil ) in function_list : if exclude is not None and name in exclude : continue if nogil : nogil = \"\" tab = '' else : nogil = '' tab = '' func = template % { '' : name , '' : dest , '' : c_type_in , '' : c_type_out , '' : preval , '' : postval , '' : '' if can_copy else '' , '' : nogil , '' : tab } output . write ( func ) output . write ( \"\" ) return output . getvalue ( ) def generate_from_template ( template , exclude = None ) : function_list = [ ( '' , '' , '' , True , True ) , ( '' , '' , '' , True , True ) , ( '' , '' , '' , True , False ) , ( '' , '' , '' , False , True ) , ( '' , '' , '' , False , True ) , ( '' , '' , '' , False , True ) ] output = StringIO ( ) for name , c_type , dtype , can_hold_na , nogil in function_list : if exclude is not None and name in exclude : continue func = template % { '' : name , '' : c_type , ", "answer": "'' : dtype ,"}, {"prompt": " from facerec . normalization import minmax import os as os import numpy as np import matplotlib . pyplot as plt ", "answer": "import matplotlib . cm as cm"}, {"prompt": " from nose . tools import * import weigh_in def test_inverses ( ) : \"\"\"\"\"\" vals = [ ( , ) , ( , None ) , ( , ) , ( , ) , ( , ) ] for current_size , prev_size in vals : desc = weigh_in . format_description ( current_size , prev_size ) ", "answer": "back_cur_size , back_prev_size = weigh_in . parse_description ( desc )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Tangible ( )"}, {"prompt": " LANGUAGES = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } def _get_languages ( languages ) : if languages is None or not len ( languages ) : languages = [ '' ] supported = [ ] for lang in languages : if lang is None or len ( lang . strip ( ) ) not in [ , ] : ", "answer": "continue"}, {"prompt": " import mahotas as mh def test_citation ( ) : from sys import stdout t = mh . citation ( False ) assert len ( stdout . getvalue ( ) ) == t2 = mh . citation ( True ) ", "answer": "assert len ( stdout . getvalue ( ) ) != "}, {"prompt": " import re from twisted . internet import protocol from twisted . protocols . basic import LineReceiver def sanitizeMetric ( name ) : \"\"\"\"\"\" name = re . sub ( '' , '' , name ) name = re . sub ( '' , '' , name ) name = re . sub ( '' , '' , name ) return name . encode ( '' ) def sanitizeMetricElement ( element ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import os , sys def parse_translation ( f , lineno ) : \"\"\"\"\"\" line = f . readline ( ) def get_line ( f , line , need_keys , lineno , default = '' ) : line = line . rstrip ( ) if not line : return lineno , need_keys [ ] , default , line key , value = line . split ( '' , ) if key not in need_keys : print '' % ( need_keys , lineno , line ) raise RuntimeError ( \"\" ) v = value while : line = f . readline ( ) line = line . rstrip ( ) lineno += if not line or line [ ] != '' : break v += '' + line [ : ] return lineno , key , v , line comments = [ ] while : if not line : return lineno , None , None , None if line . strip ( ) == '' : return lineno , comments , None , None elif line [ ] == '' : comments . append ( line [ : - ] ) else : break line = f . readline ( ) lineno += lineno , key , msgid , line = get_line ( f , line , [ '' ] , lineno ) lineno , key , value , line = get_line ( f , line , [ '' , '' ] , lineno ) if key == '' : msgid = ( msgid , value ) lineno , key , v1 , line = get_line ( f , line , [ '' ] , lineno ) lineno , key , v2 , line = get_line ( f , line , [ '' ] , lineno ) msgstr = ( v1 , v2 ) else : msgstr = value if line != '' : print '' % ( f . name , line ) raise RuntimeError ( \"\" ) return lineno , comments , msgid , msgstr def split_comments ( comments ) : \"\"\"\"\"\" flags = [ ] other = [ ] for c in comments : if len ( c ) > and c [ ] == '' : flags . append ( c ) else : other . append ( c ) return flags , other def write_msg ( comments , msgid , msgstr ) : s = [ ] s . append ( '' . join ( comments ) + '' ) if isinstance ( msgid , ( tuple , list ) ) : s . append ( '' + msgid [ ] + '' ) s . append ( '' + msgid [ ] + '' ) else : s . append ( '' + msgid + '' ) if isinstance ( msgstr , ( tuple , list ) ) : s . append ( '' + msgstr [ ] + '' ) if msgstr [ ] != '' : s . append ( '' ) else : s . append ( '' + msgstr [ ] + '' ) else : s . append ( '' + msgstr + '' ) return '' . join ( s ) def merge ( file1 , file2 , exact = False ) : \"\"\"\"\"\" import shutil if not os . path . exists ( file1 ) : shutil . copyfile ( file2 , file1 ) return source = { } f2 = file ( file2 ) lineno = while : lineno , comments , msgid , msgstr = parse_translation ( f2 , lineno ) if comments is None and msgid is None and msgstr is None : break if msgid is not None and msgid != '' and msgid != ( '' , '' ) : source [ msgid ] = msgstr , split_comments ( comments ) [ ] f2 . close ( ) infile = file1 + '' shutil . copyfile ( file1 , infile ) outfile = open ( file1 , '' ) string_count = update_count = untranslated = removed = f1 = file ( infile ) lineno = while : lineno , comments , msgid , msgstr = parse_translation ( f1 , lineno ) if comments is None and msgid is None and msgstr is None : break if msgid is None : continue else : if msgid != '' and msgid != ( '' , '' ) : string_count += if msgid != '' : if msgid in source : new_flags , comments = split_comments ( comments ) new_msgstr , new_comments = source [ msgid ] del source [ msgid ] if ( new_msgstr != msgstr and new_msgstr != '' and new_msgstr != ( '' , '' ) ) or new_comments != comments : if new_msgstr != msgstr and new_msgstr != '' and new_msgstr != ( '' , '' ) : update_count += msgstr = new_msgstr else : comments = new_comments else : if exact : removed += continue outfile . write ( write_msg ( comments , msgid , msgstr ) ) if msgid != '' and ( msgstr == '' or msgstr == ( '' , '' ) ) : untranslated += _len = len ( source ) if _len : update_count += _len string_count += _len for msgid , _v in source . iteritems ( ) : msgstr , comments = _v outfile . write ( write_msg ( comments , msgid , msgstr ) ) if msgid != '' and msgstr == '' : untranslated += f1 . close ( ) outfile . close ( ) if string_count == : print '' else : ", "answer": "print ( ''"}, {"prompt": " MAIL_SERVER = '' MAIL_PORT = MAIL_USE_TLS = False MAIL_USE_SSL = True ", "answer": "MAIL_USERNAME = ''"}, {"prompt": " \"\"\"\"\"\" import unittest import logging from thespian . actors import ActorSystem ", "answer": "def simpleActorTestLogging ( ) :"}, {"prompt": " from __future__ import absolute_import from django . contrib import admin from . models import Product , Option admin . site . register ( Product ) ", "answer": "admin . site . register ( Option ) "}, {"prompt": " import subprocess from base import Base class GitMixin ( Base ) : ", "answer": "def get_revision_list ( self ) :"}, {"prompt": " import sys if \"\" not in sys . path : sys . path . insert ( , \"\" ) import ply . yacc as yacc from calclex import tokens names = { } def p_statement_assign ( t ) : '' names [ t [ ] ] = t [ ] def p_statement_expr ( t ) : '' print ( t [ ] ) def p_expression_binop ( t ) : '''''' if t [ ] == '' : t [ ] = t [ ] + t [ ] elif t [ ] == '' : t [ ] = t [ ] - t [ ] elif t [ ] == '' : t [ ] = t [ ] * t [ ] elif t [ ] == '' : t [ ] = t [ ] / t [ ] def p_expression_uminus ( t ) : '' t [ ] = - t [ ] def p_expression_group ( t ) : '' t [ ] = t [ ] def p_expression_number ( t ) : '' t [ ] = t [ ] def p_expression_name ( t ) : '' try : t [ ] = names [ t [ ] ] except LookupError : print ( \"\" % t [ ] ) t [ ] = ", "answer": "def p_error ( t ) :"}, {"prompt": " from . error import TweepError class Cursor ( object ) : \"\"\"\"\"\" def __init__ ( self , method , * args , ** kargs ) : if hasattr ( method , '' ) : if method . pagination_mode == '' : self . iterator = CursorIterator ( method , args , kargs ) elif method . pagination_mode == '' : self . iterator = IdIterator ( method , args , kargs ) elif method . pagination_mode == '' : self . iterator = PageIterator ( method , args , kargs ) else : raise TweepError ( '' ) else : raise TweepError ( '' ) def pages ( self , limit = ) : \"\"\"\"\"\" if limit > : self . iterator . limit = limit return self . iterator def items ( self , limit = ) : \"\"\"\"\"\" i = ItemIterator ( self . iterator ) i . limit = limit return i class BaseIterator ( object ) : def __init__ ( self , method , args , kargs ) : self . method = method self . args = args self . kargs = kargs self . limit = def next ( self ) : raise NotImplementedError def prev ( self ) : raise NotImplementedError def __iter__ ( self ) : return self class CursorIterator ( BaseIterator ) : def __init__ ( self , method , args , kargs ) : BaseIterator . __init__ ( self , method , args , kargs ) self . next_cursor = - self . prev_cursor = self . count = def next ( self ) : if self . next_cursor == or ( self . limit and self . count == self . limit ) : raise StopIteration data , cursors = self . method ( cursor = self . next_cursor , * self . args , ** self . kargs ) self . prev_cursor , self . next_cursor = cursors if len ( data ) == : raise StopIteration self . count += return data def prev ( self ) : if self . prev_cursor == : raise TweepError ( '' ) data , self . next_cursor , self . prev_cursor = self . method ( cursor = self . prev_cursor , * self . args , ** self . kargs ) self . count -= return data class IdIterator ( BaseIterator ) : def __init__ ( self , method , args , kargs ) : BaseIterator . __init__ ( self , method , args , kargs ) self . max_id = kargs . get ( '' ) self . since_id = kargs . get ( '' ) ", "answer": "self . count = "}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AddField ( model_name = '' , name = '' , field = models . BooleanField ( default = False ) , preserve_default = True , ) , ", "answer": "] "}, {"prompt": " from django . test import TestCase ", "answer": "import unittest "}, {"prompt": " from cloudferry . lib . utils . cache import Memoized , Cached from tests import test class MemoizationTestCase ( test . TestCase ) : def test_treats_self_as_separate_objects ( self ) : class C ( object ) : def __init__ ( self , i ) : self . i = i @ Memoized def get_i ( self ) : return self . i o1 = C ( ) o2 = C ( ) self . assertNotEqual ( o1 . get_i ( ) , o2 . get_i ( ) ) self . assertEqual ( o1 . get_i ( ) , ) self . assertEqual ( o2 . get_i ( ) , ) def test_takes_value_from_cache ( self ) : class C ( object ) : def __init__ ( self , i ) : self . i = i @ Memoized def get_i ( self ) : return self . i def set_i ( self , i ) : self . i = i original = o = C ( original ) self . assertEqual ( o . get_i ( ) , original ) o . set_i ( ) self . assertEqual ( o . get_i ( ) , original ) ", "answer": "class CacheTestCase ( test . TestCase ) :"}, {"prompt": " from __future__ import absolute_import ", "answer": "from . . api import HasTraits , Property"}, {"prompt": " import ngsutils . bam import ngsutils . bam . export import ngsutils . bam . basecall import ngsutils . bed import StringIO import collections PileupRecords = collections . namedtuple ( '' , '' ) PileupRead = collections . namedtuple ( '' , '' ) def assertIn ( foo , bar ) : for el in bar : if foo == el : return True return False def assertNotIn ( foo , bar ) : for el in bar : if foo == el : return False return True def _matches ( valid , queries ) : extra = False check = [ False , ] * len ( valid ) for q in queries : found = False ", "answer": "for i , v in enumerate ( valid ) :"}, {"prompt": " import unittest import GafferTest import GafferUI class NumericSliderTest ( unittest . TestCase ) : def testConstruction ( self ) : s = GafferUI . NumericSlider ( value = , min = , max = ) self . assertEqual ( s . getPosition ( ) , ) self . assertEqual ( s . getValue ( ) , ) self . assertEqual ( s . getRange ( ) , ( , , , ) ) def testSetValue ( self ) : s = GafferUI . NumericSlider ( value = , min = , max = ) self . assertEqual ( s . getPosition ( ) , ) self . assertEqual ( s . getValue ( ) , ) s . setValue ( ) self . assertEqual ( s . getPosition ( ) , ) self . assertEqual ( s . getValue ( ) , ) def testSetRange ( self ) : s = GafferUI . NumericSlider ( value = , min = , max = ) self . assertEqual ( s . getPosition ( ) , ) self . assertEqual ( s . getValue ( ) , ) s . setRange ( , ) self . assertEqual ( s . getPosition ( ) , ) self . assertEqual ( s . getValue ( ) , ) def testSetZeroRange ( self ) : s = GafferUI . NumericSlider ( value = , min = , max = ) self . assertEqual ( s . getPosition ( ) , ) self . assertEqual ( s . getValue ( ) , ) s . setRange ( , ) self . assertEqual ( s . getValue ( ) , ) def testSetPosition ( self ) : s = GafferUI . NumericSlider ( value = , min = , max = ) self . assertEqual ( s . getPosition ( ) , ) self . assertEqual ( s . getValue ( ) , ) s . setPosition ( ) self . assertEqual ( s . getPosition ( ) , ) self . assertEqual ( s . getValue ( ) , ) ", "answer": "def testValuesOutsideRangeAreClamped ( self ) :"}, {"prompt": " \"\"\"\"\"\" kernel = ( ( - , - , - ) , ( - , , - ) , ( - , - , - ) ) size ( , ) img = loadImage ( \"\" ) image ( img , , ) img . loadPixels ( ) ; edgeImg = createImage ( img . width , img . height , RGB ) for y in range ( , img . height - ) : for x in range ( , img . width - ) : sum = for ky in ( - , , ) : for kx in ( - , , ) : pos = ( y + ky ) * img . width + ( x + kx ) val = red ( img . pixels [ pos ] ) sum += kernel [ ky + ] [ kx + ] * val edgeImg . pixels [ y * img . width + x ] = color ( sum ) ", "answer": "edgeImg . updatePixels ( )"}, {"prompt": " from couchdbkit import ResourceNotFound import datetime import dateutil from django . core import cache from django . core . urlresolvers import reverse , NoReverseMatch from django . template . defaultfilters import yesno from django . utils import html from django . utils . translation import ugettext as _ import json from casexml . apps . case . models import CommCareCaseAction from corehq . apps . groups . models import Group from corehq . apps . locations . models import SQLLocation from corehq . apps . users . models import CommCareUser , CouchUser from corehq . util . dates import iso_string_to_datetime from corehq . util . view_utils import absolute_reverse from dimagi . utils . decorators . memoized import memoized class CaseInfo ( object ) : def __init__ ( self , report , case ) : \"\"\"\"\"\" self . case = case self . report = report @ property def case_type ( self ) : return self . case [ '' ] @ property def case_name ( self ) : return self . case [ '' ] @ property def case_name_display ( self ) : return self . case_name or _ ( '' ) @ property def case_id ( self ) : return self . case [ '' ] @ property def external_id ( self ) : return self . case [ '' ] @ property def case_detail_url ( self ) : try : return absolute_reverse ( '' , args = [ self . report . domain , self . case_id ] ) except NoReverseMatch : return None @ property def is_closed ( self ) : return self . case [ '' ] def _dateprop ( self , prop , iso = True ) : val = self . report . date_to_json ( self . parse_date ( self . case [ prop ] ) ) if iso : val = '' . join ( val . split ( '' ) ) if val else None return val @ property def opened_on ( self ) : return self . _dateprop ( '' ) @ property def modified_on ( self ) : return self . _dateprop ( '' ) @ property def closed_on ( self ) : return self . _dateprop ( '' ) @ property def creating_user ( self ) : try : creator_id = self . case [ '' ] except KeyError : creator_id = None if '' in self . case : for action in self . case [ '' ] : if action [ '' ] == '' : action_doc = CommCareCaseAction . wrap ( action ) creator_id = action_doc . get_user_id ( ) break if not creator_id : return None return self . _user_meta ( creator_id ) def _user_meta ( self , user_id ) : return { '' : user_id , '' : self . _get_username ( user_id ) } @ property @ memoized def location ( self ) : try : return SQLLocation . objects . get ( location_id = self . owner_id ) except SQLLocation . DoesNotExist : return None @ property def owner ( self ) : if self . owning_group and self . owning_group . name : return ( '' , { '' : self . owning_group . _id , '' : self . owning_group . name } ) elif self . location : return ( '' , { '' : self . location . location_id , '' : self . location . display_name } ) else : return ( '' , self . _user_meta ( self . user_id ) ) @ property def owner_type ( self ) : return self . owner [ ] @ property def user_id ( self ) : return self . report . individual or self . owner_id @ property def owner_id ( self ) : if '' in self . case : return self . case [ '' ] elif '' in self . case : return self . case [ '' ] else : return '' @ property @ memoized def owning_group ( self ) : mc = cache . caches [ '' ] cache_key = \"\" % ( Group . __class__ . __name__ , self . owner_id ) try : if mc . has_key ( cache_key ) : cached_obj = json . loads ( mc . get ( cache_key ) ) wrapped = Group . wrap ( cached_obj ) return wrapped else : group_obj = Group . get ( self . owner_id ) mc . set ( cache_key , json . dumps ( group_obj . to_json ( ) ) ) return group_obj except Exception : return None @ memoized def _get_username ( self , user_id ) : username = self . report . usernames . get ( user_id ) if not username : mc = cache . caches [ '' ] cache_key = \"\" % ( CouchUser . __class__ . __name__ , user_id ) try : if mc . has_key ( cache_key ) : user_dict = json . loads ( mc . get ( cache_key ) ) else : user_obj = CouchUser . get_by_user_id ( user_id ) if user_id else None if user_obj : user_dict = user_obj . to_json ( ) else : user_dict = { } cache_payload = json . dumps ( user_dict ) mc . set ( cache_key , cache_payload ) if user_dict == { } : return None else : user_obj = CouchUser . wrap ( user_dict ) username = user_obj . username except Exception : return None return username def parse_date ( self , date_string ) : try : return iso_string_to_datetime ( date_string ) except : try : date_obj = dateutil . parser . parse ( date_string ) if isinstance ( date_obj , datetime . datetime ) : return date_obj . replace ( tzinfo = None ) else : return date_obj except : return date_string class CaseDisplay ( CaseInfo ) : @ property def closed_display ( self ) : return yesno ( self . is_closed , \"\" ) @ property def case_link ( self ) : url = self . case_detail_url if url : return html . mark_safe ( \"\" % ( self . case_detail_url , html . escape ( self . case_name_display ) ) ) else : return \"\" % self . case_name @ property def opened_on ( self ) : return self . _dateprop ( '' , False ) @ property def modified_on ( self ) : return self . _dateprop ( '' , False ) @ property def owner_display ( self ) : owner_type , owner = self . owner if owner_type == '' : return '' % owner [ '' ] else : return owner [ '' ] def user_not_found_display ( self , user_id ) : return _ ( \"\" ) % user_id @ property ", "answer": "def creating_user ( self ) :"}, {"prompt": " import collections as col import numpy as np import matplotlib as mpl import matplotlib . backends . backend_agg as mbb from jmpy import common from jmpy . plotting import components def boxplot ( x , y , data = None , legend = None , marker = '' , alpha = , points = True , cumprob = False , yscale = '' , cmap = '' , figsize = ( , ) , orderby = None , table = True , fig = None , axes = None , cgrid = None , violin = False , ** kwargs ) : \"\"\"\"\"\" if data is None : ( x , y , _ , legend , _ , _ ) , data = components . create_df ( x , y , legend ) df = data . copy ( ) df = df . reset_index ( ) df [ x ] = df [ x ] . astype ( '' ) df [ y ] = df [ y ] . astype ( '' ) . dropna ( ) if orderby : temp = df . sort ( x ) t = temp . groupby ( x ) [ orderby ] map_of_x = col . OrderedDict ( ) for mg in sorted ( t . groups ) : g = t . get_group ( mg ) . reset_index ( ) map_of_x [ mg ] = g [ orderby ] [ ] list_to_order = sorted ( [ value for value in map_of_x . values ( ) ] ) order = [ ] x_to_loc = { } for k , v in map_of_x . items ( ) : idx = list_to_order . index ( v ) x_to_loc [ k ] = idx order . append ( idx ) min_ , max_ = np . min ( df [ y ] ) , np . max ( df [ y ] ) if fig and not axes : fig = fig canvas = mbb . FigureCanvasAgg ( fig ) axm , axc , axl , axt = components . get_axes ( fig ) elif axes : axm = axes else : fig = mpl . figure . Figure ( figsize = figsize , tight_layout = True ) canvas = mbb . FigureCanvasAgg ( fig ) axm , axc , axl , axt = components . create_axes ( cumprob , legend , table , fig = fig ) if violin : array = [ ] for arr in sorted ( set ( df [ x ] ) ) : array . append ( df [ df [ x ] == arr ] [ y ] ) axm . violinplot ( array , showmedians = True ) else : if orderby : df . boxplot ( column = y , by = x , ax = axm , showfliers = False , positions = order , fontsize = , ** kwargs ) else : df . boxplot ( column = y , by = x , ax = axm , showfliers = False , fontsize = , ** kwargs ) unique_groups = set ( df [ x ] ) nonan_grps = [ ] for group in unique_groups : if '' not in group : nonan_grps . append ( group ) ", "answer": "if legend :"}, {"prompt": " from PyQt4 . QtCore import Qt from PyQt4 . QtGui import QTableView , QAbstractItemView class EditableTableView ( QTableView ) : def keyPressEvent ( self , event ) : if event . key ( ) == Qt . Key_Return and self . state ( ) != QAbstractItemView . EditingState : selected = self . selectionModel ( ) . selectedIndexes ( ) ", "answer": "if selected :"}, {"prompt": " import clr clr . AddReferenceByPartialName ( \"\" ) import System . Windows . Forms . Clipboard as cb def GetClipboardText ( ) : text = \"\" if cb . ContainsText ( ) : ", "answer": "text = cb . GetText ( )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) ", "answer": "result . template = \"\""}, {"prompt": " \"\"\"\"\"\" import asyncore import socket import cPickle as pickle from time import time as _time , sleep as _sleep from StringIO import StringIO from . debugging import ModuleLogger , DebugContents , bacpypes_debugging from . core import deferred from . task import FunctionTask , OneShotFunction from . comm import PDU , Client , Server from . comm import ServiceAccessPoint , ApplicationServiceElement _debug = _log = ModuleLogger ( globals ( ) ) REBIND_SLEEP_INTERVAL = class PickleActorMixIn : def __init__ ( self , * args ) : if _debug : PickleActorMixIn . _debug ( \"\" , args ) super ( PickleActorMixIn , self ) . __init__ ( * args ) self . pickleBuffer = '' def indication ( self , pdu ) : if _debug : PickleActorMixIn . _debug ( \"\" , pdu ) pdu . pduData = pickle . dumps ( pdu . pduData ) super ( PickleActorMixIn , self ) . indication ( pdu ) def response ( self , pdu ) : if _debug : PickleActorMixIn . _debug ( \"\" , pdu ) self . pickleBuffer += pdu . pduData strm = StringIO ( self . pickleBuffer ) pos = while ( pos < strm . len ) : try : msg = pickle . load ( strm ) except : break rpdu = PDU ( msg ) rpdu . update ( pdu ) super ( PickleActorMixIn , self ) . response ( rpdu ) pos = strm . tell ( ) if ( pos < strm . len ) : self . pickleBuffer = self . pickleBuffer [ pos : ] else : self . pickleBuffer = '' bacpypes_debugging ( PickleActorMixIn ) class TCPClient ( asyncore . dispatcher ) : def __init__ ( self , peer ) : if _debug : TCPClient . _debug ( \"\" , peer ) asyncore . dispatcher . __init__ ( self ) self . create_socket ( socket . AF_INET , socket . SOCK_STREAM ) self . peer = peer self . request = '' self . socketError = None if _debug : TCPClient . _debug ( \"\" ) self . connect ( peer ) if _debug : TCPClient . _debug ( \"\" ) def handle_connect ( self ) : if _debug : deferred ( TCPClient . _debug , \"\" ) def handle_expt ( self ) : pass def readable ( self ) : return def handle_read ( self ) : if _debug : deferred ( TCPClient . _debug , \"\" ) try : msg = self . recv ( ) if _debug : deferred ( TCPClient . _debug , \"\" , len ( msg ) ) self . socketError = None if not self . socket : if _debug : deferred ( TCPClient . _debug , \"\" ) else : deferred ( self . response , PDU ( msg ) ) except socket . error , err : if ( err . args [ ] == ) : deferred ( TCPClient . _error , \"\" , self . peer ) else : deferred ( TCPClient . _error , \"\" , err ) self . socketError = err def writable ( self ) : return ( len ( self . request ) != ) def handle_write ( self ) : if _debug : deferred ( TCPClient . _debug , \"\" ) try : sent = self . send ( self . request ) if _debug : deferred ( TCPClient . _debug , \"\" , sent , len ( self . request ) - sent ) self . socketError = None self . request = self . request [ sent : ] except socket . error , err : if ( err . args [ ] == ) : deferred ( TCPClient . _error , \"\" , self . peer ) else : deferred ( TCPClient . _error , \"\" , err ) self . socketError = err def handle_close ( self ) : if _debug : deferred ( TCPClient . _debug , \"\" ) self . close ( ) self . socket = None def indication ( self , pdu ) : \"\"\"\"\"\" if _debug : TCPClient . _debug ( \"\" , pdu ) self . request += pdu . pduData bacpypes_debugging ( TCPClient ) class TCPClientActor ( TCPClient ) : def __init__ ( self , director , peer ) : if _debug : TCPClientActor . _debug ( \"\" , director , peer ) TCPClient . __init__ ( self , peer ) self . director = director self . timeout = director . timeout if self . timeout > : self . timer = FunctionTask ( self . idle_timeout ) self . timer . install_task ( _time ( ) + self . timeout ) else : self . timer = None self . flushTask = None self . director . add_actor ( self ) def handle_close ( self ) : if _debug : TCPClientActor . _debug ( \"\" ) if self . flushTask : self . flushTask . suspend_task ( ) if self . timer : self . timer . suspend_task ( ) self . director . remove_actor ( self ) TCPClient . handle_close ( self ) def idle_timeout ( self ) : if _debug : TCPClientActor . _debug ( \"\" ) self . handle_close ( ) def indication ( self , pdu ) : if _debug : TCPClientActor . _debug ( \"\" , pdu ) if self . flushTask : if _debug : TCPServerActor . _debug ( \"\" ) return if self . timer : self . timer . install_task ( _time ( ) + self . timeout ) TCPClient . indication ( self , pdu ) def response ( self , pdu ) : if _debug : TCPClientActor . _debug ( \"\" , pdu ) pdu . pduSource = self . peer if self . timer : self . timer . install_task ( _time ( ) + self . timeout ) self . director . response ( pdu ) def flush ( self ) : if _debug : TCPClientActor . _debug ( \"\" ) self . flushTask = None if self . request : self . flushTask = OneShotFunction ( self . flush ) return self . handle_close ( ) bacpypes_debugging ( TCPClientActor ) class TCPPickleClientActor ( PickleActorMixIn , TCPClientActor ) : pass class TCPClientDirector ( Server , ServiceAccessPoint , DebugContents ) : _debug_contents = ( '' , '' , '' , '' ) def __init__ ( self , timeout = , actorClass = TCPClientActor , sid = None , sapID = None ) : if _debug : TCPClientDirector . _debug ( \"\" , timeout , actorClass , sid , sapID ) Server . __init__ ( self , sid ) ServiceAccessPoint . __init__ ( self , sapID ) if not issubclass ( actorClass , TCPClientActor ) : raise TypeError ( \"\" ) self . actorClass = actorClass self . timeout = timeout self . clients = { } self . reconnect = { } def add_actor ( self , actor ) : \"\"\"\"\"\" if _debug : TCPClientDirector . _debug ( \"\" , actor ) self . clients [ actor . peer ] = actor if self . serviceElement : self . sap_request ( addPeer = actor . peer ) def remove_actor ( self , actor ) : \"\"\"\"\"\" if _debug : TCPClientDirector . _debug ( \"\" , actor ) del self . clients [ actor . peer ] if self . serviceElement : self . sap_request ( delPeer = actor . peer ) if actor . peer in self . reconnect : connect_task = FunctionTask ( self . connect , actor . peer ) connect_task . install_task ( _time ( ) + self . reconnect [ actor . peer ] ) def get_actor ( self , address ) : \"\"\"\"\"\" return self . clients . get ( address , None ) def connect ( self , address , reconnect = ) : if _debug : TCPClientDirector . _debug ( \"\" , address , reconnect ) if address in self . clients : return client = self . actorClass ( self , address ) if _debug : TCPClientDirector . _debug ( \"\" , client ) if reconnect : self . reconnect [ address ] = reconnect def disconnect ( self , address ) : if _debug : TCPClientDirector . _debug ( \"\" , address ) if address not in self . clients : return if address in self . reconnect : del self . reconnect [ address ] self . clients [ address ] . handle_close ( ) def indication ( self , pdu ) : \"\"\"\"\"\" if _debug : TCPClientDirector . _debug ( \"\" , pdu ) addr = pdu . pduDestination client = self . clients . get ( addr , None ) if not client : client = self . actorClass ( self , addr ) client . indication ( pdu ) bacpypes_debugging ( TCPClientDirector ) class TCPServer ( asyncore . dispatcher ) : def __init__ ( self , sock , peer ) : if _debug : TCPServer . _debug ( \"\" , sock , peer ) asyncore . dispatcher . __init__ ( self , sock ) self . peer = peer self . request = '' self . socketError = None def handle_connect ( self ) : if _debug : deferred ( TCPServer . _debug , \"\" ) def readable ( self ) : return def handle_read ( self ) : if _debug : deferred ( TCPServer . _debug , \"\" ) try : msg = self . recv ( ) if _debug : deferred ( TCPServer . _debug , \"\" , len ( msg ) ) self . socketError = None if not self . socket : if _debug : deferred ( TCPServer . _debug , \"\" ) else : deferred ( self . response , PDU ( msg ) ) except socket . error , err : if ( err . args [ ] == ) : deferred ( TCPServer . _error , \"\" , self . peer ) else : deferred ( TCPServer . _error , \"\" , err ) self . socketError = err def writable ( self ) : return ( len ( self . request ) != ) def handle_write ( self ) : if _debug : deferred ( TCPServer . _debug , \"\" ) try : sent = self . send ( self . request ) if _debug : deferred ( TCPServer . _debug , \"\" , sent , len ( self . request ) - sent ) self . socketError = None self . request = self . request [ sent : ] except socket . error , why : if ( why . args [ ] == ) : deferred ( TCPServer . _error , \"\" , self . peer ) else : deferred ( TCPServer . _error , \"\" , why ) self . socketError = why def handle_close ( self ) : if _debug : deferred ( TCPServer . _debug , \"\" ) if not self : deferred ( TCPServer . _warning , \"\" ) return if not self . socket : deferred ( TCPServer . _warning , \"\" ) return self . close ( ) self . socket = None def indication ( self , pdu ) : \"\"\"\"\"\" if _debug : TCPServer . _debug ( \"\" , pdu ) self . request += pdu . pduData bacpypes_debugging ( TCPServer ) class TCPServerActor ( TCPServer ) : def __init__ ( self , director , sock , peer ) : if _debug : TCPServerActor . _debug ( \"\" , director , sock , peer ) TCPServer . __init__ ( self , sock , peer ) self . director = director self . timeout = director . timeout if self . timeout > : self . timer = FunctionTask ( self . idle_timeout ) self . timer . install_task ( _time ( ) + self . timeout ) else : self . timer = None self . flushTask = None self . director . add_actor ( self ) def handle_close ( self ) : if _debug : TCPServerActor . _debug ( \"\" ) if self . flushTask : self . flushTask . suspend_task ( ) ", "answer": "self . director . remove_actor ( self )"}, {"prompt": " from nose . tools import eq_ from textwrap import dedent from pyquery import PyQuery as pq from kitsune . search import es_utils , synonym_utils from kitsune . search . tests import ElasticTestCase , SynonymFactory from kitsune . sumo . tests import LocalizingClient from kitsune . sumo . tests import TestCase from kitsune . sumo . urlresolvers import reverse from kitsune . wiki . tests import DocumentFactory , RevisionFactory from kitsune . search . tasks import update_synonyms_task class TestSynonymModel ( TestCase ) : def test_serialize ( self ) : syn = SynonymFactory ( from_words = \"\" , to_words = \"\" ) eq_ ( \"\" , unicode ( syn ) ) class TestFilterGenerator ( TestCase ) : def test_name ( self ) : \"\"\"\"\"\" name , _ = es_utils . es_get_synonym_filter ( '' ) eq_ ( name , '' ) def test_no_synonyms ( self ) : \"\"\"\"\"\" _ , body = es_utils . es_get_synonym_filter ( '' ) eq_ ( body , { '' : '' , '' : [ '' ] , } ) def test_with_some_synonyms ( self ) : ", "answer": "SynonymFactory ( from_words = '' , to_words = '' )"}, {"prompt": " \"\"\"\"\"\" from BaseHTTPServer import BaseHTTPRequestHandler , HTTPServer ", "answer": "import urllib"}, {"prompt": " import collections from . bundled . traitlets import HasTraits , Dict , Instance , List , Long , Unicode from . errors import DepSolverError , MissingPackageInfoInPool from . package import PackageInfo from . repository import Repository from . requirement import Requirement from . utils import CachedScheduler MATCH_NONE = MATCH_NAME = MATCH = MATCH_PROVIDE = MATCH_REPLACE = class Pool ( HasTraits ) : \"\"\"\"\"\" repositories = List ( Instance ( Repository ) ) _packages_by_id = Dict ( ) _packages_by_name = Dict ( ) _id = Long ( ) _repository_by_name = Instance ( collections . defaultdict ) _scheduler = Instance ( CachedScheduler ) def __init__ ( self , repositories = None , ** kw ) : scheduler = CachedScheduler ( ) repository_by_name = collections . defaultdict ( list ) super ( Pool , self ) . __init__ ( self , _scheduler = scheduler , _repository_by_name = repository_by_name , ** kw ) if repositories is None : repositories = [ ] self . _packages_by_name = collections . defaultdict ( list ) if len ( repositories ) > : for repository in repositories : self . add_repository ( repository ) def has_package ( self , package ) : package_id = package . id return package_id in self . _packages_by_id def add_repository ( self , repository ) : \"\"\"\"\"\" self . repositories . append ( repository ) ", "answer": "self . _repository_by_name [ repository . name ] . append ( repository )"}, {"prompt": " \"\"\"\"\"\" import collections import logging import math from spockbot . mcdata import blocks , constants as const from spockbot . mcdata . utils import BoundingBox from spockbot . plugins . base import PluginBase , pl_announce from spockbot . plugins . tools import collision from spockbot . vector import Vector3 logger = logging . getLogger ( '' ) FP_MAGIC = ", "answer": "class PhysicsCore ( object ) :"}, {"prompt": " import abc import datetime from pyalgotrade . utils import dt from pyalgotrade import bar class TimeRange ( object ) : __metaclass__ = abc . ABCMeta @ abc . abstractmethod def belongs ( self , dateTime ) : raise NotImplementedError ( ) @ abc . abstractmethod def getBeginning ( self ) : raise NotImplementedError ( ) @ abc . abstractmethod def getEnding ( self ) : raise NotImplementedError ( ) class IntraDayRange ( TimeRange ) : def __init__ ( self , dateTime , frequency ) : super ( IntraDayRange , self ) . __init__ ( ) assert isinstance ( frequency , int ) assert frequency > assert frequency < bar . Frequency . DAY ts = int ( dt . datetime_to_timestamp ( dateTime ) ) slot = int ( ts / frequency ) slotTs = slot * frequency self . __begin = dt . timestamp_to_datetime ( slotTs , not dt . datetime_is_naive ( dateTime ) ) if not dt . datetime_is_naive ( dateTime ) : self . __begin = dt . localize ( self . __begin , dateTime . tzinfo ) self . __end = self . __begin + datetime . timedelta ( seconds = frequency ) def belongs ( self , dateTime ) : return dateTime >= self . __begin and dateTime < self . __end def getBeginning ( self ) : return self . __begin def getEnding ( self ) : return self . __end class DayRange ( TimeRange ) : def __init__ ( self , dateTime ) : super ( DayRange , self ) . __init__ ( ) self . __begin = datetime . datetime ( dateTime . year , dateTime . month , dateTime . day ) if not dt . datetime_is_naive ( dateTime ) : self . __begin = dt . localize ( self . __begin , dateTime . tzinfo ) self . __end = self . __begin + datetime . timedelta ( days = ) def belongs ( self , dateTime ) : ", "answer": "return dateTime >= self . __begin and dateTime < self . __end"}, {"prompt": " \"\"\"\"\"\" from __future__ import division import os import time from datetime import datetime from traceback import format_exc from twisted . python import log ", "answer": "from twisted . internet . threads import deferToThread"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import os import re import sys import stat import errno import fnmatch from shutil import copy2 , copystat , Error __all__ = [ '' , '' , '' , '' , '' , '' ] FULL_PERMS = RW_PERMS = _SINGLE_FULL_PERM = try : basestring except NameError : unicode = str basestring = ( str , bytes ) def mkdir_p ( path ) : \"\"\"\"\"\" try : os . makedirs ( path ) except OSError as exc : if exc . errno == errno . EEXIST and os . path . isdir ( path ) : return raise return class FilePerms ( object ) : \"\"\"\"\"\" class _FilePermProperty ( object ) : _perm_chars = '' _perm_set = frozenset ( '' ) _perm_val = { '' : , '' : , '' : } def __init__ ( self , attribute , offset ) : self . attribute = attribute self . offset = offset def __get__ ( self , fp_obj , type_ = None ) : if fp_obj is None : return self return getattr ( fp_obj , self . attribute ) def __set__ ( self , fp_obj , value ) : cur = getattr ( fp_obj , self . attribute ) if cur == value : return try : invalid_chars = set ( str ( value ) ) - self . _perm_set except TypeError : raise TypeError ( '' % value ) if invalid_chars : raise ValueError ( '' '' '' % ( invalid_chars , value , self . _perm_chars ) ) sort_key = lambda c : self . _perm_val [ c ] new_value = '' . join ( sorted ( set ( value ) , key = sort_key , reverse = True ) ) setattr ( fp_obj , self . attribute , new_value ) self . _update_integer ( fp_obj , new_value ) def _update_integer ( self , fp_obj , value ) : mode = key = '' for symbol in value : bit = ** key . index ( symbol ) mode |= ( bit << ( self . offset * ) ) fp_obj . _integer |= mode def __init__ ( self , user = '' , group = '' , other = '' ) : self . _user , self . _group , self . _other = '' , '' , '' self . _integer = self . user = user self . group = group self . other = other @ classmethod def from_int ( cls , i ) : \"\"\"\"\"\" i &= FULL_PERMS key = ( '' , '' , '' , '' , '' , '' , '' , '' ) parts = [ ] while i : parts . append ( key [ i & _SINGLE_FULL_PERM ] ) i >>= parts . reverse ( ) return cls ( * parts ) @ classmethod def from_path ( cls , path ) : \"\"\"\"\"\" stat_res = os . stat ( path ) return cls . from_int ( stat . S_IMODE ( stat_res . st_mode ) ) def __int__ ( self ) : return self . _integer user = _FilePermProperty ( '' , ) \"\" group = _FilePermProperty ( '' , ) \"\" other = _FilePermProperty ( '' , ) \"\" def __repr__ ( self ) : cn = self . __class__ . __name__ return ( '' % ( cn , self . user , self . group , self . other ) ) _TEXT_OPENFLAGS = os . O_RDWR | os . O_CREAT | os . O_EXCL if hasattr ( os , '' ) : _TEXT_OPENFLAGS |= os . O_NOINHERIT if hasattr ( os , '' ) : _TEXT_OPENFLAGS |= os . O_NOFOLLOW _BIN_OPENFLAGS = _TEXT_OPENFLAGS if hasattr ( os , '' ) : _BIN_OPENFLAGS |= os . O_BINARY try : import fcntl as fcntl except ImportError : def set_cloexec ( fd ) : \"\" pass else : def set_cloexec ( fd ) : \"\"\"\"\"\" try : flags = fcntl . fcntl ( fd , fcntl . F_GETFD , ) except IOError : pass else : flags |= fcntl . FD_CLOEXEC fcntl . fcntl ( fd , fcntl . F_SETFD , flags ) return def atomic_save ( dest_path , ** kwargs ) : \"\"\"\"\"\" return AtomicSaver ( dest_path , ** kwargs ) def path_to_unicode ( path ) : if isinstance ( path , unicode ) : return path encoding = sys . getfilesystemencoding ( ) or sys . getdefaultencoding ( ) return path . decode ( encoding ) if os . name == '' : import ctypes from ctypes import c_wchar_p from ctypes . wintypes import DWORD , LPVOID _ReplaceFile = ctypes . windll . kernel32 . ReplaceFile _ReplaceFile . argtypes = [ c_wchar_p , c_wchar_p , c_wchar_p , DWORD , LPVOID , LPVOID ] def replace ( src , dst ) : try : os . rename ( src , dst ) return except WindowsError as we : if we . errno == errno . EEXIST : pass else : raise src = path_to_unicode ( src ) dst = path_to_unicode ( dst ) bak = dst + u'' res = _ReplaceFile ( c_wchar_p ( dst ) , c_wchar_p ( src ) , c_wchar_p ( bak ) , , None , None ) if not res : raise OSError ( '' % ( dst , src ) ) return def atomic_rename ( src , dst , overwrite = False ) : \"\" if overwrite : replace ( src , dst ) else : os . rename ( src , dst ) return else : def replace ( src , dst ) : return os . rename ( src , dst ) def atomic_rename ( src , dst , overwrite = False ) : \"\" if overwrite : os . rename ( src , dst ) else : os . link ( src , dst ) os . unlink ( dst ) return _atomic_rename = atomic_rename replace . __doc__ = \"\"\"\"\"\" class AtomicSaver ( object ) : \"\"\"\"\"\" _default_file_perms = RW_PERMS def __init__ ( self , dest_path , ** kwargs ) : self . dest_path = dest_path self . overwrite = kwargs . pop ( '' , True ) self . file_perms = kwargs . pop ( '' , None ) self . overwrite_part = kwargs . pop ( '' , False ) self . part_filename = kwargs . pop ( '' , None ) self . rm_part_on_exc = kwargs . pop ( '' , True ) self . text_mode = kwargs . pop ( '' , False ) self . buffering = kwargs . pop ( '' , - ) if kwargs : raise TypeError ( '' % ( kwargs . keys ( ) , ) ) self . dest_path = os . path . abspath ( self . dest_path ) self . dest_dir = os . path . dirname ( self . dest_path ) if not self . part_filename : self . part_path = dest_path + '' else : self . part_path = os . path . join ( self . dest_dir , self . part_filename ) self . mode = '' if self . text_mode else '' self . open_flags = _TEXT_OPENFLAGS if self . text_mode else _BIN_OPENFLAGS self . part_file = None def _open_part_file ( self ) : do_chmod = True file_perms = self . file_perms if file_perms is None : try : stat_res = os . stat ( self . dest_path ) file_perms = stat . S_IMODE ( stat_res . st_mode ) except ( OSError , IOError ) : file_perms = self . _default_file_perms do_chmod = False fd = os . open ( self . part_path , self . open_flags , file_perms ) set_cloexec ( fd ) self . part_file = os . fdopen ( fd , self . mode , self . buffering ) if do_chmod : try : os . chmod ( self . part_path , file_perms ) except ( OSError , IOError ) : self . part_file . close ( ) raise return def setup ( self ) : \"\"\"\"\"\" if os . path . lexists ( self . dest_path ) : if not self . overwrite : raise OSError ( errno . EEXIST , '' , self . dest_path ) if self . overwrite_part and os . path . lexists ( self . part_path ) : os . unlink ( self . part_path ) self . _open_part_file ( ) return def __enter__ ( self ) : self . setup ( ) return self . part_file def __exit__ ( self , exc_type , exc_val , exc_tb ) : self . part_file . close ( ) if exc_type : if self . rm_part_on_exc : try : os . unlink ( self . part_path ) except Exception : pass return try : atomic_rename ( self . part_path , self . dest_path , overwrite = self . overwrite ) except OSError : if self . rm_part_on_exc : try : os . unlink ( self . part_path ) except Exception : pass raise return _CUR_DIR = os . path . dirname ( os . path . abspath ( __file__ ) ) def iter_find_files ( directory , patterns , ignored = None ) : \"\"\"\"\"\" if isinstance ( patterns , basestring ) : patterns = [ patterns ] pats_re = re . compile ( '' . join ( [ fnmatch . translate ( p ) for p in patterns ] ) ) if not ignored : ignored = [ ] elif isinstance ( ignored , basestring ) : ignored = [ ignored ] ign_re = re . compile ( '' . join ( [ fnmatch . translate ( p ) for p in ignored ] ) ) for root , dirs , files in os . walk ( directory ) : for basename in files : if pats_re . match ( basename ) : if ignored and ign_re . match ( basename ) : continue filename = os . path . join ( root , basename ) yield filename return def copy_tree ( src , dst , symlinks = False , ignore = None ) : \"\"\"\"\"\" names = os . listdir ( src ) if ignore is not None : ignored_names = ignore ( src , names ) else : ignored_names = set ( ) mkdir_p ( dst ) errors = [ ] for name in names : if name in ignored_names : continue srcname = os . path . join ( src , name ) dstname = os . path . join ( dst , name ) try : if symlinks and os . path . islink ( srcname ) : linkto = os . readlink ( srcname ) os . symlink ( linkto , dstname ) elif os . path . isdir ( srcname ) : copytree ( srcname , dstname , symlinks , ignore ) else : copy2 ( srcname , dstname ) except Error as e : errors . extend ( e . args [ ] ) except EnvironmentError as why : errors . append ( ( srcname , dstname , str ( why ) ) ) try : copystat ( src , dst ) except OSError as why : if WindowsError is not None and isinstance ( why , WindowsError ) : pass else : errors . append ( ( src , dst , str ( why ) ) ) if errors : raise Error ( errors ) copytree = copy_tree try : file except NameError : file = object class DummyFile ( file ) : def __init__ ( self , path , mode = '' , buffering = None ) : self . name = path self . mode = mode self . closed = False self . errors = None self . isatty = False self . encoding = None self . newlines = None self . softspace = def close ( self ) : self . closed = True def fileno ( self ) : return - def flush ( self ) : if self . closed : raise ValueError ( '' ) return def next ( self ) : raise StopIteration ( ) def read ( self , size = ) : if self . closed : raise ValueError ( '' ) return '' def readline ( self , size = ) : if self . closed : raise ValueError ( '' ) return '' def readlines ( self , size = ) : if self . closed : raise ValueError ( '' ) return [ ] def seek ( self ) : if self . closed : raise ValueError ( '' ) return def tell ( self ) : if self . closed : raise ValueError ( '' ) return def truncate ( self ) : if self . closed : raise ValueError ( '' ) return def write ( self , string ) : if self . closed : raise ValueError ( '' ) return def writelines ( self , list_of_strings ) : if self . closed : raise ValueError ( '' ) return def __next__ ( self ) : raise StopIteration ( ) def __enter__ ( self ) : if self . closed : raise ValueError ( '' ) return def __exit__ ( self , exc_type , exc_val , exc_tb ) : return if __name__ == '' : with atomic_save ( '' ) as f : f . write ( '' ) ", "answer": "f . write ( '' ) "}, {"prompt": " from nose . tools import ok_ , raises from linot import config from linot . interfaces . line_interface import LineClientP , LineInterface class TestLineClientP : def setUp ( self ) : self . line_cfg = config [ '' ] [ '' ] self . lineclient = LineClientP ( self . line_cfg [ '' ] , self . line_cfg [ '' ] ) def test_find_contact_by_id ( self ) : contact = self . lineclient . find_contact_by_id ( self . line_cfg [ '' ] ) ok_ ( contact . id == self . line_cfg [ '' ] ) @ raises ( ValueError ) def test_find_contact_by_id_exception ( self ) : self . lineclient . find_contact_by_id ( self . line_cfg [ '' ] [ : - ] ) class TestLineInterface : def setUp ( self ) : self . line_interface = LineInterface ( ) def test_polling_command ( self ) : test_str = '' me = self . line_interface . _client . getProfile ( ) me . sendMessage ( test_str ) result = self . line_interface . polling_command ( ) ok_ ( len ( result ) == , result ) submitter , msg = result [ ] ok_ ( submitter . code == me . id , submitter ) ok_ ( msg == test_str , '' . format ( msg , test_str ) ) def test_get_contact_by_id ( self ) : me = self . line_interface . _client . getProfile ( ) contact = self . line_interface . _get_contact_by_id ( me . id ) ok_ ( me . id == contact . id , '' . format ( me . id , contact . id ) ) def test_send_message ( self ) : test_str = '' me = self . line_interface . _client . getProfile ( ) me . sendMessage ( test_str ) result = self . line_interface . polling_command ( ) me , msg = result [ ] self . line_interface . send_message ( me , test_str ) result = self . line_interface . polling_command ( ) me , msg = result [ ] ok_ ( msg == test_str , '' . format ( msg , test_str ) ) def test_send_message_to_id ( self ) : test_str = '' me = self . line_interface . _client . getProfile ( ) me . sendMessage ( test_str ) result = self . line_interface . polling_command ( ) me , msg = result [ ] self . line_interface . _send_message_to_id ( me . code , test_str ) result = self . line_interface . polling_command ( ) me , msg = result [ ] ok_ ( msg == test_str , '' . format ( msg , test_str ) ) def test_get_display_name ( self ) : ", "answer": "test_str = ''"}, {"prompt": " from __future__ import unicode_literals import os import unittest from django . core import mail from django . test import TestCase from django . test . utils import override_settings from djrill import MandrillAPIError , MandrillRecipientsRefused MANDRILL_TEST_API_KEY = os . getenv ( '' ) @ unittest . skipUnless ( MANDRILL_TEST_API_KEY , \"\" ) @ override_settings ( MANDRILL_API_KEY = MANDRILL_TEST_API_KEY , EMAIL_BACKEND = \"\" ) class DjrillIntegrationTests ( TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . message = mail . EmailMultiAlternatives ( '' , '' , '' , [ '' ] ) self . message . attach_alternative ( '' , \"\" ) def test_send_mail ( self ) : sent_count = self . message . send ( ) self . assertEqual ( sent_count , ) response = self . message . mandrill_response self . assertIn ( response [ ] [ '' ] , [ '' , '' ] ) self . assertEqual ( response [ ] [ '' ] , '' ) self . assertGreater ( len ( response [ ] [ '' ] ) , ) def test_invalid_from ( self ) : self . message . from_email = '' try : self . message . send ( ) self . fail ( \"\" ) except MandrillAPIError as err : self . assertEqual ( err . status_code , ) self . assertIn ( \"\" , str ( err ) ) def test_invalid_to ( self ) : ", "answer": "self . message . to = [ '' ]"}, {"prompt": " from vt_manager . communication . utils . XmlHelper import XmlHelper import os import sys from vt_manager . models import * from vt_manager . controller import * from vt_manager . communication . utils import * from vt_manager . utils . ServiceThread import * import xmlrpclib , threading , logging , copy from django . conf import settings from django import forms from vt_manager . utils . HttpUtils import HttpUtils from django . db . models . query import QuerySet from vt_manager . models . VirtualMachine import VirtualMachine from vt_manager . controller . actions . ActionController import ActionController from vt_manager . utils . ServiceThread import * from django . core . exceptions import ValidationError from vt_manager . utils . HttpUtils import HttpUtils class VTDriver ( ) : CONTROLLER_TYPE_XEN = \"\" __possibleVirtTechs = [ CONTROLLER_TYPE_XEN ] @ staticmethod def getDriver ( virtType ) : from vt_manager . controller . drivers . XenDriver import XenDriver if virtType == VTDriver . CONTROLLER_TYPE_XEN : return XenDriver . getInstance ( ) @ staticmethod def getAllDrivers ( ) : from vt_manager . controller . drivers . XenDriver import XenDriver drivers = [ ] for vt in Driver . __possibleVirtTechs : drivers . append ( Driver . getDriver ( vt ) ) return drivers @ staticmethod def getAllServers ( ) : from vt_manager . models . VTServer import VTServer servers = VTServer . objects . all ( ) serversChild = [ ] for server in servers : server = server . getChildObject ( ) serversChild . append ( server ) return serversChild @ staticmethod def createServerFromPOST ( request , instance ) : from vt_manager . models . VTServer import VTServer controller = VTDriver . getDriver ( HttpUtils . getFieldInPost ( request , VTServer , \"\" ) ) return controller . createOrUpdateServerFromPOST ( request , instance ) @ staticmethod def crudServerFromInstance ( instance ) : s = xmlrpclib . Server ( instance . agentURL ) try : s . pingAuth ( \"\" , instance . agentPassword ) except : raise forms . ValidationError ( \"\" ) controller = VTDriver . getDriver ( instance . getVirtTech ( ) ) return controller . crudServerFromInstance ( instance ) @ staticmethod def setMgmtBridge ( request , server ) : name = HttpUtils . getFieldInPost ( request , \"\" ) mac = HttpUtils . getFieldInPost ( request , \"\" ) server . setMgmtBridge ( name , mac ) @ staticmethod def crudDataBridgeFromInstance ( server , ifaces , ifacesToDelete ) : serverIfaces = server . getNetworkInterfaces ( ) . filter ( isMgmt = False ) for newIface in ifaces : if newIface . id == None : server . addDataBridge ( newIface . getName ( ) , \"\" , newIface . getSwitchID ( ) , newIface . getPort ( ) ) else : server . updateDataBridge ( newIface ) for id in ifacesToDelete : if id != '' : try : server . deleteDataBridge ( serverIfaces . get ( id = id ) ) except Exception as e : raise ValidationError ( str ( e ) ) @ staticmethod def getServerById ( id ) : from vt_manager . models . VTServer import VTServer try : return VTServer . objects . get ( id = id ) . getChildObject ( ) except : raise Exception ( \"\" ) @ staticmethod def getServerByUUID ( uuid ) : try : from vt_manager . models . VTServer import VTServer return VTServer . objects . get ( uuid = uuid ) . getChildObject ( ) except : raise Exception ( \"\" ) @ staticmethod def getVMsInServer ( server ) : try : return server . vms . all ( ) except : raise Exception ( \"\" ) @ staticmethod def getInstance ( ) : raise Exception ( \"\" ) @ staticmethod def getVMbyUUID ( uuid ) : try : return VirtualMachine . objects . get ( uuid = uuid ) . getChildObject ( ) except : raise @ staticmethod def getVMbyId ( id ) : try : return VirtualMachine . objects . get ( id = id ) . getChildObject ( ) except : raise def deleteVM ( ) : raise Exception ( \"\" ) def getServerAndCreateVM ( ) : raise Exception ( \"\" ) def getServers ( self ) : return self . ServerClass . objects . all ( ) @ staticmethod def deleteServer ( server ) : server . destroy ( ) @ staticmethod def manageEthernetRanges ( request , server , totalMacRanges ) : justUnsubscribed = [ ] for macRange in server . getSubscribedMacRangesNoGlobal ( ) : try : request . POST [ '' + str ( macRange . id ) ] except : server . unsubscribeToMacRange ( macRange ) justUnsubscribed . append ( macRange ) ", "answer": "for macRange in totalMacRanges :"}, {"prompt": " from setuptools import setup , find_packages long_description = \"\"\"\"\"\" setup ( name = '' , version = '' , author = '' , author_email = '' , packages = find_packages ( ) , package_data = { '' : [ '' , '' ] , } , description = '' , long_description = long_description , license = '' , ", "answer": "entry_points = {"}, {"prompt": " import copy from appium . webdriver . mobilecommand import MobileCommand as Command class TouchAction ( object ) : def __init__ ( self , driver = None ) : self . _driver = driver self . _actions = [ ] def tap ( self , element = None , x = None , y = None , count = ) : \"\"\"\"\"\" opts = self . _get_opts ( element , x , y ) opts [ '' ] = count self . _add_action ( '' , opts ) return self def press ( self , el = None , x = None , y = None ) : \"\"\"\"\"\" self . _add_action ( '' , self . _get_opts ( el , x , y ) ) return self def long_press ( self , el = None , x = None , y = None , duration = ) : \"\"\"\"\"\" self . _add_action ( '' , self . _get_opts ( el , x , y , duration ) ) return self def wait ( self , ms = ) : \"\"\"\"\"\" if ms is None : ms = opts = { '' : ms } self . _add_action ( '' , opts ) return self def move_to ( self , el = None , x = None , y = None ) : \"\"\"\"\"\" self . _add_action ( '' , self . _get_opts ( el , x , y ) ) return self def release ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest from ddp . messages . server . result_message import ResultMessage from ddp . messages . server . result_message_parser import ResultMessageParser class ResultMessageParserTestCase ( unittest . TestCase ) : def setUp ( self ) : self . parser = ResultMessageParser ( ) self . id = '' self . error = '' self . result = { '' : [ True , ] } def test_with_error ( self ) : message = self . parser . parse ( { '' : '' , '' : self . id , '' : self . error } ) self . assertEqual ( message , ResultMessage ( self . id , error = self . error ) ) def test_with_result ( self ) : message = self . parser . parse ( { '' : '' , '' : self . id , '' : self . result } ) self . assertEqual ( message , ResultMessage ( self . id , result = self . result ) ) ", "answer": "def test_with_error_with_result ( self ) :"}, {"prompt": " from __future__ import absolute_import VERSION = ( , , , '' ) __version__ = VERSION __versionstr__ = '' . join ( map ( str , VERSION ) ) import sys if ( , ) <= sys . version_info < ( , ) : import logging logger = logging . getLogger ( '' ) logger . addHandler ( logging . NullHandler ( ) ) ", "answer": "from . client import Elasticsearch"}, {"prompt": " \"\"\"\"\"\" import matplotlib as mpl from pylab import * KB_ = MB_ = * KB_ GB_ = * MB_ NCHUNKS = linewidth = markers = [ '' , '' , '' , '' , '' , '' , '>' , '' , '' , '' ] markersize = def get_values ( filename ) : f = open ( filename ) ", "answer": "values = { \"\" : [ ] , \"\" : [ ] }"}, {"prompt": " from rockstar import RockStar ", "answer": "ada_code = \"\"\"\"\"\""}, {"prompt": " from lintreview . review import Problems from lintreview . review import Comment from lintreview . tools . pep8 import Pep8 from unittest import TestCase from nose . tools import eq_ class TestPep8 ( TestCase ) : fixtures = [ '' , '' , ] def setUp ( self ) : self . problems = Problems ( ) self . tool = Pep8 ( self . problems ) def test_match_file ( self ) : self . assertFalse ( self . tool . match_file ( '' ) ) self . assertFalse ( self . tool . match_file ( '' ) ) self . assertFalse ( self . tool . match_file ( '' ) ) self . assertTrue ( self . tool . match_file ( '' ) ) self . assertTrue ( self . tool . match_file ( '' ) ) def test_process_files__one_file_pass ( self ) : self . tool . process_files ( [ self . fixtures [ ] ] ) eq_ ( [ ] , self . problems . all ( self . fixtures [ ] ) ) def test_process_files__one_file_fail ( self ) : self . tool . process_files ( [ self . fixtures [ ] ] ) problems = self . problems . all ( self . fixtures [ ] ) eq_ ( , len ( problems ) ) fname = self . fixtures [ ] ", "answer": "expected = Comment ( fname , , , '' )"}, {"prompt": " from abc import abstractmethod import datetime try : import urlparse except ImportError : import urllib . parse as urlparse import warnings import lxml . etree import lxml . html import requests import six SHARED_SESSION = requests . Session ( ) SHARED_SESSION . headers [ '' ] = \"\" class ScrapedAttribute ( object ) : \"\"\"\"\"\" def __init__ ( self , extract = None , cleanup = None , attribute = None , multiple = False ) : if extract and attribute : raise ValueError ( \"\" ) self . _cleanup = cleanup self . _extract = extract self . attribute = attribute self . multiple = multiple self . _cleanup_method = None @ abstractmethod def get ( self , doc , scraped_page ) : raise NotImplementedError ( ) def extract ( self , element , scraped_page ) : if self . _extract : value = self . _extract ( element ) elif self . attribute is None : value = element . text_content ( ) else : value = element . get ( self . attribute ) if value is None : return if six . PY2 and isinstance ( value , str ) : value = unicode ( value ) return self . perform_cleanups ( value , element , scraped_page ) def perform_cleanups ( self , value , element , scraped_page = None ) : if self . _cleanup : value = self . _cleanup ( value ) if self . _cleanup_method : value = self . _cleanup_method ( scraped_page , value , element ) return self . cleanup ( value , element , scraped_page ) def cleanup ( self , value , elements , scraped_page = None ) : return value def __call__ ( self , func ) : self . _cleanup_method = func return self _SCRAPER_CLASSES = { } class _ScrapedMeta ( type ) : \"\"\"\"\"\" def __new__ ( cls , name , bases , namespace ) : keys = [ ] for key , value in namespace . items ( ) : if isinstance ( value , ScrapedAttribute ) : def mk_attribute ( selector ) : def method ( scraped ) : return scraped . _get_value ( selector ) return property ( method ) namespace [ key ] = mk_attribute ( value ) keys . append ( key ) ", "answer": "result = super ( _ScrapedMeta , cls ) . __new__ ( cls , name , bases , namespace )"}, {"prompt": " \"\"\"\"\"\" from . cryptomath import * from . aes import * if m2cryptoLoaded : def new ( key , mode , IV ) : return OpenSSL_AES ( key , mode , IV ) class OpenSSL_AES ( AES ) : def __init__ ( self , key , mode , IV ) : AES . __init__ ( self , key , mode , IV , \"\" ) self . key = key self . IV = IV def _createContext ( self , encrypt ) : context = m2 . cipher_ctx_new ( ) if len ( self . key ) == : cipherType = m2 . aes_128_cbc ( ) if len ( self . key ) == : cipherType = m2 . aes_192_cbc ( ) if len ( self . key ) == : cipherType = m2 . aes_256_cbc ( ) m2 . cipher_init ( context , cipherType , self . key , self . IV , encrypt ) return context def encrypt ( self , plaintext ) : AES . encrypt ( self , plaintext ) context = self . _createContext ( ) ciphertext = m2 . cipher_update ( context , plaintext ) m2 . cipher_ctx_free ( context ) self . IV = ciphertext [ - self . block_size : ] return bytearray ( ciphertext ) def decrypt ( self , ciphertext ) : ", "answer": "AES . decrypt ( self , ciphertext )"}, {"prompt": " from __future__ import unicode_literals from django . conf import settings PAGSEGURO_EMAIL = getattr ( settings , '' , '' ) PAGSEGURO_TOKEN = getattr ( settings , '' , '' ) PAGSEGURO_SANDBOX = getattr ( settings , '' , True ) PAGSEGURO_LOG_IN_MODEL = getattr ( settings , '' , True ) if PAGSEGURO_SANDBOX : CHECKOUT_URL = '' PAYMENT_URL = '' NOTIFICATION_URL = '' TRANSACTION_URL = '' SESSION_URL = '' else : CHECKOUT_URL = '' PAYMENT_URL = '' NOTIFICATION_URL = '' TRANSACTION_URL = '' SESSION_URL = '' TRANSACTION_STATUS = { '' : '' , '' : '' , '' : '' , ", "answer": "'' : '' ,"}, {"prompt": " from __future__ import unicode_literals , division \"\"\"\"\"\" __author__ = \"\" __copyright__ = \"\" __version__ = \"\" __maintainer__ = \"\" ", "answer": "__email__ = \"\""}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " import os import unittest if not '' in os . environ : os . environ [ '' ] = '' from django . conf import settings from django . db import connection from django . test . utils import setup_test_environment from django . test . utils import teardown_test_environment from django . utils . importlib import import_module TEST_MODULES = [ \"\" ] def run_tests ( ) : ", "answer": "setup_test_environment ( )"}, {"prompt": " from __future__ import unicode_literals from django . db import models class SillyModel ( models . Model ) : silly_field = models . BooleanField ( default = False ) silly_tribble = models . ForeignKey ( \"\" , models . CASCADE ) ", "answer": "is_trouble = models . BooleanField ( default = True ) "}, {"prompt": " from django . db import models class ApiKey ( models . Model ) : ", "answer": "key = models . CharField ( max_length = , unique = True ) "}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import re from pipeline . compressors import CompressorBase class MollyCSSFilter ( CompressorBase ) : _COMMENT_RE = re . compile ( r'' ) ", "answer": "_WHITESPACE_RE = re . compile ( r'' )"}, {"prompt": " import re from solum . common import exception as exc def check_url ( data ) : pt = re . compile ( r'' ) match = pt . search ( data ) if not match : msg = ( \"\" \"\" \"\" ) ", "answer": "raise exc . BadRequest ( reason = msg ) "}, {"prompt": " from selenium import selenium import unittest , time , re import seleniumtest class NewTest ( unittest . TestCase ) : ", "answer": "def setUp ( self ) :"}, {"prompt": " \"\"\"\"\"\" import encoder import optimizer import unittest import test_tools import vp8_mpeg class TestVp8Mpeg ( test_tools . FileUsingCodecTest ) : def test_OneBlackFrame ( self ) : codec = vp8_mpeg . Vp8CodecMpegMode ( ) my_optimizer = optimizer . Optimizer ( codec ) videofile = test_tools . MakeYuvFileWithOneBlankFrame ( '' ) encoding = my_optimizer . BestEncoding ( , videofile ) encoding . Execute ( ) self . assertLess ( , my_optimizer . Score ( encoding ) ) def test_ConfigurationFixups ( self ) : codec = vp8_mpeg . Vp8CodecMpegMode ( ) fixups = codec . ConfigurationFixups ( encoder . OptionValueSet ( codec . option_set , '' ) ) self . assertEqual ( '' , fixups . ToString ( ) ) def test_SuggestedTweakRefersToSameContext ( self ) : codec = vp8_mpeg . Vp8CodecMpegMode ( ) my_optimizer = optimizer . Optimizer ( codec ) videofile = test_tools . MakeYuvFileWithOneBlankFrame ( '' ) encoding = my_optimizer . BestEncoding ( , videofile ) encoding . result = { '' : , '' : } ", "answer": "next_encoding = codec . SuggestTweak ( encoding )"}, {"prompt": " \"\"\"\"\"\" import random import sys import networkx as nx __author__ = '' . join ( [ '' , '' , '' ] ) import warnings as _warnings def create_degree_sequence ( n , sfunction = None , max_tries = , ** kwds ) : _warnings . warn ( \"\" , DeprecationWarning ) \"\"\"\"\"\" tries = max_deg = n while tries < max_tries : trialseq = sfunction ( n , ** kwds ) seq = [ min ( max_deg , max ( int ( round ( s ) ) , ) ) for s in trialseq ] if nx . is_valid_degree_sequence ( seq ) : return seq tries += raise nx . NetworkXError ( \"\" % max_tries ) def pareto_sequence ( n , exponent = ) : \"\"\"\"\"\" return [ random . paretovariate ( exponent ) for i in range ( n ) ] def powerlaw_sequence ( n , exponent = ) : \"\"\"\"\"\" return [ random . paretovariate ( exponent - ) for i in range ( n ) ] def zipf_rv ( alpha , xmin = , seed = None ) : r\"\"\"\"\"\" if xmin < : raise ValueError ( \"\" ) if alpha <= : raise ValueError ( \"\" ) if not seed is None : random . seed ( seed ) a1 = alpha - b = ** a1 while True : u = - random . random ( ) v = random . random ( ) x = int ( xmin * u ** - ( / a1 ) ) t = ( + ( / x ) ) ** a1 if v * x * ( t - ) / ( b - ) <= t / b : break return x def zipf_sequence ( n , alpha = , xmin = ) : \"\"\"\"\"\" return [ zipf_rv ( alpha , xmin ) for _ in range ( n ) ] def uniform_sequence ( n ) : \"\"\"\"\"\" ", "answer": "return [ random . uniform ( , n ) for i in range ( n ) ]"}, {"prompt": " from flup . server . fcgi import WSGIServer ", "answer": "from admin import app"}, {"prompt": " \"\"\"\"\"\" __revision__ = \"\" import unittest class SimpleTest ( unittest . TestCase ) : def runTest ( self ) : \"\"\"\"\"\" import Crypto . Random . OSRNG . nt randobj = Crypto . Random . OSRNG . nt . new ( ) x = randobj . read ( ) y = randobj . read ( ) self . assertNotEqual ( x , y ) def get_tests ( config = { } ) : return [ SimpleTest ( ) ] if __name__ == '' : suite = lambda : unittest . TestSuite ( get_tests ( ) ) ", "answer": "unittest . main ( defaultTest = '' ) "}, {"prompt": " \"\"\"\"\"\" from gntp . test import GNTPTestCase class TestCustom ( GNTPTestCase ) : def test_custom_values ( self ) : self . _notify ( title = '' , custom = { '' : '' , '' : '' , ", "answer": "} ) "}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function from os import getpid from optparse import OptionParser from circuits . node import Node from circuits import Component , Debugger __version__ = \"\" USAGE = \"\" ", "answer": "VERSION = \"\" + __version__"}, {"prompt": " from collections import namedtuple from couchdbkit import ChangesStream import time CouchChange = namedtuple ( '' , [ '' , '' , '' , '' ] ) def stream_changes ( db , since , limit ) : for change in ChangesStream ( db = db , since = since , limit = limit ) : yield CouchChange ( id = change [ '' ] , rev = change [ '' ] [ ] [ '' ] , deleted = change . get ( '' , False ) , seq = change . get ( '' ) ) def stream_changes_forever ( db , since , chunk_size = , notify_caught_up = True ) : last_seq = since while True : changes = stream_changes ( db = db , since = last_seq , limit = chunk_size ) i = - change = None for i , change in enumerate ( changes ) : yield change ", "answer": "if i + < chunk_size :"}, {"prompt": " import sys if sys . version_info < ( , ) : import unittest2 as unittest else : import unittest from authy import AuthyException , AuthyFormatException from authy . api . resources import Token from authy . api . resources import Tokens from authy . api . resources import User from authy . api . resources import Users class TokensTest ( unittest . TestCase ) : def setUp ( self ) : self . users = Users ( \"\" , '' ) self . resource = Tokens ( \"\" , '' ) def test_verify_digits_token ( self ) : user = self . users . create ( '' , '' , ) try : token = self . resource . verify ( user . id , '' ) self . fail ( ) except Exception , e : self . assertIsInstance ( e , AuthyFormatException ) self . assertEqual ( e . message , '' ) def test_verify_digits_authy_id ( self ) : user = self . users . create ( '' , '' , ) try : token = self . resource . verify ( '' , '' ) self . fail ( ) except Exception , e : ", "answer": "self . assertIsInstance ( e , AuthyFormatException )"}, {"prompt": " from __future__ import absolute_import from rest_framework . response import Response from sentry . api . serializers import serialize , StreamGroupSerializer from sentry . api . paginator import OffsetPaginator from sentry . models import ( Group , GroupStatus , OrganizationMemberTeam , Project , ProjectStatus ) from . organizationmember import OrganizationMemberEndpoint ERR_INVALID_STATS_PERIOD = \"\" class OrganizationIssuesEndpoint ( OrganizationMemberEndpoint ) : def get_queryset ( self , request , organization , member , project_list ) : return Group . objects . none ( ) def get ( self , request , organization , member ) : \"\"\"\"\"\" stats_period = request . GET . get ( '' ) if stats_period not in ( None , '' , '' , '' ) : return Response ( { \"\" : ERR_INVALID_STATS_PERIOD } , status = ) elif stats_period is None : stats_period = '' elif stats_period == '' : stats_period = None project_list = Project . objects . filter ( organization = organization , team__in = OrganizationMemberTeam . objects . filter ( organizationmember = member , ) . values ( '' ) ) queryset = self . get_queryset ( request , organization , member , project_list ) status = request . GET . get ( '' , '' ) if status == '' : queryset = queryset . filter ( status = GroupStatus . UNRESOLVED , ) elif status : return Response ( { '' : '' } , status = ) queryset = queryset . filter ( project__status = ProjectStatus . VISIBLE , ) return self . paginate ( request = request , queryset = queryset , order_by = '' , paginator_cls = OffsetPaginator , on_results = lambda x : self . _on_results ( request , x , stats_period ) , ) def _on_results ( self , request , results , stats_period ) : ", "answer": "results = serialize ( results , request . user , StreamGroupSerializer ("}, {"prompt": " '''''' ", "answer": "import logging"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import threading import logging from django . conf import settings def is_ignorable_404 ( uri ) : \"\"\"\"\"\" return any ( pattern . search ( uri ) for pattern in getattr ( settings , '' , ( ) ) ) class Sentry404CatchMiddleware ( object ) : def process_response ( self , request , response ) : from raven . contrib . django . models import client if response . status_code != or is_ignorable_404 ( request . get_full_path ( ) ) or not client . is_enabled ( ) : return response data = client . get_data_from_request ( request ) data . update ( { '' : logging . INFO , '' : '' , } ) result = client . captureMessage ( message = '' % request . build_absolute_uri ( ) , data = data ) if not result : return request . sentry = { '' : data . get ( '' , client . remote . project ) , '' : client . get_ident ( result ) , } return response class SentryResponseErrorIdMiddleware ( object ) : \"\"\"\"\"\" def process_response ( self , request , response ) : if not getattr ( request , '' , None ) : return response response [ '' ] = request . sentry [ '' ] ", "answer": "return response"}, {"prompt": " \"\"\"\"\"\" import sys from zope . interface import implements , Interface from twisted . python import log , reflect from jelly import setUnjellyableForClass , setUnjellyableForClassTree , setUnjellyableFactoryForClass , unjellyableRegistry from jelly import Jellyable , Unjellyable , _Dummy , _DummyNewStyle from jelly import setInstanceState , getInstanceState setCopierForClass = setUnjellyableForClass setCopierForClassTree = setUnjellyableForClassTree setFactoryForClass = setUnjellyableFactoryForClass copyTags = unjellyableRegistry copy_atom = \"\" cache_atom = \"\" cached_atom = \"\" remote_atom = \"\" class NoSuchMethod ( AttributeError ) : \"\"\"\"\"\" class IPBRoot ( Interface ) : \"\"\"\"\"\" def rootObject ( broker ) : \"\"\"\"\"\" class Serializable ( Jellyable ) : \"\"\"\"\"\" def processUniqueID ( self ) : \"\"\"\"\"\" return id ( self ) class Referenceable ( Serializable ) : perspective = None \"\"\"\"\"\" def remoteMessageReceived ( self , broker , message , args , kw ) : \"\"\"\"\"\" args = broker . unserialize ( args ) kw = broker . unserialize ( kw ) method = getattr ( self , \"\" % message , None ) if method is None : raise NoSuchMethod ( \"\" % ( message , ) ) try : state = method ( * args , ** kw ) except TypeError : log . msg ( \"\" % ( method , args , kw ) ) raise return broker . serialize ( state , self . perspective ) def jellyFor ( self , jellier ) : \"\"\"\"\"\" return \"\" , jellier . invoker . registerReference ( self ) class Root ( Referenceable ) : \"\"\"\"\"\" implements ( IPBRoot ) def rootObject ( self , broker ) : \"\"\"\"\"\" return self class ViewPoint ( Referenceable ) : \"\"\"\"\"\" def __init__ ( self , perspective , object ) : \"\"\"\"\"\" self . perspective = perspective self . object = object def processUniqueID ( self ) : \"\"\"\"\"\" return ( id ( self . perspective ) , id ( self . object ) ) def remoteMessageReceived ( self , broker , message , args , kw ) : \"\"\"\"\"\" args = broker . unserialize ( args , self . perspective ) kw = broker . unserialize ( kw , self . perspective ) method = getattr ( self . object , \"\" % message ) try : state = apply ( method , ( self . perspective , ) + args , kw ) except TypeError : log . msg ( \"\" % ( method , args , kw ) ) raise rv = broker . serialize ( state , self . perspective , method , args , kw ) return rv class Viewable ( Serializable ) : \"\"\"\"\"\" def jellyFor ( self , jellier ) : \"\"\"\"\"\" return ViewPoint ( jellier . invoker . serializingPerspective , self ) . jellyFor ( jellier ) class Copyable ( Serializable ) : \"\"\"\"\"\" def getStateToCopy ( self ) : \"\"\"\"\"\" return self . __dict__ def getStateToCopyFor ( self , perspective ) : \"\"\"\"\"\" return self . getStateToCopy ( ) def getTypeToCopy ( self ) : \"\"\"\"\"\" return reflect . qual ( self . __class__ ) def getTypeToCopyFor ( self , perspective ) : \"\"\"\"\"\" return self . getTypeToCopy ( ) def jellyFor ( self , jellier ) : \"\"\"\"\"\" if jellier . invoker is None : return getInstanceState ( self , jellier ) p = jellier . invoker . serializingPerspective t = self . getTypeToCopyFor ( p ) state = self . getStateToCopyFor ( p ) sxp = jellier . prepare ( self ) sxp . extend ( [ t , jellier . jelly ( state ) ] ) return jellier . preserve ( self , sxp ) class Cacheable ( Copyable ) : \"\"\"\"\"\" def getStateToCacheAndObserveFor ( self , perspective , observer ) : \"\"\"\"\"\" return self . getStateToCopyFor ( perspective ) def jellyFor ( self , jellier ) : \"\"\"\"\"\" if jellier . invoker is None : return getInstanceState ( self , jellier ) luid = jellier . invoker . cachedRemotelyAs ( self , ) if luid is None : luid = jellier . invoker . cacheRemotely ( self ) p = jellier . invoker . serializingPerspective type_ = self . getTypeToCopyFor ( p ) observer = RemoteCacheObserver ( jellier . invoker , self , p ) state = self . getStateToCacheAndObserveFor ( p , observer ) l = jellier . prepare ( self ) jstate = jellier . jelly ( state ) l . extend ( [ type_ , luid , jstate ] ) return jellier . preserve ( self , l ) else : return cached_atom , luid def stoppedObserving ( self , perspective , observer ) : \"\"\"\"\"\" class RemoteCopy ( Unjellyable ) : \"\"\"\"\"\" def setCopyableState ( self , state ) : \"\"\"\"\"\" self . __dict__ = state def unjellyFor ( self , unjellier , jellyList ) : if unjellier . invoker is None : return setInstanceState ( self , unjellier , jellyList ) self . setCopyableState ( unjellier . unjelly ( jellyList [ ] ) ) return self class RemoteCache ( RemoteCopy , Serializable ) : \"\"\"\"\"\" def remoteMessageReceived ( self , broker , message , args , kw ) : \"\"\"\"\"\" args = broker . unserialize ( args ) kw = broker . unserialize ( kw ) method = getattr ( self , \"\" % message ) try : state = apply ( method , args , kw ) except TypeError : log . msg ( \"\" % ( method , args , kw ) ) raise return broker . serialize ( state , None , method , args , kw ) def jellyFor ( self , jellier ) : \"\"\"\"\"\" if jellier . invoker is None : return getInstanceState ( self , jellier ) ", "answer": "assert jellier . invoker is self . broker , \"\""}, {"prompt": " \"\"\"\"\"\" import sys , os __version__ = \"\" __all__ = [ \"\" ] FASTCGI_HELP = r\"\"\"\"\"\" FASTCGI_OPTIONS = { '' : '' , '' : None , '' : None , '' : None , '' : '' , '' : None , '' : '' , '' : None , '' : , '' : , '' : , '' : , '' : None , '' : None , '' : None , } def fastcgi_help ( message = None ) : print FASTCGI_HELP if message : print message return False def runfastcgi ( argset = [ ] , ** kwargs ) : options = FASTCGI_OPTIONS . copy ( ) options . update ( kwargs ) for x in argset : if \"\" in x : k , v = x . split ( '' , ) else : k , v = x , True options [ k . lower ( ) ] = v if \"\" in options : return fastcgi_help ( ) try : import flup except ImportError , e : print >> sys . stderr , \"\" % e ", "answer": "print >> sys . stderr , \"\""}, {"prompt": " from collections import namedtuple from corehq . apps . reminders . util import get_preferred_phone_number_for_recipient from custom . ewsghana . handlers . helpers . stock_and_receipt_parser import EWSStockAndReceiptParser from custom . ewsghana . handlers . soh import SOHHandler from custom . ewsghana . utils import send_sms ", "answer": "VerifiedNumberAdapter = namedtuple ( '' , [ '' , '' , '' , '' ] )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function from future . utils import viewkeys import re from twisted . application import internet from twisted . words . protocols import irc from twisted . internet import protocol , reactor from evennia . server . session import Session from evennia . utils import logger , utils IRC_BOLD = \"\" IRC_COLOR = \"\" IRC_RESET = \"\" IRC_ITALIC = \"\" IRC_NORMAL = \"\" IRC_UNDERLINE = \"\" IRC_WHITE = \"\" IRC_BLACK = \"\" IRC_DBLUE = \"\" IRC_DGREEN = \"\" IRC_RED = \"\" IRC_DRED = \"\" IRC_DMAGENTA = \"\" IRC_DYELLOW = \"\" IRC_YELLOW = \"\" IRC_GREEN = \"\" IRC_DCYAN = \"\" IRC_CYAN = \"\" IRC_BLUE = \"\" IRC_MAGENTA = \"\" IRC_DGREY = \"\" IRC_GRAY = \"\" IRC_COLOR_MAP = dict ( [ ( r'' , IRC_RESET ) , ( r'' , \"\" ) , ( r'' , \"\" ) , ( r'' , \"\" ) , ( r'' , \"\" ) , ( r'' , \"\" ) , ( r'' , IRC_COLOR + IRC_RED ) , ( r'' , IRC_COLOR + IRC_GREEN ) , ( r'' , IRC_COLOR + IRC_YELLOW ) , ( r'' , IRC_COLOR + IRC_BLUE ) , ( r'' , IRC_COLOR + IRC_MAGENTA ) , ( r'' , IRC_COLOR + IRC_CYAN ) , ( r'' , IRC_COLOR + IRC_WHITE ) , ( r'' , IRC_COLOR + IRC_DGREY ) , ( r'' , IRC_COLOR + IRC_DRED ) , ( r'' , IRC_COLOR + IRC_DGREEN ) , ( r'' , IRC_COLOR + IRC_DYELLOW ) , ( r'' , IRC_COLOR + IRC_DBLUE ) , ( r'' , IRC_COLOR + IRC_DMAGENTA ) , ( r'' , IRC_COLOR + IRC_DCYAN ) , ( r'' , IRC_COLOR + IRC_GRAY ) , ( r'' , IRC_COLOR + IRC_BLACK ) , ( r'' , IRC_COLOR + IRC_NORMAL + \"\" + IRC_DRED ) , ( r'' , IRC_COLOR + IRC_NORMAL + \"\" + IRC_DGREEN ) , ( r'' , IRC_COLOR + IRC_NORMAL + \"\" + IRC_DYELLOW ) , ( r'' , IRC_COLOR + IRC_NORMAL + \"\" + IRC_DBLUE ) , ( r'' , IRC_COLOR + IRC_NORMAL + \"\" + IRC_DMAGENTA ) , ( r'' , IRC_COLOR + IRC_NORMAL + \"\" + IRC_DCYAN ) , ( r'' , IRC_COLOR + IRC_NORMAL + \"\" + IRC_GRAY ) , ( r'' , IRC_COLOR + IRC_NORMAL + \"\" + IRC_BLACK ) ] ) RE_IRC_COLOR = re . compile ( r\"\" . join ( [ re . escape ( key ) for key in viewkeys ( IRC_COLOR_MAP ) ] ) , re . DOTALL ) RE_MXP = re . compile ( r'' , re . DOTALL ) RE_ANSI_ESCAPES = re . compile ( r\"\" % \"\" . join ( ( \"\" , \"\" , \"\" ) ) , re . DOTALL ) def sub_irc ( ircmatch ) : \"\"\"\"\"\" return IRC_COLOR_MAP . get ( ircmatch . group ( ) , \"\" ) def parse_irc_colors ( string ) : \"\"\"\"\"\" in_string = utils . to_str ( string ) parsed_string = \"\" parts = RE_ANSI_ESCAPES . split ( in_string ) + [ \"\" ] for part , sep in zip ( parts [ : : ] , parts [ : : ] ) : pstring = RE_IRC_COLOR . sub ( sub_irc , part ) parsed_string += \"\" % ( pstring , sep [ ] . strip ( ) ) parsed_string = RE_MXP . sub ( r'' , parsed_string ) return parsed_string class IRCBot ( irc . IRCClient , Session ) : \"\"\"\"\"\" lineRate = nickname = None logger = None factory = None channel = None def signedOn ( self ) : \"\"\"\"\"\" self . join ( self . channel ) self . stopping = False self . factory . bot = self address = \"\" % ( self . channel , self . network ) self . init_session ( \"\" , address , self . factory . sessionhandler ) self . uid = int ( self . factory . uid ) self . logged_in = True self . factory . sessionhandler . connect ( self ) logger . log_info ( \"\" % ( self . nickname , self . channel , self . network , self . port ) ) def disconnect ( self , reason = None ) : \"\"\"\"\"\" self . sessionhandler . disconnect ( self ) self . stopping = True self . transport . loseConnection ( ) def privmsg ( self , user , channel , msg ) : \"\"\"\"\"\" if not msg . startswith ( '' ) : user = user . split ( '' , ) [ ] self . data_in ( \"\" % ( user , channel , msg ) ) def action ( self , user , channel , msg ) : \"\"\"\"\"\" if not msg . startswith ( '' ) : user = user . split ( '' , ) [ ] self . data_in ( \"\" % ( user , channel , msg ) ) def data_in ( self , text = None , ** kwargs ) : \"\"\"\"\"\" self . sessionhandler . data_in ( self , text = text , ** kwargs ) def data_out ( self , text = None , ** kwargs ) : \"\"\"\"\"\" if text . startswith ( \"\" ) : text = text . split ( \"\" , ) [ ] text = parse_irc_colors ( text ) self . say ( self . channel , text ) class IRCBotFactory ( protocol . ReconnectingClientFactory ) : \"\"\"\"\"\" initialDelay = factor = maxDelay = def __init__ ( self , sessionhandler , uid = None , botname = None , channel = None , network = None , port = None , ssl = None ) : \"\"\"\"\"\" self . sessionhandler = sessionhandler self . uid = uid self . nickname = str ( botname ) self . channel = str ( channel ) self . network = str ( network ) self . port = port self . ssl = ssl self . bot = None def buildProtocol ( self , addr ) : \"\"\"\"\"\" protocol = IRCBot ( ) protocol . factory = self protocol . nickname = self . nickname protocol . channel = self . channel protocol . network = self . network protocol . port = self . port ", "answer": "protocol . ssl = self . ssl"}, {"prompt": " from pyface . qt import QtCore , QtGui from pyface . qt . QtGui import QFont from traits . api import Dict from date_editor import SimpleEditor from date_editor import CustomEditor as DateCustomEditor class CustomEditor ( DateCustomEditor ) : dates = Dict ( ) styles = Dict ( ) def init ( self , parent ) : self . control = QtGui . QCalendarWidget ( ) if not self . factory . allow_future : self . control . setMaximumDate ( QtCore . QDate . currentDate ( ) ) if not self . factory . allow_past : self . control . setMinimumDate ( QtCore . QDate . currentDate ( ) ) if self . factory . dates_trait and self . factory . styles_trait : self . sync_value ( self . factory . dates_trait , \"\" , \"\" ) self . sync_value ( self . factory . styles_trait , \"\" , \"\" ) self . control . clicked . connect ( self . update_object ) return def _dates_changed ( self , old , new ) : if old : [ map ( self . _reset_formatting , dates ) for dates in old . values ( ) ] if new : ", "answer": "styles = getattr ( self . object , self . factory . styles_trait , None )"}, {"prompt": " import numpy from chainer import cuda from chainer import function from chainer . utils import type_check if cuda . cudnn_enabled : cudnn = cuda . cudnn libcudnn = cudnn . cudnn _algorithm = libcudnn . CUDNN_SOFTMAX_ACCURATE _mode = libcudnn . CUDNN_SOFTMAX_MODE_CHANNEL class Softmax ( function . Function ) : \"\"\"\"\"\" def __init__ ( self , use_cudnn = True ) : self . use_cudnn = use_cudnn def check_type_forward ( self , in_types ) : type_check . expect ( in_types . size ( ) == ) x_type , = in_types type_check . expect ( x_type . dtype == numpy . float32 , x_type . ndim > , ) def forward ( self , x ) : ", "answer": "xp = cuda . get_array_module ( * x )"}, {"prompt": " from flask import url_for from flask_views . db . mongoengine . list import ListView from flask_views . tests . functional . db . mongoengine . base import BaseMongoTestCase class ListViewTestCase ( BaseMongoTestCase ) : \"\"\"\"\"\" def setUp ( self ) : super ( ListViewTestCase , self ) . setUp ( ) test_obj = self . TestDocument ( name = '' , username = '' , ) test_obj . save ( ) for i in range ( , ) : test_obj = self . TestDocument ( name = '' , username = '' . format ( i ) ) test_obj . save ( ) class TestView ( ListView ) : document_class = self . TestDocument filter_fields = { '' : '' , } template_name = '' items_per_page = self . app . add_url_rule ( '' , view_func = TestView . as_view ( '' ) ) def test_get_pages ( self ) : \"\"\"\"\"\" for i in range ( , ) : with self . app . test_request_context ( ) : response = self . client . get ( url_for ( '' , name = '' , page = i ) ) self . assertEqual ( , response . status_code ) def test_get_404 ( self ) : \"\"\"\"\"\" with self . app . test_request_context ( ) : response = self . client . get ( url_for ( '' , name = '' , page = ) ) self . assertEqual ( , response . status_code ) def test_template_context ( self ) : \"\"\"\"\"\" with self . app . test_request_context ( ) : response = self . client . get ( url_for ( '' , name = '' , page = ) ) ", "answer": "self . assertTrue ( '' in response . data )"}, {"prompt": " import cgi import functools from django . core . exceptions import ImproperlyConfigured from django . conf import settings from django . core . cache import cache , DEFAULT_CACHE_ALIAS from django . utils . encoding import iri_to_uri from django . utils . cache import ( get_cache_key , learn_cache_key , patch_response_headers , get_max_age ) from six import string_types , callable from six . moves . urllib . parse import urlencode from fancy_cache . utils import md5 REMEMBERED_URLS_KEY = '' LONG_TIME = * * * class RequestPath ( object ) : def __init__ ( self , request , only_get_keys , forget_get_keys ) : self . request = request self . only_get_keys = only_get_keys self . forget_get_keys = forget_get_keys assert not ( self . only_get_keys and self . forget_get_keys ) self . _prev_get_full_path = request . get_full_path def __enter__ ( self ) : if self . only_get_keys is not None : self . request . get_full_path = functools . partial ( self . get_full_path , self . request , self . only_get_keys , True ) if self . forget_get_keys is not None : self . request . get_full_path = functools . partial ( self . get_full_path , self . request , self . forget_get_keys , False ) def __exit__ ( self , exc_type , exc_value , traceback ) : if self . only_get_keys is not None or self . forget_get_keys is not None : self . request . get_full_path = self . _prev_get_full_path def get_full_path ( self , this , keys , is_only_keys ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import logging from django import shortcuts from django . utils . translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import workflows import disaster_recovery . api . api as freezer_api LOG = logging . getLogger ( __name__ ) class ActionsConfigurationAction ( workflows . Action ) : actions = forms . CharField ( required = False ) job_id = forms . CharField ( required = False ) class Meta ( object ) : name = _ ( \"\" ) slug = \"\" help_text_template = \"\" \"\" class ActionsConfiguration ( workflows . Step ) : action_class = ActionsConfigurationAction contributes = ( '' , '' ) class UpdateActions ( workflows . Workflow ) : slug = \"\" name = _ ( \"\" ) finalize_button_name = _ ( \"\" ) success_message = _ ( '' ) failure_message = _ ( '' ) success_url = \"\" default_steps = ( ActionsConfiguration , ) def handle ( self , request , context ) : try : ", "answer": "if context [ '' ] != '' :"}, {"prompt": " from . settings_base import * DATABASES = { '' : { '' : '' , '' : '' + db_suffix , '' : '' , '' : '' , '' : { '' : '' } } , ", "answer": "} "}, {"prompt": " import debile . utils . config as config_utils import os import shutil import yaml import unittest class ConfigTestCase ( unittest . TestCase ) : config = os . path . expanduser ( '' ) config_dir = os . path . expanduser ( '' ) @ classmethod ", "answer": "def setUp ( self ) :"}, {"prompt": " import unittest try : from pyface . ui . wx . grid . api import GridRow , GridColumn , SimpleGridModel except ImportError : wx_available = False else : wx_available = True @ unittest . skipUnless ( wx_available , \"\" ) class CompositeGridModelTestCase ( unittest . TestCase ) : def setUp ( self ) : self . model = SimpleGridModel ( data = [ [ None , ] , [ , ] ] , rows = [ GridRow ( label = '' ) , GridRow ( label = '' ) ] , columns = [ GridColumn ( label = '' ) , GridColumn ( label = '' ) ] ) return def test_get_column_count ( self ) : self . assertEqual ( self . model . get_column_count ( ) , ) return def test_get_row_count ( self ) : self . assertEqual ( self . model . get_row_count ( ) , ) return def test_get_row_name ( self ) : self . assertEqual ( self . model . get_row_name ( ) , '' ) self . assertEqual ( self . model . get_row_name ( ) , '' ) return def test_get_column_name ( self ) : self . assertEqual ( self . model . get_column_name ( ) , '' ) ", "answer": "self . assertEqual ( self . model . get_column_name ( ) , '' )"}, {"prompt": " from django . apps import apps from django . dispatch import Signal from django . utils import six class_prepared = Signal ( providing_args = [ \"\" ] ) class ModelSignal ( Signal ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : super ( ModelSignal , self ) . __init__ ( * args , ** kwargs ) self . unresolved_references = { } class_prepared . connect ( self . _resolve_references ) def _resolve_references ( self , sender , ** kwargs ) : opts = sender . _meta reference = ( opts . app_label , opts . object_name ) try : receivers = self . unresolved_references . pop ( reference ) except KeyError : pass else : for receiver , weak , dispatch_uid in receivers : super ( ModelSignal , self ) . connect ( receiver , sender = sender , weak = weak , dispatch_uid = dispatch_uid ) def connect ( self , receiver , sender = None , weak = True , dispatch_uid = None ) : if isinstance ( sender , six . string_types ) : try : app_label , model_name = sender . split ( '' ) except ValueError : raise ValueError ( \"\" \"\" ) try : sender = apps . get_registered_model ( app_label , model_name ) except LookupError : ref = ( app_label , model_name ) refs = self . unresolved_references . setdefault ( ref , [ ] ) refs . append ( ( receiver , weak , dispatch_uid ) ) return super ( ModelSignal , self ) . connect ( receiver , sender = sender , weak = weak , dispatch_uid = dispatch_uid ) pre_init = ModelSignal ( providing_args = [ \"\" , \"\" , \"\" ] , use_caching = True ) post_init = ModelSignal ( providing_args = [ \"\" ] , use_caching = True ) pre_save = ModelSignal ( providing_args = [ \"\" , \"\" , \"\" , \"\" ] , use_caching = True ) post_save = ModelSignal ( providing_args = [ \"\" , \"\" , \"\" , \"\" , \"\" ] , use_caching = True ) pre_delete = ModelSignal ( providing_args = [ \"\" , \"\" ] , use_caching = True ) post_delete = ModelSignal ( providing_args = [ \"\" , \"\" ] , use_caching = True ) m2m_changed = ModelSignal ( providing_args = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] , use_caching = True , ", "answer": ")"}, {"prompt": " \"\"\"\"\"\" import os from pulsar . client import action_mapper from pulsar . client import staging from pulsar . client . staging import PulsarOutputs from pulsar . client . staging . down import ResultsCollector import logging log = logging . getLogger ( __name__ ) def postprocess ( job_directory , action_executor ) : try : staging_config = job_directory . load_metadata ( \"\" , None ) collected = __collect_outputs ( job_directory , staging_config , action_executor ) return collected finally : job_directory . write_file ( \"\" , \"\" ) return False def __collect_outputs ( job_directory , staging_config , action_executor ) : collected = True if \"\" in staging_config : file_action_mapper = action_mapper . FileActionMapper ( config = staging_config [ \"\" ] ) client_outputs = staging . ClientOutputs . from_dict ( staging_config [ \"\" ] ) pulsar_outputs = __pulsar_outputs ( job_directory ) output_collector = PulsarServerOutputCollector ( job_directory , action_executor ) results_collector = ResultsCollector ( output_collector , file_action_mapper , client_outputs , pulsar_outputs ) collection_failure_exceptions = results_collector . collect ( ) if collection_failure_exceptions : log . warn ( \"\" % collection_failure_exceptions ) collected = False return collected class PulsarServerOutputCollector ( object ) : def __init__ ( self , job_directory , action_executor ) : self . job_directory = job_directory self . action_executor = action_executor def collect_output ( self , results_collector , output_type , action , name ) : if action . staging_action_local : return if not name : name = os . path . basename ( action . path ) pulsar_path = self . job_directory . calculate_path ( name , output_type ) description = \"\" % ( pulsar_path , action ) self . action_executor . execute ( lambda : action . write_from_path ( pulsar_path ) , description ) ", "answer": "def __pulsar_outputs ( job_directory ) :"}, {"prompt": " from namespaces import ANIMNS from element import Element def Animate ( ** args ) : return Element ( qname = ( ANIMNS , '' ) , ** args ) def Animatecolor ( ** args ) : return Element ( qname = ( ANIMNS , '' ) , ** args ) def Animatemotion ( ** args ) : return Element ( qname = ( ANIMNS , '' ) , ** args ) def Animatetransform ( ** args ) : return Element ( qname = ( ANIMNS , '' ) , ** args ) def Audio ( ** args ) : return Element ( qname = ( ANIMNS , '' ) , ** args ) def Command ( ** args ) : return Element ( qname = ( ANIMNS , '' ) , ** args ) def Iterate ( ** args ) : return Element ( qname = ( ANIMNS , '' ) , ** args ) def Par ( ** args ) : ", "answer": "return Element ( qname = ( ANIMNS , '' ) , ** args )"}, {"prompt": " \"\"\"\"\"\" from pandas . tseries . tools import * from pandas . tseries . offsets import * from pandas . tseries . frequencies import * day = DateOffset ( ) bday = BDay ( ) businessDay = bday try : cday = CDay ( ) customBusinessDay = CustomBusinessDay ( ) customBusinessMonthEnd = CBMonthEnd ( ) customBusinessMonthBegin = CBMonthBegin ( ) except NotImplementedError : cday = None customBusinessDay = None customBusinessMonthEnd = None customBusinessMonthBegin = None monthEnd = MonthEnd ( ) yearEnd = YearEnd ( ) yearBegin = YearBegin ( ) bmonthEnd = BMonthEnd ( ) bmonthBegin = BMonthBegin ( ) cbmonthEnd = customBusinessMonthEnd cbmonthBegin = customBusinessMonthBegin bquarterEnd = BQuarterEnd ( ) quarterEnd = QuarterEnd ( ) byearEnd = BYearEnd ( ) week = Week ( ) thisMonthEnd = MonthEnd ( ) thisBMonthEnd = BMonthEnd ( ) ", "answer": "thisYearEnd = YearEnd ( )"}, {"prompt": " from django . utils . translation import ugettext_lazy as _ from horizon import tabs class NetworkProfileTab ( tabs . Tab ) : name = _ ( \"\" ) slug = \"\" template_name = '' ", "answer": "def get_context_data ( self , request ) :"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from matplotlib import pyplot as plt"}, {"prompt": " import os , hashlib , errno from django . utils . encoding import force_text , force_bytes from storages . compat import FileSystemStorage class HashPathStorage ( FileSystemStorage ) : \"\"\"\"\"\" def save ( self , name , content , max_length = None ) : if name is None : name = content . name ", "answer": "sha1 = hashlib . sha1 ( )"}, {"prompt": " from nova . utils import import_object from nova . rpc . common import RemoteError , LOG from nova import flags FLAGS = flags . FLAGS flags . DEFINE_string ( '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" import StringIO try : from twisted . web import client except ImportError : msn = None else : from twisted . words . protocols import msn from twisted . python . hashlib import md5 from twisted . protocols import loopback from twisted . internet . defer import Deferred from twisted . trial import unittest from twisted . test . proto_helpers import StringTransport , StringIOWithoutClosing def printError ( f ) : print f class PassportTests ( unittest . TestCase ) : def setUp ( self ) : self . result = [ ] self . deferred = Deferred ( ) self . deferred . addCallback ( lambda r : self . result . append ( r ) ) self . deferred . addErrback ( printError ) def test_nexus ( self ) : \"\"\"\"\"\" protocol = msn . PassportNexus ( self . deferred , '' ) headers = { '' : '' , '' : '' , '' : '' } transport = StringTransport ( ) protocol . makeConnection ( transport ) protocol . dataReceived ( '' ) for ( h , v ) in headers . items ( ) : protocol . dataReceived ( '' % ( h , v ) ) protocol . dataReceived ( '' ) self . assertEquals ( self . result [ ] , \"\" ) def _doLoginTest ( self , response , headers ) : protocol = msn . PassportLogin ( self . deferred , '' , '' , '' , '' ) protocol . makeConnection ( StringTransport ( ) ) protocol . dataReceived ( response ) for ( h , v ) in headers . items ( ) : protocol . dataReceived ( '' % ( h , v ) ) protocol . dataReceived ( '' ) def testPassportLoginSuccess ( self ) : headers = { '' : '' , '' : '' , '' : \"\" + \"\" + \"\" } self . _doLoginTest ( '' , headers ) self . failUnless ( self . result [ ] == ( msn . LOGIN_SUCCESS , '' ) ) def testPassportLoginFailure ( self ) : headers = { '' : '' , '' : '' + '' + '' } self . _doLoginTest ( '' , headers ) self . failUnless ( self . result [ ] == ( msn . LOGIN_FAILURE , '' ) ) def testPassportLoginRedirect ( self ) : headers = { '' : '' , '' : '' , '' : '' } self . _doLoginTest ( '' , headers ) self . failUnless ( self . result [ ] == ( msn . LOGIN_REDIRECT , '' , '' ) ) if msn is not None : class DummySwitchboardClient ( msn . SwitchboardClient ) : def userTyping ( self , message ) : self . state = '' def gotSendRequest ( self , fileName , fileSize , cookie , message ) : if fileName == '' and fileSize == and cookie == : self . state = '' class DummyNotificationClient ( msn . NotificationClient ) : def loggedIn ( self , userHandle , screenName , verified ) : if userHandle == '' and screenName == '' and verified : self . state = '' def gotProfile ( self , message ) : self . state = '' def gotContactStatus ( self , code , userHandle , screenName ) : if code == msn . STATUS_AWAY and userHandle == \"\" and screenName == \"\" : self . state = '' def contactStatusChanged ( self , code , userHandle , screenName ) : if code == msn . STATUS_LUNCH and userHandle == \"\" and screenName == \"\" : self . state = '' def contactOffline ( self , userHandle ) : if userHandle == \"\" : self . state = '' def statusChanged ( self , code ) : if code == msn . STATUS_HIDDEN : self . state = '' def listSynchronized ( self , * args ) : self . state = '' def gotPhoneNumber ( self , listVersion , userHandle , phoneType , number ) : msn . NotificationClient . gotPhoneNumber ( self , listVersion , userHandle , phoneType , number ) self . state = '' def userRemovedMe ( self , userHandle , listVersion ) : msn . NotificationClient . userRemovedMe ( self , userHandle , listVersion ) c = self . factory . contacts . getContact ( userHandle ) if not c and self . factory . contacts . version == listVersion : self . state = '' def userAddedMe ( self , userHandle , screenName , listVersion ) : msn . NotificationClient . userAddedMe ( self , userHandle , screenName , listVersion ) c = self . factory . contacts . getContact ( userHandle ) if c and ( c . lists | msn . REVERSE_LIST ) and ( self . factory . contacts . version == listVersion ) and ( screenName == '' ) : self . state = '' def gotSwitchboardInvitation ( self , sessionID , host , port , key , userHandle , screenName ) : if sessionID == and host == '' and port == and key == '' and userHandle == '' and screenName == '' : self . state = '' class DispatchTests ( unittest . TestCase ) : \"\"\"\"\"\" def _versionTest ( self , serverVersionResponse ) : \"\"\"\"\"\" client = msn . DispatchClient ( ) client . userHandle = \"\" transport = StringTransport ( ) client . makeConnection ( transport ) self . assertEquals ( transport . value ( ) , \"\" ) transport . clear ( ) client . dataReceived ( serverVersionResponse ) self . assertEquals ( transport . value ( ) , \"\" ) def test_version ( self ) : \"\"\"\"\"\" self . _versionTest ( \"\" ) def test_versionWithoutCVR0 ( self ) : \"\"\"\"\"\" self . _versionTest ( \"\" ) class NotificationTests ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . client = DummyNotificationClient ( ) self . client . factory = msn . NotificationFactory ( ) self . client . state = '' def tearDown ( self ) : self . client = None def _versionTest ( self , serverVersionResponse ) : \"\"\"\"\"\" self . client . factory . userHandle = \"\" transport = StringTransport ( ) self . client . makeConnection ( transport ) self . assertEquals ( transport . value ( ) , \"\" ) transport . clear ( ) self . client . dataReceived ( serverVersionResponse ) self . assertEquals ( transport . value ( ) , \"\" ) def test_version ( self ) : \"\"\"\"\"\" self . _versionTest ( \"\" ) def test_versionWithoutCVR0 ( self ) : \"\"\"\"\"\" self . _versionTest ( \"\" ) def test_challenge ( self ) : \"\"\"\"\"\" transport = StringTransport ( ) self . client . makeConnection ( transport ) transport . clear ( ) challenge = \"\" self . client . dataReceived ( '' + challenge + '' ) response = \"\" self . assertEquals ( response , md5 ( challenge + \"\" ) . hexdigest ( ) ) self . assertEquals ( transport . value ( ) , \"\" + response ) def testLogin ( self ) : self . client . lineReceived ( '' ) self . failUnless ( ( self . client . state == '' ) , msg = '' ) def testProfile ( self ) : m = '' m += '' m += '' m += '' map ( self . client . lineReceived , m . split ( '' ) [ : - ] ) self . failUnless ( ( self . client . state == '' ) , msg = '' ) def testStatus ( self ) : t = [ ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) ] for i in t : self . client . lineReceived ( i [ ] ) self . failUnless ( ( self . client . state == i [ ] ) , msg = i [ ] ) def testListSync ( self ) : self . client . makeConnection ( StringTransport ( ) ) msn . NotificationClient . loggedIn ( self . client , '' , '' , ) lines = [ \"\" % self . client . currentID , \"\" , \"\" , \"\" , \"\" ] map ( self . client . lineReceived , lines ) contacts = self . client . factory . contacts contact = contacts . getContact ( '' ) self . failUnless ( contacts . version == , \"\" ) self . failUnless ( contact . screenName == '' , \"\" ) self . failUnless ( contacts . groups == { : '' } , \"\" ) self . failUnless ( contact . groups == [ ] and contact . lists == , \"\" ) self . failUnless ( self . client . state == '' , \"\" ) def testAsyncPhoneChange ( self ) : c = msn . MSNContact ( userHandle = '' ) self . client . factory . contacts = msn . MSNContactList ( ) self . client . factory . contacts . addContact ( c ) self . client . makeConnection ( StringTransport ( ) ) self . client . lineReceived ( \"\" ) c = self . client . factory . contacts . getContact ( '' ) self . failUnless ( self . client . state == '' , \"\" ) self . failUnless ( c . homePhone == '' , \"\" ) self . failUnless ( self . client . factory . contacts . version == , \"\" ) def testLateBPR ( self ) : \"\"\"\"\"\" self . client . makeConnection ( StringTransport ( ) ) msn . NotificationClient . loggedIn ( self . client , '' , '' , ) lines = [ \"\" % self . client . currentID , \"\" , \"\" , \"\" , \"\" , \"\" ] map ( self . client . lineReceived , lines ) contact = self . client . factory . contacts . getContact ( '' ) self . failUnless ( contact . homePhone == '' , \"\" ) def testUserRemovedMe ( self ) : self . client . factory . contacts = msn . MSNContactList ( ) contact = msn . MSNContact ( userHandle = '' ) contact . addToList ( msn . REVERSE_LIST ) self . client . factory . contacts . addContact ( contact ) self . client . lineReceived ( \"\" ) self . failUnless ( self . client . state == '' , \"\" ) def testUserAddedMe ( self ) : self . client . factory . contacts = msn . MSNContactList ( ) self . client . lineReceived ( \"\" ) self . failUnless ( self . client . state == '' , \"\" ) def testAsyncSwitchboardInvitation ( self ) : self . client . lineReceived ( \"\" ) self . failUnless ( self . client . state == \"\" ) def testCommandFailed ( self ) : \"\"\"\"\"\" id , d = self . client . _createIDMapping ( ) self . client . lineReceived ( \"\" % id ) d = self . assertFailure ( d , msn . MSNCommandFailed ) def assertErrorCode ( exception ) : self . assertEqual ( , exception . errorCode ) return d . addCallback ( assertErrorCode ) class MessageHandlingTests ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . client = DummySwitchboardClient ( ) self . client . state = '' def tearDown ( self ) : self . client = None ", "answer": "def testClientCapabilitiesCheck ( self ) :"}, {"prompt": " sql = [ \"\"\"\"\"\" , \"\"\"\"\"\" , \"\"\"\"\"\" , \"\"\"\"\"\" , \"\"\"\"\"\" , ", "answer": "\"\"\"\"\"\" ,"}, {"prompt": " import six from django . conf import settings as django_settings from django . utils . functional import LazyObject from inline_media . conf import defaults as app_settings class LazySettings ( LazyObject ) : def _setup ( self ) : self . _wrapped = Settings ( app_settings , django_settings ) def update_dict_in_depth ( a , b ) : \"\"\"\"\"\" for k , v in six . iteritems ( b ) : ", "answer": "if a . get ( k , None ) and type ( v ) == dict :"}, {"prompt": " from django . contrib import admin from oscar . core . loading import get_model Line = get_model ( '' , '' ) class LineInline ( admin . TabularInline ) : model = Line readonly_fields = ( '' , '' , '' , '' , '' , '' ) class LineAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' , '' , '' , '' , '' , '' , '' ) readonly_fields = ( '' , '' , '' , '' , '' , '' , '' , '' ) class BasketAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' , '' , '' , '' , '' , '' , '' ) ", "answer": "readonly_fields = ( '' , '' , '' )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import os import sys import timeit import numpy import theano import theano . tensor as T from theano . tensor . shared_randomstreams import RandomStreams from logistic_sgd import LogisticRegression , load_data from mlp import HiddenLayer from dA import dA class SdA ( object ) : \"\"\"\"\"\" def __init__ ( self , numpy_rng , theano_rng = None , n_ins = , hidden_layers_sizes = [ , ] , n_outs = , corruption_levels = [ , ] ) : \"\"\"\"\"\" self . sigmoid_layers = [ ] self . dA_layers = [ ] self . params = [ ] self . n_layers = len ( hidden_layers_sizes ) assert self . n_layers > if not theano_rng : theano_rng = RandomStreams ( numpy_rng . randint ( ** ) ) self . x = T . matrix ( '' ) self . y = T . ivector ( '' ) for i in range ( self . n_layers ) : if i == : input_size = n_ins else : input_size = hidden_layers_sizes [ i - ] if i == : layer_input = self . x else : layer_input = self . sigmoid_layers [ - ] . output sigmoid_layer = HiddenLayer ( rng = numpy_rng , input = layer_input , n_in = input_size , n_out = hidden_layers_sizes [ i ] , activation = T . nnet . sigmoid ) self . sigmoid_layers . append ( sigmoid_layer ) self . params . extend ( sigmoid_layer . params ) dA_layer = dA ( numpy_rng = numpy_rng , theano_rng = theano_rng , input = layer_input , n_visible = input_size , n_hidden = hidden_layers_sizes [ i ] , W = sigmoid_layer . W , bhid = sigmoid_layer . b ) self . dA_layers . append ( dA_layer ) self . logLayer = LogisticRegression ( input = self . sigmoid_layers [ - ] . output , n_in = hidden_layers_sizes [ - ] , n_out = n_outs ) self . params . extend ( self . logLayer . params ) self . finetune_cost = self . logLayer . negative_log_likelihood ( self . y ) self . errors = self . logLayer . errors ( self . y ) def pretraining_functions ( self , train_set_x , batch_size ) : '''''' index = T . lscalar ( '' ) corruption_level = T . scalar ( '' ) learning_rate = T . scalar ( '' ) batch_begin = index * batch_size batch_end = batch_begin + batch_size pretrain_fns = [ ] for dA in self . dA_layers : cost , updates = dA . get_cost_updates ( corruption_level , learning_rate ) fn = theano . function ( inputs = [ index , theano . In ( corruption_level , value = ) , theano . In ( learning_rate , value = ) ] , outputs = cost , updates = updates , givens = { self . x : train_set_x [ batch_begin : batch_end ] } ) pretrain_fns . append ( fn ) return pretrain_fns def build_finetune_functions ( self , datasets , batch_size , learning_rate ) : '''''' ( train_set_x , train_set_y ) = datasets [ ] ( valid_set_x , valid_set_y ) = datasets [ ] ( test_set_x , test_set_y ) = datasets [ ] n_valid_batches = valid_set_x . get_value ( borrow = True ) . shape [ ] n_valid_batches //= batch_size n_test_batches = test_set_x . get_value ( borrow = True ) . shape [ ] n_test_batches //= batch_size index = T . lscalar ( '' ) gparams = T . grad ( self . finetune_cost , self . params ) updates = [ ( param , param - gparam * learning_rate ) for param , gparam in zip ( self . params , gparams ) ] train_fn = theano . function ( inputs = [ index ] , outputs = self . finetune_cost , updates = updates , givens = { self . x : train_set_x [ index * batch_size : ( index + ) * batch_size ] , self . y : train_set_y [ index * batch_size : ( index + ) * batch_size ] } , name = '' ) test_score_i = theano . function ( [ index ] , self . errors , givens = { self . x : test_set_x [ index * batch_size : ( index + ) * batch_size ] , self . y : test_set_y [ index * batch_size : ( index + ) * batch_size ] } , name = '' ) valid_score_i = theano . function ( [ index ] , self . errors , givens = { self . x : valid_set_x [ index * batch_size : ( index + ) * batch_size ] , self . y : valid_set_y [ index * batch_size : ( index + ) * batch_size ] } , name = '' ) def valid_score ( ) : return [ valid_score_i ( i ) for i in range ( n_valid_batches ) ] def test_score ( ) : return [ test_score_i ( i ) for i in range ( n_test_batches ) ] return train_fn , valid_score , test_score def test_SdA ( finetune_lr = , pretraining_epochs = , pretrain_lr = , training_epochs = , dataset = '' , batch_size = ) : \"\"\"\"\"\" datasets = load_data ( dataset ) train_set_x , train_set_y = datasets [ ] valid_set_x , valid_set_y = datasets [ ] test_set_x , test_set_y = datasets [ ] n_train_batches = train_set_x . get_value ( borrow = True ) . shape [ ] n_train_batches //= batch_size numpy_rng = numpy . random . RandomState ( ) print ( '' ) sda = SdA ( numpy_rng = numpy_rng , n_ins = * , hidden_layers_sizes = [ , , ] , n_outs = ) print ( '' ) pretraining_fns = sda . pretraining_functions ( train_set_x = train_set_x , batch_size = batch_size ) print ( '' ) start_time = timeit . default_timer ( ) corruption_levels = [ , , ] for i in range ( sda . n_layers ) : for epoch in range ( pretraining_epochs ) : ", "answer": "c = [ ]"}, {"prompt": " import numpy as np from . . util . warping_functions import * from . . core import GP from . . import likelihoods from GPy . util . warping_functions import TanhWarpingFunction_d from GPy import kern class WarpedGP ( GP ) : def __init__ ( self , X , Y , kernel = None , warping_function = None , warping_terms = ) : if kernel is None : kernel = kern . RBF ( X . shape [ ] ) if warping_function == None : self . warping_function = TanhWarpingFunction_d ( warping_terms ) self . warping_params = ( np . random . randn ( self . warping_function . n_terms * + ) * ) else : self . warping_function = warping_function self . scale_data = False if self . scale_data : Y = self . _scale_data ( Y ) self . Y_untransformed = Y . copy ( ) self . predict_in_warped_space = True likelihood = likelihoods . Gaussian ( ) GP . __init__ ( self , X , self . transform_data ( ) , likelihood = likelihood , kernel = kernel ) self . link_parameter ( self . warping_function ) def _scale_data ( self , Y ) : self . _Ymax = Y . max ( ) self . _Ymin = Y . min ( ) return ( Y - self . _Ymin ) / ( self . _Ymax - self . _Ymin ) - def _unscale_data ( self , Y ) : return ( Y + ) * ( self . _Ymax - self . _Ymin ) + self . _Ymin def parameters_changed ( self ) : self . Y [ : ] = self . transform_data ( ) super ( WarpedGP , self ) . parameters_changed ( ) Kiy = self . posterior . woodbury_vector . flatten ( ) grad_y = self . warping_function . fgrad_y ( self . Y_untransformed ) grad_y_psi , grad_psi = self . warping_function . fgrad_y_psi ( self . Y_untransformed , return_covar_chain = True ) djac_dpsi = ( ( / grad_y [ : , : , None , None ] ) * grad_y_psi ) . sum ( axis = ) . sum ( axis = ) dquad_dpsi = ( Kiy [ : , None , None , None ] * grad_psi ) . sum ( axis = ) . sum ( axis = ) warping_grads = - dquad_dpsi + djac_dpsi self . warping_function . psi . gradient [ : ] = warping_grads [ : , : - ] self . warping_function . d . gradient [ : ] = warping_grads [ , - ] def transform_data ( self ) : Y = self . warping_function . f ( self . Y_untransformed . copy ( ) ) . copy ( ) return Y def log_likelihood ( self ) : ll = GP . log_likelihood ( self ) jacobian = self . warping_function . fgrad_y ( self . Y_untransformed ) return ll + np . log ( jacobian ) . sum ( ) def plot_warping ( self ) : self . warping_function . plot ( self . Y_untransformed . min ( ) , self . Y_untransformed . max ( ) ) def _get_warped_term ( self , mean , std , gh_samples , pred_init = None ) : arg1 = gh_samples . dot ( std . T ) * np . sqrt ( ) arg2 = np . ones ( shape = gh_samples . shape ) . dot ( mean . T ) return self . warping_function . f_inv ( arg1 + arg2 , y = pred_init ) def _get_warped_mean ( self , mean , std , pred_init = None , deg_gauss_hermite = ) : \"\"\"\"\"\" gh_samples , gh_weights = np . polynomial . hermite . hermgauss ( deg_gauss_hermite ) gh_samples = gh_samples [ : , None ] gh_weights = gh_weights [ None , : ] return gh_weights . dot ( self . _get_warped_term ( mean , std , gh_samples ) ) / np . sqrt ( np . pi ) def _get_warped_variance ( self , mean , std , pred_init = None , deg_gauss_hermite = ) : \"\"\"\"\"\" gh_samples , gh_weights = np . polynomial . hermite . hermgauss ( deg_gauss_hermite ) gh_samples = gh_samples [ : , None ] gh_weights = gh_weights [ None , : ] arg1 = gh_weights . dot ( self . _get_warped_term ( mean , std , gh_samples , pred_init = pred_init ) ** ) / np . sqrt ( np . pi ) arg2 = self . _get_warped_mean ( mean , std , pred_init = pred_init , deg_gauss_hermite = deg_gauss_hermite ) return arg1 - ( arg2 ** ) def predict ( self , Xnew , which_parts = '' , pred_init = None , full_cov = False , Y_metadata = None , median = False , deg_gauss_hermite = ) : mu , var = GP . _raw_predict ( self , Xnew ) mean , var = self . likelihood . predictive_values ( mu , var ) if self . predict_in_warped_space : std = np . sqrt ( var ) if median : wmean = self . warping_function . f_inv ( mean , y = pred_init ) else : ", "answer": "wmean = self . _get_warped_mean ( mean , std , pred_init = pred_init ,"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import json from hashlib import sha1 from pants . base . payload_field import PayloadField class PythonArtifact ( PayloadField ) : \"\"\"\"\"\" class MissingArgument ( Exception ) : pass class UnsupportedArgument ( Exception ) : pass UNSUPPORTED_ARGS = frozenset ( [ '' , '' , ", "answer": "'' ,"}, {"prompt": " __author__ = '' __email__ = '' ", "answer": "__version__ = '' "}, {"prompt": " '''''' from time import time from time import sleep import threading def main ( ) : if PYTHON == '' : pythonjs . configure ( direct_operator = '' ) pass starttime = time ( ) n = seq = [ ] cache = [ ] w1 = threading . start_webworker ( worker , ( , n , seq , cache ) ) sleep ( ) testtime = time ( ) - starttime primes_per_sec = len ( seq ) * ( / testtime ) print ( primes_per_sec ) print ( '' % testtime ) print ( '' ) with webworker : def worker ( start , end , seq , cache ) : print ( '' ) for i in range ( start , end ) : if i in cache : pass else : ", "answer": "cache . append ( i )"}, {"prompt": " from zope . interface import Attribute from zope . interface import Interface from zope . interface import implements class IIndexEvent ( Interface ) : \"\"\"\"\"\" class IIndexUpdate ( Interface ) : \"\"\"\"\"\" class IPackageEvent ( IIndexEvent ) : \"\"\"\"\"\" path = Attribute ( '' ) class IPackageAdded ( IPackageEvent ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " __author__ = '' import numpy as np import theano from sklearn . base import TransformerMixin from pylearn2 . datasets . vector_spaces_dataset import VectorSpacesDataset ", "answer": "from pylearn2 . space import VectorSpace , CompositeSpace"}, {"prompt": " \"\"\"\"\"\" import itertools import inspect from . core import GroupMixin , Command from . errors import CommandError class HelpFormatter : \"\"\"\"\"\" def __init__ ( self , show_hidden = False , show_check_failure = False , width = ) : self . width = width self . show_hidden = show_hidden self . show_check_failure = show_check_failure def has_subcommands ( self ) : \"\"\"\"\"\" return isinstance ( self . command , GroupMixin ) def is_bot ( self ) : \"\"\"\"\"\" return self . command is self . context . bot def is_cog ( self ) : \"\"\"\"\"\" return not self . is_bot ( ) and not isinstance ( self . command , Command ) def shorten ( self , text ) : \"\"\"\"\"\" if len ( text ) > self . width : return text [ : self . width - ] + '' return text @ property def max_name_size ( self ) : \"\"\"\"\"\" try : commands = self . command . commands if not self . is_cog ( ) else self . context . bot . commands if commands : return max ( map ( lambda c : len ( c . name ) , commands . values ( ) ) ) return except AttributeError : return len ( self . command . name ) @ property def clean_prefix ( self ) : \"\"\"\"\"\" user = self . context . bot . user return self . context . prefix . replace ( user . mention , '' + user . name ) def get_qualified_command_name ( self ) : \"\"\"\"\"\" entries = [ ] command = self . command while command . parent is not None : command = command . parent entries . append ( command . name ) return '' . join ( reversed ( entries ) ) def get_command_signature ( self ) : \"\"\"\"\"\" result = [ ] prefix = self . clean_prefix qualified = self . get_qualified_command_name ( ) cmd = self . command if len ( cmd . aliases ) > : aliases = '' . join ( cmd . aliases ) fmt = '' if qualified : fmt = '' result . append ( fmt . format ( prefix , cmd , aliases , qualified ) ) else : name = prefix + cmd . name if not qualified else prefix + qualified + '' + cmd . name result . append ( name ) params = cmd . clean_params if len ( params ) > : for name , param in params . items ( ) : ", "answer": "if param . default is not param . empty :"}, {"prompt": " import os from PySide . QtGui import * from PySide . QtCore import * from ui_Event import Ui_Event '''''' class EventWindow ( QDialog , Ui_Event ) : def __init__ ( self , parent , eventId ) : super ( EventWindow , self ) . __init__ ( parent ) self . rent = parent self . data = parent . eventData [ eventId ] self . deckAssignment = [ ] self . setupUi ( self ) self . assignWidgets ( ) self . setWindowTitle ( unicode ( \"\" % eventId ) ) def savePressed ( self ) : self . data [ \"\" ] = self . notesText . toPlainText ( ) self . data [ \"\" ] = self . deckText . text ( ) self . data [ \"\" ] = self . placeText . text ( ) ", "answer": "self . data [ \"\" ] = self . eventTypeText . text ( )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AddField ( model_name = '' , ", "answer": "name = '' ,"}, {"prompt": " \"\"\"\"\"\" from errno import ENOENT from stat import S_IFDIR , S_IFREG , S_IFLNK from sys import argv , exit import re import time import os import argparse from fuse import FUSE , FuseOSError , Operations , LoggingMixIn , fuse_get_context from bioblend import galaxy CACHE_TIME = def path_type ( path ) : parts = filter ( lambda x : len ( x ) > , path . split ( '' ) ) if path == '' : return ( '' , dict ( ) ) elif path == '' : return ( '' , dict ( ) ) elif len ( parts ) == and parts [ ] == '' : return ( '' , dict ( h_name = unesc_filename ( parts [ ] ) ) ) elif len ( parts ) == and parts [ ] == '' : return ( '' , dict ( h_name = unesc_filename ( parts [ ] ) , ds_name = unesc_filename ( parts [ ] ) ) ) print \"\" % path return ( '' , ) def esc_filename ( fname ) : def esc ( m ) : c = m . group ( ) if c == '' : return '' elif c == '' : return '' return re . sub ( r'' , esc , fname ) def unesc_filename ( fname ) : def unesc ( m ) : str = m . group ( ) if str == '' : return '' elif str == '' : return '' return re . sub ( r'' , unesc , fname ) def parse_name_with_id ( fname ) : m = re . match ( r\"\" , fname ) if m is not None : return ( m . group ( '' ) , m . group ( '' ) ) else : return ( fname , '' ) class Context ( LoggingMixIn , Operations ) : '' def __init__ ( self , api_key ) : self . gi = galaxy . GalaxyInstance ( url = '' , key = api_key ) self . datasets_cache = { } self . histories_cache = { '' : None , '' : None } def getattr ( self , path , fh = None ) : ( typ , kw ) = path_type ( path ) now = time . time ( ) if typ == '' or typ == '' : st = dict ( st_mode = ( S_IFDIR | ) , st_nlink = ) st [ '' ] = st [ '' ] = st [ '' ] = now elif typ == '' : st = dict ( st_mode = ( S_IFDIR | ) , st_nlink = ) st [ '' ] = st [ '' ] = st [ '' ] = now ", "answer": "elif typ == '' :"}, {"prompt": " __author__ = '' import wx from wx import AboutBox , AboutDialogInfo , ClientDC from wx . lib . wordwrap import wordwrap ", "answer": "from odmtools . meta import data"}, {"prompt": " import os from nose . tools import with_setup , eq_ as eq , ok_ as ok from test_common import vim , cleanup @ with_setup ( setup = cleanup ) def test_buffer ( ) : eq ( vim . current . buffer , vim . windows [ ] . buffer ) vim . command ( '' ) vim . current . window = vim . windows [ ] eq ( vim . current . buffer , vim . windows [ ] . buffer ) ok ( vim . windows [ ] . buffer != vim . windows [ ] . buffer ) @ with_setup ( setup = cleanup ) def test_cursor ( ) : eq ( vim . current . window . cursor , [ , ] ) vim . command ( '' ) eq ( vim . current . buffer [ : ] , [ '' , '' ] ) eq ( vim . current . window . cursor , [ , ] ) vim . current . window . cursor = [ , ] vim . command ( '' ) eq ( vim . current . buffer [ : ] , [ '' , '' ] ) @ with_setup ( setup = cleanup ) def test_height ( ) : vim . command ( '' ) eq ( vim . windows [ ] . height , vim . windows [ ] . height ) vim . current . window = vim . windows [ ] vim . command ( '' ) eq ( vim . windows [ ] . height , vim . windows [ ] . height // ) vim . windows [ ] . height = eq ( vim . windows [ ] . height , ) @ with_setup ( setup = cleanup ) def test_width ( ) : vim . command ( '' ) eq ( vim . windows [ ] . width , vim . windows [ ] . width ) vim . current . window = vim . windows [ ] vim . command ( '' ) eq ( vim . windows [ ] . width , vim . windows [ ] . width // ) vim . windows [ ] . width = eq ( vim . windows [ ] . width , ) @ with_setup ( setup = cleanup ) def test_vars ( ) : vim . current . window . vars [ '' ] = [ , , { '' : } ] eq ( vim . current . window . vars [ '' ] , [ , , { '' : } ] ) eq ( vim . eval ( '' ) , [ , , { '' : } ] ) @ with_setup ( setup = cleanup ) def test_options ( ) : vim . current . window . options [ '' ] = '' ", "answer": "eq ( vim . current . window . options [ '' ] , '' )"}, {"prompt": " import re from django . template import Node , Variable , VariableNode from django . template import TemplateSyntaxError , TokenParser , Library from django . template import TOKEN_TEXT , TOKEN_VAR from django . utils import translation from django . utils . encoding import force_unicode register = Library ( ) class GetAvailableLanguagesNode ( Node ) : def __init__ ( self , variable ) : self . variable = variable def render ( self , context ) : from django . conf import settings context [ self . variable ] = [ ( k , translation . ugettext ( v ) ) for k , v in settings . LANGUAGES ] return '' class GetCurrentLanguageNode ( Node ) : def __init__ ( self , variable ) : self . variable = variable def render ( self , context ) : context [ self . variable ] = translation . get_language ( ) return '' class GetCurrentLanguageBidiNode ( Node ) : def __init__ ( self , variable ) : self . variable = variable def render ( self , context ) : context [ self . variable ] = translation . get_language_bidi ( ) return '' class TranslateNode ( Node ) : def __init__ ( self , value , noop ) : self . value = Variable ( value ) self . noop = noop def render ( self , context ) : value = self . value . resolve ( context ) if self . noop : return value else : return translation . ugettext ( value ) class BlockTranslateNode ( Node ) : def __init__ ( self , extra_context , singular , plural = None , countervar = None , counter = None ) : self . extra_context = extra_context self . singular = singular self . plural = plural self . countervar = countervar self . counter = counter def render_token_list ( self , tokens ) : result = [ ] vars = [ ] for token in tokens : if token . token_type == TOKEN_TEXT : result . append ( token . contents ) elif token . token_type == TOKEN_VAR : result . append ( u'' % token . contents ) vars . append ( token . contents ) return '' . join ( result ) , vars def render ( self , context ) : tmp_context = { } for var , val in self . extra_context . items ( ) : tmp_context [ var ] = val . render ( context ) context . update ( tmp_context ) singular , vars = self . render_token_list ( self . singular ) if self . plural and self . countervar and self . counter : count = self . counter . resolve ( context ) context [ self . countervar ] = count plural , vars = self . render_token_list ( self . plural ) result = translation . ungettext ( singular , plural , count ) else : result = translation . ugettext ( singular ) result = re . sub ( u'' , u'' , result ) data = dict ( [ ( v , force_unicode ( context [ v ] ) ) for v in vars ] ) context . pop ( ) return result % data def do_get_available_languages ( parser , token ) : \"\"\"\"\"\" args = token . contents . split ( ) if len ( args ) != or args [ ] != '' : raise TemplateSyntaxError , \"\" % args return GetAvailableLanguagesNode ( args [ ] ) def do_get_current_language ( parser , token ) : \"\"\"\"\"\" args = token . contents . split ( ) if len ( args ) != or args [ ] != '' : raise TemplateSyntaxError , \"\" % args return GetCurrentLanguageNode ( args [ ] ) def do_get_current_language_bidi ( parser , token ) : \"\"\"\"\"\" args = token . contents . split ( ) if len ( args ) != or args [ ] != '' : raise TemplateSyntaxError , \"\" % args return GetCurrentLanguageBidiNode ( args [ ] ) def do_translate ( parser , token ) : \"\"\"\"\"\" class TranslateParser ( TokenParser ) : def top ( self ) : value = self . value ( ) if self . more ( ) : ", "answer": "if self . tag ( ) == '' :"}, {"prompt": " \"\"\"\"\"\" import _imp from . _bootstrap import ( SOURCE_SUFFIXES , DEBUG_BYTECODE_SUFFIXES , OPTIMIZED_BYTECODE_SUFFIXES , EXTENSION_SUFFIXES ) from . _bootstrap import BuiltinImporter from . _bootstrap import FrozenImporter from . _bootstrap import WindowsRegistryFinder from . _bootstrap import PathFinder from . _bootstrap import FileFinder from . _bootstrap import SourceFileLoader from . _bootstrap import SourcelessFileLoader ", "answer": "from . _bootstrap import ExtensionFileLoader "}, {"prompt": " import json from mock import patch import pytest from werkzeug . wrappers import Response from nameko . testing . utils import get_extension from nameko . web . handlers import http , HttpRequestHandler class ExampleService ( object ) : name = \"\" @ http ( '' , '' ) def do_get ( self , request , bar ) : return '' . format ( bar ) @ http ( '' , '' ) def do_post ( self , request ) : data = json . loads ( request . get_data ( as_text = True ) ) value = data [ '' ] return value @ http ( '' , '' ) def do_custom ( self , request ) : return Response ( '' ) @ http ( '' , '' ) def do_status_code ( self , request ) : return , '' @ http ( '' , '' ) def do_headers ( self , request ) : return , { '' : '' } , '' @ http ( '' , '' ) def fail ( self , request ) : raise ValueError ( '' ) @ http ( '' , '' , expected_exceptions = ValueError ) def fail_expected ( self , request ) : raise ValueError ( '' ) class SimpleService ( object ) : name = \"\" @ http ( '' , '' ) def method ( self , request ) : pass @ pytest . fixture def web_session ( container_factory , web_config , web_session ) : container = container_factory ( ExampleService , web_config ) container . start ( ) return web_session def test_get ( web_session ) : rv = web_session . get ( '' ) assert rv . text == '' rv = web_session . get ( '' ) assert rv . status_code == def test_post ( web_session ) : rv = web_session . post ( '' , data = json . dumps ( { '' : '' , } ) ) assert rv . text == \"\" def test_custom_response ( web_session ) : rv = web_session . get ( '' ) assert rv . text == '' def test_custom_status_code ( web_session ) : rv = web_session . get ( '' ) assert rv . text == '' assert rv . status_code == def test_custom_headers ( web_session ) : rv = web_session . get ( '' ) ", "answer": "assert rv . text == ''"}, {"prompt": " from django . contrib . contenttypes . models import ContentType from nose . tools import eq_ from kitsune . access . tests import PermissionFactory from kitsune . forums . tests import ForumTestCase , ForumFactory , ThreadFactory , PostFactory from kitsune . sumo . tests import get , post from kitsune . users . tests import UserFactory , GroupFactory class BelongsTestCase ( ForumTestCase ) : \"\"\"\"\"\" def test_posts_thread_belongs_to_forum ( self ) : \"\"\"\"\"\" f = ForumFactory ( ) t = ThreadFactory ( ) r = get ( self . client , '' , args = [ f . slug , t . id ] ) eq_ ( , r . status_code ) ", "answer": "u = r . redirect_chain [ ] [ ]"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Ship ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " from . pandas_vb_common import * from pandas . util . decorators import cache_readonly class match_strings ( object ) : goal_time = def setup ( self ) : self . uniques = tm . makeStringIndex ( ) . values self . all = self . uniques . repeat ( ) def time_match_strings ( self ) : match ( self . all , self . uniques ) class misc_cache_readonly ( object ) : goal_time = def setup ( self ) : class Foo : @ cache_readonly def prop ( self ) : ", "answer": "return "}, {"prompt": " import os import time from tdt . core import classify from tdt . core import Post from tdt . threading import Pool from common import logger from common import parameters def get_filename ( directory , post , keep_names = False ) : \"\"\"\"\"\" return os . sep . join ( ( directory , post . board , str ( post . thread ) , ( post . image . filename if keep_names else str ( post . image . tim ) ) + post . image . ext ) ) def scrape_images ( directory , keep_names , * links ) : \"\"\"\"\"\" pool = Pool ( num_threads = parameters . num_threads ) def work ( unit ) : if isinstance ( unit , Post ) : if not unit . image : return filename = get_filename ( directory , unit , keep_names ) if not os . path . exists ( filename ) : logger . info ( '' , unit . image ) image_data = unit . image . download ( bypass_cache = True ) return filename , image_data logger . debug ( '' , filename ) return logger . info ( '' , unit ) for e in unit . process ( ) : pool . push ( work , e ) for link in map ( classify , links ) : pool . push ( work , link ) pool . join ( ) logger . info ( '' ) downloaded = pool . get_results ( ) pool . close ( ) logger . info ( '' ) directories = set ( map ( lambda t : os . path . split ( t [ ] ) [ ] , downloaded ) ) for directory in directories : if not os . path . exists ( directory ) : logger . debug ( '' , directory ) os . makedirs ( directory ) logger . info ( '' ) for filename , image_data in downloaded : with open ( filename , '' ) as outfile : outfile . write ( image_data ) if __name__ == '' : from common import CommonParser parser = CommonParser ( description = '' ) parser . add_argument ( '' , nargs = '' , help = '' ) parser . add_argument ( '' , '' , metavar = '' , ", "answer": "default = '' ,"}, {"prompt": " \"\"\"\"\"\" from boto . beanstalk . layer1 import Layer1 import boto . beanstalk . response from boto . exception import BotoServerError import boto . beanstalk . exception as exception def beanstalk_wrapper ( func , name ) : def _wrapped_low_level_api ( * args , ** kwargs ) : try : response = func ( * args , ** kwargs ) except BotoServerError as e : ", "answer": "raise exception . simple ( e )"}, {"prompt": " import logging as log from . . extractors import NoExtractorError , POSTagExtractor question_types = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } TAGS = [ '' , '' , '' , '' ] ", "answer": "class Extractor ( POSTagExtractor ) :"}, {"prompt": " import time import sys import os from dronekit import connect , VehicleMode from dronekit . test import with_sitl from nose . tools import assert_equals @ with_sitl def test_115 ( connpath ) : v = connect ( connpath , wait_ready = True ) def mavlink_callback ( * args ) : mavlink_callback . count += mavlink_callback . count = v . add_message_listener ( '' , mavlink_callback ) v . mode = VehicleMode ( \"\" ) time . sleep ( ) assert mavlink_callback . count > v . remove_message_listener ( '' , mavlink_callback ) savecount = mavlink_callback . count v . armed = False ", "answer": "time . sleep ( )"}, {"prompt": " from mock import call , patch from nose . tools import istest from provy . more . debian import RailsRole , AptitudeRole , GemRole , SupervisorRole , NginxRole from provy . more . debian . web . rails import PACKAGES_TO_INSTALL from tests . unit . tools . helpers import ProvyTestCase class RailsRoleTest ( ProvyTestCase ) : def setUp ( self ) : super ( RailsRoleTest , self ) . setUp ( ) self . role = RailsRole ( prov = None , context = { '' : '' } ) self . supervisor_role = SupervisorRole ( prov = None , context = self . role . context ) @ istest def installs_necessary_packages_to_provision ( self ) : methods_to_mock = ( '' , '' , '' , '' , '' , '' , ) with self . using_stub ( AptitudeRole ) as aptitude , self . using_stub ( GemRole ) as gem , self . mock_role_methods ( * methods_to_mock ) : self . role . remote_exists_dir . return_value = False self . role . provision ( ) self . role . register_template_loader . assert_called_once_with ( '' ) self . assertEqual ( aptitude . ensure_package_installed . mock_calls , [ call ( package ) for package in PACKAGES_TO_INSTALL ] ) self . assertEqual ( gem . ensure_package_installed . mock_calls , [ call ( '' ) , call ( '' ) ] ) self . role . remote_exists_dir . assert_called_once_with ( '' ) self . assertEqual ( self . role . ensure_dir . mock_calls , [ call ( '' , sudo = True ) , call ( '' , sudo = True ) , call ( '' , sudo = True ) , call ( '' , sudo = True ) , ] ) self . role . execute . assert_called_once_with ( '' , sudo = True , stdout = False ) self . assertEqual ( self . role . update_file . mock_calls , [ call ( '' , '' , sudo = True ) , call ( '' , '' , sudo = True ) , ] ) self . role . change_path_mode . assert_called_once_with ( '' , ) @ istest def provisions_even_if_nginx_already_exists ( self ) : methods_to_mock = ( '' , '' , '' , '' , '' , ) with self . using_stub ( AptitudeRole ) , self . using_stub ( GemRole ) , self . mock_role_methods ( * methods_to_mock ) : self . role . remote_exists_dir . return_value = True self . role . provision ( ) self . assertEqual ( self . role . ensure_dir . mock_calls , [ call ( '' , sudo = True ) , call ( '' , sudo = True ) , call ( '' , sudo = True ) , ] ) @ istest def restarts_on_cleanup_if_must_be_restarted ( self ) : with patch ( '' ) as restart : self . role . ensure_restart ( ) self . role . cleanup ( ) self . assertTrue ( restart . called ) @ istest def doesnt_restart_on_cleanup_if_doesnt_need_to_be_restarted ( self ) : with patch ( '' ) as restart : self . role . cleanup ( ) self . assertFalse ( restart . called ) @ istest def ensures_site_is_disabled ( self ) : site = '' with self . using_stub ( NginxRole ) as nginx : self . role . ensure_site_disabled ( site ) nginx . ensure_site_disabled . assert_called_once_with ( site ) @ istest def ensures_site_is_enabled ( self ) : site = '' with self . using_stub ( NginxRole ) as nginx : ", "answer": "self . role . ensure_site_enabled ( site )"}, {"prompt": " addPackage ( '' ) addPackage ( '' ) addPackage ( '' ) addPackage ( '' ) addPackage ( '' ) def testHook ( ) : \"\"\"\"\"\" def printTree ( n , indent = ) : def iprint ( str ) : print '' % ( \"\" * indent , str ) iprint ( '' % n . descriptor . name ) ", "answer": "for c in n . children :"}, {"prompt": " import sublime , sublime_plugin class SelectQuoted ( sublime_plugin . TextCommand ) : def run ( self , edit , around = False ) : selections = self . view . sel ( ) newSel = [ ] for originalRegion in selections : region = originalRegion if originalRegion . a <= originalRegion . b else sublime . Region ( originalRegion . b , originalRegion . a ) newRegion = self . getStringRegion ( region , around ) if newRegion is None : newSel . append ( originalRegion ) ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" import diamond . collector import subprocess import os from diamond . collector import str_to_bool class NagiosStatsCollector ( diamond . collector . Collector ) : def get_default_config_help ( self ) : config_help = super ( NagiosStatsCollector , self ) . get_default_config_help ( ) config_help . update ( { '' : '' , '' : '' , '' : '' , '' : '' , } ) return config_help ", "answer": "def get_default_config ( self ) :"}, {"prompt": " import os import sys root_dir = os . path . dirname ( os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) ) web_dir = os . path . join ( root_dir , '' , '' ) sys . path . insert ( , root_dir ) import cherrypy from jinja2 import Environment , FileSystemLoader from rackspace_monitoring . types import Provider from rackspace_monitoring . providers import get_driver env = Environment ( loader = FileSystemLoader ( os . path . join ( web_dir , '' ) ) ) def http_methods_allowed ( methods = [ '' , '' ] ) : method = cherrypy . request . method . upper ( ) if method not in methods : cherrypy . response . headers [ '' ] = \"\" . join ( methods ) raise cherrypy . HTTPError ( ) cherrypy . tools . allow = cherrypy . Tool ( '' , http_methods_allowed ) class Root : def _driver ( self ) : cookie = cherrypy . request . cookie username = None apikey = None if cookie . has_key ( '' ) : username = cookie [ '' ] . value if cookie . has_key ( '' ) : ", "answer": "apikey = cookie [ '' ] . value"}, {"prompt": " import collections import itertools import mock from sahara . service . validations . edp import job as j from sahara . service . validations . edp import job_execution_schema as j_e_schema from sahara . service . validations . edp import job_interface as j_i from sahara . service . validations . edp import job_schema as j_schema from sahara . tests . unit . service . validation import utils as u from sahara . utils import edp def _configs ( ** kwargs ) : arg = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : True , \"\" : \"\" } arg . update ( kwargs ) return arg def _params ( ** kwargs ) : arg = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : False , \"\" : \"\" } arg . update ( kwargs ) return arg def _args ( ** kwargs ) : arg = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : False , \"\" : \"\" } arg . update ( kwargs ) return arg _mapping_types = { \"\" , \"\" , \"\" } def _job ( job_type , interface ) : return { \"\" : \"\" , \"\" : job_type , \"\" : interface } _job_types = [ _job ( edp . JOB_TYPE_HIVE , [ _configs ( ) , _params ( ) ] ) , _job ( edp . JOB_TYPE_PIG , [ _configs ( ) , _params ( ) , _args ( ) ] ) , _job ( edp . JOB_TYPE_MAPREDUCE , [ _configs ( ) ] ) , _job ( edp . JOB_TYPE_MAPREDUCE_STREAMING , [ _configs ( ) ] ) , _job ( edp . JOB_TYPE_JAVA , [ _configs ( ) , _args ( ) ] ) , _job ( edp . JOB_TYPE_SHELL , [ _configs ( ) , _params ( ) , _args ( ) ] ) , _job ( edp . JOB_TYPE_SPARK , [ _configs ( ) , _args ( ) ] ) , _job ( edp . JOB_TYPE_STORM , [ _args ( ) ] ) ] class TestJobInterfaceValidation ( u . ValidationTestCase ) : def setUp ( self ) : super ( TestJobInterfaceValidation , self ) . setUp ( ) self . _create_object_fun = j . check_interface self . scheme = j_schema . JOB_SCHEMA def test_interface ( self ) : for job in _job_types : self . _assert_create_object_validation ( data = job ) def test_no_interface ( self ) : job = _job ( edp . JOB_TYPE_PIG , None ) self . _assert_create_object_validation ( data = job ) def test_overlapping_names ( self ) : job = _job ( edp . JOB_TYPE_PIG , [ _configs ( ) , _configs ( location = \"\" ) ] ) self . _assert_create_object_validation ( data = job , bad_req_i = ( , \"\" , \"\" ) ) def test_unacceptable_types ( self ) : for job in _job_types : acceptable_types = [ arg [ '' ] for arg in job [ '' ] ] unacceptable_types = _mapping_types - set ( acceptable_types ) unacceptable_args = ( globals ( ) [ \"\" + m_type ] ( ) for m_type in unacceptable_types ) bad_job = job . copy ( ) for arg in unacceptable_args : bad_job [ '' ] = [ arg ] permutations = itertools . permutations ( acceptable_types ) msgs = [ \"\" % ( list ( permutation ) , bad_job [ '' ] ) for permutation in permutations ] self . _assert_create_object_validation ( data = bad_job , bad_req_i = ( , \"\" , msgs ) ) def test_bad_positional_arg_locations ( self ) : job = _job ( edp . JOB_TYPE_PIG , [ _args ( location = \"\" ) ] ) self . _assert_create_object_validation ( data = job , bad_req_i = ( , \"\" , \"\" \"\" ) ) job = _job ( edp . JOB_TYPE_PIG , [ _args ( location = \"\" ) ] ) self . _assert_create_object_validation ( data = job , bad_req_i = ( , \"\" , \"\" \"\" ) ) job = _job ( edp . JOB_TYPE_PIG , [ _args ( ) , _args ( location = \"\" , name = \"\" ) ] ) self . _assert_create_object_validation ( data = job , bad_req_i = ( , \"\" , \"\" \"\" ) ) def test_required_positional_arg_without_default ( self ) : arg = _args ( required = False ) del arg [ '' ] job = _job ( edp . JOB_TYPE_PIG , [ arg ] ) self . _assert_create_object_validation ( data = job , bad_req_i = ( , \"\" , \"\" \"\" ) ) def test_overlapping_locations ( self ) : job = _job ( edp . JOB_TYPE_PIG , [ _configs ( ) , _configs ( name = \"\" ) ] ) self . _assert_create_object_validation ( data = job , bad_req_i = ( , \"\" , \"\" \"\" ) ) def test_number_values ( self ) : job = _job ( edp . JOB_TYPE_PIG , [ _configs ( default = \"\" ) ] ) self . _assert_create_object_validation ( data = job , bad_req_i = ( , \"\" , \"\" ) ) @ mock . patch ( '' ) def test_data_source_values ( self , data_source ) : data_source . return_value = True job = _job ( edp . JOB_TYPE_PIG , [ _params ( default = \"\" ) ] ) self . _assert_create_object_validation ( data = job ) data_source . return_value = False self . _assert_create_object_validation ( data = job , bad_req_i = ( , \"\" , \"\" \"\" ) ) job = _job ( edp . JOB_TYPE_PIG , [ _params ( default = \"\" ) ] ) self . _assert_create_object_validation ( data = job , bad_req_i = ( , \"\" , \"\" \"\" ) ) def test_default_data_type ( self ) : param = _params ( ) del param [ '' ] job = _job ( edp . JOB_TYPE_PIG , [ param ] ) self . _assert_create_object_validation ( data = job ) assert param [ '' ] == j_i . DEFAULT_DATA_TYPE int_arg = collections . namedtuple ( \"\" , [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] ) def j_e_i_wrapper ( data ) : job = mock . Mock ( interface = [ int_arg ( ** _configs ( ) ) , int_arg ( ** _args ( ) ) , int_arg ( ** _params ( ) ) ] ) j_i . check_execution_interface ( data , job ) class TestJobExecutionInterfaceValidation ( u . ValidationTestCase ) : def setUp ( self ) : super ( TestJobExecutionInterfaceValidation , self ) . setUp ( ) self . _create_object_fun = j_e_i_wrapper self . scheme = j_e_schema . JOB_EXEC_SCHEMA def test_valid_execution ( self ) : data = { \"\" : \"\" , \"\" : { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } } self . _assert_create_object_validation ( data = data ) def test_no_execution_interface ( self ) : data = { \"\" : \"\" } self . _assert_create_object_validation ( data = data , bad_req_i = ( , \"\" , \"\" \"\" ) ) def test_bad_argument_name ( self ) : data = { \"\" : \"\" , \"\" : { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } } self . _assert_create_object_validation ( data = data , bad_req_i = ( , \"\" , \"\" \"\" ) ) def test_required_argument_missing ( self ) : data = { \"\" : \"\" , \"\" : { \"\" : \"\" } } self . _assert_create_object_validation ( data = data , bad_req_i = ( , \"\" , \"\" \"\" ) ) @ mock . patch ( '' ) def test_bad_values ( self , data_source ) : data = { \"\" : \"\" , \"\" : { \"\" : \"\" } } self . _assert_create_object_validation ( data = data , bad_req_i = ( , \"\" , \"\" ) ) data = { \"\" : \"\" , \"\" : { \"\" : \"\" , \"\" : \"\" } } self . _assert_create_object_validation ( data = data , bad_req_i = ( , \"\" , \"\" \"\" ) ) data = { \"\" : \"\" , \"\" : { \"\" : \"\" , \"\" : } } self . _assert_create_object_validation ( data = data , bad_req_i = ( , \"\" , \"\" ) ) data_source . return_value = False data = { \"\" : \"\" , \"\" : { \"\" : \"\" , \"\" : \"\" } } self . _assert_create_object_validation ( data = data , bad_req_i = ( , \"\" , \"\" \"\" ) ) def test_overlapping_data ( self ) : data = { \"\" : \"\" , \"\" : { \"\" : \"\" } , \"\" : { \"\" : { \"\" : \"\" } } } self . _assert_create_object_validation ( data = data ) data = { \"\" : \"\" , \"\" : { \"\" : \"\" } , \"\" : { \"\" : { \"\" : \"\" } } } self . _assert_create_object_validation ( data = data , bad_req_i = ( , \"\" , \"\" \"\" ", "answer": "\"\""}, {"prompt": " \"\"\"\"\"\" from airy . core . files import File class ImageFile ( File ) : \"\"\"\"\"\" def _get_width ( self ) : ", "answer": "return self . _get_image_dimensions ( ) [ ]"}, {"prompt": " from __future__ import unicode_literals from expects import * from . . _helpers import MyDict from booby import fields , errors , models class TestEmbeddedFieldDescriptor ( object ) : def test_when_set_field_value_with_dict_then_value_is_embedded_object_with_dict_values ( self ) : ", "answer": "self . group . admin = { '' : '' , '' : '' }"}, {"prompt": " import os from setuptools import setup , find_packages from friendship import VERSION f = open ( os . path . join ( os . path . dirname ( __file__ ) , '' ) ) readme = f . read ( ) f . close ( ) setup ( name = '' , version = \"\" . join ( map ( str , VERSION ) ) , description = '' , long_description = readme , author = '' , author_email = '' , url = '' , include_package_data = True , packages = find_packages ( ) , zip_safe = False , classifiers = [ '' , '' , ", "answer": "'' ,"}, {"prompt": " from openstack_dashboard . test . integration_tests . pages . project . network import routerspage from openstack_dashboard . test . integration_tests . regions import forms from openstack_dashboard . test . integration_tests . regions import tables class RoutersTable ( routerspage . RoutersTable ) : EDIT_ROUTER_FORM_FIELDS = ( \"\" , \"\" , \"\" ) @ tables . bind_row_action ( '' ) def edit_router ( self , edit_button , row ) : ", "answer": "edit_button . click ( )"}, {"prompt": " from senlinclient . common import sdk class Client ( object ) : def __init__ ( self , preferences = None , user_agent = None , ** kwargs ) : self . conn = sdk . create_connection ( preferences , user_agent , ** kwargs ) self . service = self . conn . cluster def profile_types ( self , ** query ) : \"\"\"\"\"\" return self . service . profile_types ( ** query ) def get_profile_type ( self , profile_type ) : \"\"\"\"\"\" return self . service . get_profile_type ( profile_type ) def profiles ( self , ** query ) : \"\"\"\"\"\" return self . service . profiles ( ** query ) def create_profile ( self , ** attrs ) : \"\"\"\"\"\" return self . service . create_profile ( ** attrs ) def get_profile ( self , profile ) : \"\"\"\"\"\" return self . service . get_profile ( profile ) def update_profile ( self , profile , ** attrs ) : \"\"\"\"\"\" return self . service . update_profile ( profile , ** attrs ) def delete_profile ( self , profile , ignore_missing = True ) : \"\"\"\"\"\" return self . service . delete_profile ( profile , ignore_missing ) def policy_types ( self , ** query ) : \"\"\"\"\"\" return self . service . policy_types ( ** query ) def get_policy_type ( self , policy_type ) : \"\"\"\"\"\" return self . service . get_policy_type ( policy_type ) def policies ( self , ** query ) : \"\"\"\"\"\" return self . service . policies ( ** query ) def create_policy ( self , ** attrs ) : \"\"\"\"\"\" return self . service . create_policy ( ** attrs ) def get_policy ( self , policy ) : \"\"\"\"\"\" return self . service . get_policy ( policy ) def update_policy ( self , policy , ** attrs ) : \"\"\"\"\"\" return self . service . update_policy ( policy , ** attrs ) def delete_policy ( self , policy , ignore_missing = True ) : \"\"\"\"\"\" return self . service . delete_policy ( policy , ignore_missing ) def clusters ( self , ** queries ) : \"\"\"\"\"\" return self . service . clusters ( ** queries ) def create_cluster ( self , ** attrs ) : \"\"\"\"\"\" return self . service . create_cluster ( ** attrs ) def get_cluster ( self , cluster ) : \"\"\"\"\"\" return self . service . get_cluster ( cluster ) def update_cluster ( self , cluster , ** attrs ) : \"\"\"\"\"\" return self . service . update_cluster ( cluster , ** attrs ) def delete_cluster ( self , cluster , ignore_missing = True ) : \"\"\"\"\"\" return self . service . delete_cluster ( cluster , ignore_missing ) def cluster_add_nodes ( self , cluster , nodes ) : \"\"\"\"\"\" return self . service . cluster_add_nodes ( cluster , nodes ) def cluster_del_nodes ( self , cluster , nodes ) : \"\"\"\"\"\" return self . service . cluster_del_nodes ( cluster , nodes ) def cluster_resize ( self , cluster , ** params ) : \"\"\"\"\"\" return self . service . cluster_resize ( cluster , ** params ) def cluster_scale_out ( self , cluster , count ) : \"\"\"\"\"\" return self . service . cluster_scale_out ( cluster , count ) def cluster_scale_in ( self , cluster , count ) : \"\"\"\"\"\" return self . service . cluster_scale_in ( cluster , count ) def cluster_policies ( self , cluster , ** queries ) : \"\"\"\"\"\" return self . service . cluster_policies ( cluster , ** queries ) def get_cluster_policy ( self , policy , cluster ) : \"\"\"\"\"\" return self . service . get_cluster_policy ( policy , cluster ) def cluster_attach_policy ( self , cluster , policy , ** attrs ) : \"\"\"\"\"\" return self . service . cluster_attach_policy ( cluster , policy , ** attrs ) def cluster_detach_policy ( self , cluster , policy ) : \"\"\"\"\"\" return self . service . cluster_detach_policy ( cluster , policy ) def cluster_update_policy ( self , cluster , policy , ** attrs ) : \"\"\"\"\"\" return self . service . cluster_update_policy ( cluster , policy , ** attrs ) def check_cluster ( self , cluster , ** params ) : \"\"\"\"\"\" ", "answer": "return self . service . check_cluster ( cluster , ** params )"}, {"prompt": " from setuptools import setup from setuptools import find_packages setup ( name = '' , version = '' , description = '' , url = '' , ", "answer": "download_url = '' ,"}, {"prompt": " '' from ncclient . xml_ import * from ncclient . operations . errors import OperationError , MissingCapabilityError def one_of ( * args ) : \"\" for i , arg in enumerate ( args ) : if arg is not None : for argh in args [ i + : ] : if argh is not None : raise OperationError ( \"\" ) else : return raise OperationError ( \"\" ) def datastore_or_url ( wha , loc , capcheck = None ) : node = new_ele ( wha ) if \"\" in loc : if capcheck is not None : capcheck ( \"\" ) sub_ele ( node , \"\" ) . text = loc else : sub_ele ( node , loc ) return node def build_filter ( spec , capcheck = None ) : type = None if isinstance ( spec , tuple ) : type , criteria = spec rep = new_ele ( \"\" , type = type ) if type == \"\" : rep . attrib [ \"\" ] = criteria elif type == \"\" : rep . append ( to_ele ( criteria ) ) else : raise OperationError ( \"\" ) else : rep = validated_element ( spec , ( \"\" , qualify ( \"\" ) ) ) ", "answer": "if type == \"\" and capcheck is not None :"}, {"prompt": " from six . moves import urllib class ClientException ( Exception ) : def __init__ ( self , msg , http_scheme = '' , http_host = '' , http_port = '' , ", "answer": "http_path = '' , http_query = '' , http_status = None , http_reason = '' ,"}, {"prompt": " import zookeeper , zktestbase , unittest , threading ZOO_OPEN_ACL_UNSAFE = { \"\" : , \"\" : \"\" , \"\" : \"\" } class CreationTest ( zktestbase . TestBase ) : \"\"\"\"\"\" def setUp ( self ) : zktestbase . TestBase . setUp ( self ) try : zookeeper . delete ( self . handle , \"\" ) zookeeper . delete ( self . handle , \"\" ) except : pass def test_sync_create ( self ) : self . assertEqual ( self . connected , True ) ", "answer": "ret = zookeeper . create ( self . handle , \"\" , \"\" , [ ZOO_OPEN_ACL_UNSAFE ] , zookeeper . EPHEMERAL )"}, {"prompt": " from functools import partial import pytest empty = object ( ) class cached_property ( object ) : def __init__ ( self , func ) : self . func = func def __get__ ( self , obj , cls ) : value = obj . __dict__ [ self . func . __name__ ] = self . func ( obj ) return value class SimpleProxy ( object ) : def __init__ ( self , factory ) : self . factory = factory ", "answer": "self . object = empty"}, {"prompt": " DEBUG = True TEMPLATE_DEBUG = DEBUG STATIC_ROOT = '' STATIC_URL = '' import chartkick STATICFILES_DIRS = ( chartkick . js ( ) , ) STATICFILES_FINDERS = ( '' , '' , ) SECRET_KEY = '' TEMPLATE_LOADERS = ( '' , ) MIDDLEWARE_CLASSES = ( ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from collections import OrderedDict from six . moves import range import numpy from picklable_itertools . extras import equizip from theano import config , function from blocks_extras . bricks . sequence_generator2 import SequenceGenerator from blocks . filter import VariableFilter , get_application_call , get_brick from blocks . graph import ComputationGraph from blocks . roles import INPUT , OUTPUT from blocks . utils import unpack class BeamSearch ( object ) : \"\"\"\"\"\" def __init__ ( self , samples ) : self . cg = ComputationGraph ( samples ) self . inputs = self . cg . inputs self . generator = get_brick ( samples ) if not isinstance ( self . generator , SequenceGenerator ) : raise ValueError self . generate_call = get_application_call ( samples ) if ( not self . generate_call . application == self . generator . generate ) : raise ValueError self . inner_cg = ComputationGraph ( self . generate_call . inner_outputs ) self . context_names = self . generator . generate . contexts self . state_names = self . generator . generate . states self . contexts = [ VariableFilter ( bricks = [ self . generator ] , name = name , roles = [ INPUT ] ) ( self . inner_cg ) [ ] for name in self . context_names ] self . input_states = [ ] self . input_state_names = [ ] for name in self . generator . generate . states : var = VariableFilter ( bricks = [ self . generator ] , name = name , roles = [ INPUT ] ) ( self . inner_cg ) if var : self . input_state_names . append ( name ) self . input_states . append ( var [ ] ) self . compiled = False def _compile_initial_state_and_context_computer ( self ) : initial_states = VariableFilter ( applications = [ self . generator . initial_states ] , roles = [ OUTPUT ] ) ( self . cg ) outputs = OrderedDict ( [ ( v . tag . name , v ) for v in initial_states ] ) beam_size = unpack ( VariableFilter ( applications = [ self . generator . initial_states ] , name = '' ) ( self . cg ) ) for name , context in equizip ( self . context_names , self . contexts ) : outputs [ name ] = context outputs [ '' ] = beam_size self . initial_state_and_context_computer = function ( self . inputs , outputs , on_unused_input = '' ) def _compile_next_state_computer ( self ) : next_states = [ VariableFilter ( bricks = [ self . generator ] , name = name , roles = [ OUTPUT ] ) ( self . inner_cg ) [ - ] for name in self . state_names ] samples = VariableFilter ( applications = [ self . generator . readout . sample ] , name = '' ) ( self . inner_cg . variables ) self . next_state_computer = function ( self . contexts + self . input_states + samples , next_states ) def _compile_scores_computer ( self ) : scores = self . generator . readout . scores ( ** dict ( zip ( self . input_state_names , self . input_states ) + zip ( self . context_names , self . contexts ) ) ) self . scores_computer = function ( self . contexts + self . input_states , scores , on_unused_input = '' ) def compile ( self ) : \"\"\"\"\"\" ", "answer": "self . _compile_initial_state_and_context_computer ( )"}, {"prompt": " from __future__ import unicode_literals from django . contrib . auth import get_user_model from django . core . urlresolvers import reverse from django . test import TestCase , RequestFactory from . . compat import urlparse , parse_qs , urlencode ", "answer": "from . . models import get_application_model"}, {"prompt": " from globals import WORLD_INFO , SETTINGS , LIFE , ITEMS import life as lfe import numbers import alife import logging def get_player_situation ( ) : if not SETTINGS [ '' ] : return False _life = LIFE [ SETTINGS [ '' ] ] _situation = { } _situation [ '' ] = alife . combat . has_potentially_usable_weapon ( _life ) _situation [ '' ] = len ( [ l for l in _life [ '' ] . values ( ) if l [ '' ] in [ '' , '' ] ] ) _situation [ '' ] = _life [ '' ] _situation [ '' ] = [ l for l in LIFE . values ( ) if l [ '' ] and not l [ '' ] and not l [ '' ] == _life [ '' ] ] _situation [ '' ] = [ l for l in _situation [ '' ] if alife . judgement . can_trust ( _life , l [ '' ] ) ] _situation [ '' ] = len ( lfe . get_all_inventory_items ( _life , matches = [ { '' : '' } ] ) ) > _situation [ '' ] = alife . combat . get_weapons ( _life ) _situation [ '' ] = lfe . get_all_equipped_items ( _life ) return _situation def get_group_leader_with_motive ( group_motive , online = False ) : for life in LIFE . values ( ) : if not ( life [ '' ] or not online ) or not life [ '' ] or not alife . groups . is_leader ( life , life [ '' ] , life [ '' ] ) or SETTINGS [ '' ] == life [ '' ] : continue if alife . groups . get_motive ( life , life [ '' ] ) == group_motive : return life [ '' ] return None def handle_tracked_alife ( ) : for ai in [ LIFE [ i ] for i in WORLD_INFO [ '' ] [ '' ] ] : ", "answer": "if ai [ '' ] :"}, {"prompt": " from functools import wraps from flask import request , current_app from werkzeug . exceptions import Forbidden from werkzeug import LocalProxy class Allows ( object ) : \"\"\"\"\"\" def __init__ ( self , app = None , identity_loader = None , throws = Forbidden ) : self . _identity_loader = identity_loader self . throws = throws if app : self . init_app ( app ) def init_app ( self , app ) : if not hasattr ( app , '' ) : app . extensions = { } app . extensions [ '' ] = self def requires ( self , * requirements , ** opts ) : \"\"\"\"\"\" throws = opts . get ( '' , self . throws ) def decorator ( f ) : @ wraps ( f ) def allower ( * args , ** kwargs ) : if self . fulfill ( requirements ) : return f ( * args , ** kwargs ) else : ", "answer": "raise throws"}, {"prompt": " \"\"\"\"\"\" from datetime import datetime import oandapy OANDA_ACCESS_TOKEN = \"\" OANDA_ACCOUNT_ID = def main ( ) : print \"\" , datetime . now ( ) oanda = oandapy . API ( environment = \"\" , access_token = OANDA_ACCESS_TOKEN ) response = oanda . get_prices ( instruments = \"\" ) ", "answer": "prices = response . get ( \"\" )"}, {"prompt": " from __future__ import unicode_literals import tablib from copy import deepcopy from datetime import date from decimal import Decimal from unittest import skip , skipUnless from django . conf import settings from django . contrib . auth . models import User from django . db import IntegrityError from django . db . models import Count from django . db . models . fields import FieldDoesNotExist from django . test import TestCase , TransactionTestCase , skipUnlessDBFeature from django . utils . html import strip_tags from import_export import fields , resources , results , widgets from import_export . instance_loaders import ModelInstanceLoader from . . models import ( Author , Book , Category , Entry , Profile , WithDefault , WithDynamicDefault , WithFloatField , ) try : from django . utils . encoding import force_text except ImportError : from django . utils . encoding import force_unicode as force_text class MyResource ( resources . Resource ) : name = fields . Field ( ) email = fields . Field ( ) extra = fields . Field ( ) class Meta : export_order = ( '' , '' ) class ResourceTestCase ( TestCase ) : def setUp ( self ) : self . my_resource = MyResource ( ) def test_fields ( self ) : fields = self . my_resource . fields self . assertIn ( '' , fields ) def test_field_column_name ( self ) : field = self . my_resource . fields [ '' ] self . assertIn ( field . column_name , '' ) def test_meta ( self ) : self . assertIsInstance ( self . my_resource . _meta , resources . ResourceOptions ) def test_get_export_order ( self ) : self . assertEqual ( self . my_resource . get_export_headers ( ) , [ '' , '' , '' ] ) def test_inheritance ( self ) : class A ( MyResource ) : inherited = fields . Field ( ) class Meta : import_id_fields = ( '' , ) class B ( A ) : local = fields . Field ( ) class Meta : export_order = ( '' , '' ) resource = B ( ) self . assertIn ( '' , resource . fields ) self . assertIn ( '' , resource . fields ) self . assertIn ( '' , resource . fields ) self . assertEqual ( resource . get_export_headers ( ) , [ '' , '' , '' , '' , '' ] ) self . assertEqual ( resource . _meta . import_id_fields , ( '' , ) ) def test_inheritance_with_custom_attributes ( self ) : class A ( MyResource ) : inherited = fields . Field ( ) class Meta : import_id_fields = ( '' , ) custom_attribute = True class B ( A ) : local = fields . Field ( ) resource = B ( ) self . assertEqual ( resource . _meta . custom_attribute , True ) class AuthorResource ( resources . ModelResource ) : books = fields . Field ( column_name = '' , attribute = '' , readonly = True , ) class Meta : model = Author export_order = ( '' , '' ) class BookResource ( resources . ModelResource ) : published = fields . Field ( column_name = '' ) class Meta : model = Book exclude = ( '' , ) class ProfileResource ( resources . ModelResource ) : class Meta : model = Profile exclude = ( '' , ) class WithDefaultResource ( resources . ModelResource ) : class Meta : model = WithDefault fields = ( '' , ) class ModelResourceTest ( TestCase ) : def setUp ( self ) : self . resource = BookResource ( ) self . book = Book . objects . create ( name = \"\" ) self . dataset = tablib . Dataset ( headers = [ '' , '' , '' , '' ] ) row = [ self . book . pk , '' , '' , \"\" ] self . dataset . append ( row ) def test_default_instance_loader_class ( self ) : self . assertIs ( self . resource . _meta . instance_loader_class , ModelInstanceLoader ) def test_fields ( self ) : fields = self . resource . fields self . assertIn ( '' , fields ) self . assertIn ( '' , fields ) self . assertIn ( '' , fields ) self . assertIn ( '' , fields ) def test_fields_foreign_key ( self ) : fields = self . resource . fields self . assertIn ( '' , fields ) widget = fields [ '' ] . widget self . assertIsInstance ( widget , widgets . ForeignKeyWidget ) self . assertEqual ( widget . model , Author ) def test_fields_m2m ( self ) : fields = self . resource . fields self . assertIn ( '' , fields ) def test_excluded_fields ( self ) : self . assertNotIn ( '' , self . resource . fields ) def test_init_instance ( self ) : instance = self . resource . init_instance ( ) self . assertIsInstance ( instance , Book ) def test_default ( self ) : self . assertEquals ( WithDefaultResource . fields [ '' ] . clean ( { '' : '' } ) , '' ) def test_get_instance ( self ) : instance_loader = self . resource . _meta . instance_loader_class ( self . resource ) self . resource . _meta . import_id_fields = [ '' ] instance = self . resource . get_instance ( instance_loader , self . dataset . dict [ ] ) self . assertEqual ( instance , self . book ) def test_get_instance_import_id_fields ( self ) : class BookResource ( resources . ModelResource ) : name = fields . Field ( attribute = '' , widget = widgets . CharWidget ( ) ) class Meta : model = Book import_id_fields = [ '' ] resource = BookResource ( ) instance_loader = resource . _meta . instance_loader_class ( resource ) instance = resource . get_instance ( instance_loader , self . dataset . dict [ ] ) self . assertEqual ( instance , self . book ) def test_get_instance_with_missing_field_data ( self ) : instance_loader = self . resource . _meta . instance_loader_class ( self . resource ) dataset = tablib . Dataset ( headers = [ '' , '' , '' ] ) dataset . append ( [ '' , '' , \"\" ] ) with self . assertRaises ( KeyError ) as cm : self . resource . get_instance ( instance_loader , dataset . dict [ ] ) self . assertEqual ( u\"\" \"\" % [ u'' , u'' , u'' ] , cm . exception . args [ ] ) def test_get_export_headers ( self ) : headers = self . resource . get_export_headers ( ) self . assertEqual ( headers , [ '' , '' , '' , '' , '' , '' , '' , '' , ] ) def test_export ( self ) : dataset = self . resource . export ( Book . objects . all ( ) ) self . assertEqual ( len ( dataset ) , ) def test_export_iterable ( self ) : dataset = self . resource . export ( list ( Book . objects . all ( ) ) ) self . assertEqual ( len ( dataset ) , ) def test_get_diff ( self ) : book2 = Book ( name = \"\" ) diff = self . resource . get_diff ( self . book , book2 ) headers = self . resource . get_export_headers ( ) self . assertEqual ( diff [ headers . index ( '' ) ] , u'' u'' ) self . assertFalse ( diff [ headers . index ( '' ) ] ) @ skip ( \"\" ) def test_get_diff_with_callable_related_manager ( self ) : resource = AuthorResource ( ) author = Author ( name = \"\" ) author . save ( ) author2 = Author ( name = \"\" ) self . book . author = author self . book . save ( ) diff = resource . get_diff ( author2 , author ) headers = resource . get_export_headers ( ) self . assertEqual ( diff [ headers . index ( '' ) ] , '' ) def test_import_data ( self ) : result = self . resource . import_data ( self . dataset , raise_errors = True ) self . assertFalse ( result . has_errors ( ) ) self . assertEqual ( len ( result . rows ) , ) self . assertTrue ( result . rows [ ] . diff ) self . assertEqual ( result . rows [ ] . import_type , results . RowResult . IMPORT_TYPE_UPDATE ) instance = Book . objects . get ( pk = self . book . pk ) self . assertEqual ( instance . author_email , '' ) self . assertEqual ( instance . price , Decimal ( \"\" ) ) def test_import_data_value_error_includes_field_name ( self ) : class AuthorResource ( resources . ModelResource ) : class Meta : model = Author resource = AuthorResource ( ) dataset = tablib . Dataset ( headers = [ '' , '' , '' ] ) dataset . append ( [ '' , '' , '' ] ) result = resource . import_data ( dataset , raise_errors = False ) self . assertTrue ( result . has_errors ( ) ) self . assertTrue ( result . rows [ ] . errors ) msg = ( \"\" ) actual = result . rows [ ] . errors [ ] . error self . assertIsInstance ( actual , ValueError ) self . assertEqual ( msg , str ( actual ) ) def test_import_data_error_saving_model ( self ) : row = list ( self . dataset . pop ( ) ) row [ ] = '' self . dataset . append ( row ) result = self . resource . import_data ( self . dataset , raise_errors = False ) self . assertTrue ( result . has_errors ( ) ) self . assertTrue ( result . rows [ ] . errors ) actual = result . rows [ ] . errors [ ] . error self . assertIsInstance ( actual , ValueError ) self . assertIn ( \"\" , str ( actual ) ) def test_import_data_delete ( self ) : class B ( BookResource ) : delete = fields . Field ( widget = widgets . BooleanWidget ( ) ) def for_delete ( self , row , instance ) : return self . fields [ '' ] . clean ( row ) row = [ self . book . pk , self . book . name , '' ] dataset = tablib . Dataset ( * [ row ] , headers = [ '' , '' , '' ] ) result = B ( ) . import_data ( dataset , raise_errors = True ) self . assertFalse ( result . has_errors ( ) ) self . assertEqual ( result . rows [ ] . import_type , results . RowResult . IMPORT_TYPE_DELETE ) self . assertFalse ( Book . objects . filter ( pk = self . book . pk ) ) def test_relationships_fields ( self ) : class B ( resources . ModelResource ) : class Meta : model = Book fields = ( '' , ) author = Author . objects . create ( name = \"\" ) self . book . author = author resource = B ( ) result = resource . fields [ '' ] . export ( self . book ) self . assertEqual ( result , author . name ) def test_dehydrating_fields ( self ) : class B ( resources . ModelResource ) : full_title = fields . Field ( column_name = \"\" ) class Meta : model = Book fields = ( '' , '' ) def dehydrate_full_title ( self , obj ) : return '' % ( obj . name , obj . author . name ) author = Author . objects . create ( name = \"\" ) self . book . author = author resource = B ( ) full_title = resource . export_field ( resource . get_fields ( ) [ ] , self . book ) self . assertEqual ( full_title , '' % ( self . book . name , self . book . author . name ) ) def test_widget_fomat_in_fk_field ( self ) : class B ( resources . ModelResource ) : class Meta : model = Book fields = ( '' , ) widgets = { '' : { '' : '' } , } author = Author . objects . create ( name = \"\" ) self . book . author = author resource = B ( ) result = resource . fields [ '' ] . export ( self . book ) self . assertEqual ( result , str ( date . today ( ) ) ) def test_widget_kwargs_for_field ( self ) : class B ( resources . ModelResource ) : class Meta : model = Book fields = ( '' , ) widgets = { '' : { '' : '' } , } resource = B ( ) self . book . published = date ( , , ) result = resource . fields [ '' ] . export ( self . book ) self . assertEqual ( result , \"\" ) def test_foreign_keys_export ( self ) : author1 = Author . objects . create ( name = '' ) self . book . author = author1 self . book . save ( ) dataset = self . resource . export ( Book . objects . all ( ) ) self . assertEqual ( dataset . dict [ ] [ '' ] , author1 . pk ) def test_foreign_keys_import ( self ) : author2 = Author . objects . create ( name = '' ) headers = [ '' , '' , '' ] row = [ None , '' , author2 . pk ] dataset = tablib . Dataset ( row , headers = headers ) self . resource . import_data ( dataset , raise_errors = True ) book = Book . objects . get ( name = '' ) self . assertEqual ( book . author , author2 ) def test_m2m_export ( self ) : cat1 = Category . objects . create ( name = '' ) cat2 = Category . objects . create ( name = '' ) self . book . categories . add ( cat1 ) self . book . categories . add ( cat2 ) dataset = self . resource . export ( Book . objects . all ( ) ) self . assertEqual ( dataset . dict [ ] [ '' ] , '' % ( cat1 . pk , cat2 . pk ) ) def test_m2m_import ( self ) : cat1 = Category . objects . create ( name = '' ) headers = [ '' , '' , '' ] row = [ None , '' , \"\" % cat1 . pk ] dataset = tablib . Dataset ( row , headers = headers ) self . resource . import_data ( dataset , raise_errors = True ) book = Book . objects . get ( name = '' ) self . assertIn ( cat1 , book . categories . all ( ) ) def test_m2m_options_import ( self ) : cat1 = Category . objects . create ( name = '' ) cat2 = Category . objects . create ( name = '' ) headers = [ '' , '' , '' ] row = [ None , '' , \"\" ] dataset = tablib . Dataset ( row , headers = headers ) class BookM2MResource ( resources . ModelResource ) : categories = fields . Field ( attribute = '' , widget = widgets . ManyToManyWidget ( Category , field = '' , separator = '' ) ) class Meta : model = Book resource = BookM2MResource ( ) resource . import_data ( dataset , raise_errors = True ) book = Book . objects . get ( name = '' ) self . assertIn ( cat1 , book . categories . all ( ) ) self . assertIn ( cat2 , book . categories . all ( ) ) def test_related_one_to_one ( self ) : user = User . objects . create ( username = '' ) profile = Profile . objects . create ( user = user ) Entry . objects . create ( user = user ) Entry . objects . create ( user = User . objects . create ( username = '' ) ) class EntryResource ( resources . ModelResource ) : class Meta : model = Entry fields = ( '' , '' ) resource = EntryResource ( ) dataset = resource . export ( Entry . objects . all ( ) ) self . assertEqual ( dataset . dict [ ] [ '' ] , profile . pk ) self . assertEqual ( dataset . dict [ ] [ '' ] , '' ) self . assertEqual ( dataset . dict [ ] [ '' ] , '' ) self . assertEqual ( dataset . dict [ ] [ '' ] , '' ) def test_empty_get_queryset ( self ) : dataset = self . resource . export ( Book . objects . none ( ) ) self . assertEqual ( len ( dataset ) , ) def test_import_data_skip_unchanged ( self ) : def attempted_save ( instance , real_dry_run ) : self . fail ( '' ) cat1 = Category . objects . create ( name = '' ) cat2 = Category . objects . create ( name = '' ) self . book . categories . add ( cat1 ) self . book . categories . add ( cat2 ) dataset = self . resource . export ( ) resource = deepcopy ( self . resource ) resource . _meta . skip_unchanged = True resource . save_instance = attempted_save result = resource . import_data ( dataset , raise_errors = True ) self . assertFalse ( result . has_errors ( ) ) self . assertEqual ( len ( result . rows ) , len ( dataset ) ) self . assertTrue ( result . rows [ ] . diff ) self . assertEqual ( result . rows [ ] . import_type , results . RowResult . IMPORT_TYPE_SKIP ) resource . _meta . report_skipped = False result = resource . import_data ( dataset , raise_errors = True ) self . assertFalse ( result . has_errors ( ) ) self . assertEqual ( len ( result . rows ) , ) def test_before_import_access_to_kwargs ( self ) : class B ( BookResource ) : def before_import ( self , dataset , dry_run , ** kwargs ) : if '' in kwargs : dataset . headers [ dataset . headers . index ( '' ) ] = '' dataset . insert_col ( , lambda row : kwargs [ '' ] , header = '' ) resource = B ( ) result = resource . import_data ( self . dataset , raise_errors = True , extra_arg = '' ) self . assertFalse ( result . has_errors ( ) ) self . assertEqual ( len ( result . rows ) , ) instance = Book . objects . get ( pk = self . book . pk ) self . assertEqual ( instance . author_email , '' ) def test_link_to_nonexistent_field ( self ) : with self . assertRaises ( FieldDoesNotExist ) as cm : class BrokenBook1 ( resources . ModelResource ) : class Meta : model = Book fields = ( '' , ) self . assertEqual ( \"\" , cm . exception . args [ ] ) with self . assertRaises ( FieldDoesNotExist ) as cm : class BrokenBook2 ( resources . ModelResource ) : class Meta : model = Book fields = ( '' , ) self . assertEqual ( \"\" \"\" , cm . exception . args [ ] ) def test_link_to_nonrelation_field ( self ) : with self . assertRaises ( KeyError ) as cm : class BrokenBook1 ( resources . ModelResource ) : class Meta : model = Book fields = ( '' , ) self . assertEqual ( \"\" , cm . exception . args [ ] ) with self . assertRaises ( KeyError ) as cm : class BrokenBook2 ( resources . ModelResource ) : class Meta : model = Book fields = ( '' , ) self . assertEqual ( \"\" , cm . exception . args [ ] ) def test_override_field_construction_in_resource ( self ) : class B ( resources . ModelResource ) : class Meta : model = Book fields = ( '' , ) @ classmethod def field_from_django_field ( self , field_name , django_field , readonly ) : if field_name == '' : return { '' : '' } B ( ) self . assertEqual ( { '' : '' } , B . fields [ '' ] ) def test_readonly_annotated_field_import_and_export ( self ) : class B ( BookResource ) : total_categories = fields . Field ( '' , readonly = True ) class Meta : model = Book skip_unchanged = True cat1 = Category . objects . create ( name = '' ) self . book . categories . add ( cat1 ) resource = B ( ) dataset = resource . export ( Book . objects . annotate ( total_categories = Count ( '' ) ) ) self . assertEqual ( int ( dataset . dict [ ] [ '' ] ) , ) result = resource . import_data ( dataset , raise_errors = True ) self . assertFalse ( result . has_errors ( ) ) self . assertEqual ( len ( result . rows ) , len ( dataset ) ) self . assertEqual ( result . rows [ ] . import_type , results . RowResult . IMPORT_TYPE_SKIP ) def test_follow_relationship_for_modelresource ( self ) : class EntryResource ( resources . ModelResource ) : username = fields . Field ( attribute = '' , readonly = False ) class Meta : model = Entry fields = ( '' , ) def after_save_instance ( self , instance , dry_run ) : if not dry_run : instance . user . save ( ) user = User . objects . create ( username = '' ) entry = Entry . objects . create ( user = user ) row = [ entry . pk , '' , ] self . dataset = tablib . Dataset ( headers = [ '' , '' ] ) self . dataset . append ( row ) result = EntryResource ( ) . import_data ( self . dataset , raise_errors = True , dry_run = False ) self . assertFalse ( result . has_errors ( ) ) self . assertEquals ( User . objects . get ( pk = user . pk ) . username , '' ) def test_import_data_dynamic_default_callable ( self ) : class DynamicDefaultResource ( resources . ModelResource ) : class Meta : model = WithDynamicDefault fields = ( '' , '' , ) self . assertTrue ( callable ( DynamicDefaultResource . fields [ '' ] . default ) ) resource = DynamicDefaultResource ( ) dataset = tablib . Dataset ( headers = [ '' , '' , ] ) dataset . append ( [ , None ] ) dataset . append ( [ , None ] ) resource . import_data ( dataset , raise_errors = False ) objs = WithDynamicDefault . objects . all ( ) self . assertNotEqual ( objs [ ] . name , objs [ ] . name ) def test_float_field ( self ) : class R ( resources . ModelResource ) : class Meta : model = WithFloatField resource = R ( ) dataset = tablib . Dataset ( headers = [ '' , '' , ] ) dataset . append ( [ None , None ] ) dataset . append ( [ None , '' ] ) resource . import_data ( dataset , raise_errors = True ) self . assertEqual ( WithFloatField . objects . all ( ) [ ] . f , None ) self . assertEqual ( WithFloatField . objects . all ( ) [ ] . f , None ) class ModelResourceTransactionTest ( TransactionTestCase ) : @ skipUnlessDBFeature ( '' ) def test_m2m_import_with_transactions ( self ) : resource = BookResource ( ) cat1 = Category . objects . create ( name = '' ) headers = [ '' , '' , '' ] row = [ None , '' , \"\" % cat1 . pk ] dataset = tablib . Dataset ( row , headers = headers ) result = resource . import_data ( dataset , dry_run = True , use_transactions = True ) row_diff = result . rows [ ] . diff fields = resource . get_fields ( ) id_field = resource . fields [ '' ] id_diff = row_diff [ fields . index ( id_field ) ] self . assertTrue ( id_diff ) category_field = resource . fields [ '' ] categories_diff = row_diff [ fields . index ( category_field ) ] self . assertEqual ( strip_tags ( categories_diff ) , force_text ( cat1 . pk ) ) self . assertFalse ( Book . objects . filter ( name = '' ) ) @ skipUnlessDBFeature ( '' ) def test_m2m_import_with_transactions_error ( self ) : resource = ProfileResource ( ) headers = [ '' , '' ] row = [ None , None ] dataset = tablib . Dataset ( row , headers = headers ) result = resource . import_data ( dataset , dry_run = True , use_transactions = True ) self . assertTrue ( result . has_errors ( ) ) self . assertEqual ( Profile . objects . count ( ) , ) class ModelResourceFactoryTest ( TestCase ) : def test_create ( self ) : BookResource = resources . modelresource_factory ( Book ) self . assertIn ( '' , BookResource . fields ) self . assertEqual ( BookResource . _meta . model , Book ) @ skipUnless ( ", "answer": "'' in settings . DATABASES [ '' ] [ '' ] ,"}, {"prompt": " import os import sys ", "answer": "if __name__ == \"\" :"}, {"prompt": " from __future__ import unicode_literals import logging from django . core . exceptions import ObjectDoesNotExist , ValidationError from django . db . models import Q from django . utils import six from djblets . util . decorators import augment_method_from from djblets . webapi . decorators import ( webapi_login_required , webapi_response_errors , webapi_request_fields ) from djblets . webapi . errors import ( DOES_NOT_EXIST , INVALID_FORM_DATA , NOT_LOGGED_IN , PERMISSION_DENIED ) from reviewboard . scmtools . errors import ( AuthenticationError , SCMError , RepositoryNotFoundError , UnverifiedCertificateError ) from reviewboard . scmtools . models import Repository , Tool from reviewboard . ssh . client import SSHClient from reviewboard . ssh . errors import ( SSHError , BadHostKeyError , UnknownHostKeyError ) from reviewboard . webapi . base import WebAPIResource from reviewboard . webapi . decorators import ( webapi_check_login_required , webapi_check_local_site ) from reviewboard . webapi . errors import ( BAD_HOST_KEY , MISSING_REPOSITORY , MISSING_USER_KEY , REPO_AUTHENTICATION_ERROR , REPO_INFO_ERROR , REPOSITORY_ALREADY_EXISTS , SERVER_CONFIG_ERROR , UNVERIFIED_HOST_CERT , UNVERIFIED_HOST_KEY ) from reviewboard . webapi . resources import resources class RepositoryResource ( WebAPIResource ) : \"\"\"\"\"\" model = Repository name_plural = '' fields = { '' : { '' : int , '' : '' , } , '' : { '' : six . text_type , '' : '' , } , '' : { '' : six . text_type , '' : '' '' '' , } , '' : { '' : six . text_type , '' : '' '' , '' : '' , } , '' : { '' : bool , '' : '' '' , '' : '' , } , '' : { '' : six . text_type , '' : '' '' '' '' , } , '' : { '' : six . text_type , '' : '' '' '' , '' : '' , } } uri_object_key = '' item_child_resources = [ resources . diff_file_attachment , resources . repository_branches , resources . repository_commits , resources . repository_info , ] allowed_methods = ( '' , '' , '' , '' ) @ webapi_check_login_required def get_queryset ( self , request , is_list = False , local_site_name = None , show_invisible = False , * args , ** kwargs ) : \"\"\"\"\"\" local_site = self . _get_local_site ( local_site_name ) if is_list : queryset = self . model . objects . accessible ( request . user , visible_only = not show_invisible , local_site = local_site ) q = Q ( ) if '' in request . GET : q = q & Q ( name__in = request . GET . get ( '' ) . split ( '' ) ) if '' in request . GET : paths = request . GET [ '' ] . split ( '' ) q = q & ( Q ( path__in = paths ) | Q ( mirror_path__in = paths ) ) if '' in request . GET : name_or_paths = request . GET [ '' ] . split ( '' ) q = q & ( Q ( name__in = name_or_paths ) | Q ( path__in = name_or_paths ) | Q ( mirror_path__in = name_or_paths ) ) if '' in request . GET : q = q & Q ( tool__name__in = request . GET [ '' ] . split ( '' ) ) if '' in request . GET : q = q & Q ( hosting_account__service_name__in = request . GET [ '' ] . split ( '' ) ) if '' in request . GET : usernames = request . GET [ '' ] . split ( '' ) q = q & ( Q ( username__in = usernames ) | Q ( hosting_account__username__in = usernames ) ) return queryset . filter ( q ) . distinct ( ) else : return self . model . objects . filter ( local_site = local_site ) def serialize_tool_field ( self , obj , ** kwargs ) : return obj . tool . name def has_access_permissions ( self , request , repository , * args , ** kwargs ) : return repository . is_accessible_by ( request . user ) def has_modify_permissions ( self , request , repository , * args , ** kwargs ) : return repository . is_mutable_by ( request . user ) def has_delete_permissions ( self , request , repository , * args , ** kwargs ) : return repository . is_mutable_by ( request . user ) @ webapi_check_login_required @ webapi_check_local_site @ webapi_request_fields ( optional = dict ( { '' : { '' : str , '' : '' '' , '' : '' , } , '' : { '' : str , '' : '' '' , '' : '' , } , '' : { '' : str , '' : '' '' '' , '' : '' , } , '' : { '' : str , '' : '' '' , '' : '' , } , '' : { '' : str , '' : '' '' , '' : '' , } , '' : { '' : str , '' : '' '' , '' : '' , } , '' : { '' : bool , '' : '' '' , '' : '' , } , } , ** WebAPIResource . get_list . optional_fields ) , required = WebAPIResource . get_list . required_fields , allow_unknown = True ) def get_list ( self , request , * args , ** kwargs ) : \"\"\"\"\"\" show_invisible = request . GET . get ( '' , False ) return super ( RepositoryResource , self ) . get_list ( request , show_invisible = show_invisible , * args , ** kwargs ) @ webapi_check_local_site @ augment_method_from ( WebAPIResource ) def get ( self , * args , ** kwargs ) : \"\"\"\"\"\" pass @ webapi_check_local_site @ webapi_login_required @ webapi_response_errors ( BAD_HOST_KEY , INVALID_FORM_DATA , NOT_LOGGED_IN , PERMISSION_DENIED , REPO_AUTHENTICATION_ERROR , REPO_INFO_ERROR , REPOSITORY_ALREADY_EXISTS , SERVER_CONFIG_ERROR , UNVERIFIED_HOST_CERT , UNVERIFIED_HOST_KEY ) @ webapi_request_fields ( required = { '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , } , optional = { '' : { '' : six . text_type , '' : '' '' '' , '' : '' , } , '' : { '' : six . text_type , '' : '' '' '' '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : bool , '' : '' '' '' , '' : '' , } , '' : { '' : six . text_type , '' : \"\" \"\" \"\" \"\" \"\" \"\" , '' : '' , } , '' : { '' : bool , '' : '' '' '' '' '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : bool , '' : '' , '' : '' , } , } , ) def create ( self , request , name , path , tool , trust_host = False , bug_tracker = None , encoding = None , mirror_path = None , password = None , public = None , raw_file_url = None , username = None , visible = True , local_site_name = None , * args , ** kwargs ) : \"\"\"\"\"\" local_site = self . _get_local_site ( local_site_name ) if not Repository . objects . can_create ( request . user , local_site ) : return self . get_no_access_error ( request ) try : scmtool = Tool . objects . get ( name = tool ) except Tool . DoesNotExist : return INVALID_FORM_DATA , { '' : { '' : [ '' ] , } } cert = { } error_result = self . _check_repository ( scmtool . get_scmtool_class ( ) , path , username , password , local_site , trust_host , cert , request ) if error_result is not None : return error_result if public is None : public = True repository = Repository ( name = name , path = path , mirror_path = mirror_path or '' , raw_file_url = raw_file_url or '' , username = username or '' , password = password or '' , tool = scmtool , bug_tracker = bug_tracker or '' , encoding = encoding or '' , public = public , visible = visible , local_site = local_site ) if cert : repository . extra_data [ '' ] = cert try : repository . full_clean ( ) except ValidationError as e : if hasattr ( e , '' ) and '' in e . params : return INVALID_FORM_DATA , { '' : { e . params [ '' ] : e . message , } , } else : return REPOSITORY_ALREADY_EXISTS repository . save ( ) return , { self . item_result_key : repository , } @ webapi_check_local_site @ webapi_login_required @ webapi_response_errors ( DOES_NOT_EXIST , NOT_LOGGED_IN , PERMISSION_DENIED , INVALID_FORM_DATA , SERVER_CONFIG_ERROR , BAD_HOST_KEY , UNVERIFIED_HOST_KEY , UNVERIFIED_HOST_CERT , REPO_AUTHENTICATION_ERROR , REPO_INFO_ERROR ) @ webapi_request_fields ( optional = { '' : { '' : six . text_type , '' : '' '' '' , '' : '' , } , '' : { '' : six . text_type , '' : '' '' '' '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : bool , '' : '' '' '' , '' : '' , } , '' : { '' : six . text_type , '' : \"\" \"\" \"\" \"\" \"\" \"\" , '' : '' , } , '' : { '' : bool , '' : '' '' '' '' '' , '' : '' , } , '' : { '' : six . text_type , '' : '' , '' : '' , } , '' : { '' : bool , '' : \"\" \"\" \"\" \"\" , '' : '' , } , '' : { '' : bool , '' : '' , '' : '' , } , } , ) def update ( self , request , trust_host = False , * args , ** kwargs ) : \"\"\"\"\"\" ", "answer": "try :"}, {"prompt": " import time import os from ConfigParser import RawConfigParser import fabric from fabric . api import env , run from fabric . operations import put import server_creator def install_python_and_curl ( ) : run ( \"\" \"\" \"\" \"\" \"\" ) run ( \"\" \"\" \"\" \"\" \"\" ) run ( \"\" \"\" \"\" \"\" \"\" ) run ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) def install_agent ( ) : run ( \"\" \"\" ) run ( \"\" ) run ( \"\" ) def run_tests ( ) : run ( \"\" \"\" ) run ( \"\" ) run ( \"\" ) def install_agent_and_run_tests ( ) : load_config ( ) ", "answer": "install_python_and_curl ( )"}, {"prompt": " from gwt . chart . AnnotationLocation import ( AT_THE_MOUSE , AT_THE_MOUSE_SNAP_TO_X , AT_THE_MOUSE_SNAP_TO_Y , AnnotationLocation , CENTER , CLOSEST_TO_HORIZONTAL_BASELINE , CLOSEST_TO_VERTICAL_BASELINE , EAST , FARTHEST_FROM_HORIZONTAL_BASELINE , FARTHEST_FROM_VERTICAL_BASELINE , HasHorizontalAlignment , HasVerticalAlignment , INSIDE_PIE_ARC , NORTH , NORTHEAST , NORTHWEST , ON_PIE_ARC , OUTSIDE_PIE_ARC , SOUTH , SOUTHEAST , SOUTHWEST , WEST , getAnnotationLocation , math , north , ", "answer": "south ,"}, {"prompt": " from django . core . paginator import EmptyPage from django . core . paginator import Paginator from django . core . paginator import PageNotAnInteger ", "answer": "def paginator ( page , object_list , per_page = ) :"}, {"prompt": " from app import create_app from app . config import test_config from app . database import db from app . user . models import User from sqlalchemy . sql . expression import func from faker import Factory import unittest admin_username = '' admin_email = '' admin_password = '' fake = Factory . create ( ) class TestCase ( unittest . TestCase ) : def setUp ( self ) : app = create_app ( test_config ) db . app = app self . app = app . test_client ( ) def tearDown ( self ) : pass def login ( self , username , password ) : return self . app . post ( '' , data = dict ( username = username , ", "answer": "password = password"}, {"prompt": " \"\"\"\"\"\" MEDIA_ERR_ABORTED = MEDIA_ERR_NETWORK = MEDIA_ERR_DECODE = ", "answer": "MEDIA_ERR_SRC_NOT_SUPPORTED = "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" result . attribute_template_id = ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import os import numpy as np from theano . compat import six from theano . compat . six . moves import cPickle import tempfile from numpy . testing import assert_ from os import environ , close from decimal import Decimal from tempfile import mkstemp from pylearn2 . compat import first_key , first_value from pylearn2 . config . yaml_parse import load , load_path , initialize from pylearn2 . utils import serial from pylearn2 . utils . exc import reraise_as from pylearn2 . config . yaml_parse import SCIENTIFIC_NOTATION_REGEXP import yaml import re def test_load_path ( ) : fd , fname = tempfile . mkstemp ( ) with os . fdopen ( fd , '' ) as f : f . write ( six . b ( \"\" ) ) loaded = load_path ( fname ) assert_ ( loaded [ '' ] == ) os . remove ( fname ) def test_obj ( ) : loaded = load ( \"\" ) ", "answer": "assert_ ( isinstance ( loaded [ '' ] , Decimal ) )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " from unittest import TestCase from chatterbot . conversation import Response , Signature class ResponseTests ( TestCase ) : def setUp ( self ) : self . response = Response ( \"\" ) def test_add_signature ( self ) : signature = Signature ( \"\" ) ", "answer": "self . response . add_signature ( signature )"}, {"prompt": " import os import setuptools os . putenv ( '' , '' ) README = os . path . join ( os . path . dirname ( __file__ ) , '' ) if not os . path . exists ( README ) : os . symlink ( README + '' , README ) description = ( '' '' ) with open ( README ) as f : long_description = '' . join ( f . read ( ) . split ( '' ) [ : ] ) setuptools . setup ( name = '' , version = '' , author = '' , author_email = '' , url = '' , description = description , long_description = long_description , download_url = '' , packages = [ '' , ] , install_requires = [ '' , '' , '' , ] , classifiers = [ '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from kraken . core . objects . object_3d import Object3D class ComponentInput ( Object3D ) : \"\"\"\"\"\" def __init__ ( self , name , parent = None ) : super ( ComponentInput , self ) . __init__ ( name , parent = parent ) ", "answer": "self . setShapeVisibility ( False ) "}, {"prompt": " \"\"\"\"\"\" import dis import opcode import marshal import time import struct import types import operator import traceback import imp from dis import findlinestarts , findlabels from . . utils . log import logger from . utils import show_bytecode from . decl import ModuleDeclaration , TypeDeclaration , MethodDeclaration , FieldDeclaration , ImportDeclaration from . . visitors . bytecode import BytecodeVisitor from . . visitors . classes import ClassVisitor from . . visitors . methods import MethodVisitor from . . visitors . modules import ModuleVisitor CO_OPTIMIZED = CO_NEWLOCALS = CO_VARARGS = CO_VARKEYWORDS = CO_NESTED = CO_GENERATOR = CO_NOFREE = CO_GENERATOR_ALLOWED = CO_FUTURE_DIVISION = CO_FUTURE_ABSOLUTE_IMPORT = CO_FUTURE_WITH_STATEMENT = POP_TOP = IMPORT_STAR = BUILD_CLASS = STORE_NAME = LOAD_CONST = LOAD_ATTR = IMPORT_NAME = IMPORT_FROM = STORE_FAST = CALL_FUNCTION = MAKE_FUNCTION = MAKE_CLOSURE = class BytecodeObject ( object ) : \"\"\"\"\"\" def __init__ ( self , pyc_file , lazy_load = True ) : \"\"\"\"\"\" self . code = None self . magic = None self . moddate = None self . modif_date = None self . pyc_file = pyc_file if not lazy_load : self . parse ( ) self . main_module = None self . bytecode = [ ] self . all_decls = set ( ) def parse ( self ) : \"\"\"\"\"\" fd = open ( self . pyc_file , '' ) self . magic = fd . read ( ) self . moddate = fd . read ( ) self . modif_date = long ( struct . unpack ( '' , self . moddate ) [ ] ) co = marshal . load ( fd ) self . parse_code ( co ) def parse_code ( self , co ) : \"\"\"\"\"\" self . code = co self . bytecode = [ ] try : self . load_bytecode ( self . code ) self . build_representation ( ) except Exception , ex : logger . error ( \"\" , repr ( ex ) , exc_info = ex ) def get_module ( self ) : \"\"\"\"\"\" return self . main_module def get_bytecode ( self ) : \"\"\"\"\"\" return self . bytecode @ property def declarations ( self ) : \"\"\"\"\"\" return self . all_decls @ property def has_changes ( self ) : \"\"\"\"\"\" return self . main_module . has_changes def accept ( self , visitor ) : \"\"\"\"\"\" if not self . code : self . parse ( ) if isinstance ( visitor , BytecodeVisitor ) : for i in xrange ( len ( self . bytecode ) ) : index , lineno , op , arg , cflow_in , _ = self . bytecode [ i ] visitor . visit ( index , op , arg = arg , lineno = lineno , cflow_in = cflow_in ) elif isinstance ( visitor , ModuleVisitor ) : visitor . visit ( self . main_module ) elif isinstance ( visitor , ClassVisitor ) or isinstance ( visitor , MethodVisitor ) : if not self . main_module : logger . debug ( \"\" ) return self . __depth_visitor_run ( visitor ) def __depth_visitor_run ( self , visitor ) : \"\"\"\"\"\" logger . debug ( \"\" , visitor , self . main_module ) cache = set ( ) is_class_visitor = isinstance ( visitor , ClassVisitor ) stack = [ self . main_module ] while stack : current = stack . pop ( ) children = current . children logger . debug ( \"\" , children ) for child in children : if not child : continue if ( is_class_visitor and isinstance ( child , TypeDeclaration ) ) or ( not is_class_visitor and isinstance ( child , MethodDeclaration ) ) : if child in cache : continue visitor . visit ( child ) cache . add ( child ) stack . insert ( , child ) def add_enter_code ( self , python_code , import_code = None ) : \"\"\"\"\"\" from . . rewriter . simple import SimpleRewriter rewriter = SimpleRewriter ( self . main_module ) rewriter . insert_enter_code ( python_code , import_code ) def add_exit_code ( self , python_code , import_code = None ) : \"\"\"\"\"\" from . . rewriter . simple import SimpleRewriter rewriter = SimpleRewriter ( self . main_module ) rewriter . insert_exit_code ( python_code , import_code ) def write ( self ) : \"\"\"\"\"\" if not self . has_changes : logger . debug ( \"\" , self . main_module . module_path ) return try : new_co = self . main_module . code_object source_file = self . main_module . module_path . replace ( '' , '' ) timestamp = self . modif_date try : timestamp = long ( os . stat ( source_file ) . st_mtime ) except : pass fd = open ( self . main_module . module_path , '' ) fd . write ( '' ) fd . write ( struct . pack ( '' , timestamp ) ) marshal . dump ( new_co , fd ) fd . flush ( ) fd . seek ( , ) fd . write ( imp . get_magic ( ) ) fd . close ( ) logger . debug ( \"\" , self . main_module . module_path ) return True except Exception , ex : logger . error ( \"\" , str ( ex ) ) logger . error ( \"\" , traceback . format_exc ( ) ) return False def build_representation ( self ) : \"\"\"\"\"\" if not self . bytecode : return decl_counter = self . all_decls = set ( ) decl_map = { } class_decl_indices , method_decl_indices = BytecodeObject . find_classes_methods ( self . bytecode ) interest_indices = class_decl_indices . union ( method_decl_indices ) current_co = self . bytecode [ ] [ ] self . main_module = ModuleDeclaration ( self . pyc_file , current_co ) self . main_module . bytecode = self . bytecode self . main_module . bytecode_object = self module_lines = ( , max ( [ self . bytecode [ i ] [ ] for i in xrange ( len ( self . bytecode ) ) ] ) , decl_counter ) self . main_module . lines = module_lines BytecodeObject . parse_imports ( self . main_module , self . bytecode ) decl_map [ module_lines ] = self . main_module decl_counter += self . all_decls . add ( self . main_module ) for tpl_indices in interest_indices : decl = None start_index , end_index = tpl_indices index , lineno , op , arg , _ , co = self . bytecode [ start_index ] end_lineno = max ( [ self . bytecode [ i ] [ ] for i in xrange ( start_index , min ( end_index + , len ( self . bytecode ) ) ) ] ) decl_co = BytecodeObject . next_code_object ( self . bytecode , start_index ) lines_tuple = ( lineno , end_lineno , decl_counter ) i = start_index if tpl_indices in class_decl_indices : decl = TypeDeclaration ( decl_co . co_name , decl_co ) else : decl = MethodDeclaration ( decl_co . co_name , decl_co ) decl . formal_params = BytecodeObject . get_formal_params ( decl_co ) decl . bytecode = self . bytecode [ start_index : end_index ] decl . lines = lines_tuple [ : ] self . all_decls . add ( decl ) decl_map [ lines_tuple ] = decl decl_counter += co_deps_graph = { self . main_module . code_object : { } } i , length = , len ( self . bytecode ) while i < length : op , arg , co = self . bytecode [ i ] [ ] , self . bytecode [ i ] [ ] , self . bytecode [ i ] [ ] if op == LOAD_CONST and isinstance ( arg , types . CodeType ) : if co not in co_deps_graph : co_deps_graph [ co ] = dict ( ) if arg not in co_deps_graph [ co ] : co_deps_graph [ co ] [ arg ] = dict ( ) decl_parent = self . get_decl ( code_object = co ) decl_child = self . get_decl ( code_object = arg ) decl_child . parent = decl_parent i += logger . debug ( '' + BytecodeObject . build_tree ( self . main_module ) ) def get_decl ( self , code_object = None , method_name = None , type_name = None ) : \"\"\"\"\"\" if code_object is not None : for decl in self . declarations : if decl . code_object == code_object : return decl elif method_name is not None : results = [ ] for decl in self . declarations : if isinstance ( decl , MethodDeclaration ) and decl . method_name == method_name : results . append ( decl ) if not results : return None return results [ ] if len ( results ) == else results elif type_name is not None : results = [ ] for decl in self . declarations : if isinstance ( decl , TypeDeclaration ) and decl . type_name == type_name : results . append ( decl ) if not results : return None return results [ ] if len ( results ) == else results return None @ staticmethod def build_tree ( root , indent = '' ) : \"\"\"\"\"\" buffer = '' buffer += indent + repr ( root ) + '' for c in root . children : buffer += BytecodeObject . build_tree ( c , indent + '' ) return buffer @ staticmethod def finalize_decl_object ( kind , acc_data ) : pass @ staticmethod def next_code_object ( bytecode , index ) : i = index while i < len ( bytecode ) : co = bytecode [ i ] [ ] if isinstance ( co , types . CodeType ) : return co i += return None @ staticmethod def prev_code_object ( bytecode , index ) : i = index while i <= : co = bytecode [ i ] [ ] if isinstance ( co , types . CodeType ) : return co i -= return None @ staticmethod def find_classes_methods ( bytecode ) : \"\"\"\"\"\" class_indices = set ( ) method_indices = set ( ) class_lines = set ( ) method_lines = set ( ) co_lines = { } classes_co = set ( ) methods_co = set ( ) i , length = , len ( bytecode ) while i < length : tpl = bytecode [ i ] lineno , op_code , co = tpl [ ] , tpl [ ] , tpl [ ] if op_code == BUILD_CLASS : class_co = bytecode [ i - ] [ ] co_lines [ class_co ] = lineno classes_co . add ( class_co ) class_lines . add ( lineno ) elif op_code in ( MAKE_FUNCTION , MAKE_CLOSURE ) : if i < length - and bytecode [ i + ] [ ] == CALL_FUNCTION and bytecode [ i + ] [ ] == BUILD_CLASS : i += continue prev_co = bytecode [ i - ] [ ] method_lines . add ( lineno ) methods_co . add ( prev_co ) co_lines [ prev_co ] = lineno i += for decl_co in co_lines : if decl_co not in methods_co and decl_co not in classes_co : continue dest_set = method_indices if decl_co in methods_co else class_indices i , length = , len ( bytecode ) start_index , end_index = , while i < length : co = bytecode [ i ] [ ] if co == decl_co : start_index = i j = i + while j < length : if bytecode [ j ] [ ] == decl_co : end_index = j j += break i += dest_set . add ( ( start_index , end_index ) ) return class_indices , method_indices @ staticmethod def get_formal_params ( code_object ) : \"\"\"\"\"\" varargs = bool ( code_object . co_flags & CO_VARARGS ) varkwargs = bool ( code_object . co_flags & CO_VARKEYWORDS ) args = code_object . co_varnames [ : code_object . co_argcount + varargs + varkwargs ] return args def load_bytecode ( self , code_object ) : BytecodeObject . parse_code_object ( code_object , self . bytecode ) @ staticmethod def get_parsed_code ( code_object ) : bytecode = [ ] BytecodeObject . parse_code_object ( code_object , bytecode ) return bytecode @ staticmethod def parse_code_object ( code_object , bytecode ) : \"\"\"\"\"\" if not code_object : return code = code_object . co_code labels = findlabels ( code_object . co_code ) linestarts = dict ( findlinestarts ( code_object ) ) global_free = code_object . co_cellvars + code_object . co_freevars newlocals = bool ( code_object . co_flags & CO_NEWLOCALS ) length = len ( code ) i = lineno = - extended_arg = while i < length : c = code [ i ] op = ord ( c ) if i in linestarts : lineno = linestarts [ i ] arg1 = None cflow_in = i in labels current_index = i i += if op >= opcode . HAVE_ARGUMENT : oparg = ord ( code [ i ] ) + ( ord ( code [ i + ] ) << ) + extended_arg i += label = - extended_arg = if op == opcode . EXTENDED_ARG : extended_arg = ( oparg << ) if op in opcode . hasconst : arg1 = code_object . co_consts [ oparg ] elif op in opcode . hasname : arg1 = code_object . co_names [ oparg ] elif op in opcode . haslocal : arg1 = code_object . co_varnames [ oparg ] elif op in opcode . hascompare : arg1 = opcode . cmp_op [ oparg ] elif op in opcode . hasfree : arg1 = global_free [ oparg ] elif op in opcode . hasjrel : arg1 = oparg elif op in opcode . hasjabs : arg1 = oparg else : arg1 = oparg bytecode . append ( ( current_index , lineno , op , arg1 , cflow_in , code_object ) ) if arg1 and isinstance ( arg1 , types . CodeType ) : BytecodeObject . parse_code_object ( arg1 , bytecode ) @ staticmethod def parse_imports ( main_module , bytecode ) : \"\"\"\"\"\" import_stmts = BytecodeObject . get_imports_from_bytecode ( main_module . code_object , bytecode ) for imp_stmt in import_stmts : main_module . add_import ( imp_stmt ) @ staticmethod def get_imports_from_bytecode ( code_object , bytecode ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import numpy as np from bokeh . document import Document from bokeh . models import ColumnDataSource , DataRange1d , Plot , LinearAxis , Grid from bokeh . models . markers import X from bokeh . plotting import show N = x = np . linspace ( - , , N ) y = x ** sizes = np . linspace ( , , N ) source = ColumnDataSource ( dict ( x = x , y = y , sizes = sizes ) ) xdr = DataRange1d ( ) ydr = DataRange1d ( ) plot = Plot ( title = None , x_range = xdr , y_range = ydr , plot_width = , plot_height = , h_symmetry = False , v_symmetry = False , min_border = , toolbar_location = None ) glyph = X ( x = \"\" , y = \"\" , size = \"\" , line_color = \"\" , line_width = , fill_color = None ) plot . add_glyph ( source , glyph ) xaxis = LinearAxis ( ) plot . add_layout ( xaxis , '' ) yaxis = LinearAxis ( ) plot . add_layout ( yaxis , '' ) ", "answer": "plot . add_layout ( Grid ( dimension = , ticker = xaxis . ticker ) )"}, {"prompt": " from bencode import bencode , bdecode from BT1 . btformats import check_info from os . path import exists , isfile ", "answer": "from sha import sha"}, {"prompt": " \"\"\"\"\"\" from __future__ import with_statement __author__ = '' __version__ = '' __license__ = '' if __name__ == '' : from optparse import OptionParser _cmd_parser = OptionParser ( usage = \"\" ) _opt = _cmd_parser . add_option _opt ( \"\" , action = \"\" , help = \"\" ) _opt ( \"\" , \"\" , metavar = \"\" , help = \"\" ) _opt ( \"\" , \"\" , default = '' , help = \"\" ) _opt ( \"\" , \"\" , action = \"\" , help = \"\" ) _opt ( \"\" , action = \"\" , help = \"\" ) _opt ( \"\" , action = \"\" , help = \"\" ) _cmd_options , _cmd_args = _cmd_parser . parse_args ( ) if _cmd_options . server and _cmd_options . server . startswith ( '' ) : import gevent . monkey ; gevent . monkey . patch_all ( ) import base64 , cgi , email . utils , functools , hmac , imp , itertools , mimetypes , os , re , subprocess , sys , tempfile , threading , time , urllib , warnings from datetime import date as datedate , datetime , timedelta from tempfile import TemporaryFile from traceback import format_exc , print_exc try : from json import dumps as json_dumps , loads as json_lds except ImportError : try : from simplejson import dumps as json_dumps , loads as json_lds except ImportError : try : from django . utils . simplejson import dumps as json_dumps , loads as json_lds except ImportError : def json_dumps ( data ) : raise ImportError ( \"\" ) json_lds = json_dumps py = sys . version_info py3k = py >= ( , , ) py25 = py < ( , , ) py31 = ( , , ) <= py < ( , , ) def _e ( ) : return sys . exc_info ( ) [ ] try : _stdout , _stderr = sys . stdout . write , sys . stderr . write except IOError : _stdout = lambda x : sys . stdout . write ( x ) _stderr = lambda x : sys . stderr . write ( x ) if py3k : import http . client as httplib import _thread as thread from urllib . parse import urljoin , SplitResult as UrlSplitResult from urllib . parse import urlencode , quote as urlquote , unquote as urlunquote urlunquote = functools . partial ( urlunquote , encoding = '' ) from http . cookies import SimpleCookie from collections import MutableMapping as DictMixin import pickle from io import BytesIO basestring = str unicode = str json_loads = lambda s : json_lds ( touni ( s ) ) callable = lambda x : hasattr ( x , '' ) imap = map def _raise ( * a ) : raise a [ ] ( a [ ] ) . with_traceback ( a [ ] ) else : import httplib import thread from urlparse import urljoin , SplitResult as UrlSplitResult from urllib import urlencode , quote as urlquote , unquote as urlunquote from Cookie import SimpleCookie from itertools import imap import cPickle as pickle from StringIO import StringIO as BytesIO if py25 : msg = \"\" warnings . warn ( msg , DeprecationWarning ) from UserDict import DictMixin def next ( it ) : return it . next ( ) bytes = str else : from collections import MutableMapping as DictMixin json_loads = json_lds eval ( compile ( '' , '' , '' ) ) def tob ( s , enc = '' ) : return s . encode ( enc ) if isinstance ( s , unicode ) else bytes ( s ) def touni ( s , enc = '' , err = '' ) : return s . decode ( enc , err ) if isinstance ( s , bytes ) else unicode ( s ) tonat = touni if py3k else tob if py31 : from io import TextIOWrapper class NCTextIOWrapper ( TextIOWrapper ) : def close ( self ) : pass def update_wrapper ( wrapper , wrapped , * a , ** ka ) : try : functools . update_wrapper ( wrapper , wrapped , * a , ** ka ) except AttributeError : pass def depr ( message , hard = False ) : warnings . warn ( message , DeprecationWarning , stacklevel = ) def makelist ( data ) : if isinstance ( data , ( tuple , list , set , dict ) ) : return list ( data ) elif data : return [ data ] else : return [ ] class DictProperty ( object ) : '''''' def __init__ ( self , attr , key = None , read_only = False ) : self . attr , self . key , self . read_only = attr , key , read_only def __call__ ( self , func ) : functools . update_wrapper ( self , func , updated = [ ] ) self . getter , self . key = func , self . key or func . __name__ return self def __get__ ( self , obj , cls ) : if obj is None : return self key , storage = self . key , getattr ( obj , self . attr ) if key not in storage : storage [ key ] = self . getter ( obj ) return storage [ key ] def __set__ ( self , obj , value ) : if self . read_only : raise AttributeError ( \"\" ) getattr ( obj , self . attr ) [ self . key ] = value def __delete__ ( self , obj ) : if self . read_only : raise AttributeError ( \"\" ) del getattr ( obj , self . attr ) [ self . key ] class cached_property ( object ) : '''''' def __init__ ( self , func ) : self . __doc__ = getattr ( func , '' ) self . func = func def __get__ ( self , obj , cls ) : if obj is None : return self value = obj . __dict__ [ self . func . __name__ ] = self . func ( obj ) return value class lazy_attribute ( object ) : '''''' def __init__ ( self , func ) : functools . update_wrapper ( self , func , updated = [ ] ) self . getter = func def __get__ ( self , obj , cls ) : value = self . getter ( cls ) setattr ( cls , self . __name__ , value ) return value class BottleException ( Exception ) : \"\"\"\"\"\" pass class RouteError ( BottleException ) : \"\"\"\"\"\" class RouteReset ( BottleException ) : \"\"\"\"\"\" class RouterUnknownModeError ( RouteError ) : pass class RouteSyntaxError ( RouteError ) : \"\"\"\"\"\" class RouteBuildError ( RouteError ) : \"\"\"\"\"\" def _re_flatten ( p ) : '''''' if '' not in p : return p return re . sub ( r'' , lambda m : m . group ( ) if len ( m . group ( ) ) % else m . group ( ) + '' , p ) class Router ( object ) : '''''' default_pattern = '' default_filter = '' def __init__ ( self , strict = False ) : self . rules = [ ] self . _groups = { } self . builder = { } self . static = { } self . dynamic = [ ] self . strict_order = strict self . filters = { '' : lambda conf : ( _re_flatten ( conf or self . default_pattern ) , None , None ) , '' : lambda conf : ( r'' , int , lambda x : str ( int ( x ) ) ) , '' : lambda conf : ( r'' , float , lambda x : str ( float ( x ) ) ) , '' : lambda conf : ( r'' , None , None ) } def add_filter ( self , name , func ) : '''''' self . filters [ name ] = func rule_syntax = re . compile ( '' '' '' '' ) def _itertokens ( self , rule ) : offset , prefix = , '' for match in self . rule_syntax . finditer ( rule ) : prefix += rule [ offset : match . start ( ) ] g = match . groups ( ) if len ( g [ ] ) % : prefix += match . group ( ) [ len ( g [ ] ) : ] offset = match . end ( ) continue if prefix : yield prefix , None , None name , filtr , conf = g [ : ] if g [ ] is None else g [ : ] yield name , filtr or '' , conf or None offset , prefix = match . end ( ) , '' if offset <= len ( rule ) or prefix : yield prefix + rule [ offset : ] , None , None def add ( self , rule , method , target , name = None ) : '''''' anons = keys = [ ] pattern = '' filters = [ ] builder = [ ] is_static = True for key , mode , conf in self . _itertokens ( rule ) : if mode : is_static = False if mode == '' : mode = self . default_filter mask , in_filter , out_filter = self . filters [ mode ] ( conf ) if not key : pattern += '' % mask key = '' % anons anons += else : pattern += '' % ( key , mask ) keys . append ( key ) if in_filter : filters . append ( ( key , in_filter ) ) builder . append ( ( key , out_filter or str ) ) elif key : pattern += re . escape ( key ) builder . append ( ( None , key ) ) self . builder [ rule ] = builder if name : self . builder [ name ] = builder if is_static and not self . strict_order : group = self . static . setdefault ( self . build ( rule ) , { } ) group [ method ] = ( target , None ) return try : re_pattern = re . compile ( '' % pattern ) re_match = re_pattern . match except re . error : raise RouteSyntaxError ( \"\" % ( rule , _e ( ) ) ) if filters : def getargs ( path ) : url_args = re_match ( path ) . groupdict ( ) for name , wildcard_filter in filters : try : url_args [ name ] = wildcard_filter ( url_args [ name ] ) except ValueError : raise HTTPError ( , '' ) return url_args elif re_pattern . groupindex : def getargs ( path ) : return re_match ( path ) . groupdict ( ) else : getargs = None flatpat = _re_flatten ( pattern ) if flatpat in self . _groups : group = self . _groups [ flatpat ] if method in group : if DEBUG : msg = '' warnings . warn ( msg % ( method , rule ) , RuntimeWarning ) self . _groups [ flatpat ] [ method ] = ( target , getargs ) return mdict = self . _groups [ flatpat ] = { method : ( target , getargs ) } try : combined = '' % ( self . dynamic [ - ] [ ] . pattern , flatpat ) self . dynamic [ - ] = ( re . compile ( combined ) , self . dynamic [ - ] [ ] ) self . dynamic [ - ] [ ] . append ( mdict ) except ( AssertionError , IndexError ) : self . dynamic . append ( ( re . compile ( '' % flatpat ) , [ mdict ] ) ) def build ( self , _name , * anons , ** query ) : '''''' builder = self . builder . get ( _name ) if not builder : raise RouteBuildError ( \"\" , _name ) try : for i , value in enumerate ( anons ) : query [ '' % i ] = value url = '' . join ( [ f ( query . pop ( n ) ) if n else f for ( n , f ) in builder ] ) return url if not query else url + '' + urlencode ( query ) except KeyError : raise RouteBuildError ( '' % _e ( ) . args [ ] ) def match ( self , environ ) : '''''' path , targets , urlargs = environ [ '' ] or '' , None , { } if path in self . static : targets = self . static [ path ] else : for combined , rules in self . dynamic : match = combined . match ( path ) if not match : continue targets = rules [ match . lastindex - ] break if not targets : raise HTTPError ( , \"\" + repr ( environ [ '' ] ) ) method = environ [ '' ] . upper ( ) if method in targets : target , getargs = targets [ method ] elif method == '' and '' in targets : target , getargs = targets [ '' ] elif '' in targets : target , getargs = targets [ '' ] else : allowed = [ verb for verb in targets if verb != '' ] if '' in allowed and '' not in allowed : allowed . append ( '' ) raise HTTPError ( , \"\" , Allow = \"\" . join ( allowed ) ) return target , getargs ( path ) if getargs else { } class Route ( object ) : '''''' def __init__ ( self , app , rule , method , callback , name = None , plugins = None , skiplist = None , ** config ) : self . app = app self . rule = rule self . method = method self . callback = callback self . name = name or None self . plugins = plugins or [ ] self . skiplist = skiplist or [ ] self . config = ConfigDict ( config ) def __call__ ( self , * a , ** ka ) : depr ( \"\" \"\" \"\" ) return self . call ( * a , ** ka ) @ cached_property def call ( self ) : '''''' return self . _make_callback ( ) def reset ( self ) : '''''' self . __dict__ . pop ( '' , None ) def prepare ( self ) : '''''' self . call @ property def _context ( self ) : depr ( '' ) return dict ( rule = self . rule , method = self . method , callback = self . callback , name = self . name , app = self . app , config = self . config , apply = self . plugins , skip = self . skiplist ) def all_plugins ( self ) : '''''' unique = set ( ) for p in reversed ( self . app . plugins + self . plugins ) : if True in self . skiplist : break name = getattr ( p , '' , False ) if name and ( name in self . skiplist or name in unique ) : continue if p in self . skiplist or type ( p ) in self . skiplist : continue if name : unique . add ( name ) yield p def _make_callback ( self ) : callback = self . callback for plugin in self . all_plugins ( ) : try : if hasattr ( plugin , '' ) : api = getattr ( plugin , '' , ) context = self if api > else self . _context callback = plugin . apply ( callback , context ) else : callback = plugin ( callback ) except RouteReset : return self . _make_callback ( ) if not callback is self . callback : update_wrapper ( callback , self . callback ) return callback def __repr__ ( self ) : return '' % ( self . method , self . rule , self . callback ) class Bottle ( object ) : \"\"\"\"\"\" def __init__ ( self , catchall = True , autojson = True ) : self . catchall = catchall self . resources = ResourceManager ( ) self . config = ConfigDict ( ) self . config . autojson = autojson self . routes = [ ] self . router = Router ( ) self . error_handler = { } self . plugins = [ ] self . hooks = HooksPlugin ( ) self . install ( self . hooks ) if self . config . autojson : self . install ( JSONPlugin ( ) ) self . install ( TemplatePlugin ( ) ) def mount ( self , prefix , app , ** options ) : '''''' if isinstance ( app , basestring ) : depr ( '' , True ) segments = [ p for p in prefix . split ( '' ) if p ] if not segments : raise ValueError ( '' ) path_depth = len ( segments ) def mountpoint_wrapper ( ) : try : request . path_shift ( path_depth ) rs = HTTPResponse ( [ ] ) def start_response ( status , headerlist , exc_info = None ) : if exc_info : try : _raise ( * exc_info ) finally : exc_info = None rs . status = status for name , value in headerlist : rs . add_header ( name , value ) return rs . body . append body = app ( request . environ , start_response ) if body and rs . body : body = itertools . chain ( rs . body , body ) rs . body = body or rs . body return rs finally : request . path_shift ( - path_depth ) options . setdefault ( '' , True ) options . setdefault ( '' , '' ) options . setdefault ( '' , { '' : prefix , '' : app } ) options [ '' ] = mountpoint_wrapper self . route ( '' % '' . join ( segments ) , ** options ) if not prefix . endswith ( '' ) : self . route ( '' + '' . join ( segments ) , ** options ) def merge ( self , routes ) : '''''' if isinstance ( routes , Bottle ) : routes = routes . routes for route in routes : self . add_route ( route ) def install ( self , plugin ) : '''''' if hasattr ( plugin , '' ) : plugin . setup ( self ) if not callable ( plugin ) and not hasattr ( plugin , '' ) : raise TypeError ( \"\" ) self . plugins . append ( plugin ) self . reset ( ) return plugin def uninstall ( self , plugin ) : '''''' removed , remove = [ ] , plugin for i , plugin in list ( enumerate ( self . plugins ) ) [ : : - ] : if remove is True or remove is plugin or remove is type ( plugin ) or getattr ( plugin , '' , True ) == remove : removed . append ( plugin ) del self . plugins [ i ] if hasattr ( plugin , '' ) : plugin . close ( ) if removed : self . reset ( ) return removed def run ( self , ** kwargs ) : '''''' run ( self , ** kwargs ) def reset ( self , route = None ) : '''''' if route is None : routes = self . routes elif isinstance ( route , Route ) : routes = [ route ] else : routes = [ self . routes [ route ] ] for route in routes : route . reset ( ) if DEBUG : for route in routes : route . prepare ( ) self . hooks . trigger ( '' ) def close ( self ) : '''''' for plugin in self . plugins : if hasattr ( plugin , '' ) : plugin . close ( ) self . stopped = True def match ( self , environ ) : \"\"\"\"\"\" return self . router . match ( environ ) def get_url ( self , routename , ** kargs ) : \"\"\"\"\"\" scriptname = request . environ . get ( '' , '' ) . strip ( '' ) + '' location = self . router . build ( routename , ** kargs ) . lstrip ( '' ) return urljoin ( urljoin ( '' , scriptname ) , location ) def add_route ( self , route ) : '''''' self . routes . append ( route ) self . router . add ( route . rule , route . method , route , name = route . name ) if DEBUG : route . prepare ( ) def route ( self , path = None , method = '' , callback = None , name = None , apply = None , skip = None , ** config ) : \"\"\"\"\"\" if callable ( path ) : path , callback = None , path plugins = makelist ( apply ) skiplist = makelist ( skip ) def decorator ( callback ) : if isinstance ( callback , basestring ) : callback = load ( callback ) for rule in makelist ( path ) or yieldroutes ( callback ) : for verb in makelist ( method ) : verb = verb . upper ( ) route = Route ( self , rule , verb , callback , name = name , plugins = plugins , skiplist = skiplist , ** config ) self . add_route ( route ) return callback return decorator ( callback ) if callback else decorator def get ( self , path = None , method = '' , ** options ) : \"\"\"\"\"\" return self . route ( path , method , ** options ) def post ( self , path = None , method = '' , ** options ) : \"\"\"\"\"\" return self . route ( path , method , ** options ) def put ( self , path = None , method = '' , ** options ) : \"\"\"\"\"\" return self . route ( path , method , ** options ) def delete ( self , path = None , method = '' , ** options ) : \"\"\"\"\"\" return self . route ( path , method , ** options ) def error ( self , code = ) : \"\"\"\"\"\" def wrapper ( handler ) : self . error_handler [ int ( code ) ] = handler return handler return wrapper def hook ( self , name ) : \"\"\"\"\"\" def wrapper ( func ) : self . hooks . add ( name , func ) return func return wrapper def handle ( self , path , method = '' ) : \"\"\"\"\"\" depr ( \"\" ) if isinstance ( path , dict ) : return self . _handle ( path ) return self . _handle ( { '' : path , '' : method . upper ( ) } ) def default_error_handler ( self , res ) : return tob ( template ( ERROR_PAGE_TEMPLATE , e = res ) ) def _handle ( self , environ ) : try : environ [ '' ] = self request . bind ( environ ) response . bind ( ) route , args = self . router . match ( environ ) environ [ '' ] = route environ [ '' ] = route environ [ '' ] = args return route . call ( ** args ) except HTTPResponse : return _e ( ) except RouteReset : route . reset ( ) return self . _handle ( environ ) except ( KeyboardInterrupt , SystemExit , MemoryError ) : raise except Exception : if not self . catchall : raise stacktrace = format_exc ( ) environ [ '' ] . write ( stacktrace ) return HTTPError ( , \"\" , _e ( ) , stacktrace ) def _cast ( self , out , peek = None ) : \"\"\"\"\"\" if not out : if '' not in response : response [ '' ] = return [ ] if isinstance ( out , ( tuple , list ) ) and isinstance ( out [ ] , ( bytes , unicode ) ) : out = out [ ] [ : ] . join ( out ) if isinstance ( out , unicode ) : out = out . encode ( response . charset ) if isinstance ( out , bytes ) : if '' not in response : response [ '' ] = len ( out ) return [ out ] if isinstance ( out , HTTPError ) : out . apply ( response ) out = self . error_handler . get ( out . status_code , self . default_error_handler ) ( out ) return self . _cast ( out ) if isinstance ( out , HTTPResponse ) : out . apply ( response ) return self . _cast ( out . body ) if hasattr ( out , '' ) : if '' in request . environ : return request . environ [ '' ] ( out ) elif hasattr ( out , '' ) or not hasattr ( out , '' ) : return WSGIFileWrapper ( out ) try : iout = iter ( out ) first = next ( iout ) while not first : first = next ( iout ) except StopIteration : return self . _cast ( '' ) except HTTPResponse : first = _e ( ) except ( KeyboardInterrupt , SystemExit , MemoryError ) : raise except Exception : if not self . catchall : raise first = HTTPError ( , '' , _e ( ) , format_exc ( ) ) if isinstance ( first , HTTPResponse ) : return self . _cast ( first ) elif isinstance ( first , bytes ) : new_iter = itertools . chain ( [ first ] , iout ) elif isinstance ( first , unicode ) : encoder = lambda x : x . encode ( response . charset ) new_iter = imap ( encoder , itertools . chain ( [ first ] , iout ) ) else : msg = '' % type ( first ) return self . _cast ( HTTPError ( , msg ) ) if hasattr ( out , '' ) : new_iter = _closeiter ( new_iter , out . close ) return new_iter def wsgi ( self , environ , start_response ) : \"\"\"\"\"\" try : out = self . _cast ( self . _handle ( environ ) ) if response . _status_code in ( , , , ) or environ [ '' ] == '' : if hasattr ( out , '' ) : out . close ( ) out = [ ] start_response ( response . _status_line , response . headerlist ) return out except ( KeyboardInterrupt , SystemExit , MemoryError ) : raise except Exception : if not self . catchall : raise err = '' % html_escape ( environ . get ( '' , '' ) ) if DEBUG : err += '' '' % ( html_escape ( repr ( _e ( ) ) ) , html_escape ( format_exc ( ) ) ) environ [ '' ] . write ( err ) headers = [ ( '' , '' ) ] start_response ( '' , headers , sys . exc_info ( ) ) return [ tob ( err ) ] def __call__ ( self , environ , start_response ) : '''''' return self . wsgi ( environ , start_response ) class BaseRequest ( object ) : \"\"\"\"\"\" __slots__ = ( '' ) MEMFILE_MAX = MAX_PARAMS = def __init__ ( self , environ = None ) : \"\"\"\"\"\" self . environ = { } if environ is None else environ self . environ [ '' ] = self @ DictProperty ( '' , '' , read_only = True ) def app ( self ) : '''''' raise RuntimeError ( '' ) @ DictProperty ( '' , '' , read_only = True ) def route ( self ) : \"\"\"\"\"\" raise RuntimeError ( '' ) @ DictProperty ( '' , '' , read_only = True ) def url_args ( self ) : \"\"\"\"\"\" raise RuntimeError ( '' ) @ property def path ( self ) : '''''' return '' + self . environ . get ( '' , '' ) . lstrip ( '' ) @ property def method ( self ) : '''''' return self . environ . get ( '' , '' ) . upper ( ) @ DictProperty ( '' , '' , read_only = True ) def headers ( self ) : '''''' return WSGIHeaderDict ( self . environ ) def get_header ( self , name , default = None ) : '''''' return self . headers . get ( name , default ) @ DictProperty ( '' , '' , read_only = True ) def cookies ( self ) : \"\"\"\"\"\" cookies = SimpleCookie ( self . environ . get ( '' , '' ) ) . values ( ) if len ( cookies ) > self . MAX_PARAMS : raise HTTPError ( , '' ) return FormsDict ( ( c . key , c . value ) for c in cookies ) def get_cookie ( self , key , default = None , secret = None ) : \"\"\"\"\"\" value = self . cookies . get ( key ) if secret and value : dec = cookie_decode ( value , secret ) return dec [ ] if dec and dec [ ] == key else default return value or default @ DictProperty ( '' , '' , read_only = True ) def query ( self ) : '''''' get = self . environ [ '' ] = FormsDict ( ) pairs = _parse_qsl ( self . environ . get ( '' , '' ) ) if len ( pairs ) > self . MAX_PARAMS : raise HTTPError ( , '' ) for key , value in pairs : get [ key ] = value return get @ DictProperty ( '' , '' , read_only = True ) def forms ( self ) : \"\"\"\"\"\" forms = FormsDict ( ) for name , item in self . POST . allitems ( ) : if not isinstance ( item , FileUpload ) : forms [ name ] = item return forms @ DictProperty ( '' , '' , read_only = True ) def params ( self ) : \"\"\"\"\"\" params = FormsDict ( ) for key , value in self . query . allitems ( ) : params [ key ] = value for key , value in self . forms . allitems ( ) : params [ key ] = value return params @ DictProperty ( '' , '' , read_only = True ) def files ( self ) : \"\"\"\"\"\" files = FormsDict ( ) for name , item in self . POST . allitems ( ) : if isinstance ( item , FileUpload ) : files [ name ] = item return files @ DictProperty ( '' , '' , read_only = True ) def json ( self ) : '''''' if '' in self . environ . get ( '' , '' ) : return json_loads ( self . _get_body_string ( ) ) return None @ DictProperty ( '' , '' , read_only = True ) def _body ( self ) : maxread = max ( , self . content_length ) stream = self . environ [ '' ] body = BytesIO ( ) if maxread < self . MEMFILE_MAX else TemporaryFile ( mode = '' ) while maxread > : part = stream . read ( min ( maxread , self . MEMFILE_MAX ) ) if not part : break body . write ( part ) maxread -= len ( part ) self . environ [ '' ] = body body . seek ( ) return body def _get_body_string ( self ) : '''''' clen = self . content_length if clen > self . MEMFILE_MAX : raise HTTPError ( , '' ) if clen < : clen = self . MEMFILE_MAX + data = self . body . read ( clen ) if len ( data ) > self . MEMFILE_MAX : raise HTTPError ( , '' ) return data @ property def body ( self ) : \"\"\"\"\"\" self . _body . seek ( ) return self . _body GET = query @ DictProperty ( '' , '' , read_only = True ) def POST ( self ) : \"\"\"\"\"\" post = FormsDict ( ) if not self . content_type . startswith ( '' ) : pairs = _parse_qsl ( tonat ( self . _get_body_string ( ) , '' ) ) if len ( pairs ) > self . MAX_PARAMS : raise HTTPError ( , '' ) for key , value in pairs : post [ key ] = value return post safe_env = { '' : '' } for key in ( '' , '' , '' ) : if key in self . environ : safe_env [ key ] = self . environ [ key ] args = dict ( fp = self . body , environ = safe_env , keep_blank_values = True ) if py31 : args [ '' ] = NCTextIOWrapper ( args [ '' ] , encoding = '' , newline = '' ) elif py3k : args [ '' ] = '' data = cgi . FieldStorage ( ** args ) data = data . list or [ ] if len ( data ) > self . MAX_PARAMS : raise HTTPError ( , '' ) for item in data : if item . filename : post [ item . name ] = FileUpload ( item . file , item . name , item . filename , item . headers ) else : post [ item . name ] = item . value return post @ property def COOKIES ( self ) : '''''' depr ( '' ) return self . cookies @ property def url ( self ) : \"\"\"\"\"\" return self . urlparts . geturl ( ) @ DictProperty ( '' , '' , read_only = True ) def urlparts ( self ) : '''''' env = self . environ http = env . get ( '' ) or env . get ( '' , '' ) host = env . get ( '' ) or env . get ( '' ) if not host : host = env . get ( '' , '' ) port = env . get ( '' ) if port and port != ( '' if http == '' else '' ) : host += '' + port path = urlquote ( self . fullpath ) return UrlSplitResult ( http , host , path , env . get ( '' ) , '' ) @ property def fullpath ( self ) : \"\"\"\"\"\" return urljoin ( self . script_name , self . path . lstrip ( '' ) ) @ property def query_string ( self ) : \"\"\"\"\"\" return self . environ . get ( '' , '' ) @ property def script_name ( self ) : '''''' script_name = self . environ . get ( '' , '' ) . strip ( '' ) return '' + script_name + '' if script_name else '' def path_shift ( self , shift = ) : '''''' script = self . environ . get ( '' , '' ) self [ '' ] , self [ '' ] = path_shift ( script , self . path , shift ) @ property def content_length ( self ) : '''''' return int ( self . environ . get ( '' ) or - ) @ property def content_type ( self ) : '''''' return self . environ . get ( '' , '' ) . lower ( ) @ property def is_xhr ( self ) : '''''' requested_with = self . environ . get ( '' , '' ) return requested_with . lower ( ) == '' @ property def is_ajax ( self ) : '''''' return self . is_xhr @ property def auth ( self ) : \"\"\"\"\"\" basic = parse_auth ( self . environ . get ( '' , '' ) ) if basic : return basic ruser = self . environ . get ( '' ) if ruser : return ( ruser , None ) return None @ property def remote_route ( self ) : \"\"\"\"\"\" proxy = self . environ . get ( '' ) if proxy : return [ ip . strip ( ) for ip in proxy . split ( '' ) ] remote = self . environ . get ( '' ) return [ remote ] if remote else [ ] @ property def remote_addr ( self ) : \"\"\"\"\"\" route = self . remote_route return route [ ] if route else None def copy ( self ) : \"\"\"\"\"\" return Request ( self . environ . copy ( ) ) def get ( self , value , default = None ) : return self . environ . get ( value , default ) def __getitem__ ( self , key ) : return self . environ [ key ] def __delitem__ ( self , key ) : self [ key ] = \"\" ; del ( self . environ [ key ] ) def __iter__ ( self ) : return iter ( self . environ ) def __len__ ( self ) : return len ( self . environ ) def keys ( self ) : return self . environ . keys ( ) def __setitem__ ( self , key , value ) : \"\"\"\"\"\" if self . environ . get ( '' ) : raise KeyError ( '' ) self . environ [ key ] = value todelete = ( ) if key == '' : todelete = ( '' , '' , '' , '' , '' , '' ) elif key == '' : todelete = ( '' , '' ) elif key . startswith ( '' ) : todelete = ( '' , '' ) for key in todelete : self . environ . pop ( '' + key , None ) def __repr__ ( self ) : return '' % ( self . __class__ . __name__ , self . method , self . url ) def __getattr__ ( self , name ) : '''''' try : var = self . environ [ '' % name ] return var . __get__ ( self ) if hasattr ( var , '' ) else var except KeyError : raise AttributeError ( '' % name ) def __setattr__ ( self , name , value ) : if name == '' : return object . __setattr__ ( self , name , value ) self . environ [ '' % name ] = value def _hkey ( s ) : return s . title ( ) . replace ( '' , '' ) class HeaderProperty ( object ) : def __init__ ( self , name , reader = None , writer = str , default = '' ) : self . name , self . default = name , default self . reader , self . writer = reader , writer self . __doc__ = '' % name . title ( ) def __get__ ( self , obj , cls ) : if obj is None : return self value = obj . headers . get ( self . name , self . default ) return self . reader ( value ) if self . reader else value def __set__ ( self , obj , value ) : obj . headers [ self . name ] = self . writer ( value ) def __delete__ ( self , obj ) : del obj . headers [ self . name ] class BaseResponse ( object ) : \"\"\"\"\"\" default_status = default_content_type = '' bad_headers = { : set ( ( '' , ) ) , : set ( ( '' , '' , '' , '' , '' , '' , '' , '' ) ) } def __init__ ( self , body = '' , status = None , headers = None , ** more_headers ) : self . _cookies = None self . _headers = { } self . body = body self . status = status or self . default_status if headers : if isinstance ( headers , dict ) : headers = headers . items ( ) for name , value in headers : self . add_header ( name , value ) if more_headers : for name , value in more_headers . items ( ) : self . add_header ( name , value ) def copy ( self ) : '''''' copy = Response ( ) copy . status = self . status copy . _headers = dict ( ( k , v [ : ] ) for ( k , v ) in self . _headers . items ( ) ) return copy def __iter__ ( self ) : return iter ( self . body ) def close ( self ) : if hasattr ( self . body , '' ) : self . body . close ( ) @ property def status_line ( self ) : '''''' return self . _status_line @ property def status_code ( self ) : '''''' return self . _status_code def _set_status ( self , status ) : if isinstance ( status , int ) : code , status = status , _HTTP_STATUS_LINES . get ( status ) elif '' in status : status = status . strip ( ) code = int ( status . split ( ) [ ] ) else : raise ValueError ( '' ) if not <= code <= : raise ValueError ( '' ) self . _status_code = code self . _status_line = str ( status or ( '' % code ) ) def _get_status ( self ) : return self . _status_line status = property ( _get_status , _set_status , None , '''''' ) del _get_status , _set_status @ property def headers ( self ) : '''''' hdict = HeaderDict ( ) hdict . dict = self . _headers return hdict def __contains__ ( self , name ) : return _hkey ( name ) in self . _headers def __delitem__ ( self , name ) : del self . _headers [ _hkey ( name ) ] def __getitem__ ( self , name ) : return self . _headers [ _hkey ( name ) ] [ - ] def __setitem__ ( self , name , value ) : self . _headers [ _hkey ( name ) ] = [ str ( value ) ] def get_header ( self , name , default = None ) : '''''' return self . _headers . get ( _hkey ( name ) , [ default ] ) [ - ] def set_header ( self , name , value ) : '''''' self . _headers [ _hkey ( name ) ] = [ str ( value ) ] def add_header ( self , name , value ) : '''''' self . _headers . setdefault ( _hkey ( name ) , [ ] ) . append ( str ( value ) ) def iter_headers ( self ) : '''''' return self . headerlist def wsgiheader ( self ) : depr ( '' ) return self . headerlist @ property def headerlist ( self ) : '''''' out = [ ] headers = list ( self . _headers . items ( ) ) if '' not in self . _headers : headers . append ( ( '' , [ self . default_content_type ] ) ) if self . _status_code in self . bad_headers : bad_headers = self . bad_headers [ self . _status_code ] headers = [ h for h in headers if h [ ] not in bad_headers ] out += [ ( name , val ) for name , vals in headers for val in vals ] if self . _cookies : for c in self . _cookies . values ( ) : out . append ( ( '' , c . OutputString ( ) ) ) return out content_type = HeaderProperty ( '' ) content_length = HeaderProperty ( '' , reader = int ) @ property def charset ( self , default = '' ) : \"\"\"\"\"\" if '' in self . content_type : return self . content_type . split ( '' ) [ - ] . split ( '' ) [ ] . strip ( ) return default @ property def COOKIES ( self ) : \"\"\"\"\"\" depr ( '' ) if not self . _cookies : self . _cookies = SimpleCookie ( ) return self . _cookies def set_cookie ( self , name , value , secret = None , ** options ) : '''''' if not self . _cookies : self . _cookies = SimpleCookie ( ) if secret : value = touni ( cookie_encode ( ( name , value ) , secret ) ) elif not isinstance ( value , basestring ) : raise TypeError ( '' ) if len ( value ) > : raise ValueError ( '' ) self . _cookies [ name ] = value for key , value in options . items ( ) : if key == '' : if isinstance ( value , timedelta ) : value = value . seconds + value . days * * if key == '' : if isinstance ( value , ( datedate , datetime ) ) : value = value . timetuple ( ) elif isinstance ( value , ( int , float ) ) : value = time . gmtime ( value ) value = time . strftime ( \"\" , value ) self . _cookies [ name ] [ key . replace ( '' , '' ) ] = value def delete_cookie ( self , key , ** kwargs ) : '''''' kwargs [ '' ] = - kwargs [ '' ] = self . set_cookie ( key , '' , ** kwargs ) def __repr__ ( self ) : out = '' for name , value in self . headerlist : out += '' % ( name . title ( ) , value . strip ( ) ) return out _lctx = threading . local ( ) def local_property ( name ) : def fget ( self ) : try : return getattr ( _lctx , name ) except AttributeError : raise RuntimeError ( \"\" ) def fset ( self , value ) : setattr ( _lctx , name , value ) def fdel ( self ) : delattr ( _lctx , name ) return property ( fget , fset , fdel , '' % name ) class LocalRequest ( BaseRequest ) : '''''' bind = BaseRequest . __init__ environ = local_property ( '' ) class LocalResponse ( BaseResponse ) : '''''' bind = BaseResponse . __init__ _status_line = local_property ( '' ) _status_code = local_property ( '' ) _cookies = local_property ( '' ) _headers = local_property ( '' ) body = local_property ( '' ) Request = BaseRequest Response = BaseResponse class HTTPResponse ( Response , BottleException ) : def __init__ ( self , body = '' , status = None , headers = None , header = None , ** more_headers ) : if header or '' in more_headers : depr ( '' ) if header : more_headers . update ( header ) if '' in more_headers : body = more_headers . pop ( '' ) super ( HTTPResponse , self ) . __init__ ( body , status , headers , ** more_headers ) def apply ( self , response ) : response . _status_code = self . _status_code response . _status_line = self . _status_line response . _headers = self . _headers response . _cookies = self . _cookies response . body = self . body def _output ( self , value = None ) : depr ( '' ) if value is None : return self . body self . body = value output = property ( _output , _output , doc = '' ) class HTTPError ( HTTPResponse ) : default_status = def __init__ ( self , status = None , body = None , exception = None , traceback = None , ** options ) : self . exception = exception self . traceback = traceback super ( HTTPError , self ) . __init__ ( body , status , ** options ) class PluginError ( BottleException ) : pass class JSONPlugin ( object ) : name = '' api = def __init__ ( self , json_dumps = json_dumps ) : self . json_dumps = json_dumps def apply ( self , callback , route ) : dumps = self . json_dumps if not dumps : return callback def wrapper ( * a , ** ka ) : try : rv = callback ( * a , ** ka ) except HTTPError : rv = _e ( ) if isinstance ( rv , dict ) : json_response = dumps ( rv ) response . content_type = '' return json_response elif isinstance ( rv , HTTPResponse ) and isinstance ( rv . body , dict ) : rv . body = dumps ( rv . body ) rv . content_type = '' return rv return wrapper class HooksPlugin ( object ) : name = '' api = _names = '' , '' , '' def __init__ ( self ) : self . hooks = dict ( ( name , [ ] ) for name in self . _names ) self . app = None def _empty ( self ) : return not ( self . hooks [ '' ] or self . hooks [ '' ] ) def setup ( self , app ) : self . app = app def add ( self , name , func ) : '''''' was_empty = self . _empty ( ) self . hooks . setdefault ( name , [ ] ) . append ( func ) if self . app and was_empty and not self . _empty ( ) : self . app . reset ( ) def remove ( self , name , func ) : '''''' was_empty = self . _empty ( ) if name in self . hooks and func in self . hooks [ name ] : self . hooks [ name ] . remove ( func ) if self . app and not was_empty and self . _empty ( ) : self . app . reset ( ) def trigger ( self , name , * a , ** ka ) : '''''' hooks = self . hooks [ name ] if ka . pop ( '' , False ) : hooks = hooks [ : : - ] return [ hook ( * a , ** ka ) for hook in hooks ] def apply ( self , callback , route ) : if self . _empty ( ) : return callback def wrapper ( * a , ** ka ) : self . trigger ( '' ) rv = callback ( * a , ** ka ) self . trigger ( '' , reversed = True ) return rv return wrapper class TemplatePlugin ( object ) : '''''' name = '' api = def apply ( self , callback , route ) : conf = route . config . get ( '' ) if isinstance ( conf , ( tuple , list ) ) and len ( conf ) == : return view ( conf [ ] , ** conf [ ] ) ( callback ) elif isinstance ( conf , str ) : return view ( conf ) ( callback ) else : return callback class _ImportRedirect ( object ) : def __init__ ( self , name , impmask ) : '''''' self . name = name self . impmask = impmask self . module = sys . modules . setdefault ( name , imp . new_module ( name ) ) self . module . __dict__ . update ( { '' : __file__ , '' : [ ] , '' : [ ] , '' : self } ) sys . meta_path . append ( self ) def find_module ( self , fullname , path = None ) : if '' not in fullname : return packname , modname = fullname . rsplit ( '' , ) if packname != self . name : return return self def load_module ( self , fullname ) : if fullname in sys . modules : return sys . modules [ fullname ] packname , modname = fullname . rsplit ( '' , ) realname = self . impmask % modname __import__ ( realname ) module = sys . modules [ fullname ] = sys . modules [ realname ] setattr ( self . module , modname , module ) module . __loader__ = self return module class MultiDict ( DictMixin ) : \"\"\"\"\"\" def __init__ ( self , * a , ** k ) : self . dict = dict ( ( k , [ v ] ) for ( k , v ) in dict ( * a , ** k ) . items ( ) ) def __len__ ( self ) : return len ( self . dict ) def __iter__ ( self ) : return iter ( self . dict ) def __contains__ ( self , key ) : return key in self . dict def __delitem__ ( self , key ) : del self . dict [ key ] def __getitem__ ( self , key ) : return self . dict [ key ] [ - ] def __setitem__ ( self , key , value ) : self . append ( key , value ) def keys ( self ) : return self . dict . keys ( ) if py3k : def values ( self ) : return ( v [ - ] for v in self . dict . values ( ) ) def items ( self ) : return ( ( k , v [ - ] ) for k , v in self . dict . items ( ) ) def allitems ( self ) : return ( ( k , v ) for k , vl in self . dict . items ( ) for v in vl ) iterkeys = keys itervalues = values iteritems = items iterallitems = allitems else : def values ( self ) : return [ v [ - ] for v in self . dict . values ( ) ] def items ( self ) : return [ ( k , v [ - ] ) for k , v in self . dict . items ( ) ] ", "answer": "def iterkeys ( self ) : return self . dict . iterkeys ( )"}, {"prompt": " class ListO ( object ) : \"\"\"\"\"\" def __init__ ( self , buffer = None ) : self . _buffer = buffer if self . _buffer is None : self . _buffer = [ ] def isatty ( self ) : return False def close ( self ) : pass def flush ( self ) : pass def seek ( self , n , mode = ) : pass def readline ( self ) : pass def reset ( self ) : pass ", "answer": "def write ( self , x ) :"}, {"prompt": " from flask . ext . wtf import Form from wtforms import StringField , PasswordField , BooleanField , SubmitField from wtforms . validators import Required , Length ", "answer": "class LoginForm ( Form ) :"}, {"prompt": " import base64 import logging import netaddr import six from ryu . lib import hub LOG = logging . getLogger ( __name__ ) DEFAULT_TIMEOUT = OUTPUT = '' COPY_TTL_OUT = '' COPY_TTL_IN = '' SET_MPLS_TTL = '' DEC_MPLS_TTL = '' PUSH_VLAN = '' POP_VLAN = '' PUSH_MPLS = '' POP_MPLS = '' SET_QUEUE = '' GROUP = '' SET_NW_TTL = '' DEC_NW_TTL = '' SET_FIELD = '' PUSH_PBB = '' POP_PBB = '' EXPERIMENTER = '' def get_logger ( logger = None ) : if logger is not None : return logger return LOG def match_vid_to_str ( value , mask , ofpvid_present ) : if mask is not None : return '' % ( value , mask ) if value & ofpvid_present : return str ( value & ~ ofpvid_present ) return '' % value def to_action ( dic , ofp , parser , action_type , util ) : actions = { COPY_TTL_OUT : parser . OFPActionCopyTtlOut , COPY_TTL_IN : parser . OFPActionCopyTtlIn , DEC_MPLS_TTL : parser . OFPActionDecMplsTtl , POP_VLAN : parser . OFPActionPopVlan , DEC_NW_TTL : parser . OFPActionDecNwTtl , POP_PBB : parser . OFPActionPopPbb } need_ethertype = { PUSH_VLAN : parser . OFPActionPushVlan , PUSH_MPLS : parser . OFPActionPushMpls , POP_MPLS : parser . OFPActionPopMpls , PUSH_PBB : parser . OFPActionPushPbb } if action_type in actions : return actions [ action_type ] ( ) elif action_type in need_ethertype : ethertype = int ( dic . get ( '' ) ) return need_ethertype [ action_type ] ( ethertype ) elif action_type == OUTPUT : out_port = util . ofp_port_from_user ( dic . get ( '' , ofp . OFPP_ANY ) ) max_len = util . ofp_cml_from_user ( dic . get ( '' , ofp . OFPCML_MAX ) ) return parser . OFPActionOutput ( out_port , max_len ) elif action_type == SET_MPLS_TTL : mpls_ttl = int ( dic . get ( '' ) ) return parser . OFPActionSetMplsTtl ( mpls_ttl ) elif action_type == SET_QUEUE : queue_id = util . ofp_queue_from_user ( dic . get ( '' ) ) return parser . OFPActionSetQueue ( queue_id ) elif action_type == GROUP : group_id = util . ofp_group_from_user ( dic . get ( '' ) ) return parser . OFPActionGroup ( group_id ) elif action_type == SET_NW_TTL : nw_ttl = int ( dic . get ( '' ) ) return parser . OFPActionSetNwTtl ( nw_ttl ) elif action_type == SET_FIELD : field = dic . get ( '' ) value = dic . get ( '' ) return parser . OFPActionSetField ( ** { field : value } ) elif action_type == EXPERIMENTER : experimenter = int ( dic . get ( '' ) ) data_type = dic . get ( '' , '' ) if data_type not in ( '' , '' ) : LOG . error ( '' , data_type ) return None data = dic . get ( '' , '' ) if data_type == '' : data = base64 . b64decode ( data ) return parser . OFPActionExperimenterUnknown ( experimenter , data ) return None def to_match_eth ( value ) : if '' in value : value = value . split ( '' ) return value [ ] , value [ ] return value def to_match_ip ( value ) : if '' in value : ( ip_addr , ip_mask ) = value . split ( '' ) if ip_mask . isdigit ( ) : ip = netaddr . ip . IPNetwork ( value ) ip_addr = str ( ip . ip ) ip_mask = str ( ip . netmask ) return ip_addr , ip_mask return value def to_match_vid ( value , ofpvid_present ) : if isinstance ( value , six . integer_types ) : return value | ofpvid_present else : if '' in value : val = value . split ( '' ) return int ( val [ ] , ) , int ( val [ ] , ) else : if value . isdigit ( ) : return int ( value , ) | ofpvid_present return int ( value , ) def to_match_masked_int ( value ) : if isinstance ( value , str ) and '' in value : value = value . split ( '' ) return ( str_to_int ( value [ ] ) , str_to_int ( value [ ] ) ) return str_to_int ( value ) def send_experimenter ( dp , exp , logger = None ) : experimenter = exp . get ( '' , ) exp_type = exp . get ( '' , ) data_type = exp . get ( '' , '' ) if data_type not in ( '' , '' ) : LOG . error ( '' , data_type ) data = exp . get ( '' , '' ) if data_type == '' : data = base64 . b64decode ( data ) expmsg = dp . ofproto_parser . OFPExperimenter ( dp , experimenter , exp_type , data ) send_msg ( dp , expmsg , logger ) def send_msg ( dp , msg , logger = None ) : if msg . xid is None : dp . set_xid ( msg ) get_logger ( logger ) . debug ( '' , msg . xid , msg ) dp . send_msg ( msg ) def send_stats_request ( dp , stats , waiters , msgs , logger = None ) : dp . set_xid ( stats ) waiters_per_dp = waiters . setdefault ( dp . id , { } ) lock = hub . Event ( ) previous_msg_len = len ( msgs ) waiters_per_dp [ stats . xid ] = ( lock , msgs ) send_msg ( dp , stats , logger ) lock . wait ( timeout = DEFAULT_TIMEOUT ) current_msg_len = len ( msgs ) while current_msg_len > previous_msg_len : previous_msg_len = current_msg_len lock . wait ( timeout = DEFAULT_TIMEOUT ) current_msg_len = len ( msgs ) if not lock . is_set ( ) : del waiters_per_dp [ stats . xid ] def str_to_int ( str_num ) : return int ( str ( str_num ) , ) class OFCtlUtil ( object ) : def __init__ ( self , ofproto ) : self . ofproto = ofproto self . deprecated_value = [ '' , '' , '' ] def _reserved_num_from_user ( self , num , prefix ) : if isinstance ( num , int ) : return num ", "answer": "else :"}, {"prompt": " import binascii import logging import io import struct from pycoin . block import Block , BlockHeader from pycoin . encoding import double_sha256 from pycoin . serialize import b2h_rev , bitcoin_streamer from pycoin . tx . Tx import Tx from pycoinnet . InvItem import InvItem from pycoinnet . PeerAddress import PeerAddress MESSAGE_STRUCTURES = { '' : ( \"\" \"\" ) , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : ( \"\" ) , '' : \"\" , } def _make_parser ( the_struct = '' ) : def f ( message_stream ) : struct_items = [ s . split ( \"\" ) for s in the_struct . split ( ) ] names = [ s [ ] for s in struct_items ] types = '' . join ( s [ ] for s in struct_items ) return bitcoin_streamer . parse_as_dict ( names , types , message_stream ) return f def _message_parsers ( ) : return dict ( ( k , _make_parser ( v ) ) for k , v in MESSAGE_STRUCTURES . items ( ) ) def fixup_merkleblock ( d , f ) : def recurse ( level_widths , level_index , node_index , hashes , flags , flag_index , tx_acc ) : idx , r = divmod ( flag_index , ) mask = ( << r ) flag_index += if flags [ idx ] & mask == : h = hashes . pop ( ) return h , flag_index if level_index == len ( level_widths ) - : h = hashes . pop ( ) tx_acc . append ( h ) return h , flag_index left_hash , flag_index = recurse ( level_widths , level_index + , node_index * , hashes , flags , flag_index , tx_acc ) if node_index * + < level_widths [ level_index + ] : right_hash , flag_index = recurse ( level_widths , level_index + , node_index * + , hashes , flags , flag_index , tx_acc ) if left_hash == right_hash : raise ValueError ( \"\" % node_index ) else : right_hash = left_hash ", "answer": "return double_sha256 ( left_hash + right_hash ) , flag_index"}, {"prompt": " import collections import uuid import mock from neutron . agent . common import ovs_lib from neutron . agent . linux import ip_lib from neutron . tests import base as tests_base from neutron . tests . common import net_helpers from neutron . tests . functional . agent . linux import base class OVSBridgeTestBase ( base . BaseOVSLinuxTestCase ) : def setUp ( self ) : super ( OVSBridgeTestBase , self ) . setUp ( ) self . ovs = ovs_lib . BaseOVS ( ) self . br = self . useFixture ( net_helpers . OVSBridgeFixture ( ) ) . bridge def create_ovs_port ( self , * interface_attrs ) : attrs = collections . OrderedDict ( interface_attrs ) attrs . setdefault ( '' , '' ) port_name = tests_base . get_rand_device_name ( net_helpers . PORT_PREFIX ) return ( port_name , self . br . add_port ( port_name , * attrs . items ( ) ) ) def create_ovs_vif_port ( self , iface_id = None , mac = None , iface_field = '' ) : if iface_id is None : iface_id = base . get_rand_name ( ) if mac is None : mac = base . get_rand_name ( ) attrs = ( '' , { iface_field : iface_id , '' : mac } ) port_name , ofport = self . create_ovs_port ( attrs ) return ovs_lib . VifPort ( port_name , ofport , iface_id , mac , self . br ) class OVSBridgeTestCase ( OVSBridgeTestBase ) : def test_port_lifecycle ( self ) : ( port_name , ofport ) = self . create_ovs_port ( ( '' , '' ) ) self . assertTrue ( int ( ofport ) ) self . assertTrue ( int ( self . br . get_port_ofport ( port_name ) ) ) self . assertTrue ( self . br . port_exists ( port_name ) ) self . assertEqual ( self . br . br_name , self . br . get_bridge_for_iface ( port_name ) ) self . br . delete_port ( port_name ) self . assertFalse ( self . br . port_exists ( port_name ) ) def test_duplicate_port_may_exist_false ( self ) : port_name , ofport = self . create_ovs_port ( ( '' , '' ) ) cmd = self . br . ovsdb . add_port ( self . br . br_name , port_name , may_exist = False ) self . assertRaises ( RuntimeError , cmd . execute , check_error = True ) def test_delete_port_if_exists_false ( self ) : cmd = self . br . ovsdb . del_port ( '' , if_exists = False ) self . assertRaises ( RuntimeError , cmd . execute , check_error = True ) def test_replace_port ( self ) : port_name = tests_base . get_rand_device_name ( net_helpers . PORT_PREFIX ) self . br . replace_port ( port_name , ( '' , '' ) ) self . assertTrue ( self . br . port_exists ( port_name ) ) self . assertEqual ( '' , self . br . db_get_val ( '' , port_name , '' ) ) self . br . replace_port ( port_name , ( '' , '' ) , ( '' , { '' : '' } ) ) self . assertTrue ( self . br . port_exists ( port_name ) ) self . assertEqual ( '' , self . br . db_get_val ( '' , port_name , '' ) [ '' ] ) def test_attribute_lifecycle ( self ) : ( port_name , ofport ) = self . create_ovs_port ( ) tag = self . ovs . set_db_attribute ( '' , port_name , '' , tag ) self . assertEqual ( tag , self . ovs . db_get_val ( '' , port_name , '' ) ) self . assertEqual ( tag , self . br . get_port_tag_dict ( ) [ port_name ] ) self . ovs . clear_db_attribute ( '' , port_name , '' ) self . assertEqual ( [ ] , self . ovs . db_get_val ( '' , port_name , '' ) ) self . assertEqual ( [ ] , self . br . get_port_tag_dict ( ) [ port_name ] ) def test_get_bridge_external_bridge_id ( self ) : self . ovs . set_db_attribute ( '' , self . br . br_name , '' , { '' : self . br . br_name } ) self . assertEqual ( self . br . br_name , self . ovs . get_bridge_external_bridge_id ( self . br . br_name ) ) def test_controller_lifecycle ( self ) : controllers = { '' , '' } self . br . set_controller ( controllers ) self . assertSetEqual ( controllers , set ( self . br . get_controller ( ) ) ) self . br . del_controller ( ) self . assertEqual ( [ ] , self . br . get_controller ( ) ) def test_non_index_queries ( self ) : controllers = [ '' ] self . br . set_controller ( controllers ) cmd = self . br . ovsdb . db_set ( '' , self . br . br_name , ( '' , '' ) ) cmd . execute ( check_error = True ) self . assertEqual ( '' , self . br . db_get_val ( '' , self . br . br_name , '' ) ) def test_set_fail_mode_secure ( self ) : self . br . set_secure_mode ( ) self . _assert_br_fail_mode ( ovs_lib . FAILMODE_SECURE ) def test_set_fail_mode_standalone ( self ) : self . br . set_standalone_mode ( ) self . _assert_br_fail_mode ( ovs_lib . FAILMODE_STANDALONE ) def _assert_br_fail_mode ( self , fail_mode ) : self . assertEqual ( self . br . db_get_val ( '' , self . br . br_name , '' ) , fail_mode ) def test_set_protocols ( self ) : self . br . set_protocols ( '' ) self . assertEqual ( self . br . db_get_val ( '' , self . br . br_name , '' ) , \"\" ) def test_get_datapath_id ( self ) : brdev = ip_lib . IPDevice ( self . br . br_name ) dpid = brdev . link . attributes [ '' ] . replace ( '' , '' ) self . br . set_db_attribute ( '' , self . br . br_name , '' , dpid ) self . assertIn ( dpid , self . br . get_datapath_id ( ) ) def test_add_tunnel_port ( self ) : attrs = { '' : '' , '' : '' , } port_name = tests_base . get_rand_device_name ( net_helpers . PORT_PREFIX ) self . br . add_tunnel_port ( port_name , attrs [ '' ] , attrs [ '' ] ) self . assertEqual ( self . ovs . db_get_val ( '' , port_name , '' ) , '' ) options = self . ovs . db_get_val ( '' , port_name , '' ) for attr , val in attrs . items ( ) : self . assertEqual ( val , options [ attr ] ) def test_add_patch_port ( self ) : local = tests_base . get_rand_device_name ( net_helpers . PORT_PREFIX ) peer = '' self . br . add_patch_port ( local , peer ) self . assertEqual ( self . ovs . db_get_val ( '' , local , '' ) , '' ) options = self . ovs . db_get_val ( '' , local , '' ) self . assertEqual ( peer , options [ '' ] ) def test_get_port_name_list ( self ) : ports = { self . create_ovs_port ( ) [ ] for i in range ( ) } self . assertSetEqual ( ports , set ( self . br . get_port_name_list ( ) ) ) def test_get_iface_name_list ( self ) : ifaces = { self . create_ovs_port ( ) [ ] for i in range ( ) } self . assertSetEqual ( ifaces , set ( self . br . get_iface_name_list ( ) ) ) def test_get_port_stats ( self ) : ( port_name , ofport ) = self . create_ovs_port ( ) stats = set ( self . br . get_port_stats ( port_name ) . keys ( ) ) self . assertTrue ( set ( [ '' , '' ] ) . issubset ( stats ) ) def test_get_vif_ports ( self ) : for i in range ( ) : self . create_ovs_port ( ) vif_ports = [ self . create_ovs_vif_port ( ) for i in range ( ) ] ports = self . br . get_vif_ports ( ) self . assertEqual ( , len ( ports ) ) self . assertTrue ( all ( [ isinstance ( x , ovs_lib . VifPort ) for x in ports ] ) ) self . assertEqual ( sorted ( [ x . port_name for x in vif_ports ] ) , sorted ( [ x . port_name for x in ports ] ) ) def test_get_vif_ports_with_bond ( self ) : for i in range ( ) : self . create_ovs_port ( ) vif_ports = [ self . create_ovs_vif_port ( ) for i in range ( ) ] orig = self . br . get_port_name_list new_port_name_list = lambda : orig ( ) + [ '' ] mock . patch . object ( self . br , '' , new = new_port_name_list ) . start ( ) ports = self . br . get_vif_ports ( ) self . assertEqual ( , len ( ports ) ) self . assertTrue ( all ( [ isinstance ( x , ovs_lib . VifPort ) for x in ports ] ) ) self . assertEqual ( sorted ( [ x . port_name for x in vif_ports ] ) , sorted ( [ x . port_name for x in ports ] ) ) def test_get_vif_port_set ( self ) : for i in range ( ) : self . create_ovs_port ( ) vif_ports = [ self . create_ovs_vif_port ( ) for i in range ( ) ] ports = self . br . get_vif_port_set ( ) expected = set ( [ x . vif_id for x in vif_ports ] ) self . assertEqual ( expected , ports ) def test_get_vif_port_set_with_missing_port ( self ) : self . create_ovs_port ( ) vif_ports = [ self . create_ovs_vif_port ( ) ] ", "answer": "orig = self . br . get_port_name_list"}, {"prompt": " from django . conf . urls . defaults import patterns , url from django . utils . translation import ugettext as _ urlpatterns = patterns ( '' , url ( r'' , '' , name = '' ) , url ( r'' % _ ( '' ) , '' , name = '' ) , ", "answer": "url ( r'' % _ ( '' ) , '' , name = '' ) ,"}, {"prompt": " import AutoCopyright . constants import datetime import re import sublime import os from AutoCopyright . CopyrightCommand import CopyrightCommand from AutoCopyright . Exception import MissingOwnerException class UpdateCopyrightCommand ( CopyrightCommand ) : \"\"\"\"\"\" def __init__ ( self , view ) : \"\"\"\"\"\" CopyrightCommand . __init__ ( self , view ) self . patterns = None self . matched_pattern = None self . edit = None def run ( self , edit ) : \"\"\"\"\"\" try : self . edit = edit self . __update_copyright ( ) except MissingOwnerException : self . handle_missing_owner_exception ( ) def __find_copyright ( self ) : \"\"\"\"\"\" patterns = self . get_patterns ( ) for pattern in patterns : region = self . view . find ( pattern , ) if region is not None and self . __is_in_comment ( region ) : ", "answer": "self . matched_pattern = pattern"}, {"prompt": " from __future__ import absolute_import , unicode_literals from django . core . exceptions import PermissionDenied from django . utils . translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework . exceptions import ValidationError from rest_framework . reverse import reverse from acls . models import AccessControlList ", "answer": "from permissions import Permission"}, {"prompt": " '''''' from __future__ import unicode_literals from . . model . hashes import Hashes from . . one_drive_object_base import OneDriveObjectBase class File ( OneDriveObjectBase ) : def __init__ ( self , prop_dict = { } ) : self . _prop_dict = prop_dict @ property def hashes ( self ) : \"\"\"\"\"\" if \"\" in self . _prop_dict : if isinstance ( self . _prop_dict [ \"\" ] , OneDriveObjectBase ) : return self . _prop_dict [ \"\" ] else : self . _prop_dict [ \"\" ] = Hashes ( self . _prop_dict [ \"\" ] ) return self . _prop_dict [ \"\" ] return None @ hashes . setter def hashes ( self , val ) : self . _prop_dict [ \"\" ] = val @ property def mime_type ( self ) : \"\"\"\"\"\" if \"\" in self . _prop_dict : ", "answer": "return self . _prop_dict [ \"\" ]"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " import glob import os import shutil import zipfile import pytest from pyleus import __version__ from pyleus import exception from pyleus . cli import build from pyleus . testing import mock class TestBuild ( object ) : @ mock . patch . object ( os . path , '' , autospec = True ) def test__open_jar_jarfile_not_found ( self , mock_exists ) : mock_exists . return_value = False with pytest . raises ( exception . JarError ) : build . _open_jar ( \"\" ) mock_exists . assert_called_once_with ( \"\" ) @ mock . patch . object ( os . path , '' , autospec = True ) @ mock . patch . object ( zipfile , '' , autospec = True ) def test__open_jar_not_jarfile ( self , mock_is_zipfile , mock_exists ) : mock_exists . return_value = True mock_is_zipfile . return_value = False with pytest . raises ( exception . JarError ) : build . _open_jar ( \"\" ) mock_is_zipfile . assert_called_once_with ( \"\" ) @ mock . patch . object ( os , '' , autospec = True ) def test__zip_dir ( self , mock_walk ) : mock_arc = mock . Mock ( autospec = True ) mock_walk . return_value = [ ( \"\" , [ \"\" ] , [ \"\" ] ) , ( \"\" , [ ] , [ \"\" ] ) ] build . _zip_dir ( \"\" , mock_arc ) mock_walk . assert_any_call ( \"\" ) expected = [ mock . call ( \"\" , \"\" , zipfile . ZIP_DEFLATED ) , mock . call ( \"\" , \"\" , zipfile . ZIP_DEFLATED ) , ] mock_arc . write . assert_has_calls ( expected ) @ mock . patch . object ( zipfile , '' , autospec = True ) @ mock . patch . object ( build , '' , autospec = True ) def test__pack_jar ( self , mock_zip_dir , mock_zipfile ) : build . _pack_jar ( \"\" , \"\" ) mock_zipfile . assert_called_once_with ( \"\" , \"\" ) mock_zip_dir . assert_called_once_with ( \"\" , mock_zipfile . return_value ) @ mock . patch . object ( os . path , '' , autospec = True ) def test__validate_venv_dir_contains_venv ( self , mock_exists ) : mock_exists . return_value = True with pytest . raises ( exception . InvalidTopologyError ) : build . _validate_venv ( \"\" , \"\" ) mock_exists . assert_called_once_with ( \"\" ) @ mock . patch . object ( build , '' , autospec = True ) @ mock . patch . object ( build , '' , autospec = True ) def test__set_up_virtualenv_with_requirements ( self , mock_venv , mock_remove_base_jar ) : venv = mock_venv . return_value build . _set_up_virtualenv ( venv_name = \"\" , tmp_dir = \"\" , req = \"\" , include_packages = [ \"\" , \"\" ] , system_site_packages = True , pypi_index_url = \"\" , python_interpreter = \"\" , verbose = False ) expected_install = [ mock . call ( \"\" . format ( __version__ ) ) , mock . call ( \"\" ) , mock . call ( \"\" ) ] venv . install_package . assert_has_calls ( expected_install ) venv . install_from_requirements . assert_called_once_with ( \"\" ) mock_remove_base_jar . assert_called_once_with ( venv ) @ mock . patch . object ( build , '' , autospec = True ) @ mock . patch . object ( build , '' , autospec = True ) def test__set_up_virtualenv_without_requirements ( self , mock_venv , mock_remove_base_jar ) : venv = mock_venv . return_value build . _set_up_virtualenv ( venv_name = \"\" , tmp_dir = \"\" , req = None , include_packages = [ \"\" , \"\" ] , system_site_packages = True , pypi_index_url = \"\" , python_interpreter = \"\" , verbose = False ) expected_install = [ mock . call ( \"\" . format ( __version__ ) ) , mock . call ( \"\" ) , mock . call ( \"\" ) ] venv . install_package . assert_has_calls ( expected_install ) assert venv . install_from_requirements . call_count == mock_remove_base_jar . assert_called_once_with ( venv ) @ mock . patch . object ( glob , '' , autospec = True ) def test__content_to_copy ( self , mock_glob ) : mock_glob . return_value = [ \"\" , \"\" , \"\" , \"\" ] ", "answer": "content = build . _content_to_copy ( \"\" , [ \"\" ,"}, {"prompt": " from falcon . routing . compiled import CompiledRouter from falcon . routing . util import create_http_method_map from falcon . routing . util import compile_uri_template ", "answer": "DefaultRouter = CompiledRouter "}, {"prompt": " \"\"\"\"\"\" import pygame import pygame . locals from mpf . media_controller . core . display import DisplayElement class Shape ( DisplayElement ) : \"\"\"\"\"\" def __init__ ( self , slide , machine , shape , x = None , y = None , h_pos = None , v_pos = None , layer = , ** kwargs ) : super ( Shape , self ) . __init__ ( slide , x , y , h_pos , v_pos , layer ) self . slide = slide self . shape = shape . lower ( ) if '' in kwargs : self . name = kwargs [ '' ] else : self . name = '' self . adjust_colors ( ** kwargs ) if '' not in kwargs : kwargs [ '' ] = if shape == '' : self . box ( width = kwargs [ '' ] , height = kwargs [ '' ] , thickness = kwargs [ '' ] ) elif shape == '' : self . line ( end_x = kwargs [ '' ] , end_y = kwargs [ '' ] , thickness = kwargs [ '' ] ) else : raise Exception ( \"\" + shape ) self . element_surface . set_colorkey ( ( , , ) ) self . layer = layer self . set_position ( x , y , h_pos , v_pos ) def box ( self , width , height , thickness ) : self . create_element_surface ( width , height ) pygame . draw . rect ( self . element_surface , self . adjusted_color , ( , , width , height ) , thickness ) def line ( self , start_x , start_y , end_x , end_y , thickness ) : self . create_element_surface ( abs ( start_x - end_x ) , abs ( start_y - end_y ) ) pygame . draw . line ( self . element_surface , self . adjusted_color , ", "answer": "( start_x , start_y ) , ( end_x , end_y ) , thickness )"}, {"prompt": " from interface . gtp_wrapper import run_gtp ", "answer": "from multiprocessing import Process"}, {"prompt": " from django . conf . urls import patterns , include , url ", "answer": "import views"}, {"prompt": " '''''' __docformat__ = '' __version__ = '' import ctypes as c import gzip import marshal import sys class AnonymousStruct ( c . Structure ) : __slots__ = ( ) _fields_ = ( ( '' , c . c_int ) , ) class AnonymousUnion ( c . Union ) : __slots__ = ( ) _fields_ = ( ( '' , c . c_int ) , ) class EnumType ( type ( c . c_int ) ) : def __new__ ( metaclass , name , bases , dict ) : cls = type ( c . c_int ) . __new__ ( metaclass , name , bases , dict ) return cls class Enum ( c . c_int ) : __metaclass__ = EnumType _values_ = ( ) @ classmethod def from_param ( cls , obj ) : assert obj in cls . _values_ return cls ( obj ) class FFILibrary ( object ) : def __init__ ( self , ffi_file , lib ) : data = gzip . GzipFile ( mode = '' , fileobj = ffi_file ) . read ( ) self . lib = lib self . map = marshal . loads ( data ) self . type_map = { } self . forward_map = { } self . builtin_type_map = { '' : None , '' : c . c_char , '' : c . c_char , '' : c . c_byte , '' : c . c_wchar , '' : c . c_short , '' : c . c_short , '' : c . c_ushort , '' : c . c_int , '' : c . c_int , '' : c . c_uint , '' : c . c_long , '' : c . c_long , '' : c . c_ulong , '' : c . c_longlong , '' : c . c_longlong , '' : c . c_ulonglong , '' : c . c_float , '' : c . c_double , '' : c . c_int , } def dump ( self , name ) : print self . map [ name ] def __getattr__ ( self , name ) : kind , value = self . map [ name ] if kind == '' : result = value elif kind == '' : result = self . get_type ( value ) elif kind == '' : result = self . get_enum_type ( name , value ) elif kind == '' : result = self . get_class_type ( name , value , c . Structure ) elif kind == '' : result = self . get_class_type ( name , value , c . Union ) elif kind == '' : address = c . addressof ( getattr ( self . lib , name ) ) result_type = self . get_type ( value ) result = result_type . from_address ( address ) elif kind == '' : address = c . addressof ( getattr ( self . lib , name ) ) result_type = self . get_type ( value ) result = result_type . from_address ( address ) else : raise RuntimeError ( kind ) setattr ( self , name , result ) return result def get_type ( self , parts ) : try : return self . type_map [ parts ] except KeyError : pass result = self . get_base_type ( parts [ ] ) for part in parts [ : ] : if part == '' : result = c . POINTER ( result ) elif type ( part ) is tuple : if part [ ] == '' : result = self . get_function_type ( result , part [ : ] ) elif part [ ] == '' : result = self . get_array_type ( result , part [ : ] ) else : raise RuntimeError ( part ) else : raise RuntimeError ( part ) self . type_map [ parts ] = result return result def get_base_type ( self , name ) : try : return self . type_map [ name ] except KeyError : pass try : return self . builtin_type_map [ name ] except KeyError : pass try : return self . forward_map [ name ] except KeyError : pass try : kind , value = self . map [ name ] except KeyError : if name . startswith ( '' ) : return AnonymousStruct elif name . startswith ( '' ) : return AnonymousUnion else : raise RuntimeError ( '' % name ) if kind == '' : return self . get_type ( value ) elif kind == '' : return self . get_enum_type ( name , value ) elif kind == '' : return self . get_class_type ( name , value , c . Structure ) elif kind == '' : return self . get_class_type ( name , value , c . Union ) else : raise RuntimeError ( kind ) def get_enum_type ( self , name , items ) : class _FFIEnum ( Enum ) : pass _FFIEnum . __name__ = name ", "answer": "for key , value in items :"}, {"prompt": " from itertools import chain from urllib import urlencode from django import forms from django . db . models . fields import BLANK_CHOICE_DASH from django . forms . widgets import flatatt from django . utils . encoding import force_unicode from django . utils . safestring import mark_safe from django . utils . translation import ugettext as _ class LinkWidget ( forms . Widget ) : def __init__ ( self , attrs = None , choices = ( ) ) : super ( LinkWidget , self ) . __init__ ( attrs ) self . choices = choices def value_from_datadict ( self , data , files , name ) : value = super ( LinkWidget , self ) . value_from_datadict ( data , files , name ) self . data = data return value def render ( self , name , value , attrs = None , choices = ( ) ) : if not hasattr ( self , '' ) : self . data = { } if value is None : value = '' final_attrs = self . build_attrs ( attrs ) output = [ u'' % flatatt ( final_attrs ) ] options = self . render_options ( choices , [ value ] , name ) if options : output . append ( options ) output . append ( '' ) return mark_safe ( u'' . join ( output ) ) def render_options ( self , choices , selected_choices , name ) : selected_choices = set ( force_unicode ( v ) for v in selected_choices ) output = [ ] for option_value , option_label in chain ( self . choices , choices ) : if isinstance ( option_label , ( list , tuple ) ) : for option in option_label : output . append ( self . render_option ( name , selected_choices , * option ) ) else : output . append ( self . render_option ( name , selected_choices , option_value , option_label ) ) return u'' . join ( output ) def render_option ( self , name , selected_choices , option_value , option_label ) : option_value = force_unicode ( option_value ) if option_label == BLANK_CHOICE_DASH [ ] [ ] : option_label = _ ( \"\" ) data = self . data . copy ( ) data [ name ] = option_value selected = data == self . data or option_value in selected_choices ", "answer": "try :"}, {"prompt": " try : from setuptools import setup except ImportError : print ( '' ) sys . exit ( ) import os import sys import codecs def read ( filename ) : return codecs . open ( filename , encoding = '' ) . read ( ) long_description = '' . join ( [ read ( '' ) , read ( '' ) , read ( '' ) ] ) __doc__ = long_description requirements = [ ] if sys . version_info < ( , ) : requirements . append ( '' ) root_folder = os . path . dirname ( os . path . abspath ( __file__ ) ) folder = os . path . join ( root_folder , '' , '' ) paths = os . listdir ( folder ) companies = [ path for path in paths if os . path . isdir ( os . path . join ( folder , path ) ) and os . path . exists ( os . path . join ( folder , path , '' ) ) ] folder = os . path . join ( root_folder , '' , '' , '' ) paths = os . listdir ( folder ) legacy_companies = [ path for path in paths if os . path . isdir ( os . path . join ( folder , path ) ) and os . path . exists ( os . path . join ( folder , path , '' ) ) ] setup ( name = '' , version = '' , license = '' , ", "answer": "description = '' ,"}, {"prompt": " '''''' import threading import logging import copy log = logging . getLogger ( __name__ ) class SaltEventsdWorker ( threading . Thread ) : '''''' def __init__ ( self , qdata , name , event_map , backends , ** kwargs ) : threading . Thread . __init__ ( self ) self . setName ( name ) self . events = qdata self . event_map = event_map self . backends = backends self . kwargs = kwargs self . active_backends = { } def run ( self ) : '''''' log . info ( \"\" . format ( threading . currentThread ( ) . getName ( ) ) ) if isinstance ( self . events , dict ) : self . _store_stats ( ) elif isinstance ( self . events , list ) : self . _store_data ( ) def _init_backend ( self , backend ) : '''''' try : setup_backend = copy . deepcopy ( self . backends [ backend ] ) setup_backend . setup ( self . name , ** self . kwargs ) self . active_backends [ backend ] = setup_backend except KeyError : log . error ( \"\" . format ( backend ) ) def _cleanup ( self ) : '''''' for ( name , backend ) in self . active_backends . items ( ) : backend . shutdown ( ) def _store_stats ( self ) : self . _init_backend ( '' ) self . active_backends [ '' ] . send ( self . events , None ) def _store_data ( self ) : ", "answer": "''''''"}, {"prompt": " from django_fakery import factory , Blueprint chef = factory . blueprint ( '' , fields = { '' : '' } ) pizza = Blueprint ( '' , fields = { ", "answer": "'' : chef ,"}, {"prompt": " from guppy . heapy . test import support class TestCase ( support . TestCase ) : def setUp ( self ) : support . TestCase . setUp ( self ) self . sets = self . guppy . sets heapdefs = getattr ( self . sets . setsc , '' ) , self . root = [ ] self . heapyc = self . guppy . heapy . heapyc self . hv = self . heapyc . HeapView ( self . root , heapdefs ) self . nodeset = self . sets . immnodeset self . mutnodeset = self . sets . mutnodeset self . nodegraph = self . heapyc . NodeGraph class TestHeapView ( TestCase ) : ", "answer": "def test_hiding_tag ( self ) :"}, {"prompt": " from __future__ import division __credits__ = [ \"\" ] from pyqi . core . interfaces . optparse import ( OptparseUsageExample , OptparseOption , OptparseResult ) from pyqi . core . command import ( make_command_in_collection_lookup_f , make_command_out_collection_lookup_f ) from pyqi . commands . make_release import CommandConstructor cmd_in_lookup = make_command_in_collection_lookup_f ( CommandConstructor ) cmd_out_lookup = make_command_out_collection_lookup_f ( CommandConstructor ) usage_examples = [ OptparseUsageExample ( ShortDesc = \"\" , LongDesc = \"\" ", "answer": "\"\" ,"}, {"prompt": " \"\"\"\"\"\" ", "answer": "sqldb = \"\" "}, {"prompt": " \"\"\"\"\"\" import copy import json from cafe . engine . models . base import AutoMarshallingListModel , AutoMarshallingModel class Network ( AutoMarshallingModel ) : \"\"\"\"\"\" NETWORK = '' def __init__ ( self , id_ = None , name = None , admin_state_up = None , status = None , subnets = None , shared = None , tenant_id = None , ** kwargs ) : super ( Network , self ) . __init__ ( ) self . id = id_ self . name = name self . admin_state_up = admin_state_up self . status = status self . subnets = subnets self . shared = shared ", "answer": "self . tenant_id = tenant_id"}, {"prompt": " import toto from toto . invocation import * from tornado . ioloop import IOLoop @ asynchronous def invoke ( handler , params ) : def receive_message ( message ) : handler . respond ( result = { '' : message } ) ", "answer": "handler . register_event_handler ( '' , receive_message , deregister_on_finish = True ) "}, {"prompt": " \"\"\"\"\"\" from ryu . base import app_manager from ryu . controller import handler from ryu . lib import dpid as lib_dpid from ryu . lib import hub from ryu . lib . packet import vrrp from ryu . services . protocols . vrrp import api as vrrp_api from ryu . services . protocols . vrrp import event as vrrp_event from ryu . services . protocols . vrrp import monitor_openflow from ryu . topology import event as topo_event from ryu . topology import api as topo_api from . import vrrp_common class VRRPConfigApp ( vrrp_common . VRRPCommon ) : _IFNAME0 = _IFNAME1 = def __init__ ( self , * args , ** kwargs ) : super ( VRRPConfigApp , self ) . __init__ ( * args , ** kwargs ) self . start_main = False @ handler . set_ev_cls ( topo_event . EventSwitchEnter ) def _switch_enter_handler ( self , ev ) : if self . start_main : return switches = topo_api . get_switch ( self ) if len ( switches ) < : return self . start_main = True app_mgr = app_manager . AppManager . get_instance ( ) self . logger . debug ( '' , app_mgr . applications ) self . switches = app_mgr . applications [ '' ] hub . spawn ( self . _main ) def _configure_vrrp_router ( self , vrrp_version , priority , ip_addr , switch_index , vrid ) : switches = self . switches self . logger . debug ( '' , switches . dps ) dpid = sorted ( switches . dps . keys ( ) ) [ switch_index ] self . logger . debug ( '' , lib_dpid . dpid_to_str ( dpid ) ) self . logger . debug ( '' , switches . port_state ) port_no = sorted ( switches . port_state [ dpid ] . keys ( ) ) [ ] self . logger . debug ( '' , port_no ) port = switches . port_state [ dpid ] [ port_no ] self . logger . debug ( '' , port ) mac = port . hw_addr self . logger . debug ( '' , mac ) interface = vrrp_event . VRRPInterfaceOpenFlow ( mac , ip_addr , None , dpid , port_no ) ", "answer": "self . logger . debug ( '' , interface )"}, {"prompt": " import unittest from swift . common . header_key_dict import HeaderKeyDict class TestHeaderKeyDict ( unittest . TestCase ) : def test_case_insensitive ( self ) : headers = HeaderKeyDict ( ) headers [ '' ] = headers [ '' ] = headers [ '' ] = self . assertEqual ( headers [ '' ] , '' ) self . assertEqual ( headers [ '' ] , '' ) self . assertEqual ( headers [ '' ] , '' ) def test_setdefault ( self ) : headers = HeaderKeyDict ( ) headers . setdefault ( '' , '' ) self . assertEqual ( headers [ '' ] , '' ) ret = headers . setdefault ( '' , '' ) self . assertEqual ( ret , '' ) ret = headers . setdefault ( '' , '' ) self . assertEqual ( ret , '' ) headers . setdefault ( '' , None ) def test_del_contains ( self ) : headers = HeaderKeyDict ( ) headers [ '' ] = self . assertTrue ( '' in headers ) del headers [ '' ] self . assertTrue ( '' not in headers ) def test_update ( self ) : headers = HeaderKeyDict ( ) headers . update ( { '' : '' } ) ", "answer": "headers . update ( [ ( '' , '' ) ] )"}, {"prompt": " from __future__ import print_function import os from pylearn2 . utils . string_utils import preprocess def main ( ) : base = '' base = preprocess ( base ) paths = sorted ( os . listdir ( base ) ) assert len ( paths ) == words = { } for i , path in enumerate ( paths ) : if i % == : print ( i ) path = base + path f = open ( path , '' ) lines = f . readlines ( ) for line in lines : word = line [ : - ] if word not in words : words [ word ] = else : words [ word ] += ranked_words = sorted ( words . keys ( ) , key = lambda x : - words [ x ] ) ranked_words = [ word_ + '' for word_ in ranked_words [ : ] ] f = open ( '' , '' ) f . writelines ( ranked_words ) f . close ( ) ", "answer": "if __name__ == \"\" :"}, {"prompt": " from __future__ import absolute_import , unicode_literals from django . contrib . contenttypes . models import ContentType from django . db import connection from django . db . models . query import get_prefetcher from django . test import TestCase from django . test . utils import override_settings from django . utils import six from django . utils . encoding import force_text from . models import ( Author , Book , Reader , Qualification , Teacher , Department , TaggedItem , Bookmark , AuthorAddress , FavoriteAuthors , AuthorWithAge , BookWithYear , BookReview , Person , House , Room , Employee , Comment , LessonEntry , WordEntry , Author2 ) class PrefetchRelatedTests ( TestCase ) : def setUp ( self ) : self . book1 = Book . objects . create ( title = \"\" ) self . book2 = Book . objects . create ( title = \"\" ) self . book3 = Book . objects . create ( title = \"\" ) self . book4 = Book . objects . create ( title = \"\" ) self . author1 = Author . objects . create ( name = \"\" , first_book = self . book1 ) self . author2 = Author . objects . create ( name = \"\" , first_book = self . book1 ) self . author3 = Author . objects . create ( name = \"\" , first_book = self . book1 ) self . author4 = Author . objects . create ( name = \"\" , first_book = self . book4 ) self . book1 . authors . add ( self . author1 , self . author2 , self . author3 ) self . book2 . authors . add ( self . author1 ) self . book3 . authors . add ( self . author3 ) self . book4 . authors . add ( self . author4 ) self . reader1 = Reader . objects . create ( name = \"\" ) self . reader2 = Reader . objects . create ( name = \"\" ) self . reader1 . books_read . add ( self . book1 , self . book4 ) self . reader2 . books_read . add ( self . book2 , self . book4 ) def test_m2m_forward ( self ) : with self . assertNumQueries ( ) : lists = [ list ( b . authors . all ( ) ) for b in Book . objects . prefetch_related ( '' ) ] normal_lists = [ list ( b . authors . all ( ) ) for b in Book . objects . all ( ) ] self . assertEqual ( lists , normal_lists ) def test_m2m_reverse ( self ) : with self . assertNumQueries ( ) : lists = [ list ( a . books . all ( ) ) for a in Author . objects . prefetch_related ( '' ) ] normal_lists = [ list ( a . books . all ( ) ) for a in Author . objects . all ( ) ] self . assertEqual ( lists , normal_lists ) def test_foreignkey_forward ( self ) : with self . assertNumQueries ( ) : books = [ a . first_book for a in Author . objects . prefetch_related ( '' ) ] normal_books = [ a . first_book for a in Author . objects . all ( ) ] self . assertEqual ( books , normal_books ) def test_foreignkey_reverse ( self ) : with self . assertNumQueries ( ) : lists = [ list ( b . first_time_authors . all ( ) ) for b in Book . objects . prefetch_related ( '' ) ] self . assertQuerysetEqual ( self . book2 . authors . all ( ) , [ \"\" ] ) def test_onetoone_reverse_no_match ( self ) : with self . assertNumQueries ( ) : book = Book . objects . prefetch_related ( '' ) . all ( ) [ ] with self . assertNumQueries ( ) : with self . assertRaises ( BookWithYear . DoesNotExist ) : book . bookwithyear def test_survives_clone ( self ) : with self . assertNumQueries ( ) : lists = [ list ( b . first_time_authors . all ( ) ) for b in Book . objects . prefetch_related ( '' ) . exclude ( id = ) ] def test_len ( self ) : with self . assertNumQueries ( ) : qs = Book . objects . prefetch_related ( '' ) length = len ( qs ) lists = [ list ( b . first_time_authors . all ( ) ) for b in qs ] def test_bool ( self ) : with self . assertNumQueries ( ) : qs = Book . objects . prefetch_related ( '' ) x = bool ( qs ) lists = [ list ( b . first_time_authors . all ( ) ) for b in qs ] def test_count ( self ) : with self . assertNumQueries ( ) : qs = Book . objects . prefetch_related ( '' ) [ b . first_time_authors . count ( ) for b in qs ] def test_exists ( self ) : with self . assertNumQueries ( ) : qs = Book . objects . prefetch_related ( '' ) [ b . first_time_authors . exists ( ) for b in qs ] def test_in_and_prefetch_related ( self ) : \"\"\"\"\"\" qs = Book . objects . prefetch_related ( '' ) self . assertTrue ( qs [ ] in qs ) def test_clear ( self ) : \"\"\"\"\"\" with self . assertNumQueries ( ) : with_prefetch = Author . objects . prefetch_related ( '' ) without_prefetch = with_prefetch . prefetch_related ( None ) lists = [ list ( a . books . all ( ) ) for a in without_prefetch ] def test_m2m_then_m2m ( self ) : \"\"\"\"\"\" with self . assertNumQueries ( ) : qs = Author . objects . prefetch_related ( '' ) lists = [ [ [ six . text_type ( r ) for r in b . read_by . all ( ) ] for b in a . books . all ( ) ] for a in qs ] self . assertEqual ( lists , [ [ [ \"\" ] , [ \"\" ] ] , [ [ \"\" ] ] , [ [ \"\" ] , [ ] ] , [ [ \"\" , \"\" ] ] , ] ) def test_overriding_prefetch ( self ) : with self . assertNumQueries ( ) : qs = Author . objects . prefetch_related ( '' , '' ) lists = [ [ [ six . text_type ( r ) for r in b . read_by . all ( ) ] for b in a . books . all ( ) ] for a in qs ] self . assertEqual ( lists , [ [ [ \"\" ] , [ \"\" ] ] , [ [ \"\" ] ] , [ [ \"\" ] , [ ] ] , [ [ \"\" , \"\" ] ] , ] ) with self . assertNumQueries ( ) : qs = Author . objects . prefetch_related ( '' , '' ) lists = [ [ [ six . text_type ( r ) for r in b . read_by . all ( ) ] for b in a . books . all ( ) ] for a in qs ] self . assertEqual ( lists , [ [ [ \"\" ] , [ \"\" ] ] , [ [ \"\" ] ] , [ [ \"\" ] , [ ] ] , [ [ \"\" , \"\" ] ] , ] ) def test_get ( self ) : \"\"\"\"\"\" with self . assertNumQueries ( ) : author = Author . objects . prefetch_related ( '' ) . get ( name = \"\" ) lists = [ [ six . text_type ( r ) for r in b . read_by . all ( ) ] for b in author . books . all ( ) ] self . assertEqual ( lists , [ [ \"\" ] , [ \"\" ] ] ) def test_foreign_key_then_m2m ( self ) : \"\"\"\"\"\" with self . assertNumQueries ( ) : qs = Author . objects . select_related ( '' ) . prefetch_related ( '' ) lists = [ [ six . text_type ( r ) for r in a . first_book . read_by . all ( ) ] for a in qs ] self . assertEqual ( lists , [ [ \"\" ] , [ \"\" ] , [ \"\" ] , [ \"\" , \"\" ] ] ) def test_attribute_error ( self ) : qs = Reader . objects . all ( ) . prefetch_related ( '' ) with self . assertRaises ( AttributeError ) as cm : list ( qs ) self . assertTrue ( '' in str ( cm . exception ) ) def test_invalid_final_lookup ( self ) : qs = Book . objects . prefetch_related ( '' ) with self . assertRaises ( ValueError ) as cm : list ( qs ) self . assertTrue ( '' in str ( cm . exception ) ) self . assertTrue ( \"\" in str ( cm . exception ) ) class DefaultManagerTests ( TestCase ) : def setUp ( self ) : self . qual1 = Qualification . objects . create ( name = \"\" ) self . qual2 = Qualification . objects . create ( name = \"\" ) self . qual3 = Qualification . objects . create ( name = \"\" ) self . qual4 = Qualification . objects . create ( name = \"\" ) self . teacher1 = Teacher . objects . create ( name = \"\" ) self . teacher2 = Teacher . objects . create ( name = \"\" ) self . teacher3 = Teacher . objects . create ( name = \"\" ) self . teacher1 . qualifications . add ( self . qual1 , self . qual2 , self . qual3 , self . qual4 ) self . teacher2 . qualifications . add ( self . qual1 ) self . teacher3 . qualifications . add ( self . qual2 ) self . dept1 = Department . objects . create ( name = \"\" ) self . dept2 = Department . objects . create ( name = \"\" ) self . dept1 . teachers . add ( self . teacher1 , self . teacher2 ) self . dept2 . teachers . add ( self . teacher1 , self . teacher3 ) def test_m2m_then_m2m ( self ) : with self . assertNumQueries ( ) : qs = Department . objects . prefetch_related ( '' ) depts = \"\" . join ( [ \"\" % ( dept . name , \"\" . join ( six . text_type ( t ) for t in dept . teachers . all ( ) ) ) for dept in qs ] ) self . assertEqual ( depts , \"\" \"\" ) class GenericRelationTests ( TestCase ) : def setUp ( self ) : book1 = Book . objects . create ( title = \"\" ) book2 = Book . objects . create ( title = \"\" ) book3 = Book . objects . create ( title = \"\" ) reader1 = Reader . objects . create ( name = \"\" ) reader2 = Reader . objects . create ( name = \"\" ) reader3 = Reader . objects . create ( name = \"\" ) book1 . read_by . add ( reader1 , reader2 ) book2 . read_by . add ( reader2 ) book3 . read_by . add ( reader3 ) self . book1 , self . book2 , self . book3 = book1 , book2 , book3 self . reader1 , self . reader2 , self . reader3 = reader1 , reader2 , reader3 def test_prefetch_GFK ( self ) : TaggedItem . objects . create ( tag = \"\" , content_object = self . book1 ) TaggedItem . objects . create ( tag = \"\" , content_object = self . reader1 ) TaggedItem . objects . create ( tag = \"\" , content_object = self . book2 ) TaggedItem . objects . create ( tag = \"\" , content_object = self . reader3 ) with self . assertNumQueries ( ) : qs = TaggedItem . objects . prefetch_related ( '' ) list ( qs ) def test_prefetch_GFK_nonint_pk ( self ) : Comment . objects . create ( comment = \"\" , content_object = self . book1 ) with self . assertNumQueries ( ) : qs = Comment . objects . prefetch_related ( '' ) [ c . content_object for c in qs ] def test_traverse_GFK ( self ) : \"\"\"\"\"\" TaggedItem . objects . create ( tag = \"\" , content_object = self . book1 ) TaggedItem . objects . create ( tag = \"\" , content_object = self . book2 ) TaggedItem . objects . create ( tag = \"\" , content_object = self . book3 ) TaggedItem . objects . create ( tag = \"\" , content_object = self . reader1 ) TaggedItem . objects . create ( tag = \"\" , content_object = self . reader2 ) ct = ContentType . objects . get_for_model ( Book ) with self . assertNumQueries ( ) : qs = TaggedItem . objects . filter ( content_type = ct , tag = '' ) . prefetch_related ( '' ) readers_of_awesome_books = set ( [ r . name for tag in qs for r in tag . content_object . read_by . all ( ) ] ) self . assertEqual ( readers_of_awesome_books , set ( [ \"\" , \"\" , \"\" ] ) ) def test_nullable_GFK ( self ) : TaggedItem . objects . create ( tag = \"\" , content_object = self . book1 , created_by = self . reader1 ) TaggedItem . objects . create ( tag = \"\" , content_object = self . book2 ) TaggedItem . objects . create ( tag = \"\" , content_object = self . book3 ) with self . assertNumQueries ( ) : result = [ t . created_by for t in TaggedItem . objects . prefetch_related ( '' ) ] self . assertEqual ( result , [ t . created_by for t in TaggedItem . objects . all ( ) ] ) def test_generic_relation ( self ) : b = Bookmark . objects . create ( url = '' ) t1 = TaggedItem . objects . create ( content_object = b , tag = '' ) t2 = TaggedItem . objects . create ( content_object = b , tag = '' ) with self . assertNumQueries ( ) : tags = [ t . tag for b in Bookmark . objects . prefetch_related ( '' ) for t in b . tags . all ( ) ] self . assertEqual ( sorted ( tags ) , [ \"\" , \"\" ] ) def test_charfield_GFK ( self ) : b = Bookmark . objects . create ( url = '' ) t1 = TaggedItem . objects . create ( content_object = b , tag = '' ) t2 = TaggedItem . objects . create ( content_object = b , favorite = b , tag = '' ) with self . assertNumQueries ( ) : bookmark = Bookmark . objects . filter ( pk = b . pk ) . prefetch_related ( '' , '' ) [ ] self . assertEqual ( sorted ( [ i . tag for i in bookmark . tags . all ( ) ] ) , [ \"\" , \"\" ] ) self . assertEqual ( [ i . tag for i in bookmark . favorite_tags . all ( ) ] , [ \"\" ] ) class MultiTableInheritanceTest ( TestCase ) : def setUp ( self ) : self . book1 = BookWithYear . objects . create ( title = \"\" , published_year = ) self . book2 = BookWithYear . objects . create ( title = \"\" , published_year = ) self . author1 = AuthorWithAge . objects . create ( name = '' , first_book = self . book1 , age = ) self . author2 = AuthorWithAge . objects . create ( name = '' , first_book = self . book1 , age = ) self . author3 = AuthorWithAge . objects . create ( name = '' , first_book = self . book2 , age = ) self . authorAddress = AuthorAddress . objects . create ( author = self . author1 , address = '' ) self . book2 . aged_authors . add ( self . author2 , self . author3 ) ", "answer": "self . br1 = BookReview . objects . create ("}, {"prompt": " import json import os import re from django . core . urlresolvers import reverse from django . test import TestCase from corehq . apps . app_manager . tests . util import add_build from corehq . apps . app_manager . util import new_careplan_module from corehq . apps . app_manager . views import AppSummaryView from corehq . apps . builds . models import BuildSpec from corehq import toggles from corehq . apps . users . models import WebUser from corehq . apps . domain . models import Domain from corehq . apps . app_manager . models import ( AdvancedModule , Application , APP_V1 , APP_V2 , Module , ReportModule , ShadowModule , ) from . test_form_versioning import BLANK_TEMPLATE class TestViews ( TestCase ) : app = None build = None @ classmethod def setUpClass ( cls ) : cls . domain = Domain ( name = '' , is_active = True ) cls . domain . save ( ) cls . username = '' cls . password = '' cls . user = WebUser . create ( cls . domain . name , cls . username , cls . password , is_active = True ) cls . user . is_superuser = True cls . user . save ( ) cls . build = add_build ( version = '' , build_number = ) cls . app = Application . new_app ( cls . domain . name , \"\" , application_version = APP_V2 ) cls . app . build_spec = BuildSpec . from_string ( '' ) toggles . CUSTOM_PROPERTIES . set ( \"\" . format ( domain = cls . domain . name ) , True ) def setUp ( self ) : self . client . login ( username = self . username , password = self . password ) @ classmethod def tearDownClass ( cls ) : cls . user . delete ( ) cls . build . delete ( ) if cls . app : cls . app . delete ( ) cls . domain . delete ( ) def test_download_file_bad_xform_404 ( self ) : '''''' module = self . app . add_module ( Module . new_module ( \"\" , \"\" ) ) build1 = { '' : '' , '' : } build2 = { '' : '' , '' : } add_build ( ** build1 ) add_build ( ** build2 ) ", "answer": "with open ( os . path . join ( os . path . dirname ( __file__ ) , \"\" , \"\" ) ) as f :"}, {"prompt": " \"\"\"\"\"\" __author__ = \"\" __revision__ = \"\" __version__ = \"\" import errno import os import os . path import re import shutil import stat import string import sys import tempfile import time import traceback import types import UserList __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] try : import difflib except ImportError : __all__ . append ( '' ) def is_List ( e ) : return type ( e ) is types . ListType or isinstance ( e , UserList . UserList ) try : from UserString import UserString except ImportError : class UserString : pass if hasattr ( types , '' ) : def is_String ( e ) : return type ( e ) is types . StringType or type ( e ) is types . UnicodeType or isinstance ( e , UserString ) else : def is_String ( e ) : return type ( e ) is types . StringType or isinstance ( e , UserString ) tempfile . template = '' if os . name in ( '' , '' ) : tempfile . template = '' + str ( os . getpid ( ) ) + '' else : tempfile . template = '' re_space = re . compile ( '' ) _Cleanup = [ ] _chain_to_exitfunc = None def _clean ( ) : global _Cleanup cleanlist = filter ( None , _Cleanup ) del _Cleanup [ : ] cleanlist . reverse ( ) for test in cleanlist : test . cleanup ( ) if _chain_to_exitfunc : _chain_to_exitfunc ( ) try : import atexit except ImportError : try : _chain_to_exitfunc = sys . exitfunc except AttributeError : pass sys . exitfunc = _clean else : atexit . register ( _clean ) try : zip except NameError : def zip ( * lists ) : result = [ ] for i in xrange ( min ( map ( len , lists ) ) ) : result . append ( tuple ( map ( lambda l , i = i : l [ i ] , lists ) ) ) return result class Collector : def __init__ ( self , top ) : self . entries = [ top ] def __call__ ( self , arg , dirname , names ) : pathjoin = lambda n , d = dirname : os . path . join ( d , n ) self . entries . extend ( map ( pathjoin , names ) ) def _caller ( tblist , skip ) : string = \"\" arr = [ ] for file , line , name , text in tblist : if file [ - : ] == \"\" : break arr = [ ( file , line , name , text ) ] + arr atfrom = \"\" for file , line , name , text in arr [ skip : ] : if name in ( \"\" , \"\" ) : name = \"\" else : name = \"\" + name + \"\" string = string + ( \"\" % ( atfrom , line , file , name ) ) atfrom = \"\" return string def fail_test ( self = None , condition = , function = None , skip = ) : \"\"\"\"\"\" if not condition : return if not function is None : function ( ) of = \"\" desc = \"\" sep = \"\" if not self is None : if self . program : of = \"\" + self . program sep = \"\" if self . description : desc = \"\" + self . description + \"\" sep = \"\" at = _caller ( traceback . extract_stack ( ) , skip ) sys . stderr . write ( \"\" + of + desc + sep + at ) sys . exit ( ) def no_result ( self = None , condition = , function = None , skip = ) : \"\"\"\"\"\" if not condition : return if not function is None : function ( ) of = \"\" desc = \"\" sep = \"\" if not self is None : if self . program : of = \"\" + self . program sep = \"\" if self . description : desc = \"\" + self . description + \"\" sep = \"\" if os . environ . get ( '' ) : at = _caller ( traceback . extract_stack ( ) , skip ) sys . stderr . write ( \"\" + of + desc + sep + at ) else : sys . stderr . write ( \"\" ) sys . exit ( ) def pass_test ( self = None , condition = , function = None ) : \"\"\"\"\"\" if not condition : return if not function is None : function ( ) sys . stderr . write ( \"\" ) sys . exit ( ) def match_exact ( lines = None , matches = None ) : \"\"\"\"\"\" if not is_List ( lines ) : lines = string . split ( lines , \"\" ) if not is_List ( matches ) : matches = string . split ( matches , \"\" ) if len ( lines ) != len ( matches ) : return for i in range ( len ( lines ) ) : if lines [ i ] != matches [ i ] : return return def match_re ( lines = None , res = None ) : \"\"\"\"\"\" if not is_List ( lines ) : lines = string . split ( lines , \"\" ) if not is_List ( res ) : res = string . split ( res , \"\" ) if len ( lines ) != len ( res ) : return for i in range ( len ( lines ) ) : s = \"\" + res [ i ] + \"\" ", "answer": "try :"}, {"prompt": " import codecs import ConfigParser import logging from logging . handlers import RotatingFileHandler from notes_db import NotesDB , SyncError , ReadError , WriteError import argparse import os import sys import time from utils import KeyValueObject , SubjectMixin import view import webbrowser try : import markdown except ImportError : HAVE_MARKDOWN = False else : HAVE_MARKDOWN = True try : import docutils import docutils . core except ImportError : HAVE_DOCUTILS = False else : HAVE_DOCUTILS = True VERSION = \"\" class Config : \"\"\"\"\"\" def __init__ ( self , app_dir ) : \"\"\"\"\"\" self . app_dir = app_dir home = os . path . abspath ( os . path . expanduser ( '' ) ) defaults = { '' : app_dir , '' : app_dir , '' : home , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : os . path . join ( home , '' ) , '' : os . path . join ( home , '' ) , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : None , } args = self . parse_cmd_line_opts ( ) cfg_files = [ os . path . join ( app_dir , '' ) , os . path . join ( home , '' ) , os . path . join ( home , '' ) , os . path . join ( home , '' ) , os . path . join ( home , '' ) ] if args is not None and args . cfg is not None : cfg_files . extend ( [ os . path . join ( app_dir , args . cfg ) , args . cfg ] ) cp = ConfigParser . SafeConfigParser ( defaults ) self . files_read = cp . read ( cfg_files ) cfg_sec = '' if not cp . has_section ( cfg_sec ) : cp . add_section ( cfg_sec ) self . ok = False else : self . ok = True self . sn_username = cp . get ( cfg_sec , '' , raw = True ) self . sn_password = cp . get ( cfg_sec , '' , raw = True ) self . simplenote_sync = cp . getint ( cfg_sec , '' ) self . db_path = cp . get ( cfg_sec , '' ) self . notes_as_txt = cp . getint ( cfg_sec , '' ) self . txt_path = os . path . join ( home , cp . get ( cfg_sec , '' ) ) self . search_mode = cp . get ( cfg_sec , '' ) self . case_sensitive = cp . getint ( cfg_sec , '' ) self . search_tags = cp . getint ( cfg_sec , '' ) self . sort_mode = cp . getint ( cfg_sec , '' ) self . pinned_ontop = cp . getint ( cfg_sec , '' ) self . housekeeping_interval = cp . getint ( cfg_sec , '' ) self . housekeeping_interval_ms = self . housekeeping_interval * self . theme = cp . get ( cfg_sec , '' ) self . font_family = cp . get ( cfg_sec , '' ) self . font_size = cp . getint ( cfg_sec , '' ) self . list_font_family = cp . get ( cfg_sec , '' ) self . list_font_family_fixed = cp . get ( cfg_sec , '' ) self . list_font_size = cp . getint ( cfg_sec , '' ) self . layout = cp . get ( cfg_sec , '' ) self . print_columns = cp . getint ( cfg_sec , '' ) self . background_color = cp . get ( cfg_sec , '' ) self . rest_css_path = cp . get ( cfg_sec , '' ) self . debug = cp . getint ( cfg_sec , '' ) def parse_cmd_line_opts ( self ) : if __name__ != '' : return None parser = argparse . ArgumentParser ( ) parser . add_argument ( '' , '' , default = '' , dest = '' , metavar = '' , help = '' ) args = parser . parse_args ( ) return args class NotesListModel ( SubjectMixin ) : \"\"\"\"\"\" def __init__ ( self ) : SubjectMixin . __init__ ( self ) self . list = [ ] self . match_regexps = [ ] def set_list ( self , alist ) : self . list = alist self . notify_observers ( '' , None ) def get_idx ( self , key ) : \"\"\"\"\"\" found = [ i for i , e in enumerate ( self . list ) if e . key == key ] if found : return found [ ] else : return - class Controller : \"\"\"\"\"\" def __init__ ( self , config ) : self . config = config self . config . app_version = VERSION if not os . path . exists ( self . config . db_path ) : os . mkdir ( self . config . db_path ) log_filename = os . path . join ( self . config . db_path , '' ) lhandler = RotatingFileHandler ( log_filename , maxBytes = , backupCount = ) lhandler . setLevel ( logging . DEBUG ) lhandler . setFormatter ( logging . Formatter ( fmt = '' ) ) logger = logging . getLogger ( ) if self . config . debug == : logger . setLevel ( logging . DEBUG ) logger . addHandler ( lhandler ) logging . debug ( '' ) logging . debug ( '' % ( str ( self . config . files_read ) , ) ) if self . config . sn_username == '' : self . config . simplenote_sync = css = self . config . rest_css_path if css : if css . startswith ( \"\" ) : css = css . replace ( \"\" , os . path . abspath ( os . path . expanduser ( '' ) ) , ) self . config . rest_css_path = css if not os . path . exists ( css ) : self . config . rest_css_path = None self . notes_list_model = NotesListModel ( ) self . view = view . View ( self . config , self . notes_list_model ) try : self . notes_db = NotesDB ( self . config ) except ReadError , e : emsg = \"\" + str ( e ) self . view . show_error ( '' , emsg ) exit ( ) self . notes_db . add_observer ( '' , self . observer_notes_db_synced_note ) self . notes_db . add_observer ( '' , self . observer_notes_db_change_note_status ) if self . config . simplenote_sync : self . notes_db . add_observer ( '' , self . observer_notes_db_sync_full ) self . sync_full ( ) self . view . add_observer ( '' , self . observer_view_click_notelink ) self . view . add_observer ( '' , self . observer_view_delete_note ) self . view . add_observer ( '' , self . observer_view_select_note ) self . view . add_observer ( '' , self . observer_view_change_entry ) self . view . add_observer ( '' , self . observer_view_change_text ) self . view . add_observer ( '' , self . observer_view_change_pinned ) self . view . add_observer ( '' , self . observer_view_create_note ) self . view . add_observer ( '' , self . observer_view_keep_house ) self . view . add_observer ( '' , self . observer_view_markdown ) self . view . add_observer ( '' , self . observer_view_rest ) self . view . add_observer ( '' , self . observer_view_delete_tag ) self . view . add_observer ( '' , self . observer_view_add_tag ) if self . config . simplenote_sync : self . view . add_observer ( '' , lambda v , et , e : self . sync_full ( ) ) self . view . add_observer ( '' , self . observer_view_sync_current_note ) self . view . add_observer ( '' , self . observer_view_close ) self . view . set_cs ( self . config . case_sensitive , silent = True ) self . view . set_search_mode ( self . config . search_mode , silent = True ) self . view . add_observer ( '' , self . observer_view_change_cs ) self . view . add_observer ( '' , self . observer_view_change_search_mode ) nn , match_regexp , active_notes = self . notes_db . filter_notes ( ) self . notes_list_model . set_list ( nn ) self . notes_list_model . match_regexp = match_regexp self . view . set_note_tally ( len ( nn ) , active_notes , len ( self . notes_db . notes ) ) self . selected_note_idx = - self . view . select_note ( ) def get_selected_note_key ( self ) : if self . selected_note_idx >= : return self . notes_list_model . list [ self . selected_note_idx ] . key else : return None def main_loop ( self ) : if not self . config . files_read : self . view . show_warning ( '' , '' ) elif not self . config . ok : wmsg = ( '' + '' ) % ( str ( self . config . files_read ) , ) self . view . show_warning ( '' , wmsg ) self . view . main_loop ( ) def observer_notes_db_change_note_status ( self , notes_db , evt_type , evt ) : skey = self . get_selected_note_key ( ) if skey == evt . key : self . view . set_note_status ( self . notes_db . get_note_status ( skey ) ) def observer_notes_db_sync_full ( self , notes_db , evt_type , evt ) : logging . debug ( evt . msg ) self . view . set_status_text ( evt . msg ) def observer_notes_db_synced_note ( self , notes_db , evt_type , evt ) : \"\"\"\"\"\" selected_note_o = self . notes_list_model . list [ self . selected_note_idx ] if selected_note_o . key == evt . lkey : if selected_note_o . note [ '' ] != evt . old_note [ '' ] : self . view . mute_note_data_changes ( ) self . view . set_note_data ( selected_note_o . note , reset_undo = False ) self . view . unmute_note_data_changes ( ) def observer_view_click_notelink ( self , view , evt_type , note_name ) : idx = self . view . select_note_by_name ( note_name ) if idx < : self . view . set_search_entry_text ( note_name ) def observer_view_delete_note ( self , view , evt_type , evt ) : assert ( evt . sel == self . selected_note_idx ) key = self . get_selected_note_key ( ) nidx = evt . sel + if nidx >= and nidx < self . view . get_number_of_notes ( ) : self . view . select_note ( nidx ) self . notes_db . delete_note ( key ) self . view . set_search_entry_text ( self . view . get_search_entry_text ( ) ) def helper_markdown_to_html ( self ) : if self . selected_note_idx >= : key = self . notes_list_model . list [ self . selected_note_idx ] . key c = self . notes_db . get_note_content ( key ) logging . debug ( \"\" % ( key , ) ) if HAVE_MARKDOWN : logging . debug ( \"\" % ( key , ) ) html = markdown . markdown ( c ) logging . debug ( \"\" ) else : logging . debug ( \"\" ) html = \"\" html += \"\" fn = os . path . join ( self . config . db_path , key + '' ) f = codecs . open ( fn , mode = '' , encoding = '' ) s = u\"\"\"\"\"\" % ( '' if self . view . get_continuous_rendering ( ) else \"\" , html , ) f . write ( s ) f . close ( ) return fn def helper_rest_to_html ( self ) : if self . selected_note_idx >= : key = self . notes_list_model . list [ self . selected_note_idx ] . key c = self . notes_db . get_note_content ( key ) if HAVE_DOCUTILS : settings = { } if self . config . rest_css_path : settings [ '' ] = self . config . rest_css_path html = docutils . core . publish_string ( c , writer_name = '' , settings_overrides = settings ) else : html = \"\" html += \"\" fn = os . path . join ( self . config . db_path , key + '' ) f = codecs . open ( fn , mode = '' , encoding = '' ) s = u\"\"\"\"\"\" % ( unicode ( html , '' ) , ) f . write ( s ) f . close ( ) return fn def observer_view_markdown ( self , view , evt_type , evt ) : fn = self . helper_markdown_to_html ( ) fn_uri = '' + os . path . abspath ( fn ) webbrowser . open ( fn_uri ) def observer_view_rest ( self , view , evt_type , evt ) : fn = self . helper_rest_to_html ( ) fn_uri = '' + os . path . abspath ( fn ) webbrowser . open ( fn_uri ) def helper_save_sync_msg ( self ) : saven = self . notes_db . get_save_queue_len ( ) if self . config . simplenote_sync : syncn = self . notes_db . get_sync_queue_len ( ) wfsn = self . notes_db . waiting_for_simplenote else : syncn = wfsn = savet = '' % ( saven , ) if saven > else '' synct = '' % ( syncn , ) if syncn > else '' wfsnt = '' if wfsn else '' return '' . join ( [ i for i in [ savet , synct , wfsnt ] if i ] ) def observer_view_keep_house ( self , view , evt_type , evt ) : nsaved = self . notes_db . save_threaded ( ) msg = self . helper_save_sync_msg ( ) if self . config . simplenote_sync : nsynced , sync_errors = self . notes_db . sync_to_server_threaded ( ) if sync_errors : msg = '' . join ( [ i for i in [ msg , '' ] if i ] ) self . view . set_status_text ( msg ) if self . view . get_continuous_rendering ( ) : self . helper_markdown_to_html ( ) def observer_view_select_note ( self , view , evt_type , evt ) : self . select_note ( evt . sel ) def observer_view_sync_current_note ( self , view , evt_type , evt ) : if self . selected_note_idx >= : key = self . notes_list_model . list [ self . selected_note_idx ] . key ret = self . notes_db . sync_note_unthreaded ( key ) if ret and ret [ ] == True : self . view . update_selected_note_data ( self . notes_db . notes [ key ] ) self . view . set_status_text ( '' ) elif ret [ ] == False : self . view . set_status_text ( '' ) elif ret is None : self . view . set_status_text ( '' ) def observer_view_change_cs ( self , view , evt_type , evt ) : if evt . value != self . config . case_sensitive : self . config . case_sensitive = evt . value self . view . refresh_notes_list ( ) def observer_view_change_search_mode ( self , view , evt_type , evt ) : if evt . value != self . config . search_mode : self . config . search_mode = evt . value self . view . refresh_notes_list ( ) def observer_view_change_entry ( self , view , evt_type , evt ) : k = self . get_selected_note_key ( ) nn , match_regexp , active_notes = self . notes_db . filter_notes ( evt . value ) self . notes_list_model . set_list ( nn ) self . notes_list_model . match_regexp = match_regexp self . view . set_note_tally ( len ( nn ) , active_notes , len ( self . notes_db . notes ) ) idx = self . notes_list_model . get_idx ( k ) if idx < : ", "answer": "self . view . select_note ( )"}, {"prompt": " import urllib import sqlite3 import datetime import tweepy from xml . dom . minidom import parseString from settings import * class Item : title = \"\" link = \"\" class CustomUrlOpener ( urllib . FancyURLopener ) : version = \"\" def getFeedData ( ) : urllib . _urlopener = CustomUrlOpener ( ) feedRequest = urllib . urlopen ( HACKER_NEWS_RSS_URL ) feedString = feedRequest . read ( ) feedRequest . close ( ) return parseString ( feedString ) def iterateItems ( feedData ) : results = [ ] for element in feedData . getElementsByTagName ( \"\" ) : item = Item ( ) item . title = element . getElementsByTagName ( \"\" ) [ ] . childNodes [ ] . data item . link = element . getElementsByTagName ( \"\" ) [ ] . childNodes [ ] . data item . commentLink = element . getElementsByTagName ( \"\" ) [ ] . childNodes [ ] . data results . append ( item ) return results def isSchemaThere ( conn ) : cur = conn . cursor ( ) cur . execute ( \"\" ) if len ( cur . fetchall ( ) ) > : return True return False def createSchema ( conn ) : cur = conn . cursor ( ) cur . execute ( \"\" ) def isNewLink ( item ) : conn = sqlite3 . connect ( LOCAL_LINK_DB ) if isSchemaThere ( conn ) == False : createSchema ( conn ) cur = conn . cursor ( ) cur . execute ( \"\" , ( item . link , ) ) isNew = len ( cur . fetchall ( ) ) == conn . commit ( ) conn . close ( ) return isNew def insertLink ( item ) : conn = sqlite3 . connect ( LOCAL_LINK_DB ) cur = conn . cursor ( ) cur . execute ( \"\" , ( item . title , item . link , ) ) conn . commit ( ) conn . close ( ) def fixCommentLink ( link ) : protocolEnd = if \"\" in link : protocolEnd = link . index ( \"\" ) + len ( \"\" ) return \"\" + link [ protocolEnd : ] else : return \"\" + link . lstrip ( \"\" ) def getTweetText ( item ) : maxTitleTextLength = TWITTER_MAX - ( TCO_SHORT_URL_LENGTH + len ( DIVIDER_TEXT ) ) if item . link < > item . commentLink : maxTitleTextLength -= ( len ( COMMENT_TEXT ) + TCO_SHORT_URL_LENGTH ) ", "answer": "tweetText = item . title . strip ( \"\" ) [ : maxTitleTextLength ] + DIVIDER_TEXT + item . link"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) result . setStringAttribute ( \"\" , \"\" ) result . options_mask = result . pvp_status = PVPSTATUS . PvPStatus_None ", "answer": "return result "}, {"prompt": " \"\"\"\"\"\" __metaclass__ = type import time from zope . interface import implements from twisted . python import reflect from twisted . python . failure import Failure from twisted . internet import base , defer from twisted . internet . interfaces import IReactorTime class LoopingCall : \"\"\"\"\"\" call = None running = False deferred = None interval = None _expectNextCallAt = _runAtStart = False starttime = None def __init__ ( self , f , * a , ** kw ) : self . f = f self . a = a self . kw = kw from twisted . internet import reactor self . clock = reactor def withCount ( cls , countCallable ) : \"\"\"\"\"\" def counter ( ) : now = self . clock . seconds ( ) lastTime = self . _realLastTime if lastTime is None : lastTime = self . starttime if self . _runAtStart : lastTime -= self . interval self . _realLastTime = now lastInterval = self . _intervalOf ( lastTime ) thisInterval = self . _intervalOf ( now ) count = thisInterval - lastInterval return countCallable ( count ) self = cls ( counter ) self . _realLastTime = None return self withCount = classmethod ( withCount ) def _intervalOf ( self , t ) : \"\"\"\"\"\" elapsedTime = t - self . starttime intervalNum = int ( elapsedTime / self . interval ) return intervalNum def start ( self , interval , now = True ) : \"\"\"\"\"\" assert not self . running , ( \"\" \"\" ) if interval < : raise ValueError , \"\" self . running = True d = self . deferred = defer . Deferred ( ) self . starttime = self . clock . seconds ( ) self . _expectNextCallAt = self . starttime self . interval = interval self . _runAtStart = now if now : self ( ) else : self . _reschedule ( ) return d def stop ( self ) : \"\"\"\"\"\" assert self . running , ( \"\" \"\" ) self . running = False if self . call is not None : self . call . cancel ( ) self . call = None d , self . deferred = self . deferred , None d . callback ( self ) def __call__ ( self ) : def cb ( result ) : if self . running : self . _reschedule ( ) else : d , self . deferred = self . deferred , None d . callback ( self ) def eb ( failure ) : self . running = False d , self . deferred = self . deferred , None d . errback ( failure ) self . call = None d = defer . maybeDeferred ( self . f , * self . a , ** self . kw ) d . addCallback ( cb ) d . addErrback ( eb ) def _reschedule ( self ) : \"\"\"\"\"\" if self . interval == : self . call = self . clock . callLater ( , self ) return currentTime = self . clock . seconds ( ) untilNextTime = ( self . _expectNextCallAt - currentTime ) % self . interval nextTime = max ( self . _expectNextCallAt + self . interval , currentTime + untilNextTime ) if nextTime == currentTime : nextTime += self . interval self . _expectNextCallAt = nextTime self . call = self . clock . callLater ( nextTime - currentTime , self ) def __repr__ ( self ) : if hasattr ( self . f , '' ) : func = self . f . func_name if hasattr ( self . f , '' ) : func = self . f . im_class . __name__ + '' + func else : func = reflect . safe_repr ( self . f ) return '' % ( self . interval , func , reflect . safe_repr ( self . a ) , reflect . safe_repr ( self . kw ) ) class SchedulerError ( Exception ) : \"\"\"\"\"\" class SchedulerStopped ( SchedulerError ) : \"\"\"\"\"\" class TaskFinished ( SchedulerError ) : \"\"\"\"\"\" class TaskDone ( TaskFinished ) : \"\"\"\"\"\" class TaskStopped ( TaskFinished ) : \"\"\"\"\"\" class TaskFailed ( TaskFinished ) : \"\"\"\"\"\" class NotPaused ( SchedulerError ) : \"\"\"\"\"\" class _Timer ( object ) : MAX_SLICE = def __init__ ( self ) : self . end = time . time ( ) + self . MAX_SLICE def __call__ ( self ) : return time . time ( ) >= self . end _EPSILON = def _defaultScheduler ( x ) : from twisted . internet import reactor return reactor . callLater ( _EPSILON , x ) class CooperativeTask ( object ) : \"\"\"\"\"\" def __init__ ( self , iterator , cooperator ) : \"\"\"\"\"\" self . _iterator = iterator self . _cooperator = cooperator self . _deferreds = [ ] self . _pauseCount = self . _completionState = None self . _completionResult = None cooperator . _addTask ( self ) def whenDone ( self ) : \"\"\"\"\"\" d = defer . Deferred ( ) if self . _completionState is None : self . _deferreds . append ( d ) else : d . callback ( self . _completionResult ) return d def pause ( self ) : \"\"\"\"\"\" self . _checkFinish ( ) self . _pauseCount += if self . _pauseCount == : self . _cooperator . _removeTask ( self ) def resume ( self ) : \"\"\"\"\"\" if self . _pauseCount == : raise NotPaused ( ) self . _pauseCount -= if self . _pauseCount == and self . _completionState is None : self . _cooperator . _addTask ( self ) def _completeWith ( self , completionState , deferredResult ) : \"\"\"\"\"\" self . _completionState = completionState self . _completionResult = deferredResult if not self . _pauseCount : self . _cooperator . _removeTask ( self ) for d in self . _deferreds : d . callback ( deferredResult ) def stop ( self ) : \"\"\"\"\"\" self . _checkFinish ( ) self . _completeWith ( TaskStopped ( ) , Failure ( TaskStopped ( ) ) ) def _checkFinish ( self ) : \"\"\"\"\"\" if self . _completionState is not None : raise self . _completionState def _oneWorkUnit ( self ) : \"\"\"\"\"\" try : result = self . _iterator . next ( ) except StopIteration : self . _completeWith ( TaskDone ( ) , self . _iterator ) except : self . _completeWith ( TaskFailed ( ) , Failure ( ) ) else : if isinstance ( result , defer . Deferred ) : self . pause ( ) def failLater ( f ) : self . _completeWith ( TaskFailed ( ) , f ) result . addCallbacks ( lambda result : self . resume ( ) , failLater ) class Cooperator ( object ) : \"\"\"\"\"\" def __init__ ( self , terminationPredicateFactory = _Timer , scheduler = _defaultScheduler , started = True ) : \"\"\"\"\"\" self . _tasks = [ ] self . _metarator = iter ( ( ) ) self . _terminationPredicateFactory = terminationPredicateFactory self . _scheduler = scheduler self . _delayedCall = None self . _stopped = False self . _started = started def coiterate ( self , iterator , doneDeferred = None ) : \"\"\"\"\"\" if doneDeferred is None : doneDeferred = defer . Deferred ( ) CooperativeTask ( iterator , self ) . whenDone ( ) . chainDeferred ( doneDeferred ) return doneDeferred def cooperate ( self , iterator ) : \"\"\"\"\"\" return CooperativeTask ( iterator , self ) def _addTask ( self , task ) : \"\"\"\"\"\" if self . _stopped : self . _tasks . append ( task ) task . _completeWith ( SchedulerStopped ( ) , Failure ( SchedulerStopped ( ) ) ) else : self . _tasks . append ( task ) self . _reschedule ( ) def _removeTask ( self , task ) : \"\"\"\"\"\" self . _tasks . remove ( task ) def _tasksWhileNotStopped ( self ) : \"\"\"\"\"\" terminator = self . _terminationPredicateFactory ( ) while self . _tasks : for t in self . _metarator : yield t if terminator ( ) : return self . _metarator = iter ( self . _tasks ) def _tick ( self ) : \"\"\"\"\"\" self . _delayedCall = None for taskObj in self . _tasksWhileNotStopped ( ) : taskObj . _oneWorkUnit ( ) self . _reschedule ( ) _mustScheduleOnStart = False def _reschedule ( self ) : if not self . _started : self . _mustScheduleOnStart = True return if self . _delayedCall is None and self . _tasks : self . _delayedCall = self . _scheduler ( self . _tick ) def start ( self ) : \"\"\"\"\"\" self . _stopped = False self . _started = True if self . _mustScheduleOnStart : del self . _mustScheduleOnStart self . _reschedule ( ) def stop ( self ) : \"\"\"\"\"\" self . _stopped = True for taskObj in self . _tasks : taskObj . _completeWith ( SchedulerStopped ( ) , Failure ( SchedulerStopped ( ) ) ) self . _tasks = [ ] if self . _delayedCall is not None : self . _delayedCall . cancel ( ) self . _delayedCall = None _theCooperator = Cooperator ( ) def coiterate ( iterator ) : \"\"\"\"\"\" return _theCooperator . coiterate ( iterator ) def cooperate ( iterator ) : \"\"\"\"\"\" return _theCooperator . cooperate ( iterator ) class Clock : \"\"\"\"\"\" implements ( IReactorTime ) rightNow = def __init__ ( self ) : ", "answer": "self . calls = [ ]"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals try : from urlparse import urlparse , parse_qs , parse_qsl , urlunparse ", "answer": "except ImportError :"}, {"prompt": " from django . core . management . base import BaseCommand from chronam . core . management . commands import configure_logging from chronam . core . index import index_pages configure_logging ( \"\" , \"\" ) ", "answer": "class Command ( BaseCommand ) :"}, {"prompt": " import inspect import logging import sys LOG = logging . getLogger ( '' ) HANDSHAKE_DISPATCHER = \"\" CONFIG_DISPATCHER = \"\" MAIN_DISPATCHER = \"\" DEAD_DISPATCHER = \"\" class _Caller ( object ) : \"\"\"\"\"\" def __init__ ( self , dispatchers , ev_source ) : \"\"\"\"\"\" self . dispatchers = dispatchers self . ev_source = ev_source def set_ev_cls ( ev_cls , dispatchers = None ) : def _set_ev_cls_dec ( handler ) : if '' not in dir ( handler ) : handler . callers = { } for e in _listify ( ev_cls ) : handler . callers [ e ] = _Caller ( _listify ( dispatchers ) , e . __module__ ) return handler return _set_ev_cls_dec def set_ev_handler ( ev_cls , dispatchers = None ) : def _set_ev_cls_dec ( handler ) : if '' not in dir ( handler ) : handler . callers = { } for e in _listify ( ev_cls ) : handler . callers [ e ] = _Caller ( _listify ( dispatchers ) , None ) return handler return _set_ev_cls_dec def _has_caller ( meth ) : return hasattr ( meth , '' ) def _listify ( may_list ) : if may_list is None : may_list = [ ] if not isinstance ( may_list , list ) : may_list = [ may_list ] return may_list def register_instance ( i ) : for _k , m in inspect . getmembers ( i , inspect . ismethod ) : if _has_caller ( m ) : for ev_cls , c in m . callers . items ( ) : i . register_handler ( ev_cls , m ) def _is_method ( f ) : return inspect . isfunction ( f ) or inspect . ismethod ( f ) def get_dependent_services ( cls ) : services = [ ] for _k , m in inspect . getmembers ( cls , _is_method ) : if _has_caller ( m ) : for ev_cls , c in m . callers . items ( ) : service = getattr ( sys . modules [ ev_cls . __module__ ] , '' , None ) if service : if cls . __module__ != service : services . append ( service ) m = sys . modules [ cls . __module__ ] services . extend ( getattr ( m , '' , [ ] ) ) services = list ( set ( services ) ) return services def register_service ( service ) : \"\"\"\"\"\" ", "answer": "frm = inspect . stack ( ) [ ]"}, {"prompt": " class Klam ( Service ) : def __init__ ( self , apikey = None ) : self . apikey = apikey def shrink ( self , bigurl , tags = None ) : parameters = { '' : bigurl , '' : '' } ", "answer": "if self . apikey :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " from django . conf import settings ", "answer": "from django . http import HttpResponseRedirect"}, {"prompt": " '''''' import cv2 import numpy as np import sys def data_matrix_demo ( cap ) : window_name = \"\" frame_number = need_to_save = False while : ret , frame = cap . read ( ) if not ret : break gray = cv2 . cvtColor ( frame , cv2 . COLOR_RGB2GRAY ) codes , corners , dmtx = cv2 . findDataMatrix ( gray ) cv2 . drawDataMatrixCodes ( frame , codes , corners ) cv2 . imshow ( window_name , frame ) key = cv2 . waitKey ( ) c = chr ( key & ) if c in [ '' , '' , chr ( ) ] : break if c == '' : need_to_save = True if need_to_save and codes : filename = ( \"\" % frame_number ) cv2 . imwrite ( filename , frame ) print \"\" + filename need_to_save = False frame_number += if __name__ == '' : print __doc__ if len ( sys . argv ) == : cap = cv2 . VideoCapture ( ) else : ", "answer": "cap = cv2 . VideoCapture ( sys . argv [ ] )"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals import os import pytest from cookiecutter import generate from cookiecutter import utils from cookiecutter import exceptions @ pytest . fixture ( scope = '' ) def remove_output_folder ( request ) : \"\"\"\"\"\" def finalizer_remove_output_folder ( ) : if os . path . exists ( '' ) : utils . rmtree ( '' ) request . addfinalizer ( finalizer_remove_output_folder ) @ pytest . mark . usefixtures ( '' , '' ) ", "answer": "def test_output_folder ( ) :"}, {"prompt": " \"\"\"\"\"\" import warnings from numbers import Integral import numpy as np from . volumeutils import ( native_code , swapped_code , make_dt_codes , array_from_file ) from . spatialimages import SpatialImage from . arraywriters import make_array_writer from . wrapstruct import WrapStruct from . fileslice import canonical_slicers , predict_shape , slice2outax BLOCK_SIZE = main_header_dtd = [ ( '' , '' ) , ( '' , '' ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , '' ) , ( '' , np . uint32 ) , ( '' , '' ) , ( '' , np . float32 ) , ( '' , '' ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . float32 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint32 ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , '' ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . float32 ) , ( '' , '' ) , ( '' , np . float32 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , '' ) , ( '' , np . uint16 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , '' ) , ( '' , np . uint16 ) , ( '' , '' ) ] hdr_dtype = np . dtype ( main_header_dtd ) subheader_dtd = [ ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . int16 ) , ( '' , np . int16 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint32 ) , ( '' , np . uint32 ) , ( '' , np . uint16 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint32 ) , ( '' , np . uint32 ) , ( '' , np . uint32 ) , ( '' , np . uint32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint16 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , '' ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . float32 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , np . uint16 ) , ( '' , '' ) , ( '' , '' ) ] subhdr_dtype = np . dtype ( subheader_dtd ) _dtdefs = ( ( , '' , np . uint8 ) , ( , '' , np . int16 ) , ( , '' , np . int32 ) , ( , '' , np . float32 ) , ( , '' , np . float32 ) , ( , '' , np . int16 ) , ( , '' , np . int32 ) ) data_type_codes = make_dt_codes ( _dtdefs ) ft_defs = ( ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) ) file_type_codes = dict ( ft_defs ) patient_orient_defs = ( ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) ) patient_orient_codes = dict ( patient_orient_defs ) patient_orient_radiological = [ , , , ] patient_orient_neurological = [ , , , ] class EcatHeader ( WrapStruct ) : \"\"\"\"\"\" template_dtype = hdr_dtype _ft_codes = file_type_codes _patient_orient_codes = patient_orient_codes def __init__ ( self , binaryblock = None , endianness = None , check = True ) : \"\"\"\"\"\" super ( EcatHeader , self ) . __init__ ( binaryblock , endianness , check ) @ classmethod def guessed_endian ( klass , hdr ) : \"\"\"\"\"\" if not hdr [ '' ] == : return swapped_code else : return native_code @ classmethod def default_structarr ( klass , endianness = None ) : '''''' hdr_data = super ( EcatHeader , klass ) . default_structarr ( endianness ) hdr_data [ '' ] = '' hdr_data [ '' ] = hdr_data [ '' ] = hdr_data [ '' ] = hdr_data [ '' ] = return hdr_data def get_data_dtype ( self ) : \"\"\"\"\"\" raise NotImplementedError ( \"\" ) def get_patient_orient ( self ) : \"\"\"\"\"\" code = self . _structarr [ '' ] . item ( ) if code not in self . _patient_orient_codes : raise KeyError ( '' % code ) return self . _patient_orient_codes [ code ] def get_filetype ( self ) : \"\"\"\"\"\" code = self . _structarr [ '' ] . item ( ) if code not in self . _ft_codes : raise KeyError ( '' % code ) return self . _ft_codes [ code ] @ classmethod def _get_checks ( klass ) : '''''' return ( ) def read_mlist ( fileobj , endianness ) : \"\"\"\"\"\" dt = np . dtype ( np . int32 ) if endianness is not native_code : dt = dt . newbyteorder ( endianness ) mlists = [ ] mlist_index = mlist_block_no = while True : fileobj . seek ( ( mlist_block_no - ) * BLOCK_SIZE ) dat = fileobj . read ( BLOCK_SIZE ) rows = np . ndarray ( shape = ( , ) , dtype = dt , buffer = dat ) n_unused , mlist_block_no , _ , n_rows = rows [ ] if not ( n_unused + n_rows ) == : mlist = [ ] return mlist mlists . append ( rows [ : n_rows + ] ) mlist_index += n_rows if mlist_block_no <= : break return np . row_stack ( mlists ) def get_frame_order ( mlist ) : \"\"\"\"\"\" ids = mlist [ : , ] . copy ( ) n_valid = np . sum ( ids > ) ids [ ids <= ] = ids . max ( ) + valid_order = np . argsort ( ids ) if not all ( valid_order == sorted ( valid_order ) ) : warnings . warn_explicit ( '' '' '' '' % valid_order , UserWarning , '' , ) id_dict = { } for i in range ( n_valid ) : id_dict [ i ] = [ valid_order [ i ] , ids [ valid_order [ i ] ] ] return id_dict def get_series_framenumbers ( mlist ) : \"\"\"\"\"\" nframes = len ( mlist ) frames_order = get_frame_order ( mlist ) mlist_nframes = len ( frames_order ) trueframenumbers = np . arange ( nframes - mlist_nframes , nframes ) frame_dict = { } try : for frame_stored , ( true_order , _ ) in frames_order . items ( ) : frame_dict [ frame_stored ] = trueframenumbers [ true_order ] + return frame_dict except : raise IOError ( '' ) def read_subheaders ( fileobj , mlist , endianness ) : \"\"\"\"\"\" subheaders = [ ] dt = subhdr_dtype if endianness is not native_code : dt = dt . newbyteorder ( endianness ) for mat_id , sh_blkno , sh_last_blkno , mat_stat in mlist : if sh_blkno == : break offset = ( sh_blkno - ) * BLOCK_SIZE fileobj . seek ( offset ) tmpdat = fileobj . read ( BLOCK_SIZE ) sh = np . ndarray ( shape = ( ) , dtype = dt , buffer = tmpdat ) subheaders . append ( sh ) return subheaders class EcatSubHeader ( object ) : _subhdrdtype = subhdr_dtype _data_type_codes = data_type_codes def __init__ ( self , hdr , mlist , fileobj ) : \"\"\"\"\"\" self . _header = hdr self . endianness = hdr . endianness self . _mlist = mlist self . fileobj = fileobj self . subheaders = read_subheaders ( fileobj , mlist , hdr . endianness ) def get_shape ( self , frame = ) : \"\"\"\"\"\" subhdr = self . subheaders [ frame ] x = subhdr [ '' ] . item ( ) y = subhdr [ '' ] . item ( ) z = subhdr [ '' ] . item ( ) return ( x , y , z ) def get_nframes ( self ) : \"\"\"\"\"\" framed = get_frame_order ( self . _mlist ) return len ( framed ) def _check_affines ( self ) : \"\"\"\"\"\" nframes = self . get_nframes ( ) if nframes == : return True affs = [ self . get_frame_affine ( i ) for i in range ( nframes ) ] if affs : i = iter ( affs ) first = i . next ( ) for item in i : if not np . all ( first == item ) : return False return True def get_frame_affine ( self , frame = ) : \"\"\"\"\"\" subhdr = self . subheaders [ frame ] x_off = subhdr [ '' ] y_off = subhdr [ '' ] z_off = subhdr [ '' ] zooms = self . get_zooms ( frame = frame ) dims = self . get_shape ( frame ) origin_offset = ( np . array ( dims ) - ) / aff = np . diag ( zooms ) aff [ : , - ] = - origin_offset * zooms [ : - ] + np . array ( [ x_off , y_off , z_off ] ) return aff def get_zooms ( self , frame = ) : \"\"\"\"\"\" subhdr = self . subheaders [ frame ] x_zoom = subhdr [ '' ] * y_zoom = subhdr [ '' ] * z_zoom = subhdr [ '' ] * return ( x_zoom , y_zoom , z_zoom , ) def _get_data_dtype ( self , frame ) : dtcode = self . subheaders [ frame ] [ '' ] . item ( ) return self . _data_type_codes . dtype [ dtcode ] def _get_frame_offset ( self , frame = ) : return int ( self . _mlist [ frame ] [ ] * BLOCK_SIZE ) def _get_oriented_data ( self , raw_data , orientation = None ) : '''''' if orientation is None : orientation = self . _header [ '' ] elif orientation == '' : orientation = patient_orient_neurological [ ] elif orientation == '' : orientation = patient_orient_radiological [ ] else : raise ValueError ( '' ) if orientation in patient_orient_neurological : raw_data = raw_data [ : : - , : : - , : : - ] elif orientation in patient_orient_radiological : raw_data = raw_data [ : : , : : - , : : - ] return raw_data def raw_data_from_fileobj ( self , frame = , orientation = None ) : '''''' dtype = self . _get_data_dtype ( frame ) if self . _header . endianness is not native_code : dtype = dtype . newbyteorder ( self . _header . endianness ) shape = self . get_shape ( frame ) offset = self . _get_frame_offset ( frame ) fid_obj = self . fileobj raw_data = array_from_file ( shape , dtype , fid_obj , offset = offset ) raw_data = self . _get_oriented_data ( raw_data , orientation ) return raw_data def data_from_fileobj ( self , frame = , orientation = None ) : '''''' header = self . _header subhdr = self . subheaders [ frame ] raw_data = self . raw_data_from_fileobj ( frame , orientation ) data = raw_data * np . asscalar ( header [ '' ] ) data = data * np . asscalar ( subhdr [ '' ] ) return data class EcatImageArrayProxy ( object ) : '''''' def __init__ ( self , subheader ) : self . _subheader = subheader self . _data = None x , y , z = subheader . get_shape ( ) nframes = subheader . get_nframes ( ) self . _shape = ( x , y , z , nframes ) @ property def shape ( self ) : return self . _shape @ property def is_proxy ( self ) : return True def __array__ ( self ) : '''''' data = np . empty ( self . shape ) frame_mapping = get_frame_order ( self . _subheader . _mlist ) for i in sorted ( frame_mapping ) : data [ : , : , : , i ] = self . _subheader . data_from_fileobj ( frame_mapping [ i ] [ ] ) return data def __getitem__ ( self , sliceobj ) : \"\"\"\"\"\" sliceobj = canonical_slicers ( sliceobj , self . shape ) ax_inds = [ i for i , obj in enumerate ( sliceobj ) if obj is not None ] assert len ( ax_inds ) == len ( self . shape ) frame_mapping = get_frame_order ( self . _subheader . _mlist ) slice3 = sliceobj [ ax_inds [ ] ] in_slicer = sliceobj [ : ax_inds [ ] ] + sliceobj [ ax_inds [ ] + : ] if isinstance ( slice3 , Integral ) : data = self . _subheader . data_from_fileobj ( frame_mapping [ slice3 ] [ ] ) return data [ in_slicer ] out_shape = predict_shape ( sliceobj , self . shape ) out_data = np . empty ( out_shape ) out_slicer = [ slice ( None ) ] * len ( out_shape ) in2out_ind = slice2outax ( len ( self . shape ) , sliceobj ) [ ] for i in list ( range ( self . shape [ ] ) ) [ slice3 ] : data = self . _subheader . data_from_fileobj ( frame_mapping [ i ] [ ] ) out_slicer [ in2out_ind ] = i out_data [ tuple ( out_slicer ) ] = data [ in_slicer ] return out_data class EcatImage ( SpatialImage ) : \"\"\"\"\"\" _header = EcatHeader header_class = _header valid_exts = ( '' , ) _subheader = EcatSubHeader files_types = ( ( '' , '' ) , ( '' , '' ) ) ImageArrayProxy = EcatImageArrayProxy def __init__ ( self , dataobj , affine , header , subheader , mlist , extra = None , file_map = None ) : \"\"\"\"\"\" self . _subheader = subheader self . _mlist = mlist self . _dataobj = dataobj if affine is not None : affine = np . array ( affine , dtype = np . float64 , copy = True ) if not affine . shape == ( , ) : raise ValueError ( '' ) self . _affine = affine if extra is None : extra = { } self . extra = extra self . _header = header if file_map is None : file_map = self . __class__ . make_file_map ( ) self . file_map = file_map self . _data_cache = None @ property def affine ( self ) : if not self . _subheader . _check_affines ( ) : warnings . warn ( '' '' , UserWarning ) return self . _affine def get_frame_affine ( self , frame ) : \"\"\"\"\"\" return self . _subheader . get_frame_affine ( frame = frame ) def get_frame ( self , frame , orientation = None ) : '''''' return self . _subheader . data_from_fileobj ( frame , orientation ) def get_data_dtype ( self , frame ) : subhdr = self . _subheader dt = subhdr . _get_data_dtype ( frame ) return dt @ property def shape ( self ) : x , y , z = self . _subheader . get_shape ( ) nframes = self . _subheader . get_nframes ( ) return ( x , y , z , nframes ) def get_mlist ( self ) : \"\"\"\"\"\" return self . _mlist def get_subheaders ( self ) : \"\"\"\"\"\" return self . _subheader @ classmethod def from_filespec ( klass , filespec ) : return klass . from_filename ( filespec ) @ staticmethod def _get_fileholders ( file_map ) : \"\"\"\"\"\" return file_map [ '' ] , file_map [ '' ] @ classmethod def from_file_map ( klass , file_map ) : \"\"\"\"\"\" hdr_file , img_file = klass . _get_fileholders ( file_map ) hdr_fid = hdr_file . get_prepare_fileobj ( mode = '' ) header = klass . _header . from_fileobj ( hdr_fid ) hdr_copy = header . copy ( ) mlist = np . zeros ( ( header [ '' ] , ) , dtype = np . int32 ) mlist_data = read_mlist ( hdr_fid , hdr_copy . endianness ) mlist [ : len ( mlist_data ) ] = mlist_data subheaders = klass . _subheader ( hdr_copy , mlist , hdr_fid ) data = klass . ImageArrayProxy ( subheaders ) if not subheaders . _check_affines ( ) : warnings . warn ( '' '' , UserWarning ) aff = subheaders . get_frame_affine ( ) img = klass ( data , aff , header , subheaders , mlist , extra = None , file_map = file_map ) return img def _get_empty_dir ( self ) : '''''' return np . array ( [ , , , ] , dtype = np . int32 ) def _write_data ( self , data , stream , pos , dtype = None , endianness = None ) : '''''' if dtype is None : dtype = data . dtype if endianness is None : endianness = native_code stream . seek ( pos ) make_array_writer ( data . newbyteorder ( endianness ) , dtype ) . to_fileobj ( stream ) def to_file_map ( self , file_map = None ) : '''''' if file_map is None : file_map = self . file_map self . get_data ( ) hdr = self . header mlist = self . _mlist subheaders = self . get_subheaders ( ) dir_pos = entry_pos = dir_pos + current_dir = self . _get_empty_dir ( ) hdr_fh , img_fh = self . _get_fileholders ( file_map ) hdrf = hdr_fh . get_prepare_fileobj ( mode = '' ) imgf = hdrf hdr . write_to ( hdrf ) ", "answer": "for index in range ( , self . header [ '' ] ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import migrations , models class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ ", "answer": "migrations . AddField ("}, {"prompt": " \"\"\"\"\"\" __all__ = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ) WS_NORMAL = WS_GOING_AWAY = WS_PROTOCOL_ERROR = WS_DATA_CANNOT_ACCEPT = WS_RESERVED = WS_NO_STATUS_CODE = WS_CLOSED_ABNORMALLY = WS_MESSAGE_NOT_CONSISTENT = WS_MESSAGE_VIOLATE_POLICY = WS_MESSAGE_TOO_BIG = WS_SERVER_DIDNT_RETURN_EXTENSIONS = WS_UNEXPECTED_CONDITION = WS_FAILURE_TLS = def is_not_used ( code ) : \"\"\"\"\"\" return <= code <= def is_reserved ( code ) : \"\"\"\"\"\" ", "answer": "return <= code <= "}, {"prompt": " import sys from utils import sh def main ( destdir ) : sh ( \"\" ) sh ( \"\" ) sh ( '' ) sh ( '' ) sh ( '' ) sh ( '' ) sh ( '' ) sh ( '' ) sh ( \"\" ) ", "answer": "sh ( \"\" )"}, {"prompt": " import reil import reil . x86 . translator as x86 from concolica . utils import * from concolica . vulnerabilities import * from smt import bitvector as bv def operand_value ( s , o ) : output = o if isinstance ( o , reil . ImmediateOperand ) : output = bv . Constant ( o . size , o . value ) elif isinstance ( o , reil . RegisterOperand ) : output = s . registers [ o . name ] if output . size > o . size : output = output . extract ( o . size ) elif output . size < o . size : output = output . zero_extend_to ( o . size ) return output def op_add ( i , s ) : a = operand_value ( s , i . input0 ) b = operand_value ( s , i . input1 ) dst = i . output ", "answer": "operation_size = max ( a . size , b . size , dst . size )"}, {"prompt": " \"\"\"\"\"\" from cStringIO import StringIO import docutils . core from pyth import document from pyth . format import PythWriter from pyth . plugins . rst . writer import RSTWriter class LatexWriter ( PythWriter ) : @ classmethod def write ( klass , document , target = None , stylesheet = \"\" ) : \"\"\"\"\"\" writer = LatexWriter ( document , target , stylesheet ) return writer . go ( ) def __init__ ( self , doc , target = None , stylesheet = \"\" ) : \"\"\"\"\"\" self . document = doc self . stylesheet = stylesheet self . target = target if target is not None else StringIO ( ) @ property def full_stylesheet ( self ) : \"\"\"\"\"\" latex_fragment = r\"\"\"\"\"\" % ( self . document . properties . get ( \"\" ) , self . document . properties . get ( \"\" ) , self . document . properties . get ( \"\" ) ) return latex_fragment + self . stylesheet def go ( self ) : rst = RSTWriter . write ( self . document ) . getvalue ( ) settings = dict ( input_encoding = \"\" , ", "answer": "output_encoding = \"\" ,"}, {"prompt": " import re from functools import partial import sublime from sublime_plugin import WindowCommand , TextCommand , EventListener from . util import find_view_by_settings , get_setting from . cmd import GitCmd from . helpers import GitDiffHelper , GitErrorHelper , GitStatusHelper RE_DIFF_HEAD = re . compile ( r'' ) GIT_DIFF_TITLE = '' GIT_DIFF_TITLE_PREFIX = GIT_DIFF_TITLE + '' GIT_DIFF_CACHED_TITLE = '' GIT_DIFF_CACHED_TITLE_PREFIX = GIT_DIFF_CACHED_TITLE + '' GIT_DIFF_CLEAN = \"\" GIT_DIFF_CLEAN_CACHED = \"\" GIT_DIFF_VIEW_SYNTAX = '' GIT_DIFF_UNSTAGE_ERROR = \"\" GIT_DIFF_STAGE_ERROR = \"\" class GitDiffCommand ( WindowCommand , GitCmd ) : \"\"\"\"\"\" def run ( self , repo = None , path = None , cached = False ) : repo = repo or self . get_repo ( ) if not repo : return path = path or repo title = self . get_view_title ( path , cached ) git_view = '' % ( '' if cached else '' ) view = find_view_by_settings ( self . window , git_view = git_view , git_repo = repo , git_diff_path = path ) if not view : view = self . window . new_file ( ) view . set_name ( title ) view . set_syntax_file ( GIT_DIFF_VIEW_SYNTAX ) view . set_scratch ( True ) view . set_read_only ( True ) view . settings ( ) . set ( '' , git_view ) view . settings ( ) . set ( '' , repo ) view . settings ( ) . set ( '' , path ) view . settings ( ) . set ( '' , cached ) view . settings ( ) . set ( '' , ) self . window . focus_view ( view ) view . run_command ( '' , { '' : path , '' : cached , '' : True } ) def get_view_title ( self , path = None , cached = False ) : if cached : return GIT_DIFF_CACHED_TITLE_PREFIX + path if path else GIT_DIFF_CACHED_TITLE else : return GIT_DIFF_TITLE_PREFIX + path if path else GIT_DIFF_TITLE class GitDiffCachedCommand ( GitDiffCommand ) : \"\"\"\"\"\" def run ( self , path = None ) : super ( GitDiffCachedCommand , self ) . run ( path = path , cached = True ) class GitDiffCurrentFileCommand ( GitCmd , GitStatusHelper , TextCommand ) : \"\"\"\"\"\" def run ( self , edit , cached = False ) : filename = self . view . file_name ( ) if not filename : sublime . error_message ( '' ) return repo = self . get_repo ( ) if not repo : return in_git = self . file_in_git ( repo , filename ) if not in_git : sublime . error_message ( '' % filename . replace ( repo , '' ) . lstrip ( '' ) ) return self . view . window ( ) . run_command ( '' , { '' : repo , '' : filename , '' : cached } ) class GitDiffCachedCurrentFileCommand ( GitDiffCurrentFileCommand ) : \"\"\"\"\"\" def run ( self , edit ) : super ( GitDiffCachedCurrentFileCommand , self ) . run ( edit , cached = True ) class GitDiffTextCmd ( GitCmd , GitDiffHelper ) : def move_to_point ( self , point ) : self . view . sel ( ) . clear ( ) self . view . sel ( ) . add ( sublime . Region ( point ) ) if not self . view . visible_region ( ) . contains ( point ) : view = self . view sublime . set_timeout ( partial ( view . show , point , True ) , ) def parse_diff ( self ) : sections = [ ] state = None prev_file = None current_file = { } current_hunks = [ ] prev_hunk = None current_hunk = None for line in self . view . lines ( sublime . Region ( , self . view . size ( ) ) ) : linetext = self . view . substr ( line ) if linetext . startswith ( '' ) : state = '' if prev_file != line : if prev_file is not None : if current_hunk : current_hunks . append ( current_hunk ) sections . append ( ( current_file , current_hunks ) ) prev_file = line prev_hunk = None current_file = line current_hunks = [ ] elif state == '' and RE_DIFF_HEAD . match ( linetext ) : current_file = current_file . cover ( line ) elif linetext . startswith ( '' ) : state = '' if prev_hunk != line : if prev_hunk is not None : current_hunks . append ( current_hunk ) prev_hunk = line current_hunk = line elif state == '' and linetext [ ] in ( '' , '' , '' ) : current_hunk = current_hunk . cover ( line ) elif state == '' : current_file = current_file . cover ( line ) if current_file and current_hunk : current_hunks . append ( current_hunk ) sections . append ( ( current_file , current_hunks ) ) return sections def build_lookup ( self , parsed_diff ) : lookup = [ ] for header , hunks in parsed_diff : for h in hunks : lookup . append ( ( h , header ) ) return lookup def get_hunks_from_selection ( self , selection ) : if not selection : return None diffspec = self . parse_diff ( ) lookup = self . build_lookup ( diffspec ) hunks = { } for s in selection : for hunk , header in lookup : if s . intersects ( hunk ) or hunk . contains ( s ) or ( s . begin ( ) == self . view . size ( ) and hunk . contains ( s . begin ( ) - ) ) : hunks . setdefault ( ( header . begin ( ) , header . end ( ) ) , [ ] ) . append ( hunk ) return hunks def create_patch ( self , selected_hunks ) : patch = [ ] for ( hstart , hend ) , hunks in selected_hunks . items ( ) : header = sublime . Region ( hstart , hend ) for head in self . view . lines ( header ) : headline = self . view . substr ( head ) if headline . startswith ( '' ) or headline . startswith ( '' ) : ", "answer": "patch . append ( \"\" % headline . strip ( ) )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations ", "answer": "class Migration ( migrations . Migration ) :"}, {"prompt": " from openstack import exceptions from openstack import profile from openstack . tests . unit import base class TestProfile ( base . TestCase ) : def test_init ( self ) : prof = profile . Profile ( ) expected = [ '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " import unittest from fractions import Fraction as Frac from smt . decoder . stackdecoder import _future_cost_estimate from smt . decoder . stackdecoder import _create_estimate_dict from smt . decoder . stackdecoder import ArgumentNotSatisfied from smt . decoder . stackdecoder import future_cost_estimate from smt . decoder . stackdecoder import TransPhraseProb from smt . decoder . stackdecoder import Phrase from sqlalchemy import create_engine from sqlalchemy . orm import sessionmaker class DBSetup ( object ) : def __init__ ( self , db = \"\" ) : self . db = db self . tables = [ TransPhraseProb , Phrase ] def __enter__ ( self ) : self . engine = create_engine ( self . db ) for Table in self . tables : Table . __table__ . create ( self . engine ) Session = sessionmaker ( bind = self . engine ) self . session = Session ( ) return self def __exit__ ( self , exc_type , exc_value , traceback ) : for Table in self . tables : Table . __table__ . drop ( self . engine , checkfirst = True ) self . session . close ( ) class FutureCostEstimateTest ( unittest . TestCase ) : def setUp ( self ) : self . maxDiff = None def test_future_cost_estimate_2to1 ( self ) : sentences = u\"\" . split ( ) transfrom = transto = init_val = db = \"\" dataset = [ ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ] val = { ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , } with DBSetup ( db ) as dbobj : dbobj . session . add_all ( TransPhraseProb ( lang1p = item [ ] , lang2p = item [ ] , p2_1 = item [ ] , p1_2 = item [ ] ) for item in dataset ) dbobj . session . add_all ( Phrase ( lang1p = item [ ] , lang2p = item [ ] ) for item in dataset ) dbobj . session . commit ( ) ans = future_cost_estimate ( sentences , transfrom = transfrom , transto = transto , init_val = init_val , db = db ) self . assertEqual ( ans , val ) def test_future_cost_estimate_2to1_argument_not_satisfied ( self ) : sentences = u\"\" . split ( ) transfrom = transto = init_val = db = \"\" dataset = [ ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ] val = { ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , ( , ) : - , } with DBSetup ( db ) as dbobj : dbobj . session . add_all ( TransPhraseProb ( lang1p = item [ ] , lang2p = item [ ] , p2_1 = item [ ] , p1_2 = item [ ] ) for item in dataset ) dbobj . session . add_all ( Phrase ( lang1p = item [ ] , lang2p = item [ ] ) for item in dataset ) dbobj . session . commit ( ) ans = future_cost_estimate ( sentences , transfrom = transfrom , transto = transto , init_val = init_val , db = db ) self . assertEqual ( ans , val ) def test_future_cost_estimate_1to2 ( self ) : sentences = u\"\" . split ( ) transfrom = transto = init_val = db = \"\" dataset = [ ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ( \"\" , \"\" , Frac ( - , ) , ) , ", "answer": "( \"\" , \"\" , Frac ( - , ) , ) ,"}, {"prompt": " import LT . Server import sys server0 = LT . Server . LTServer ( ) server1 = LT . Server . LTServer ( ) server0 . add ( , \"\" ) server1 . add ( , \"\" ) server0 . add ( , LT . Server . read_file ( sys . argv [ ] ) ) server1 . add ( , LT . Server . read_file ( sys . argv [ ] ) ) server0 . start ( ) server1 . start ( ) print \"\" ", "answer": "raw_input ( )"}, {"prompt": " from __future__ import unicode_literals from django . db import migrations , models class Migration ( migrations . Migration ) : dependencies = [ ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , primary_key = True , serialize = False , auto_created = True ) ) , ", "answer": "( '' , models . CharField ( max_length = ) ) ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " import os import subprocess def handle_false ( value ) : ", "answer": "if not value or value . lower ( ) == '' :"}, {"prompt": " from . tf_linear_regression import TfLinearRegression ", "answer": "__all__ = [ \"\" ] "}, {"prompt": " import re import json from crispy_forms . bootstrap import StrictButton , InlineField , FormActions from crispy_forms . helper import FormHelper from crispy_forms . layout import Div from django import forms from django . core . urlresolvers import reverse from django . forms . forms import Form from django . forms . fields import * from crispy_forms import layout as crispy from crispy_forms import bootstrap as twbscrispy from django . utils . safestring import mark_safe from corehq . apps . hqwebapp . crispy import ( BootstrapMultiField , HiddenFieldWithErrors , FieldsetAccordionGroup ) from corehq . apps . style . crispy import FieldWithHelpBubble from corehq . apps . style import crispy as hqcrispy from corehq . apps . app_manager . dbaccessors import get_built_app_ids from corehq . apps . app_manager . models import Application from corehq . apps . sms . models import FORWARD_ALL , FORWARD_BY_KEYWORD , SQLMobileBackend from django . core . exceptions import ValidationError from corehq . apps . reminders . forms import RecordListField , validate_time from django . utils . translation import ugettext as _ , ugettext_noop , ugettext_lazy from corehq . apps . sms . util import ( validate_phone_number , strip_plus , get_sms_backend_classes ) from corehq . apps . domain . models import DayTimeWindow from corehq . apps . users . models import CommCareUser from corehq . apps . groups . models import Group from corehq . apps . hqwebapp . crispy import ErrorsOnlyField from dimagi . utils . django . fields import TrimmedCharField from dimagi . utils . couch . database import iter_docs from django . conf import settings FORWARDING_CHOICES = ( ( FORWARD_ALL , ugettext_noop ( \"\" ) ) , ( FORWARD_BY_KEYWORD , ugettext_noop ( \"\" ) ) , ) ENABLED = \"\" DISABLED = \"\" ENABLED_DISABLED_CHOICES = ( ( DISABLED , ugettext_noop ( \"\" ) ) , ( ENABLED , ugettext_noop ( \"\" ) ) , ) DEFAULT = \"\" CUSTOM = \"\" DEFAULT_CUSTOM_CHOICES = ( ( DEFAULT , ugettext_noop ( \"\" ) ) , ( CUSTOM , ugettext_noop ( \"\" ) ) , ) MESSAGE_COUNTER_CHOICES = ( ( DEFAULT , ugettext_noop ( \"\" ) ) , ( CUSTOM , ugettext_noop ( \"\" ) ) , ) SMS_CONVERSATION_LENGTH_CHOICES = ( ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ) SHOW_ALL = \"\" SHOW_INVALID = \"\" HIDE_ALL = \"\" TIME_BEFORE = \"\" TIME_AFTER = \"\" TIME_BETWEEN = \"\" WELCOME_RECIPIENT_NONE = '' WELCOME_RECIPIENT_CASE = '' WELCOME_RECIPIENT_MOBILE_WORKER = '' WELCOME_RECIPIENT_ALL = '' WELCOME_RECIPIENT_CHOICES = ( ( WELCOME_RECIPIENT_NONE , ugettext_lazy ( '' ) ) , ( WELCOME_RECIPIENT_CASE , ugettext_lazy ( '' ) ) , ( WELCOME_RECIPIENT_MOBILE_WORKER , ugettext_lazy ( '' ) ) , ( WELCOME_RECIPIENT_ALL , ugettext_lazy ( '' ) ) , ) class ForwardingRuleForm ( Form ) : forward_type = ChoiceField ( choices = FORWARDING_CHOICES ) keyword = CharField ( required = False ) backend_id = CharField ( ) def clean_keyword ( self ) : forward_type = self . cleaned_data . get ( \"\" ) keyword = self . cleaned_data . get ( \"\" , \"\" ) . strip ( ) if forward_type == FORWARD_BY_KEYWORD : if keyword == \"\" : raise ValidationError ( _ ( \"\" ) ) return keyword else : return None class LoadBalancingBackendFormMixin ( Form ) : phone_numbers = CharField ( required = False ) def clean_phone_numbers ( self ) : \"\"\"\"\"\" value = self . cleaned_data . get ( \"\" ) result = [ ] try : value = json . loads ( value ) assert isinstance ( value , list ) for item in value : assert isinstance ( item , dict ) assert \"\" in item result . append ( item [ \"\" ] ) except ( AssertionError , ValueError ) : raise ValidationError ( _ ( \"\" \"\" ) ) if len ( result ) == : raise ValidationError ( _ ( \"\" \"\" ) ) for phone_number in result : validate_phone_number ( phone_number ) return result class SettingsForm ( Form ) : use_default_sms_response = ChoiceField ( required = False , label = ugettext_noop ( \"\" ) , choices = ENABLED_DISABLED_CHOICES , ) default_sms_response = TrimmedCharField ( required = False , label = \"\" , ) use_restricted_sms_times = ChoiceField ( required = False , label = ugettext_noop ( \"\" ) , choices = ( ( DISABLED , ugettext_noop ( \"\" ) ) , ( ENABLED , ugettext_noop ( \"\" ) ) , ) , ) restricted_sms_times_json = CharField ( required = False , widget = forms . HiddenInput , ) send_to_duplicated_case_numbers = ChoiceField ( required = False , label = ugettext_noop ( \"\" ) , choices = ENABLED_DISABLED_CHOICES , ) use_custom_case_username = ChoiceField ( required = False , choices = DEFAULT_CUSTOM_CHOICES , ) custom_case_username = TrimmedCharField ( required = False , label = ugettext_noop ( \"\" ) , ) use_custom_message_count_threshold = ChoiceField ( required = False , choices = MESSAGE_COUNTER_CHOICES , ) custom_message_count_threshold = IntegerField ( required = False , label = ugettext_noop ( \"\" ) , ) use_sms_conversation_times = ChoiceField ( required = False , label = ugettext_noop ( \"\" ) , choices = ENABLED_DISABLED_CHOICES , ) sms_conversation_times_json = CharField ( required = False , widget = forms . HiddenInput , ) sms_conversation_length = ChoiceField ( required = False , label = ugettext_noop ( \"\" ) , choices = SMS_CONVERSATION_LENGTH_CHOICES , ) survey_traffic_option = ChoiceField ( required = False , label = ugettext_noop ( \"\" ) , choices = ( ( SHOW_ALL , ugettext_noop ( \"\" ) ) , ( SHOW_INVALID , ugettext_noop ( \"\" \"\" ) ) , ( HIDE_ALL , ugettext_noop ( \"\" ) ) , ) , ) count_messages_as_read_by_anyone = ChoiceField ( required = False , label = ugettext_noop ( \"\" ) , choices = ( ( ENABLED , ugettext_noop ( \"\" ) ) , ( DISABLED , ugettext_noop ( \"\" ) ) , ) , ) use_custom_chat_template = ChoiceField ( required = False , choices = DEFAULT_CUSTOM_CHOICES , ) custom_chat_template = TrimmedCharField ( required = False , label = ugettext_noop ( \"\" ) , ) sms_case_registration_enabled = ChoiceField ( required = False , choices = ENABLED_DISABLED_CHOICES , label = ugettext_noop ( \"\" ) , ) sms_case_registration_type = TrimmedCharField ( required = False , label = ugettext_noop ( \"\" ) , ) sms_case_registration_owner_id = ChoiceField ( required = False , label = ugettext_noop ( \"\" ) , ) sms_case_registration_user_id = ChoiceField ( required = False , label = ugettext_noop ( \"\" ) , ) sms_mobile_worker_registration_enabled = ChoiceField ( required = False , choices = ENABLED_DISABLED_CHOICES , label = ugettext_noop ( \"\" ) , ) registration_welcome_message = ChoiceField ( choices = WELCOME_RECIPIENT_CHOICES , label = ugettext_lazy ( \"\" ) , ) @ property def section_general ( self ) : fields = [ hqcrispy . B3MultiField ( _ ( \"\" ) , crispy . Div ( InlineField ( \"\" , data_bind = \"\" , ) , css_class = '' ) , crispy . Div ( InlineField ( \"\" , css_class = \"\" , placeholder = _ ( \"\" ) , data_bind = \"\" , ) , css_class = '' ) , help_bubble_text = _ ( \"\" \"\" \"\" ) , css_id = \"\" , field_class = '' ) , FieldWithHelpBubble ( \"\" , data_bind = \"\" , help_bubble_text = _ ( \"\" \"\" \"\" \"\" ) , ) , hqcrispy . B3MultiField ( \"\" , HiddenFieldWithErrors ( \"\" , data_bind = \"\" ) , crispy . Div ( data_bind = \"\" \"\" \"\" \"\" , ) , data_bind = \"\" , field_class = '' ) , FieldWithHelpBubble ( \"\" , help_bubble_text = _ ( \"\" \"\" \"\" \"\" \"\" ) , ) , ] return crispy . Fieldset ( _ ( \"\" ) , * fields ) @ property def section_registration ( self ) : fields = [ FieldWithHelpBubble ( \"\" , help_bubble_text = _ ( \"\" \"\" \"\" \"\" \"\" ) , data_bind = \"\" , ) , crispy . Div ( FieldWithHelpBubble ( \"\" , placeholder = _ ( \"\" ) , help_bubble_text = _ ( \"\" \"\" ) , ) , FieldWithHelpBubble ( \"\" , help_bubble_text = _ ( \"\" \"\" ) , ) , FieldWithHelpBubble ( \"\" , help_bubble_text = _ ( \"\" \"\" ) , ) , data_bind = \"\" , ) , FieldWithHelpBubble ( \"\" , help_bubble_text = _ ( \"\" \"\" \"\" \"\" \"\" ) , ) , FieldWithHelpBubble ( '' , help_bubble_text = _ ( \"\" \"\" \"\" \"\" \"\" ) , ) , ] return crispy . Fieldset ( _ ( \"\" ) , * fields ) @ property def section_chat ( self ) : fields = [ hqcrispy . B3MultiField ( _ ( \"\" ) , crispy . Div ( InlineField ( \"\" , data_bind = \"\" , ) , css_class = '' ) , crispy . Div ( InlineField ( \"\" , css_class = \"\" , data_bind = \"\" , ) , css_class = '' ) , help_bubble_text = _ ( \"\" \"\" \"\" \"\" ) , css_id = \"\" , field_class = '' ) , hqcrispy . B3MultiField ( _ ( \"\" ) , crispy . Div ( InlineField ( \"\" , data_bind = \"\" , ) , css_class = '' ) , crispy . Div ( InlineField ( \"\" , css_class = \"\" , data_bind = \"\" , ) , css_class = '' ) , help_bubble_text = _ ( \"\" \"\" \"\" \"\" \"\" ) , css_id = \"\" , field_class = '' ) , FieldWithHelpBubble ( \"\" , data_bind = \"\" , help_bubble_text = _ ( \"\" \"\" \"\" ) , ) , hqcrispy . B3MultiField ( \"\" , HiddenFieldWithErrors ( \"\" , data_bind = \"\" ) , crispy . Div ( data_bind = \"\" \"\" \"\" \"\" , ) , data_bind = \"\" , label_class = '' , field_class = '' ) , crispy . Div ( FieldWithHelpBubble ( \"\" , help_bubble_text = _ ( \"\" \"\" \"\" \"\" ) , ) , data_bind = \"\" , ) , FieldWithHelpBubble ( \"\" , help_bubble_text = _ ( \"\" \"\" \"\" \"\" \"\" ) , ) , FieldWithHelpBubble ( \"\" , help_bubble_text = _ ( \"\" \"\" \"\" \"\" \"\" ) , ) , ] if self . _cchq_is_previewer : fields . append ( hqcrispy . B3MultiField ( _ ( \"\" ) , crispy . Div ( InlineField ( \"\" , data_bind = \"\" , ) , css_class = '' ) , crispy . Div ( InlineField ( \"\" , data_bind = \"\" , ) , css_class = '' ) , help_bubble_text = _ ( \"\" \"\" ) , css_id = \"\" , field_class = '' ) ) return crispy . Fieldset ( _ ( \"\" ) , * fields ) def __init__ ( self , data = None , cchq_domain = None , cchq_is_previewer = False , * args , ** kwargs ) : self . _cchq_domain = cchq_domain self . _cchq_is_previewer = cchq_is_previewer super ( SettingsForm , self ) . __init__ ( data , * args , ** kwargs ) self . populate_dynamic_choices ( ) self . helper = FormHelper ( ) self . helper . form_class = \"\" self . helper . label_class = '' self . helper . field_class = '' self . helper . layout = crispy . Layout ( self . section_general , self . section_registration , self . section_chat , hqcrispy . FormActions ( twbscrispy . StrictButton ( _ ( \"\" ) , type = \"\" , css_class = \"\" , ) , ) , ) self . restricted_sms_times_widget_context = { \"\" : \"\" , \"\" : _ ( \"\" ) , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } self . sms_conversation_times_widget_context = { \"\" : \"\" , \"\" : _ ( \"\" \"\" \"\" ) , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } @ property def enable_registration_welcome_sms_for_case ( self ) : return ( self . cleaned_data . get ( '' ) in ( WELCOME_RECIPIENT_CASE , WELCOME_RECIPIENT_ALL ) ) @ property def enable_registration_welcome_sms_for_mobile_worker ( self ) : return ( self . cleaned_data . get ( '' ) in ( WELCOME_RECIPIENT_MOBILE_WORKER , WELCOME_RECIPIENT_ALL ) ) @ property def current_values ( self ) : current_values = { } for field_name in self . fields . keys ( ) : value = self [ field_name ] . value ( ) if field_name in [ \"\" , \"\" ] : if isinstance ( value , basestring ) : current_values [ field_name ] = json . loads ( value ) else : current_values [ field_name ] = value else : current_values [ field_name ] = value return current_values def populate_dynamic_choices ( self ) : groups = Group . get_case_sharing_groups ( self . _cchq_domain ) users = CommCareUser . by_domain ( self . _cchq_domain ) domain_group_choices = [ ( group . _id , group . name ) for group in groups ] domain_user_choices = [ ( user . _id , user . raw_username ) for user in users ] domain_owner_choices = domain_group_choices + domain_user_choices choose = [ ( \"\" , _ ( \"\" ) ) ] self . fields [ \"\" ] . choices = ( choose + domain_owner_choices ) self . fields [ \"\" ] . choices = ( choose + domain_user_choices ) def _clean_dependent_field ( self , bool_field , field ) : if self . cleaned_data . get ( bool_field ) : value = self . cleaned_data . get ( field , None ) if not value : raise ValidationError ( _ ( \"\" ) ) return value else : return None def clean_use_default_sms_response ( self ) : return self . cleaned_data . get ( \"\" ) == ENABLED def clean_default_sms_response ( self ) : return self . _clean_dependent_field ( \"\" , \"\" ) def clean_use_custom_case_username ( self ) : return self . cleaned_data . get ( \"\" ) == CUSTOM def clean_custom_case_username ( self ) : return self . _clean_dependent_field ( \"\" , \"\" ) def clean_use_custom_message_count_threshold ( self ) : return ( self . cleaned_data . get ( \"\" ) == CUSTOM ) def clean_custom_message_count_threshold ( self ) : value = self . _clean_dependent_field ( \"\" , \"\" ) if value is not None and value <= : raise ValidationError ( _ ( \"\" ) ) return value def clean_use_custom_chat_template ( self ) : if not self . _cchq_is_previewer : return None return self . cleaned_data . get ( \"\" ) == CUSTOM def clean_custom_chat_template ( self ) : if not self . _cchq_is_previewer : return None value = self . _clean_dependent_field ( \"\" , \"\" ) if value is not None and value not in settings . CUSTOM_CHAT_TEMPLATES : raise ValidationError ( _ ( \"\" ) ) return value def _clean_time_window_json ( self , field_name ) : try : time_window_json = json . loads ( self . cleaned_data . get ( field_name ) ) except ValueError : raise ValidationError ( _ ( \"\" \"\" ) ) result = [ ] for window in time_window_json : day = window . get ( \"\" ) start_time = window . get ( \"\" ) end_time = window . get ( \"\" ) time_input_relationship = window . get ( \"\" ) try : day = int ( day ) assert day >= - and day <= except ( ValueError , AssertionError ) : raise ValidationError ( _ ( \"\" ) ) if time_input_relationship == TIME_BEFORE : end_time = validate_time ( end_time ) result . append ( DayTimeWindow ( day = day , start_time = None , end_time = end_time , ) ) elif time_input_relationship == TIME_AFTER : start_time = validate_time ( start_time ) result . append ( DayTimeWindow ( day = day , start_time = start_time , end_time = None , ) ) else : ", "answer": "start_time = validate_time ( start_time )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from __future__ import division , print_function , unicode_literals from sacred . utils import iter_prefixes , join_paths class ConfigSummary ( dict ) : ", "answer": "def __init__ ( self , added = ( ) , modified = ( ) , typechanged = ( ) ,"}, {"prompt": " import sys , rospy , tf , actionlib , moveit_commander from geometry_msgs . msg import * from move_base_msgs . msg import MoveBaseAction , MoveBaseGoal from tf . transformations import quaternion_from_euler from control_msgs . msg import ( GripperCommandAction , GripperCommandGoal ) if __name__ == '' : moveit_commander . roscpp_initialize ( sys . argv ) rospy . init_node ( '' ) args = rospy . myargv ( argv = sys . argv ) gripper = actionlib . SimpleActionClient ( \"\" , GripperCommandAction ) gripper . wait_for_server ( ) move_base = actionlib . SimpleActionClient ( '' , MoveBaseAction ) move_base . wait_for_server ( ) goal = MoveBaseGoal ( ) goal . target_pose . header . frame_id = '' goal . target_pose . pose . position . x = orient = Quaternion ( * quaternion_from_euler ( , , ) ) goal . target_pose . pose . orientation = orient move_base . send_goal ( goal ) move_base . wait_for_result ( ) arm = moveit_commander . MoveGroupCommander ( \"\" ) arm . allow_replanning ( True ) p = Pose ( ) p . position . x = ", "answer": "p . position . z = "}, {"prompt": " '''''' from math import sqrt def z_score ( rule ) : return sqrt ( rule . coverage ) * ( rule . mean - rule . kb . mean ) / rule . kb . sd def t_score ( rule ) : return sqrt ( rule . coverage ) * ( rule . mean - rule . kb . mean ) / rule . sd def enrichment_score ( rule ) : if rule . coverage == rule . kb . n_examples ( ) : return if rule . coverage == : return - / float ( rule . kb . n_examples ( ) ) increment = { } incr1 = / float ( rule . coverage ) incr2 = / float ( rule . kb . n_examples ( ) - rule . coverage ) max_diff = for ex in rule . kb . examples : increment [ ex ] = - incr2 for ex in rule . examples ( ) : increment [ ex ] = incr1 partial = for ex in rule . kb . examples : partial += increment [ ex ] if partial > max_diff : max_diff = partial return max_diff def wracc ( rule ) : nX = rule . coverage N = len ( rule . kb . examples ) nXY = rule . distribution [ rule . target ] nY = rule . kb . distribution [ rule . target ] if nX : return nX / float ( N ) * ( nXY / float ( nX ) - nY / float ( N ) ) else : return def precision ( rule ) : nX = rule . coverage nXY = rule . distribution [ rule . target ] if nX : return nXY / float ( nX ) else : return def chisq ( rule ) : N = len ( rule . kb . examples ) z = rule . distribution [ rule . target ] / float ( N ) x = rule . coverage / float ( N ) y = rule . kb . distribution [ rule . target ] / float ( N ) if x not in [ , ] and y not in [ , ] : return N * ( z - x * y ) ** / float ( x * y * ( - x ) * ( - y ) ) else : return def lift ( rule ) : nX = float ( rule . coverage ) N = float ( len ( rule . kb . examples ) ) nXY = rule . distribution [ rule . target ] nY = rule . kb . distribution [ rule . target ] if nX != and N != : return ( nXY / nX ) / ( nY / N ) else : return def leverage ( rule ) : nX = float ( rule . coverage ) N = float ( len ( rule . kb . examples ) ) nXY = rule . distribution [ rule . target ] ", "answer": "nY = rule . kb . distribution [ rule . target ]"}, {"prompt": " from fuel . datasets import H5PYDataset from fuel . transformers . defaults import uint8_pixels_to_floatX from fuel . utils import find_in_data_path class SVHN ( H5PYDataset ) : \"\"\"\"\"\" _filename = '' default_transformers = uint8_pixels_to_floatX ( ( '' , ) ) def __init__ ( self , which_format , which_sets , ** kwargs ) : self . which_format = which_format super ( SVHN , self ) . __init__ ( file_or_path = find_in_data_path ( self . filename ) , which_sets = which_sets , ** kwargs ) ", "answer": "@ property"}, {"prompt": " from __future__ import with_statement import unittest import time import datetime import pwd import grp import os import IECore import Gaffer import GafferTest class FileSystemPathTest ( GafferTest . TestCase ) : def test ( self ) : p = Gaffer . FileSystemPath ( __file__ ) self . assert_ ( p . isValid ( ) ) self . assert_ ( p . isLeaf ( ) ) while len ( p ) : del p [ - ] self . assert_ ( p . isValid ( ) ) self . assert_ ( not p . isLeaf ( ) ) def testIsLeaf ( self ) : path = Gaffer . FileSystemPath ( \"\" ) self . assert_ ( not path . isLeaf ( ) ) def testConstructWithFilter ( self ) : p = Gaffer . FileSystemPath ( __file__ ) self . failUnless ( p . getFilter ( ) is None ) f = Gaffer . FileNamePathFilter ( [ \"\" ] ) p = Gaffer . FileSystemPath ( __file__ , filter = f ) self . failUnless ( p . getFilter ( ) . isSame ( f ) ) def testBrokenSymbolicLinks ( self ) : os . symlink ( self . temporaryDirectory ( ) + \"\" , self . temporaryDirectory ( ) + \"\" ) d = Gaffer . FileSystemPath ( self . temporaryDirectory ( ) ) c = d . children ( ) self . assertEqual ( len ( c ) , ) l = c [ ] self . assertEqual ( str ( l ) , self . temporaryDirectory ( ) + \"\" ) self . assertEqual ( l . isValid ( ) , True ) info = l . info ( ) self . failUnless ( info is not None ) def testSymLinkInfo ( self ) : with open ( self . temporaryDirectory ( ) + \"\" , \"\" ) as f : f . write ( \"\" ) os . symlink ( self . temporaryDirectory ( ) + \"\" , self . temporaryDirectory ( ) + \"\" ) a = Gaffer . FileSystemPath ( self . temporaryDirectory ( ) + \"\" ) l = Gaffer . FileSystemPath ( self . temporaryDirectory ( ) + \"\" ) aInfo = a . info ( ) self . assertEqual ( aInfo [ \"\" ] , l . info ( ) [ \"\" ] ) os . remove ( str ( a ) ) self . assertNotEqual ( aInfo [ \"\" ] , l . info ( ) [ \"\" ] ) def testCopy ( self ) : p = Gaffer . FileSystemPath ( self . temporaryDirectory ( ) ) p2 = p . copy ( ) self . assertEqual ( p , p2 ) self . assertEqual ( str ( p ) , str ( p2 ) ) def testEmptyPath ( self ) : p = Gaffer . FileSystemPath ( ) self . assertEqual ( str ( p ) , \"\" ) self . assertTrue ( p . isEmpty ( ) ) self . assertFalse ( p . isValid ( ) ) def testRelativePath ( self ) : os . chdir ( self . temporaryDirectory ( ) ) with open ( self . temporaryDirectory ( ) + \"\" , \"\" ) as f : f . write ( \"\" ) p = Gaffer . FileSystemPath ( \"\" ) self . assertEqual ( str ( p ) , \"\" ) self . assertFalse ( p . isEmpty ( ) ) self . assertTrue ( p . isValid ( ) ) p2 = Gaffer . FileSystemPath ( \"\" ) self . assertEqual ( str ( p2 ) , \"\" ) self . assertFalse ( p2 . isEmpty ( ) ) self . assertFalse ( p2 . isValid ( ) ) def testRelativePathChildren ( self ) : os . chdir ( self . temporaryDirectory ( ) ) os . mkdir ( \"\" ) with open ( self . temporaryDirectory ( ) + \"\" , \"\" ) as f : f . write ( \"\" ) p = Gaffer . FileSystemPath ( \"\" ) ", "answer": "c = p . children ( )"}, {"prompt": " \"\"\"\"\"\" import logging from copy import copy from homeassistant . components . media_player import ( ATTR_APP_ID , ATTR_APP_NAME , ATTR_MEDIA_ALBUM_ARTIST , ATTR_MEDIA_ALBUM_NAME , ATTR_MEDIA_ARTIST , ATTR_MEDIA_CHANNEL , ATTR_MEDIA_CONTENT_ID , ATTR_MEDIA_CONTENT_TYPE , ATTR_MEDIA_DURATION , ATTR_MEDIA_EPISODE , ATTR_MEDIA_PLAYLIST , ATTR_MEDIA_SEASON , ATTR_MEDIA_SEEK_POSITION , ATTR_MEDIA_SERIES_TITLE , ATTR_MEDIA_TITLE , ATTR_MEDIA_TRACK , ATTR_MEDIA_VOLUME_LEVEL , ATTR_MEDIA_VOLUME_MUTED , ATTR_SUPPORTED_MEDIA_COMMANDS , DOMAIN , SERVICE_PLAY_MEDIA , SUPPORT_TURN_OFF , SUPPORT_TURN_ON , SUPPORT_VOLUME_MUTE , SUPPORT_VOLUME_SET , SUPPORT_VOLUME_STEP , SUPPORT_SELECT_SOURCE , ATTR_INPUT_SOURCE , SERVICE_SELECT_SOURCE , MediaPlayerDevice ) from homeassistant . const import ( ATTR_ENTITY_ID , ATTR_ENTITY_PICTURE , CONF_NAME , SERVICE_MEDIA_NEXT_TRACK , SERVICE_MEDIA_PAUSE , SERVICE_MEDIA_PLAY , SERVICE_MEDIA_PLAY_PAUSE , SERVICE_MEDIA_PREVIOUS_TRACK , SERVICE_MEDIA_SEEK , SERVICE_TURN_OFF , SERVICE_TURN_ON , SERVICE_VOLUME_DOWN , SERVICE_VOLUME_MUTE , SERVICE_VOLUME_SET , SERVICE_VOLUME_UP , STATE_IDLE , STATE_OFF , STATE_ON ) from homeassistant . helpers . event import track_state_change from homeassistant . helpers . service import call_from_config ATTR_ACTIVE_CHILD = '' CONF_ATTRS = '' CONF_CHILDREN = '' CONF_COMMANDS = '' CONF_PLATFORM = '' CONF_SERVICE = '' CONF_SERVICE_DATA = '' CONF_STATE = '' OFF_STATES = [ STATE_IDLE , STATE_OFF ] REQUIREMENTS = [ ] _LOGGER = logging . getLogger ( __name__ ) def setup_platform ( hass , config , add_devices , discovery_info = None ) : \"\"\"\"\"\" if not validate_config ( config ) : return player = UniversalMediaPlayer ( hass , config [ CONF_NAME ] , config [ CONF_CHILDREN ] , config [ CONF_COMMANDS ] , config [ CONF_ATTRS ] ) add_devices ( [ player ] ) def validate_config ( config ) : \"\"\"\"\"\" del config [ CONF_PLATFORM ] if CONF_NAME not in config : _LOGGER . error ( '' ) return False validate_children ( config ) validate_commands ( config ) validate_attributes ( config ) del_keys = [ ] for key in config : if key not in [ CONF_NAME , CONF_CHILDREN , CONF_COMMANDS , CONF_ATTRS ] : _LOGGER . warning ( '' , config [ CONF_NAME ] , key ) del_keys . append ( key ) for key in del_keys : del config [ key ] return True def validate_children ( config ) : \"\"\"\"\"\" if CONF_CHILDREN not in config : _LOGGER . info ( '' , config [ CONF_NAME ] ) config [ CONF_CHILDREN ] = [ ] elif not isinstance ( config [ CONF_CHILDREN ] , list ) : _LOGGER . warning ( '' '' , config [ CONF_NAME ] ) config [ CONF_CHILDREN ] = [ ] def validate_commands ( config ) : \"\"\"\"\"\" if CONF_COMMANDS not in config : config [ CONF_COMMANDS ] = { } elif not isinstance ( config [ CONF_COMMANDS ] , dict ) : _LOGGER . warning ( '' '' , config [ CONF_NAME ] ) config [ CONF_COMMANDS ] = { } def validate_attributes ( config ) : \"\"\"\"\"\" if CONF_ATTRS not in config : config [ CONF_ATTRS ] = { } elif not isinstance ( config [ CONF_ATTRS ] , dict ) : _LOGGER . warning ( '' '' , config [ CONF_NAME ] ) config [ CONF_ATTRS ] = { } for key , val in config [ CONF_ATTRS ] . items ( ) : attr = val . split ( '' , ) if len ( attr ) == : attr . append ( None ) config [ CONF_ATTRS ] [ key ] = attr class UniversalMediaPlayer ( MediaPlayerDevice ) : \"\"\"\"\"\" def __init__ ( self , hass , name , children , commands , attributes ) : \"\"\"\"\"\" self . hass = hass self . _name = name self . _children = children self . _cmds = commands self . _attrs = attributes self . _child_state = None def on_dependency_update ( * _ ) : \"\"\"\"\"\" self . update_ha_state ( True ) depend = copy ( children ) for entity in attributes . values ( ) : depend . append ( entity [ ] ) track_state_change ( hass , depend , on_dependency_update ) def _entity_lkp ( self , entity_id , state_attr = None ) : \"\"\"\"\"\" state_obj = self . hass . states . get ( entity_id ) if state_obj is None : return if state_attr : return state_obj . attributes . get ( state_attr ) return state_obj . state def _override_or_child_attr ( self , attr_name ) : \"\"\"\"\"\" if attr_name in self . _attrs : return self . _entity_lkp ( self . _attrs [ attr_name ] [ ] , self . _attrs [ attr_name ] [ ] ) return self . _child_attr ( attr_name ) def _child_attr ( self , attr_name ) : \"\"\"\"\"\" active_child = self . _child_state return active_child . attributes . get ( attr_name ) if active_child else None def _call_service ( self , service_name , service_data = None , allow_override = False ) : \"\"\"\"\"\" if allow_override and service_name in self . _cmds : call_from_config ( self . hass , self . _cmds [ service_name ] , blocking = True ) return if service_data is None : service_data = { } active_child = self . _child_state service_data [ ATTR_ENTITY_ID ] = active_child . entity_id self . hass . services . call ( DOMAIN , service_name , service_data , blocking = True ) @ property def should_poll ( self ) : \"\"\"\"\"\" return False @ property def master_state ( self ) : \"\"\"\"\"\" if CONF_STATE in self . _attrs : master_state = self . _entity_lkp ( self . _attrs [ CONF_STATE ] [ ] , self . _attrs [ CONF_STATE ] [ ] ) return master_state if master_state else STATE_OFF else : return None @ property def name ( self ) : \"\"\"\"\"\" return self . _name @ property def state ( self ) : \"\"\"\"\"\" master_state = self . master_state if master_state == STATE_OFF : return STATE_OFF active_child = self . _child_state if active_child : return active_child . state return master_state if master_state else STATE_OFF @ property def volume_level ( self ) : \"\"\"\"\"\" return self . _child_attr ( ATTR_MEDIA_VOLUME_LEVEL ) @ property def is_volume_muted ( self ) : \"\"\"\"\"\" return self . _override_or_child_attr ( ATTR_MEDIA_VOLUME_MUTED ) in [ True , STATE_ON ] @ property def media_content_id ( self ) : \"\"\"\"\"\" return self . _child_attr ( ATTR_MEDIA_CONTENT_ID ) @ property def media_content_type ( self ) : \"\"\"\"\"\" return self . _child_attr ( ATTR_MEDIA_CONTENT_TYPE ) @ property def media_duration ( self ) : \"\"\"\"\"\" return self . _child_attr ( ATTR_MEDIA_DURATION ) @ property def media_image_url ( self ) : \"\"\"\"\"\" return self . _child_attr ( ATTR_ENTITY_PICTURE ) @ property def media_title ( self ) : \"\"\"\"\"\" return self . _child_attr ( ATTR_MEDIA_TITLE ) @ property def media_artist ( self ) : \"\"\"\"\"\" return self . _child_attr ( ATTR_MEDIA_ARTIST ) @ property def media_album_name ( self ) : \"\"\"\"\"\" return self . _child_attr ( ATTR_MEDIA_ALBUM_NAME ) @ property def media_album_artist ( self ) : \"\"\"\"\"\" return self . _child_attr ( ATTR_MEDIA_ALBUM_ARTIST ) @ property def media_track ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from cafe . drivers . unittest . decorators import ( DataDrivenFixture , data_driven_test ) from cloudcafe . blockstorage . datasets import BlockstorageDatasets from cloudroast . blockstorage . volumes_api . integration . oscli . fixtures import ( CinderCLI_IntegrationFixture ) @ DataDrivenFixture class CinderCLI_VolumeSmoke ( CinderCLI_IntegrationFixture ) : @ data_driven_test ( BlockstorageDatasets . volume_types ( ) ) def ddtest_create_minimum_sized_volume ( self , volume_type_name , volume_type_id ) : size = self . volumes . behaviors . get_configured_volume_type_property ( \"\" , id_ = volume_type_id , name = volume_type_name ) name = self . random_volume_name ( ) resp = self . cinder . client . create ( size = size , volume_type = volume_type_id , display_name = name ) self . assertIsNotNone ( resp . entity , '' ) self . assertEquals ( resp . return_code , , \"\" ) volume = resp . entity self . addCleanup ( self . cinder . client . delete , volume . id_ ) self . assertEqual ( int ( size ) , int ( volume . size ) , \"\" ) self . assertEqual ( name , volume . display_name , \"\" ) @ data_driven_test ( BlockstorageDatasets . volume_types ( ) ) def ddtest_delete_volume_by_id ( self , volume_type_name , volume_type_id ) : size = self . volumes . behaviors . get_configured_volume_type_property ( \"\" , id_ = volume_type_id , name = volume_type_name ) volume = self . volumes . behaviors . create_available_volume ( size = size , volume_type = volume_type_id ) resp = self . cinder . client . delete ( volume . id_ ) self . assertEquals ( len ( resp . standard_out ) , , \"\" ) self . addCleanup ( self . cinder . client . delete , volume . id_ ) self . assertTrue ( self . volumes . behaviors . delete_volume_confirmed ( volume . id_ , size , ) , \"\" . format ( volume . id_ ) ) @ data_driven_test ( BlockstorageDatasets . volume_types ( ) ) def ddtest_delete_volume_by_name ( self , volume_type_name , volume_type_id ) : size = self . volumes . behaviors . get_configured_volume_type_property ( \"\" , id_ = volume_type_id , name = volume_type_name ) volume = self . volumes . behaviors . create_available_volume ( size = size , volume_type = volume_type_id , name = self . random_volume_name ( ) ) resp = self . cinder . client . delete ( volume . name ) self . assertEquals ( len ( resp . standard_out ) , , \"\" ) self . addCleanup ( self . cinder . client . delete , volume . id_ ) self . assertTrue ( ", "answer": "self . volumes . behaviors . delete_volume_confirmed ( volume . name , size ) ,"}, {"prompt": " \"\"\"\"\"\" import datetime import logging import unittest import ast from bson . objectid import ObjectId import tornado . testing import motor import twcommon . misc import two . execute import two . symbols import two . task from two . execute import EvalPropContext from twcommon . excepts import SymbolError import twest . mock from twest . mock import NotFound class TestEvalAsync ( twest . mock . MockAppTestCase ) : mockappargs = { '' : True , '' : True } @ tornado . gen . coroutine def resetTables ( self ) : self . exuid = ObjectId ( ) self . exwid = ObjectId ( ) self . exiid = ObjectId ( ) self . exlocid = ObjectId ( ) self . exscid = ObjectId ( ) self . loctx = two . task . LocContext ( uid = self . exuid , wid = self . exwid , scid = self . exscid , iid = self . exiid , locid = self . exlocid ) yield motor . Op ( self . app . mongodb . worldprop . remove , { } ) yield motor . Op ( self . app . mongodb . worldprop . insert , { '' : self . exwid , '' : self . exlocid , '' : '' , '' : } ) yield motor . Op ( self . app . mongodb . worldprop . insert , { '' : self . exwid , '' : self . exlocid , '' : '' , '' : '' } ) yield motor . Op ( self . app . mongodb . worldprop . insert , { '' : self . exwid , '' : None , '' : '' , '' : } ) yield motor . Op ( self . app . mongodb . worldprop . insert , { '' : self . exwid , '' : self . exlocid , '' : '' , '' : } ) yield motor . Op ( self . app . mongodb . instanceprop . remove , { } ) yield motor . Op ( self . app . mongodb . instanceprop . insert , { '' : self . exiid , '' : self . exlocid , '' : '' , '' : } ) yield motor . Op ( self . app . mongodb . instanceprop . insert , { '' : self . exiid , '' : self . exlocid , '' : '' , '' : } ) yield motor . Op ( self . app . mongodb . instanceprop . insert , { '' : self . exiid , '' : self . exlocid , '' : '' , '' : [ , , ] } ) yield motor . Op ( self . app . mongodb . instanceprop . insert , { '' : self . exiid , '' : self . exlocid , '' : '' , '' : { '' : , '' : , '' : } } ) yield motor . Op ( self . app . mongodb . instanceprop . insert , { '' : self . exiid , '' : None , '' : '' , '' : } ) yield motor . Op ( self . app . mongodb . instanceprop . insert , { '' : self . exiid , '' : self . exlocid , '' : '' , '' : } ) @ tornado . testing . gen_test def test_global_funcs ( self ) : yield self . resetTables ( ) task = two . task . Task ( self . app , None , , , twcommon . misc . now ( ) ) ctx = EvalPropContext ( task , loctx = self . loctx , level = LEVEL_EXECUTE ) res = yield ctx . eval ( '' , evaltype = EVALTYPE_CODE ) self . assertEqual ( res , ) res = yield ctx . eval ( '' , evaltype = EVALTYPE_CODE ) self . assertEqual ( res , ) res = yield ctx . eval ( '' , evaltype = EVALTYPE_CODE ) self . assertEqual ( res , ) res = yield ctx . eval ( '' , evaltype = EVALTYPE_CODE ) self . assertEqual ( res , ) res = yield ctx . eval ( '' , evaltype = EVALTYPE_CODE ) self . assertEqual ( res , ) res = yield ctx . eval ( '' , evaltype = EVALTYPE_CODE ) self . assertEqual ( res , ) res = yield ctx . eval ( '' , evaltype = EVALTYPE_CODE ) self . assertEqual ( res , ) ", "answer": "res = yield ctx . eval ( '' , evaltype = EVALTYPE_CODE )"}, {"prompt": " \"\"\"\"\"\" import urlparse from urllib import quote as urlquote from twisted . internet import reactor from twisted . internet . protocol import ClientFactory from twisted . web . resource import Resource from twisted . web . server import NOT_DONE_YET from twisted . web . http import HTTPClient , Request , HTTPChannel class ProxyClient ( HTTPClient ) : \"\"\"\"\"\" _finished = False def __init__ ( self , command , rest , version , headers , data , father ) : self . father = father self . command = command self . rest = rest if \"\" in headers : del headers [ \"\" ] headers [ \"\" ] = \"\" headers . pop ( '' , None ) self . headers = headers self . data = data def connectionMade ( self ) : self . sendCommand ( self . command , self . rest ) for header , value in self . headers . items ( ) : self . sendHeader ( header , value ) self . endHeaders ( ) self . transport . write ( self . data ) def handleStatus ( self , version , code , message ) : self . father . setResponseCode ( int ( code ) , message ) def handleHeader ( self , key , value ) : if key . lower ( ) in [ '' , '' , '' ] : self . father . responseHeaders . setRawHeaders ( key , [ value ] ) else : self . father . responseHeaders . addRawHeader ( key , value ) def handleResponsePart ( self , buffer ) : self . father . write ( buffer ) def handleResponseEnd ( self ) : \"\"\"\"\"\" if not self . _finished : self . _finished = True self . father . finish ( ) self . transport . loseConnection ( ) class ProxyClientFactory ( ClientFactory ) : \"\"\"\"\"\" protocol = ProxyClient def __init__ ( self , command , rest , version , headers , data , father ) : self . father = father self . command = command self . rest = rest self . headers = headers self . data = data self . version = version def buildProtocol ( self , addr ) : return self . protocol ( self . command , self . rest , self . version , self . headers , self . data , self . father ) def clientConnectionFailed ( self , connector , reason ) : \"\"\"\"\"\" self . father . setResponseCode ( , \"\" ) self . father . responseHeaders . addRawHeader ( \"\" , \"\" ) self . father . write ( \"\" ) self . father . finish ( ) class ProxyRequest ( Request ) : \"\"\"\"\"\" protocols = { '' : ProxyClientFactory } ports = { '' : } def __init__ ( self , channel , queued , reactor = reactor ) : Request . __init__ ( self , channel , queued ) self . reactor = reactor def process ( self ) : parsed = urlparse . urlparse ( self . uri ) protocol = parsed [ ] host = parsed [ ] port = self . ports [ protocol ] if '' in host : host , port = host . split ( '' ) port = int ( port ) rest = urlparse . urlunparse ( ( '' , '' ) + parsed [ : ] ) if not rest : rest = rest + '' class_ = self . protocols [ protocol ] headers = self . getAllHeaders ( ) . copy ( ) if '' not in headers : headers [ '' ] = host self . content . seek ( , ) s = self . content . read ( ) clientFactory = class_ ( self . method , rest , self . clientproto , headers , s , self ) self . reactor . connectTCP ( host , port , clientFactory ) class Proxy ( HTTPChannel ) : \"\"\"\"\"\" requestFactory = ProxyRequest class ReverseProxyRequest ( Request ) : \"\"\"\"\"\" proxyClientFactoryClass = ProxyClientFactory def __init__ ( self , channel , queued , reactor = reactor ) : Request . __init__ ( self , channel , queued ) self . reactor = reactor def process ( self ) : \"\"\"\"\"\" self . received_headers [ '' ] = self . factory . host clientFactory = self . proxyClientFactoryClass ( self . method , self . uri , self . clientproto , self . getAllHeaders ( ) , self . content . read ( ) , self ) self . reactor . connectTCP ( self . factory . host , self . factory . port , clientFactory ) class ReverseProxy ( HTTPChannel ) : \"\"\"\"\"\" requestFactory = ReverseProxyRequest class ReverseProxyResource ( Resource ) : \"\"\"\"\"\" proxyClientFactoryClass = ProxyClientFactory def __init__ ( self , host , port , path , reactor = reactor ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from pyface . qt import QtGui , QtCore from traits . api import Float , Any , Str , Trait from traitsui . editors . api import RangeEditor from traitsui . qt4 . editor import Editor from traitsui . qt4 . extra . range_slider import RangeSlider class _BoundsEditor ( Editor ) : evaluate = Any min = Any max = Any low = Any high = Any format = Str def init ( self , parent ) : \"\"\"\"\"\" factory = self . factory if not factory . low_name : self . low = factory . low if not factory . high_name : self . high = factory . high self . max = factory . max self . min = factory . min self . format = factory . format self . evaluate = factory . evaluate self . sync_value ( factory . evaluate_name , '' , '' ) self . sync_value ( factory . low_name , '' , '' ) self . sync_value ( factory . high_name , '' , '' ) self . control = QtGui . QWidget ( ) panel = QtGui . QHBoxLayout ( self . control ) panel . setContentsMargins ( , , , ) self . _label_lo = QtGui . QLineEdit ( self . format % self . low ) QtCore . QObject . connect ( self . _label_lo , QtCore . SIGNAL ( '' ) , self . update_low_on_enter ) panel . addWidget ( self . _label_lo ) sh = self . _label_lo . sizeHint ( ) sh . setWidth ( sh . width ( ) / ) self . _label_lo . setMaximumSize ( sh ) self . control . slider = slider = RangeSlider ( QtCore . Qt . Horizontal ) slider . setTracking ( factory . auto_set ) slider . setMinimum ( ) slider . setMaximum ( ) slider . setPageStep ( ) slider . setSingleStep ( ) slider . setLow ( self . _convert_to_slider ( self . low ) ) slider . setHigh ( self . _convert_to_slider ( self . high ) ) QtCore . QObject . connect ( slider , QtCore . SIGNAL ( '' ) , self . update_object_on_scroll ) panel . addWidget ( slider ) self . _label_hi = QtGui . QLineEdit ( self . format % self . high ) QtCore . QObject . connect ( self . _label_hi , QtCore . SIGNAL ( '' ) , self . update_high_on_enter ) panel . addWidget ( self . _label_hi ) sh = self . _label_hi . sizeHint ( ) sh . setWidth ( sh . width ( ) / ) self . _label_hi . setMaximumSize ( sh ) self . set_tooltip ( slider ) self . set_tooltip ( self . _label_lo ) self . set_tooltip ( self . _label_hi ) def update_low_on_enter ( self ) : try : try : low = eval ( unicode ( self . _label_lo . text ( ) ) . strip ( ) ) if self . evaluate is not None : low = self . evaluate ( low ) except Exception as ex : low = self . low self . _label_lo . setText ( self . format % self . low ) if not self . factory . is_float : low = int ( low ) if low > self . high : low = self . high - self . _step_size ( ) self . _label_lo . setText ( self . format % low ) self . control . slider . setLow ( self . _convert_to_slider ( low ) ) self . low = low except : pass def update_high_on_enter ( self ) : try : try : high = eval ( unicode ( self . _label_hi . text ( ) ) . strip ( ) ) if self . evaluate is not None : high = self . evaluate ( high ) except : high = self . high self . _label_hi . setText ( self . format % self . high ) if not self . factory . is_float : high = int ( high ) if high < self . low : high = self . low + self . _step_size ( ) self . _label_hi . setText ( self . format % high ) self . control . slider . setHigh ( self . _convert_to_slider ( high ) ) self . high = high except : pass def update_object_on_scroll ( self , pos ) : low = self . _convert_from_slider ( self . control . slider . low ( ) ) high = self . _convert_from_slider ( self . control . slider . high ( ) ) if self . factory . is_float : self . low = low self . high = high else : self . low = int ( low ) self . high = int ( high ) self . control . slider . setLow ( self . _convert_to_slider ( low ) ) self . control . slider . setHigh ( self . _convert_to_slider ( high ) ) def update_editor ( self ) : return def _check_max_and_min ( self ) : if self . max is None : self . max = self . high if self . min is None : self . min = self . low def _step_size ( self ) : slider_delta = self . control . slider . maximum ( ) - self . control . slider . minimum ( ) range_delta = self . max - self . min return float ( range_delta ) / slider_delta def _convert_from_slider ( self , slider_val ) : self . _check_max_and_min ( ) return self . min + slider_val * self . _step_size ( ) def _convert_to_slider ( self , value ) : self . _check_max_and_min ( ) return self . control . slider . minimum ( ) + ( value - self . min ) / self . _step_size ( ) def _low_changed ( self , low ) : if self . control is None : return if self . _label_lo is not None : self . _label_lo . setText ( self . format % low ) self . control . slider . setLow ( self . _convert_to_slider ( low ) ) def _high_changed ( self , high ) : if self . control is None : return ", "answer": "if self . _label_hi is not None :"}, {"prompt": " from kalapy import db ", "answer": "class Foo ( db . Model ) :"}, {"prompt": " from __future__ import absolute_import , print_function , division import unittest from six . moves import xrange import theano from theano . tensor import * from theano . tests import unittest_tools as utt from numpy . testing import dec class TestRealImag ( unittest . TestCase ) : def test0 ( self ) : x = zvector ( ) rng = numpy . random . RandomState ( ) xval = numpy . asarray ( list ( numpy . complex ( rng . randn ( ) , rng . randn ( ) ) for i in xrange ( ) ) ) assert numpy . all ( xval . real == theano . function ( [ x ] , real ( x ) ) ( xval ) ) assert numpy . all ( xval . imag == theano . function ( [ x ] , imag ( x ) ) ( xval ) ) def test_on_real_input ( self ) : x = dvector ( ) rng = numpy . random . RandomState ( ) xval = rng . randn ( ) numpy . all ( == theano . function ( [ x ] , imag ( x ) ) ( xval ) ) numpy . all ( xval == theano . function ( [ x ] , real ( x ) ) ( xval ) ) x = imatrix ( ) xval = numpy . asarray ( rng . randn ( , ) * , dtype = '' ) numpy . all ( == theano . function ( [ x ] , imag ( x ) ) ( xval ) ) numpy . all ( xval == theano . function ( [ x ] , real ( x ) ) ( xval ) ) def test_cast ( self ) : x = zvector ( ) self . assertRaises ( TypeError , cast , x , '' ) def test_complex ( self ) : rng = numpy . random . RandomState ( ) m = fmatrix ( ) c = complex ( m [ ] , m [ ] ) assert c . type == cvector r , i = [ real ( c ) , imag ( c ) ] assert r . type == fvector assert i . type == fvector f = theano . function ( [ m ] , [ r , i ] ) mval = numpy . asarray ( rng . randn ( , ) , dtype = '' ) rval , ival = f ( mval ) ", "answer": "assert numpy . all ( rval == mval [ ] ) , ( rval , mval [ ] )"}, {"prompt": " \"\"\"\"\"\" import unittest from dfvfs . resolver import bde_resolver_helper from tests . resolver import test_lib class BDEResolverHelperTest ( test_lib . ResolverHelperTestCase ) : \"\"\"\"\"\" def testNewFileObject ( self ) : \"\"\"\"\"\" resolver_helper_object = bde_resolver_helper . BDEResolverHelper ( ) self . _TestNewFileObject ( resolver_helper_object ) def testNewFileSystem ( self ) : \"\"\"\"\"\" ", "answer": "resolver_helper_object = bde_resolver_helper . BDEResolverHelper ( )"}, {"prompt": " import json import hmac import hashlib from django . http import HttpResponse import django . contrib . auth as djangoAuth from django . core . context_processors import csrf from django . shortcuts import render_to_response from django . views . decorators . csrf import ( csrf_exempt , csrf_protect , ensure_csrf_cookie ) import sys sys . path . append ( \"\" ) import crudAPI import httpStatusCodes import auth . models as authModels import auth . authConstants as authConstants hashAlgoMemoizer = { } def __getHashDigest ( obj , hashAlgoName = '' ) : if not obj : return httpStatusCodes . BAD_REQUEST , None hashAlgo = hashAlgoMemoizer . get ( hashAlgoName , None ) if not hashAlgo : hashAlgo = getattr ( hashlib , hashAlgoName , None ) if not hashAlgo : return httpStatusCodes . METHOD_NOT_ALLOWED , None hashAlgoMemoizer [ hashAlgoName ] = hashAlgo if not isinstance ( obj , bytes ) : if not hasattr ( obj , '' ) : return httpStatusCodes . METHOD_NOT_ALLOWED , None obj = crudAPI . byteFy ( str ( obj ) ) return httpStatusCodes . OK , hashAlgo ( obj ) . hexdigest ( ) def _requiredHttpMethodCheck ( request , methodName ) : method = request . method if method != methodName : resp = HttpResponse ( ) resp . status_code = httpStatusCodes . METHOD_NOT_ALLOWED resp . write ( json . dumps ( { '' : '' % ( methodName ) } ) ) return resp def credentialFieldCheck ( credentials , expectedFields = [ '' , '' , '' ] ) : for keyword in expectedFields : retr = credentials . get ( keyword , None ) if not retr : response = HttpResponse ( ) response . write ( json . dumps ( { '' : '' % ( keyword ) } ) ) response . status_code = httpStatusCodes . BAD_REQUEST return response @ csrf_protect @ ensure_csrf_cookie def newUser ( request ) : notMethodCheckResponse = _requiredHttpMethodCheck ( request , '' ) if notMethodCheckResponse : return notMethodCheckResponse status , reqBody = crudAPI . _altParseRequestBody ( request , '' , True ) if status != httpStatusCodes . OK : resp = HttpResponse ( ) resp . status_code = httpStatusCodes . BAD_REQUEST resp . write ( json . dumps ( { '' : '' } ) ) return resp missingCredsResponse = credentialFieldCheck ( reqBody , [ '' , '' ] ) if missingCredsResponse : return missingCredsResponse appAccessId = reqBody [ '' ] appLookUp = authModels . App . objects . filter ( _accessId = appAccessId ) if not appLookUp : response . status_code = httpStatusCodes . NOT_FOUND response . write ( json . dumps ( { '' : '' } ) ) return response djangoUser = djangoAuth . models . User . objects . filter ( username = reqBody [ '' ] ) resp = HttpResponse ( ) if not djangoUser : status , user = createDjangoUser ( reqBody ) if status != httpStatusCodes . OK : resp . status_code = status return resp else : user = djangoUser [ ] authUserQuery = authModels . AuthUser . objects . filter ( djangoUser_id = user . id , app_id = appLookUp [ ] . id ) response = HttpResponse ( ) if authUserQuery : response . status_code = httpStatusCodes . CONFLICT response . write ( json . dumps ( { '' : '' } ) ) else : try : newAuthEntry = authModels . AuthUser ( djangoUser_id = user . id , app_id = appLookUp [ ] . id , meta = reqBody . get ( '' , '' ) ) newAuthEntry . save ( ) except Exception , e : print ( e ) response . status_code = httpStatusCodes . BAD_REQUEST response . write ( json . dumps ( { '' : '' } ) ) else : response . status_code = httpStatusCodes . OK response . write ( json . dumps ( { '' : '' } ) ) return response def createDjangoUser ( userCredentials ) : allowedAttrs = [ '' , '' , '' , '' ] createdB = { } for pickedKey in allowedAttrs : createdB [ pickedKey ] = userCredentials . get ( pickedKey , '' ) createdB [ '' ] = authModels . generateUUID ( ) . hex try : freshUser = djangoAuth . models . User . objects . create_user ( ** createdB ) except Exception , e : return httpStatusCodes . INTERNAL_SERVER_ERROR , e else : return httpStatusCodes . OK , freshUser def checkHMACValidity ( userKey , msg , purportedResponse ) : return hmac . HMAC ( key = userKey , msg = msg , digestmod = hashlib . sha256 ) . hexdigest ( ) == purportedResponse @ csrf_protect @ ensure_csrf_cookie def loginByPassword ( request ) : '''''' notMethodCheckResponse = _requiredHttpMethodCheck ( request , '' ) if notMethodCheckResponse : return notMethodCheckResponse status , bodyParseResponse = crudAPI . _altParseRequestBody ( request , '' ) response = HttpResponse ( ) if status != httpStatusCodes . OK : response . status_code = httpStatusCodes . BAD_REQUEST response . write ( json . dumps ( { '' : '' } ) ) return response credentials = bodyParseResponse missingCredsResponse = credentialFieldCheck ( credentials , [ '' , '' , '' , '' ] ) if missingCredsResponse : return missingCredsResponse appLookUp = authModels . App . objects . filter ( _accessId = credentials [ '' ] ) if not appLookUp : response . status_code = httpStatusCodes . NOT_FOUND response . write ( json . dumps ( { '' : '' } ) ) return response logout ( request ) djangoUser = djangoAuth . authenticate ( username = credentials [ '' ] , password = credentials [ '' ] ) if not djangoUser : response . status_code = httpStatusCodes . FORBIDDEN response . write ( json . dumps ( { '' : '' } ) ) return response headApp = appLookUp [ ] appUser = authModels . AuthUser . objects . filter ( app_id = headApp . id , djangoUser_id = djangoUser . id , _accessId = credentials [ '' ] ) if not appUser : response . status_code = httpStatusCodes . FORBIDDEN response . write ( json . dumps ( { '' : '' } ) ) return response try : djangoAuth . login ( request , djangoUser ) except Exception , e : print ( e ) response . status_code = httpStatusCodes . BAD_REQUEST else : csrf ( request ) response . status_code = httpStatusCodes . OK response . write ( json . dumps ( { '' : '' } ) ) return response @ csrf_protect @ ensure_csrf_cookie def loginBySignature ( request ) : '''''' notMethodCheckResponse = _requiredHttpMethodCheck ( request , '' ) if notMethodCheckResponse : return notMethodCheckResponse status , bodyParseResponse = crudAPI . _altParseRequestBody ( request , '' ) response = HttpResponse ( ) if status != httpStatusCodes . OK : response . status_code = httpStatusCodes . BAD_REQUEST response . write ( json . dumps ( { '' : '' } ) ) return response credentials = bodyParseResponse missingCredsResponse = credentialFieldCheck ( credentials , [ '' , '' , '' ] ) if missingCredsResponse : return missingCredsResponse response = HttpResponse ( ) appLookUp = authModels . App . objects . filter ( _accessId = credentials [ '' ] ) if not appLookUp : response . status_code = httpStatusCodes . NOT_FOUND response . write ( json . dumps ( { '' : '' } ) ) return response userAccessId = credentials [ '' ] userLookUp = authModels . AuthUser . objects . filter ( ", "answer": "app_id = appLookUp [ ] . id , _accessId = userAccessId )"}, {"prompt": " \"\"\"\"\"\" from pyface . api import FileDialog , OK from pyface . action . api import Action from traits . api import Instance , Property , Str class SceneAction ( Action ) : \"\"\"\"\"\" scene_manager = Property ( Instance ( '' ) ) def _get_scene_manager ( self ) : \"\"\"\"\"\" from tvtk . plugins . scene . i_scene_manager import ( ISceneManager ) return self . window . get_service ( ISceneManager ) class NewScene ( Action ) : \"\"\"\"\"\" name = '' def perform ( self , event ) : \"\"\"\"\"\" from tvtk . plugins . scene . scene_editor import SceneEditor editor = self . window . edit ( object ( ) , kind = SceneEditor ) return editor class SaveScene ( SceneAction ) : \"\"\"\"\"\" name = '' def perform ( self , event ) : \"\"\"\"\"\" extensions = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] wildcard = '' . join ( extensions ) dialog = FileDialog ( parent = self . window . control , title = '' , action = '' , wildcard = wildcard ) if dialog . open ( ) == OK : scene = self . scene_manager . current_scene if scene is not None : scene . save ( dialog . path ) return class SaveSceneToImage ( SceneAction ) : \"\"\"\"\"\" ", "answer": "name = ''"}, {"prompt": " \"\"\"\"\"\" import optparse import os import os . path import re import shutil import sys import tempfile import unittest try : import xml . etree . ElementTree as ET except ImportError : import elementtree . ElementTree as ET from ganeti import constants from ganeti import errors from ganeti import ovf from ganeti import utils from ganeti import pathutils import testutils OUTPUT_DIR = \"\" GANETI_DISKS = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } GANETI_NETWORKS = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } GANETI_HYPERVISOR = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } GANETI_OS = { \"\" : \"\" } GANETI_BACKEND = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } GANETI_NAME = \"\" GANETI_TEMPLATE = \"\" GANETI_TAGS = None GANETI_VERSION = \"\" VIRTUALBOX_DISKS = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } VIRTUALBOX_NETWORKS = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } VIRTUALBOX_HYPERVISOR = { \"\" : \"\" } VIRTUALBOX_OS = { \"\" : None } VIRTUALBOX_BACKEND = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } VIRTUALBOX_NAME = None VIRTUALBOX_TEMPLATE = None VIRTUALBOX_TAGS = None VIRTUALBOX_VERSION = None EMPTY_DISKS = { } EMPTY_NETWORKS = { } EMPTY_HYPERVISOR = { \"\" : \"\" } EMPTY_OS = { } EMPTY_BACKEND = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } EMPTY_NAME = None EMPTY_TEMPLATE = None EMPTY_TAGS = None EMPTY_VERSION = None CMDARGS_DISKS = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } CMDARGS_NETWORKS = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } CMDARGS_HYPERVISOR = { \"\" : \"\" } CMDARGS_OS = { \"\" : \"\" } CMDARGS_BACKEND = { \"\" : False , \"\" : \"\" , \"\" : \"\" , } CMDARGS_NAME = \"\" CMDARGS_TEMPLATE = \"\" CMDARGS_TAGS = \"\" ARGS_EMPTY = { \"\" : None , \"\" : [ ] , \"\" : [ ] , \"\" : \"\" , \"\" : False , \"\" : False , \"\" : \"\" , \"\" : False , } ARGS_EXPORT_DIR = dict ( ARGS_EMPTY , ** { \"\" : OUTPUT_DIR , \"\" : None , \"\" : None , \"\" : None , \"\" : { } , \"\" : False , \"\" : None , \"\" : None , } ) ARGS_VBOX = dict ( ARGS_EXPORT_DIR , ** { \"\" : OUTPUT_DIR , \"\" : \"\" , \"\" : \"\" , \"\" : ( \"\" , { } ) , \"\" : { } , \"\" : { } , \"\" : [ ] , } ) ARGS_COMPLETE = dict ( ARGS_VBOX , ** { \"\" : { \"\" : \"\" , \"\" : \"\" , \"\" : False } , \"\" : [ ( , { \"\" : \"\" } ) ] , \"\" : [ ( \"\" , { \"\" : \"\" } ) ] , \"\" : \"\" , \"\" : \"\" , } ) ARGS_BROKEN = dict ( ARGS_EXPORT_DIR , ** { \"\" : True , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : { } , \"\" : { } , } ) EXP_ARGS_COMPRESSED = dict ( ARGS_EXPORT_DIR , ** { \"\" : True , } ) EXP_DISKS_LIST = [ { \"\" : \"\" , \"\" : \"\" , \"\" : , \"\" : , \"\" : \"\" , } , { \"\" : \"\" , \"\" : , \"\" : , \"\" : \"\" , } , ] EXP_NETWORKS_LIST = [ { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } , ] EXP_PARTIAL_GANETI_DICT = { \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : \"\" , \"\" : \"\" , } EXP_GANETI_DICT = { \"\" : None , \"\" : \"\" , \"\" : { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } , \"\" : \"\" , \"\" : None , \"\" : { \"\" : \"\" } } EXP_NAME = \"\" EXP_VCPUS = EXP_MEMORY = EXPORT_EMPTY = ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) EXPORT_DISKS_EMPTY = ( \"\" \"\" ) EXPORT_DISKS = ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) EXPORT_NETWORKS_EMPTY = ( \"\" \"\" ) EXPORT_NETWORKS = ( \"\" \"\" ) EXPORT_GANETI_INCOMPLETE = ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) EXPORT_GANETI = ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) EXPORT_SYSTEM = ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ", "answer": "\"\""}, {"prompt": " from __future__ import print_function import pytest import random import struct ", "answer": "from pymtl import *"}, {"prompt": " \"\"\"\"\"\" import os import sys import contextlib import subprocess import signal import threading import Queue from qisys import ui import qisys . error import qisys . envsetter _FIND_PROGRAM_CACHE = dict ( ) SIGINT_EVENT = threading . Event ( ) class Process ( object ) : \"\"\"\"\"\" OK = FAILED = TIME_OUT = ZOMBIE = INTERRUPTED = NOT_RUN = def __init__ ( self , cmd , cwd = None , env = None , capture = True ) : self . cmd = cmd self . cwd = cwd self . env = env self . out = \"\" self . returncode = None self . _process = None self . exception = None self . return_type = Process . FAILED self . capture = capture def run ( self , timeout = None ) : def target ( ) : ui . debug ( \"\" ) ui . debug ( \"\" , subprocess . list2cmdline ( self . cmd ) ) try : opts = dict ( ) if os . name == '' : opts = { '' : os . setsid , '' : True } elif os . name == '' : opts = { '' : subprocess . CREATE_NEW_PROCESS_GROUP , } kwargs = { \"\" : self . cwd , \"\" : self . env } kwargs . update ( opts ) if self . capture : kwargs [ \"\" ] = subprocess . PIPE ", "answer": "kwargs [ \"\" ] = subprocess . STDOUT"}, {"prompt": " from __future__ import print_function , division , absolute_import import re import os import sys import subprocess from os . path import isdir , isfile , join , expanduser from conda . utils import memoized def find_executable ( executable , include_others = True ) : global dir_paths if include_others : if sys . platform == '' : dir_paths = [ join ( sys . prefix , '' ) , '' ] else : dir_paths = [ join ( sys . prefix , '' ) ] else : dir_paths = [ ] dir_paths . extend ( os . environ [ '' ] . split ( os . pathsep ) ) for dir_path in dir_paths : if sys . platform == '' : for ext in ( '' , '' , '' ) : path = join ( dir_path , executable + ext ) if isfile ( path ) : return path else : path = join ( dir_path , executable ) if isfile ( expanduser ( path ) ) : return expanduser ( path ) return None @ memoized def find_commands ( include_others = True ) : if include_others : if sys . platform == '' : dir_paths = [ join ( sys . prefix , '' ) , '' ] else : dir_paths = [ join ( sys . prefix , '' ) ] else : dir_paths = [ ] ", "answer": "if sys . platform == '' :"}, {"prompt": " import copy from zope . interface import implements from twisted . words . protocols . jabber import jid from wokkel . generic import parseXml , stripNamespace from wokkel . pubsub import Subscription from idavoll import error , iidavoll class Storage : implements ( iidavoll . IStorage ) defaultConfig = { '' : { \"\" : True , \"\" : True , \"\" : '' , } , '' : { \"\" : True , \"\" : '' , } } def __init__ ( self , dbpool ) : self . dbpool = dbpool def getNode ( self , nodeIdentifier ) : return self . dbpool . runInteraction ( self . _getNode , nodeIdentifier ) def _getNode ( self , cursor , nodeIdentifier ) : configuration = { } cursor . execute ( \"\"\"\"\"\" , ( nodeIdentifier , ) ) row = cursor . fetchone ( ) if not row : raise error . NodeNotFound ( ) if row . node_type == '' : configuration = { '' : row . persist_items , '' : row . deliver_payloads , '' : row . send_last_published_item } node = LeafNode ( nodeIdentifier , configuration ) node . dbpool = self . dbpool return node elif row . node_type == '' : configuration = { '' : row . deliver_payloads , '' : row . send_last_published_item } node = CollectionNode ( nodeIdentifier , configuration ) node . dbpool = self . dbpool return node def getNodeIds ( self ) : d = self . dbpool . runQuery ( \"\"\"\"\"\" ) d . addCallback ( lambda results : [ r [ ] for r in results ] ) return d def createNode ( self , nodeIdentifier , owner , config ) : return self . dbpool . runInteraction ( self . _createNode , nodeIdentifier , owner , config ) def _createNode ( self , cursor , nodeIdentifier , owner , config ) : if config [ '' ] != '' : raise error . NoCollections ( ) owner = owner . userhost ( ) try : cursor . execute ( \"\"\"\"\"\" , ( nodeIdentifier , config [ '' ] , config [ '' ] , config [ '' ] ) ) except cursor . _pool . dbapi . IntegrityError : raise error . NodeExists ( ) cursor . execute ( \"\"\"\"\"\" , ( owner , ) ) if not cursor . fetchone ( ) : cursor . execute ( \"\"\"\"\"\" , ( owner , ) ) cursor . execute ( \"\"\"\"\"\" , ( nodeIdentifier , owner ) ) def deleteNode ( self , nodeIdentifier ) : return self . dbpool . runInteraction ( self . _deleteNode , nodeIdentifier ) def _deleteNode ( self , cursor , nodeIdentifier ) : cursor . execute ( \"\"\"\"\"\" , ( nodeIdentifier , ) ) if cursor . rowcount != : raise error . NodeNotFound ( ) def getAffiliations ( self , entity ) : d = self . dbpool . runQuery ( \"\"\"\"\"\" , ( entity . userhost ( ) , ) ) d . addCallback ( lambda results : [ tuple ( r ) for r in results ] ) return d def getSubscriptions ( self , entity ) : def toSubscriptions ( rows ) : subscriptions = [ ] for row in rows : subscriber = jid . internJID ( '' % ( row . jid , row . resource ) ) subscription = Subscription ( row . node , subscriber , row . state ) subscriptions . append ( subscription ) return subscriptions d = self . dbpool . runQuery ( \"\"\"\"\"\" , ( entity . userhost ( ) , ) ) d . addCallback ( toSubscriptions ) return d def getDefaultConfiguration ( self , nodeType ) : return self . defaultConfig [ nodeType ] class Node : implements ( iidavoll . INode ) def __init__ ( self , nodeIdentifier , config ) : self . nodeIdentifier = nodeIdentifier self . _config = config def _checkNodeExists ( self , cursor ) : cursor . execute ( \"\"\"\"\"\" , ( self . nodeIdentifier , ) ) if not cursor . fetchone ( ) : raise error . NodeNotFound ( ) def getType ( self ) : return self . nodeType def getConfiguration ( self ) : return self . _config def setConfiguration ( self , options ) : config = copy . copy ( self . _config ) for option in options : if option in config : config [ option ] = options [ option ] d = self . dbpool . runInteraction ( self . _setConfiguration , config ) d . addCallback ( self . _setCachedConfiguration , config ) return d def _setConfiguration ( self , cursor , config ) : self . _checkNodeExists ( cursor ) cursor . execute ( \"\"\"\"\"\" , ( config [ \"\" ] , config [ \"\" ] , config [ \"\" ] , self . nodeIdentifier ) ) def _setCachedConfiguration ( self , void , config ) : self . _config = config def getMetaData ( self ) : config = copy . copy ( self . _config ) ", "answer": "config [ \"\" ] = self . nodeType"}, {"prompt": " import rospy import threading , time , pyttsx import actionlib from basics . msg import TalkAction , TalkGoal , TalkResult class TalkNode ( ) : def __init__ ( self , node_name , action_name ) : rospy . init_node ( node_name ) self . server = actionlib . SimpleActionServer ( action_name , TalkAction , self . do_talk , False ) self . engine = pyttsx . init ( ) self . engine_thread = threading . Thread ( target = self . loop ) self . engine_thread . start ( ) self . engine . setProperty ( '' , rospy . get_param ( '' , ) ) self . engine . setProperty ( '' , rospy . get_param ( '' , ) ) self . preempt = rospy . get_param ( '' , False ) self . server . start ( ) def loop ( self ) : self . engine . startLoop ( False ) while not rospy . is_shutdown ( ) : self . engine . iterate ( ) time . sleep ( ) self . engine . endLoop ( ) def do_talk ( self , goal ) : self . engine . say ( goal . sentence ) while self . engine . isBusy ( ) : ", "answer": "if self . preempt and self . server . is_preempt_requested ( ) :"}, {"prompt": " import time import os . path import inflector from json_to_model . parser import NodeType from jinja2 import Environment , PackageLoader type_map = { NodeType . TYPE_ARRAY : '' , NodeType . TYPE_BOOL : '' , NodeType . TYPE_INT : '' , NodeType . TYPE_FLOAT : '' , NodeType . TYPE_STRING : '' , } retain_map = { NodeType . TYPE_OBJECT : '' , NodeType . TYPE_ARRAY : '' , NodeType . TYPE_BOOL : '' , NodeType . TYPE_INT : '' , NodeType . TYPE_FLOAT : '' , NodeType . TYPE_STRING : '' , } english = inflector . English ( ) name_table = { '' : '' , '' : '' } def get_property_type ( context , node ) : result = type_map . get ( node . type , None ) if result is None : return '' % english . classify ( node . class_name ) return result def get_property_name ( context , node ) : name = english . variablize ( node . name ) if name in name_table : return name_table [ name ] return name def get_type_of_first_obj_in_array ( context , node ) : if node . type == NodeType . TYPE_ARRAY : if len ( node . children ) > : return get_property_type ( context , node . children [ ] ) return None def property_is_inherited ( context , node , property ) : c = node . super_class found = False while c is not None : found = property in c . children c = c . super_class return found def gen_code ( pathname , context ) : env = Environment ( loader = PackageLoader ( '' , '' ) ) header_template = env . get_template ( '' ) source_template = env . get_template ( '' ) for class_name , clazz in context . classes . iteritems ( ) : original_name = class_name class_name = english . classify ( original_name ) properties = [ ] includes = set ( ) for node in clazz . children : if property_is_inherited ( context , clazz , node ) : continue properties . append ( { '' : get_property_type ( context , node ) , '' : get_property_name ( context , node ) , '' : node . name , '' : retain_map [ node . type ] , '' : get_type_of_first_obj_in_array ( context , node ) } ) ", "answer": "if node . class_name :"}, {"prompt": " '''''' import os import unittest import ngsutils . gtf . query from ngsutils . gtf import GTF fname = os . path . join ( os . path . dirname ( __file__ ) , '' ) class GTFQueryTest ( unittest . TestCase ) : def testQuery ( self ) : ", "answer": "genes = list ( ngsutils . gtf . query . gtf_query ( GTF ( fname , cache_enabled = False ) , '' , , ) )"}, {"prompt": " import pandas as pd from bokeh . charts import Horizon , output_file , show AAPL = pd . read_csv ( \"\" , parse_dates = [ '' ] ) MSFT = pd . read_csv ( \"\" , parse_dates = [ '' ] ) ", "answer": "IBM = pd . read_csv ("}, {"prompt": " from gzip import GzipFile from StringIO import StringIO from . core import Middleware def compress ( data , level = ) : out = StringIO ( ) f = GzipFile ( fileobj = out , mode = '' , compresslevel = level ) f . write ( data ) ", "answer": "f . close ( )"}, {"prompt": " import mock import netaddr from neutron_lib import constants from oslo_config import cfg from oslo_db import exception as db_exc from oslo_utils import uuidutils from neutron . common import exceptions as n_exc from neutron import context from neutron . ipam import requests as ipam_req from neutron . ipam import subnet_alloc from neutron import manager from neutron . tests . unit . db import test_db_base_plugin_v2 from neutron . tests . unit import testlib_api class TestSubnetAllocation ( testlib_api . SqlTestCase ) : def setUp ( self ) : super ( TestSubnetAllocation , self ) . setUp ( ) self . _tenant_id = '' self . setup_coreplugin ( test_db_base_plugin_v2 . DB_PLUGIN_KLASS ) self . plugin = manager . NeutronManager . get_plugin ( ) self . ctx = context . get_admin_context ( ) cfg . CONF . set_override ( '' , True ) def _create_subnet_pool ( self , plugin , ctx , name , prefix_list , min_prefixlen , ip_version , max_prefixlen = constants . ATTR_NOT_SPECIFIED , default_prefixlen = constants . ATTR_NOT_SPECIFIED , default_quota = constants . ATTR_NOT_SPECIFIED , shared = False , is_default = False ) : subnetpool = { '' : { '' : name , '' : self . _tenant_id , '' : prefix_list , '' : min_prefixlen , '' : max_prefixlen , '' : default_prefixlen , '' : shared , '' : is_default , '' : default_quota } } return plugin . create_subnetpool ( ctx , subnetpool ) def _get_subnetpool ( self , ctx , plugin , id ) : return plugin . get_subnetpool ( ctx , id ) def test_allocate_any_subnet ( self ) : prefix_list = [ '' , '' ] sp = self . _create_subnet_pool ( self . plugin , self . ctx , '' , prefix_list , , ) ", "answer": "sp = self . plugin . _get_subnetpool ( self . ctx , sp [ '' ] )"}, {"prompt": " from __future__ import print_function , unicode_literals import json from liberapay . testing import Harness class Tests ( Harness ) : def test_anonymous ( self ) : alice = self . make_participant ( '' , balance = ) bob = self . make_participant ( '' ) alice . set_tip_to ( bob , '' ) data = json . loads ( self . client . GET ( '' ) . body ) assert data [ '' ] == '' assert '' not in data data = json . loads ( self . client . GET ( '' ) . body ) ", "answer": "assert data [ '' ] == ''"}, {"prompt": " \"\"\"\"\"\" import sys import pydoc import os import re import builtins from IPython . core . iplib import InteractiveShell from IPython . kernel . core . redirector_output_trap import RedirectorOutputTrap from IPython . kernel . core . sync_traceback_trap import SyncTracebackTrap import IPython . utils . io from linefrontendbase import LineFrontEndBase , common_prefix def mk_system_call ( system_call_function , command ) : \"\"\"\"\"\" def my_system_call ( args ) : system_call_function ( \"\" % ( command , args ) ) my_system_call . __doc__ = \"\" % command return my_system_call class PrefilterFrontEnd ( LineFrontEndBase ) : \"\"\"\"\"\" debug = False def __init__ ( self , ipython0 = None , * args , ** kwargs ) : \"\"\"\"\"\" LineFrontEndBase . __init__ ( self , * args , ** kwargs ) self . shell . output_trap = RedirectorOutputTrap ( out_callback = self . write , err_callback = self . write , ) self . shell . traceback_trap = SyncTracebackTrap ( formatters = self . shell . traceback_trap . formatters , ) self . save_output_hooks ( ) if ipython0 is None : def my_rawinput ( x = None ) : return '' old_rawinput = builtins . raw_input builtins . raw_input = my_rawinput ipython0 = InteractiveShell ( parent = None , user_ns = self . shell . user_ns , user_global_ns = self . shell . user_global_ns ) builtins . raw_input = old_rawinput self . ipython0 = ipython0 self . ipython0 . set_hook ( '' , lambda s , string : self . write ( \"\" + string ) ) self . ipython0 . write = self . write self . _ip = _ip = self . ipython0 self . _ip . system = self . system_call if not sys . platform . startswith ( '' ) : self . ipython0 . magic_ls = mk_system_call ( self . system_call , '' ) self . release_output ( ) if not '' in kwargs and self . banner is None : self . banner = self . ipython0 . banner self . start ( ) def show_traceback ( self ) : \"\"\"\"\"\" self . ipython0 . showtraceback ( tb_offset = - ) self . release_output ( ) def execute ( self , python_string , raw_string = None ) : if self . debug : print ( '' , repr ( python_string ) ) self . capture_output ( ) LineFrontEndBase . execute ( self , python_string , raw_string = raw_string ) self . release_output ( ) def save_output_hooks ( self ) : \"\"\"\"\"\" self . __old_cout_write = Term . cout . write self . __old_cerr_write = Term . cerr . write self . __old_stdout = sys . stdout self . __old_stderr = sys . stderr self . __old_help_output = pydoc . help . output self . __old_display_hook = sys . displayhook def capture_output ( self ) : \"\"\"\"\"\" self . save_output_hooks ( ) Term . cout . write = self . write Term . cerr . write = self . write sys . stdout = Term . cout sys . stderr = Term . cerr pydoc . help . output = self . shell . output_trap . out def release_output ( self ) : \"\"\"\"\"\" Term . cout . write = self . __old_cout_write Term . cerr . write = self . __old_cerr_write sys . stdout = self . __old_stdout sys . stderr = self . __old_stderr pydoc . help . output = self . __old_help_output sys . displayhook = self . __old_display_hook def complete ( self , line ) : word = self . _get_completion_text ( line ) completions = self . ipython0 . complete ( word ) key = lambda x : x . replace ( '' , '' ) completions . sort ( key = key ) if completions : prefix = common_prefix ( completions ) line = line [ : - len ( word ) ] + prefix return line , completions def prefilter_input ( self , input_string ) : \"\"\"\"\"\" input_string = LineFrontEndBase . prefilter_input ( self , input_string ) filtered_lines = [ ] self . capture_output ( ) self . last_result = dict ( number = self . prompt_number ) try : try : for line in input_string . split ( '' ) : pf = self . ipython0 . prefilter_manager . prefilter_lines filtered_lines . append ( pf ( line , False ) . rstrip ( ) ) except : self . ipython0 . showsyntaxerror ( ) self . after_execute ( ) finally : self . release_output ( ) filtered_string = '' . join ( filtered_lines ) return filtered_string def system_call ( self , command_string ) : \"\"\"\"\"\" return os . system ( command_string ) def do_exit ( self ) : \"\"\"\"\"\" self . ipython0 . atexit_operations ( ) ", "answer": "def _get_completion_text ( self , line ) :"}, {"prompt": " HOSTNAME = '' IP_ADDR = '' ", "answer": "ROOT_MEMEX_PORT = '' "}, {"prompt": " from __future__ import print_function , division , absolute_import import errno import imp import os import shutil import stat import subprocess import sys import tempfile import threading import warnings import numpy as np from numba import unittest_support as unittest from numba import utils , vectorize , jit , generated_jit , types , appdirs from numba . errors import NumbaWarning from . support import TestCase , tag , temp_directory , import_dynamic def dummy ( x ) : return x def add ( x , y ) : return x + y def addsub ( x , y , z ) : return x - y + z def addsub_defaults ( x , y = , z = ) : return x - y + z def star_defaults ( x , y = , * z ) : return x , y , z def generated_usecase ( x , y = ) : if isinstance ( x , types . Complex ) : def impl ( x , y ) : return x + y else : def impl ( x , y ) : return x - y return impl def bad_generated_usecase ( x , y = ) : if isinstance ( x , types . Complex ) : def impl ( x ) : return x else : def impl ( x , y = ) : return x - y return impl class BaseTest ( TestCase ) : jit_args = dict ( nopython = True ) def compile_func ( self , pyfunc ) : def check ( * args , ** kwargs ) : expected = pyfunc ( * args , ** kwargs ) result = f ( * args , ** kwargs ) self . assertPreciseEqual ( result , expected ) f = jit ( ** self . jit_args ) ( pyfunc ) return f , check class TestDispatcher ( BaseTest ) : def test_no_argument ( self ) : @ jit def foo ( ) : return foo ( ) def test_coerce_input_types ( self ) : c_add = jit ( nopython = True ) ( add ) self . assertPreciseEqual ( c_add ( , ) , add ( , ) ) self . assertPreciseEqual ( c_add ( , ) , add ( , ) ) self . assertPreciseEqual ( c_add ( , ) , add ( , ) ) self . assertPreciseEqual ( c_add ( , ) , add ( , ) ) c_add = jit ( '' , nopython = True ) ( add ) self . assertPreciseEqual ( c_add ( , ) , add ( , ) ) self . assertPreciseEqual ( c_add ( , ) , add ( , ) ) with self . assertRaises ( TypeError ) : c_add ( , ) def test_ambiguous_new_version ( self ) : \"\"\"\"\"\" @ jit def foo ( a , b ) : return a + b INT = FLT = self . assertAlmostEqual ( foo ( INT , FLT ) , INT + FLT ) self . assertEqual ( len ( foo . overloads ) , ) self . assertAlmostEqual ( foo ( FLT , INT ) , FLT + INT ) self . assertEqual ( len ( foo . overloads ) , ) self . assertAlmostEqual ( foo ( FLT , FLT ) , FLT + FLT ) self . assertEqual ( len ( foo . overloads ) , ) self . assertAlmostEqual ( foo ( , ) , INT + INT ) self . assertEqual ( len ( foo . overloads ) , , \"\" \"\" ) def test_lock ( self ) : \"\"\"\"\"\" errors = [ ] @ jit def foo ( x ) : return x + def wrapper ( ) : try : self . assertEqual ( foo ( ) , ) except BaseException as e : errors . append ( e ) threads = [ threading . Thread ( target = wrapper ) for i in range ( ) ] for t in threads : t . start ( ) for t in threads : t . join ( ) ", "answer": "self . assertFalse ( errors )"}, {"prompt": " from __future__ import absolute_import class HeaderFooterItem ( object ) : \"\"\"\"\"\" CENTER = '' LEFT = '' RIGHT = '' REPLACE_LIST = ( ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ) __slots__ = ( '' , '' , '' , '' , '' ) def __init__ ( self , type ) : self . type = type self . font_name = \"\" self . font_size = None self . font_color = \"\" self . text = None def has ( self ) : return True if self . text else False def get ( self ) : t = [ ] if self . text : t . append ( '' % self . type ) t . append ( '' % self . font_name ) if self . font_size : t . append ( '' % self . font_size ) t . append ( '' % self . font_color ) text = self . text for old , new in self . REPLACE_LIST : text = text . replace ( old , new ) t . append ( text ) return '' . join ( t ) def set ( self , text ) : \"\"\"\"\"\" if text is None : return m = FONT_REGEX . search ( text ) if m : self . font_name = m . group ( '' ) text = FONT_REGEX . sub ( '' , text ) m = SIZE_REGEX . search ( text ) if m : self . font_size = int ( m . group ( '' ) ) text = SIZE_REGEX . sub ( '' , text ) m = COLOR_REGEX . search ( text ) if m : self . font_color = m . group ( '' ) text = COLOR_REGEX . sub ( '' , text ) self . text = text class HeaderFooter ( object ) : \"\"\"\"\"\" __slots__ = ( '' , '' , '' , '' , '' , '' ) def __init__ ( self ) : self . left_header = HeaderFooterItem ( HeaderFooterItem . LEFT ) self . center_header = HeaderFooterItem ( HeaderFooterItem . CENTER ) self . right_header = HeaderFooterItem ( HeaderFooterItem . RIGHT ) self . left_footer = HeaderFooterItem ( HeaderFooterItem . LEFT ) self . center_footer = HeaderFooterItem ( HeaderFooterItem . CENTER ) self . right_footer = HeaderFooterItem ( HeaderFooterItem . RIGHT ) def hasHeader ( self ) : return True if self . left_header . has ( ) or self . center_header . has ( ) or self . right_header . has ( ) else False def hasFooter ( self ) : return True if self . left_footer . has ( ) or self . center_footer . has ( ) or self . right_footer . has ( ) else False def getHeader ( self ) : t = [ ] if self . left_header . has ( ) : t . append ( self . left_header . get ( ) ) if self . center_header . has ( ) : t . append ( self . center_header . get ( ) ) if self . right_header . has ( ) : t . append ( self . right_header . get ( ) ) return '' . join ( t ) ", "answer": "def getFooter ( self ) :"}, {"prompt": " from __future__ import print_function , division import warnings import numpy as np from astropy import log as logger from . . util . functions import FreezableClass , bool2str , str2bool , is_numpy_array from . . filter import Filter class OutputConf ( FreezableClass ) : def __init__ ( self ) : '''''' self . output_density = '' self . output_density_diff = '' self . output_specific_energy = '' self . output_n_photons = '' self . _freeze ( ) @ classmethod def read ( cls , group ) : self = cls ( ) self . output_density = group . attrs [ '' ] . decode ( '' ) self . output_density_diff = group . attrs [ '' ] . decode ( '' ) self . output_specific_energy = group . attrs [ '' ] . decode ( '' ) self . output_n_photons = group . attrs [ '' ] . decode ( '' ) return self def write ( self , group ) : group . attrs [ '' ] = np . string_ ( self . output_density . encode ( '' ) ) group . attrs [ '' ] = np . string_ ( self . output_density_diff . encode ( '' ) ) group . attrs [ '' ] = np . string_ ( self . output_specific_energy . encode ( '' ) ) group . attrs [ '' ] = np . string_ ( self . output_n_photons . encode ( '' ) ) class RunConf ( object ) : def __init__ ( self ) : '''''' self . set_n_initial_iterations ( ) self . n_photons = { } self . set_propagation_check_frequency ( ) self . set_seed ( - ) self . set_raytracing ( False ) self . set_max_interactions ( ) self . set_max_reabsorptions ( ) self . set_pda ( False ) self . set_mrw ( False ) self . set_convergence ( False ) self . set_kill_on_absorb ( False ) self . set_kill_on_scatter ( False ) self . set_forced_first_scattering ( True ) self . set_output_bytes ( ) self . set_sample_sources_evenly ( False ) self . set_enforce_energy_range ( True ) self . set_copy_input ( True ) self . _monochromatic = False self . set_specific_energy_type ( '' ) super ( RunConf , self ) . __init__ ( ) def set_propagation_check_frequency ( self , frequency ) : '''''' if not np . isscalar ( frequency ) or isinstance ( frequency , basestring ) : raise TypeError ( \"\" ) if frequency < or frequency > : raise ValueError ( \"\" ) self . _frequency = frequency def _read_propagation_check_frequency ( self , group ) : self . _frequency = group . attrs [ '' ] def _write_propagation_check_frequency ( self , group ) : group . attrs [ '' ] = self . _frequency def set_seed ( self , seed ) : '''''' if type ( seed ) != int or seed >= : raise ValueError ( \"\" ) self . _seed = seed def _read_seed ( self , group ) : self . _seed = group . attrs [ '' ] def _write_seed ( self , group ) : group . attrs [ '' ] = self . _seed def set_n_initial_iterations ( self , n_iter ) : '''''' self . n_iter = n_iter def _read_n_initial_iterations ( self , group ) : self . n_iter = group . attrs [ '' ] def _write_n_initial_iterations ( self , group ) : group . attrs [ '' ] = self . n_iter def set_n_photons ( self , initial = None , imaging = None , imaging_sources = None , imaging_dust = None , raytracing_sources = None , raytracing_dust = None , stats = ) : '''''' self . n_photons . clear ( ) if self . n_iter == : if initial is not None : raise Exception ( \"\" ) else : if '' in self . n_photons : del self . n_photons [ '' ] else : if initial is None : raise Exception ( \"\" ) else : self . n_photons [ '' ] = initial if self . raytracing : if raytracing_sources is None : raise Exception ( \"\" ) else : self . n_photons [ '' ] = raytracing_sources if raytracing_dust is None : raise Exception ( \"\" ) else : self . n_photons [ '' ] = raytracing_dust else : if raytracing_sources is not None : raise Exception ( \"\" ) if raytracing_dust is not None : raise Exception ( \"\" ) if self . _monochromatic : if imaging_sources is None : raise Exception ( \"\" ) else : self . n_photons [ '' ] = imaging_sources if imaging_dust is None : raise Exception ( \"\" ) else : self . n_photons [ '' ] = imaging_dust if imaging is not None : raise Exception ( \"\" ) else : if imaging_sources is not None : raise Exception ( \"\" ) if imaging_dust is not None : raise Exception ( \"\" ) if imaging is None : raise Exception ( \"\" ) else : self . n_photons [ '' ] = imaging self . n_photons [ '' ] = stats def _read_n_photons ( self , group ) : if self . n_iter != : self . n_photons [ '' ] = group . attrs [ '' ] if self . _monochromatic : self . n_photons [ '' ] = group . attrs [ '' ] self . n_photons [ '' ] = group . attrs [ '' ] else : self . n_photons [ '' ] = group . attrs [ '' ] if self . raytracing : self . n_photons [ '' ] = group . attrs [ '' ] self . n_photons [ '' ] = group . attrs [ '' ] self . n_photons [ '' ] = group . attrs [ '' ] def _write_n_photons ( self , group ) : if self . n_photons == { } : raise Exception ( \"\" ) if self . n_iter == : if '' in self . n_photons and self . n_photons [ '' ] is not None : raise Exception ( \"\" ) else : if '' in self . n_photons and self . n_photons [ '' ] is not None : group . attrs [ '' ] = self . n_photons [ '' ] else : raise Exception ( \"\" ) if self . _monochromatic : if '' in self . n_photons : group . attrs [ '' ] = self . n_photons [ '' ] else : raise Exception ( \"\" ) if '' in self . n_photons : group . attrs [ '' ] = self . n_photons [ '' ] else : raise Exception ( \"\" ) if '' in self . n_photons : raise Exception ( \"\" ) else : if '' in self . n_photons : raise Exception ( \"\" ) if '' in self . n_photons : raise Exception ( \"\" ) if '' in self . n_photons : group . attrs [ '' ] = self . n_photons [ '' ] else : raise Exception ( \"\" ) if self . raytracing : if '' in self . n_photons : group . attrs [ '' ] = self . n_photons [ '' ] else : raise Exception ( \"\" ) if '' in self . n_photons : group . attrs [ '' ] = self . n_photons [ '' ] else : raise Exception ( \"\" ) else : if '' in self . n_photons : raise Exception ( \"\" ) if '' in self . n_photons : raise Exception ( \"\" ) group . attrs [ '' ] = self . n_photons [ '' ] def set_raytracing ( self , raytracing ) : '''''' self . raytracing = raytracing def _read_raytracing ( self , group ) : self . raytracing = str2bool ( group . attrs [ '' ] ) def _write_raytracing ( self , group ) : group . attrs [ '' ] = bool2str ( self . raytracing ) def set_max_interactions ( self , inter_max , warn = True ) : '''''' self . n_inter_max = inter_max self . n_inter_max_warn = warn def _read_max_interactions ( self , group ) : self . n_inter_max = group . attrs [ '' ] if '' in group . attrs : self . n_inter_max_warn = str2bool ( group . attrs [ '' ] ) else : self . n_inter_max_warn = True def _write_max_interactions ( self , group ) : group . attrs [ '' ] = self . n_inter_max group . attrs [ '' ] = bool2str ( self . n_inter_max_warn ) def set_max_reabsorptions ( self , reabs_max , warn = True ) : '''''' self . n_reabs_max = reabs_max self . n_reabs_max_warn = warn def _read_max_reabsorptions ( self , group ) : self . n_reabs_max = group . attrs [ '' ] if '' in group . attrs : self . n_reabs_max_warn = str2bool ( group . attrs [ '' ] ) else : self . n_reabs_max_warn = True def _write_max_reabsorptions ( self , group ) : group . attrs [ '' ] = self . n_reabs_max group . attrs [ '' ] = bool2str ( self . n_reabs_max_warn ) def set_pda ( self , pda ) : '''''' self . pda = pda def _read_pda ( self , group ) : self . pda = str2bool ( group . attrs [ '' ] ) def _write_pda ( self , group ) : group . attrs [ '' ] = bool2str ( self . pda ) def set_mrw ( self , mrw , gamma = , inter_max = , warn = True ) : '''''' self . mrw = mrw self . mrw_gamma = gamma self . n_inter_mrw_max = inter_max self . n_inter_mrw_max_warn = warn def _read_mrw ( self , group ) : self . mrw = str2bool ( group . attrs [ '' ] ) if self . mrw : self . mrw_gamma = group . attrs [ '' ] self . n_inter_mrw_max = group . attrs [ '' ] if '' in group . attrs : self . n_inter_mrw_max_warn = str2bool ( group . attrs [ '' ] ) else : self . n_inter_mrw_max_warn = True def _write_mrw ( self , group ) : group . attrs [ '' ] = bool2str ( self . mrw ) if self . mrw : group . attrs [ '' ] = self . mrw_gamma group . attrs [ '' ] = self . n_inter_mrw_max group . attrs [ '' ] = bool2str ( self . n_inter_mrw_max_warn ) def set_convergence ( self , convergence , percentile = , absolute = , relative = ) : '''''' self . check_convergence = True self . convergence_percentile = percentile self . convergence_absolute = absolute self . convergence_relative = relative def _read_convergence ( self , group ) : self . check_convergence = str2bool ( group . attrs [ '' ] ) if self . check_convergence : self . convergence_percentile = group . attrs [ '' ] self . convergence_absolute = group . attrs [ '' ] self . convergence_relative = group . attrs [ '' ] def _write_convergence ( self , group ) : group . attrs [ '' ] = bool2str ( self . check_convergence ) if self . check_convergence : group . attrs [ '' ] = self . convergence_percentile group . attrs [ '' ] = self . convergence_absolute group . attrs [ '' ] = self . convergence_relative def set_kill_on_absorb ( self , kill_on_absorb ) : '''''' self . kill_on_absorb = kill_on_absorb def _read_kill_on_absorb ( self , group ) : self . kill_on_absorb = str2bool ( group . attrs [ '' ] ) def _write_kill_on_absorb ( self , group ) : group . attrs [ '' ] = bool2str ( self . kill_on_absorb ) def set_kill_on_scatter ( self , kill_on_scatter ) : '''''' self . kill_on_scatter = kill_on_scatter def _read_kill_on_scatter ( self , group ) : if '' in group . attrs : self . kill_on_scatter = str2bool ( group . attrs [ '' ] ) else : self . kill_on_scatter = False def _write_kill_on_scatter ( self , group ) : group . attrs [ '' ] = bool2str ( self . kill_on_scatter ) def set_forced_first_scattering ( self , forced_first_scattering ) : '''''' self . forced_first_scattering = forced_first_scattering def _read_forced_first_scattering ( self , group ) : self . forced_first_scattering = str2bool ( group . attrs [ '' ] ) def _write_forced_first_scattering ( self , group ) : group . attrs [ '' ] = bool2str ( self . forced_first_scattering ) def set_enforce_energy_range ( self , enforce ) : '''''' self . enforce_energy_range = enforce def _read_enforce_energy_range ( self , group ) : self . enforce_energy_range = str2bool ( group . attrs [ '' ] ) def _write_enforce_energy_range ( self , group ) : group . attrs [ '' ] = bool2str ( self . enforce_energy_range ) def set_copy_input ( self , copy ) : '''''' self . copy_input = copy def _read_copy_input ( self , group ) : self . copy_input = str2bool ( group . attrs [ '' ] ) def _write_copy_input ( self , group ) : group . attrs [ '' ] = bool2str ( self . copy_input ) def set_output_bytes ( self , io_bytes ) : '''''' self . physics_io_bytes = io_bytes def _read_output_bytes ( self , group ) : self . physics_io_bytes = group . attrs [ '' ] def _write_output_bytes ( self , group ) : group . attrs [ '' ] = self . physics_io_bytes def set_sample_sources_evenly ( self , sample_sources_evenly ) : '''''' self . sample_sources_evenly = sample_sources_evenly def _read_sample_sources_evenly ( self , group ) : self . sample_sources_evenly = str2bool ( group . attrs [ '' ] ) def _write_sample_sources_evenly ( self , group ) : group . attrs [ '' ] = bool2str ( self . sample_sources_evenly ) def set_specific_energy_type ( self , specific_energy_type ) : '''''' if specific_energy_type in [ '' , '' ] : self . specific_energy_type = specific_energy_type else : raise ValueError ( \"\" ) def _read_specific_energy_type ( self , group ) : if '' in group . attrs : self . specific_energy_type = group . attrs [ '' ] . decode ( '' ) else : self . specific_energy_type = '' def _write_specific_energy_type ( self , group ) : group . attrs [ '' ] = np . string_ ( self . specific_energy_type . encode ( '' ) ) def read_run_conf ( self , group ) : '''''' self . _read_propagation_check_frequency ( group ) self . _read_seed ( group ) self . _read_n_initial_iterations ( group ) self . _read_raytracing ( group ) self . _read_n_photons ( group ) self . _read_max_interactions ( group ) self . _read_max_reabsorptions ( group ) self . _read_pda ( group ) self . _read_mrw ( group ) self . _read_convergence ( group ) self . _read_kill_on_absorb ( group ) self . _read_kill_on_scatter ( group ) self . _read_forced_first_scattering ( group ) self . _read_output_bytes ( group ) self . _read_sample_sources_evenly ( group ) self . _read_enforce_energy_range ( group ) self . _read_copy_input ( group ) self . _read_specific_energy_type ( group ) def write_run_conf ( self , group ) : '''''' ", "answer": "self . _write_propagation_check_frequency ( group )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import logging from contextlib import closing from raven . _compat import text_type __all__ = ( '' , '' ) logger = logging . getLogger ( '' ) class SerializationManager ( object ) : logger = logger def __init__ ( self ) : self . __registry = [ ] self . __serializers = { } @ property def serializers ( self ) : for serializer in self . __registry : yield serializer def register ( self , serializer ) : if serializer not in self . __registry : self . __registry . append ( serializer ) return serializer class Serializer ( object ) : logger = logger def __init__ ( self , manager ) : self . manager = manager self . context = set ( ) self . serializers = [ ] for serializer in manager . serializers : self . serializers . append ( serializer ( self ) ) def close ( self ) : ", "answer": "del self . serializers"}, {"prompt": " \"\"\"\"\"\" import warnings from twisted . trial import unittest , util ", "answer": "METHOD_WARNING_MSG = \"\""}, {"prompt": " \"\"\"\"\"\" from nltk . compat import string_types from nltk . corpus . reader import WordListCorpusReader from nltk . corpus . reader . api import * class IgnoreReadmeCorpusView ( StreamBackedCorpusView ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : StreamBackedCorpusView . __init__ ( self , * args , ** kwargs ) self . _open ( ) read_blankline_block ( self . _stream ) self . _filepos = [ self . _stream . tell ( ) ] class OpinionLexiconCorpusReader ( WordListCorpusReader ) : \"\"\"\"\"\" CorpusView = IgnoreReadmeCorpusView def words ( self , fileids = None ) : \"\"\"\"\"\" if fileids is None : fileids = self . _fileids elif isinstance ( fileids , compat . string_types ) : fileids = [ fileids ] return concat ( [ self . CorpusView ( path , self . _read_word_block , encoding = enc ) for ( path , enc , fileid ) in self . abspaths ( fileids , True , True ) ] ) ", "answer": "def positive ( self ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import inspect from nose . plugins . skip import SkipTest import re import sys from theano . compat import six class Reader ( object ) : \"\"\"\"\"\" def __init__ ( self , data ) : \"\"\"\"\"\" if isinstance ( data , list ) : self . _str = data else : self . _str = data . split ( '' ) self . reset ( ) def __getitem__ ( self , n ) : return self . _str [ n ] def reset ( self ) : self . _l = def read ( self ) : if not self . eof ( ) : out = self [ self . _l ] self . _l += return out else : return '' def seek_next_non_empty_line ( self ) : for l in self [ self . _l : ] : if l . strip ( ) : break else : self . _l += def eof ( self ) : return self . _l >= len ( self . _str ) def read_to_condition ( self , condition_func ) : start = self . _l for line in self [ start : ] : if condition_func ( line ) : return self [ start : self . _l ] self . _l += if self . eof ( ) : return self [ start : self . _l + ] return [ ] def read_to_next_empty_line ( self ) : self . seek_next_non_empty_line ( ) def is_empty ( line ) : return not line . strip ( ) return self . read_to_condition ( is_empty ) def read_to_next_unindented_line ( self ) : def is_unindented ( line ) : return ( line . strip ( ) and ( len ( line . lstrip ( ) ) == len ( line ) ) ) return self . read_to_condition ( is_unindented ) def peek ( self , n = ) : if self . _l + n < len ( self . _str ) : return self [ self . _l + n ] else : return '' def is_empty ( self ) : return not '' . join ( self . _str ) . strip ( ) def __iter__ ( self ) : for line in self . _str : yield line class NumpyDocString ( object ) : def __init__ ( self , docstring , name = None ) : if name : self . name = name docstring = docstring . split ( '' ) try : indent = min ( len ( s ) - len ( s . lstrip ( ) ) for s in docstring if s . strip ( ) ) except ValueError : indent = for n , line in enumerate ( docstring ) : docstring [ n ] = docstring [ n ] [ indent : ] self . _doc = Reader ( docstring ) self . _parsed_data = { '' : '' , '' : '' , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : '' , '' : '' , '' : { } , '' : [ ] , '' : [ ] , } self . section_order = [ ] self . _parse ( ) def __getitem__ ( self , key ) : return self . _parsed_data [ key ] def __setitem__ ( self , key , val ) : if key not in self . _parsed_data : raise ValueError ( \"\" % key ) else : self . _parsed_data [ key ] = val def _is_at_section ( self ) : self . _doc . seek_next_non_empty_line ( ) if self . _doc . eof ( ) : return False l1 = self . _doc . peek ( ) . strip ( ) if l1 . startswith ( '' ) : return True l2 = self . _doc . peek ( ) . strip ( ) return ( len ( l1 ) == len ( l2 ) and l2 == '' * len ( l1 ) ) def _strip ( self , doc ) : i = j = for i , line in enumerate ( doc ) : if line . strip ( ) : break for j , line in enumerate ( doc [ : : - ] ) : if line . strip ( ) : break return doc [ i : len ( doc ) - j ] def _read_to_next_section ( self ) : section = self . _doc . read_to_next_empty_line ( ) while not self . _is_at_section ( ) and not self . _doc . eof ( ) : if not self . _doc . peek ( - ) . strip ( ) : section += [ '' ] section += self . _doc . read_to_next_empty_line ( ) return section def _read_sections ( self ) : while not self . _doc . eof ( ) : data = self . _read_to_next_section ( ) name = data [ ] . strip ( ) if name . startswith ( '' ) : yield name , data [ : ] elif len ( data ) < : yield StopIteration else : yield name , self . _strip ( data [ : ] ) def _parse_param_list ( self , content ) : r = Reader ( content ) params = [ ] while not r . eof ( ) : header = r . read ( ) . strip ( ) if '' in header : arg_name , arg_type = header . split ( '' ) [ : ] else : arg_name , arg_type = header , '' desc = r . read_to_next_unindented_line ( ) for n , line in enumerate ( desc ) : desc [ n ] = line . strip ( ) desc = desc params . append ( ( arg_name , arg_type , desc ) ) return params def _parse_see_also ( self , content ) : \"\"\"\"\"\" functions = [ ] current_func = None rest = [ ] for line in content : if not line . strip ( ) : continue if '' in line : if current_func : functions . append ( ( current_func , rest ) ) r = line . split ( '' , ) current_func = r [ ] . strip ( ) r [ ] = r [ ] . strip ( ) if r [ ] : rest = [ r [ ] ] else : rest = [ ] elif not line . startswith ( '' ) : if current_func : functions . append ( ( current_func , rest ) ) current_func = None rest = [ ] if '' in line : for func in line . split ( '' ) : func = func . strip ( ) if func : functions . append ( ( func , [ ] ) ) elif line . strip ( ) : current_func = line . strip ( ) elif current_func is not None : rest . append ( line . strip ( ) ) if current_func : functions . append ( ( current_func , rest ) ) return functions def _parse_index ( self , section , content ) : \"\"\"\"\"\" def strip_each_in ( lst ) : return [ s . strip ( ) for s in lst ] out = { } section = section . split ( '' ) if len ( section ) > : out [ '' ] = strip_each_in ( section [ ] . split ( '' ) ) [ ] for line in content : line = line . split ( '' ) if len ( line ) > : out [ line [ ] ] = strip_each_in ( line [ ] . split ( '' ) ) return out def _parse_summary ( self ) : \"\"\"\"\"\" summary = self . _doc . read_to_next_empty_line ( ) summary_str = \"\" . join ( [ s . strip ( ) for s in summary ] ) if re . compile ( '' ) . match ( summary_str ) : self [ '' ] = summary_str if not self . _is_at_section ( ) : self [ '' ] = self . _doc . read_to_next_empty_line ( ) elif re . compile ( '' ) . match ( summary_str ) : self [ '' ] = '' self . _doc . reset ( ) else : self [ '' ] = summary if not self . _is_at_section ( ) : self [ '' ] = self . _read_to_next_section ( ) def _parse ( self ) : self . _doc . reset ( ) self . _parse_summary ( ) for ( section , content ) in self . _read_sections ( ) : if not section . startswith ( '' ) : section = '' . join ( [ s . capitalize ( ) for s in section . split ( '' ) ] ) if section in ( '' , '' , '' , '' , '' , '' , '' ) : self [ section ] = self . _parse_param_list ( content ) self . section_order . append ( section ) elif section . startswith ( '' ) : self [ '' ] = self . _parse_index ( section , content ) self . section_order . append ( '' ) elif section . lower ( ) == '' : self [ '' ] = self . _parse_see_also ( content ) self . section_order . append ( '' ) else : self [ section ] = content self . section_order . append ( section ) def _str_header ( self , name , symbol = '' ) : return [ name , len ( name ) * symbol ] def _str_indent ( self , doc , indent = ) : out = [ ] for line in doc : out += [ '' * indent + line ] return out def _str_signature ( self ) : if not self [ '' ] : return [ ] return [ \"\" % self [ '' ] . replace ( '' , '' ) ] + [ '' ] def _str_summary ( self ) : return self [ '' ] + [ '' ] def _str_extended_summary ( self ) : return self [ '' ] + [ '' ] def _str_param_list ( self , name ) : out = [ ] if self [ name ] : out += self . _str_header ( name ) for param , param_type , desc in self [ name ] : out += [ '' % ( param , param_type ) ] out += self . _str_indent ( desc ) out += [ '' ] return out def _str_section ( self , name ) : out = [ ] if self [ name ] : out += self . _str_header ( name ) out += self [ name ] out += [ '' ] return out def _str_see_also ( self ) : if not self [ '' ] : return [ ] out = [ ] out += self . _str_header ( \"\" ) last_had_desc = True for func , desc in self [ '' ] : if desc or last_had_desc : out += [ '' ] out += [ \"\" % func ] else : out [ - ] += \"\" % func if desc : out += self . _str_indent ( desc ) last_had_desc = True else : last_had_desc = False out += [ '' ] return out def _str_index ( self ) : idx = self [ '' ] out = [ ] out += [ '' % idx . get ( '' , '' ) ] for section , references in six . iteritems ( idx ) : if section == '' : continue out += [ '' % ( section , '' . join ( references ) ) ] return out def __str__ ( self ) : out = [ ] out += self . _str_signature ( ) out += self . _str_summary ( ) out += self . _str_extended_summary ( ) for param_list in ( '' , '' , '' , '' , '' ) : out += self . _str_param_list ( param_list ) out += self . _str_see_also ( ) for s in ( '' , '' , '' ) : out += self . _str_section ( s ) out += self . _str_index ( ) return '' . join ( out ) def get_errors ( self , check_order = True ) : errors = [ ] self . _doc . reset ( ) for j , line in enumerate ( self . _doc ) : if len ( line ) > : if hasattr ( self , '' ) : errors . append ( \"\" \"\" % ( self . name , j + , line [ : ] ) ) else : errors . append ( \"\" \"\" % ( j + , line [ : ] ) ) if check_order : canonical_order = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] canonical_order_copy = list ( canonical_order ) for s in self . section_order : while canonical_order_copy and s != canonical_order_copy [ ] : canonical_order_copy . pop ( ) if not canonical_order_copy : errors . append ( \"\" \"\" % ( s , canonical_order ) ) return errors def indent ( str , indent = ) : indent_str = '' * indent if str is None : return indent_str lines = str . split ( '' ) return '' . join ( indent_str + l for l in lines ) class NumpyFunctionDocString ( NumpyDocString ) : def __init__ ( self , docstring , function ) : super ( NumpyFunctionDocString , self ) . __init__ ( docstring ) args , varargs , keywords , defaults = inspect . getargspec ( function ) if ( args and args != [ '' ] ) or varargs or keywords or defaults : self . has_parameters = True else : self . has_parameters = False def _parse ( self ) : self . _parsed_data = { '' : '' , '' : '' , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : '' , '' : '' , '' : { } , } return NumpyDocString . _parse ( self ) def get_errors ( self ) : errors = NumpyDocString . get_errors ( self ) if not self [ '' ] : pass if not self [ '' ] : errors . append ( \"\" ) if len ( \"\" . join ( self [ '' ] ) ) > * : errors . append ( \"\" ) if not self [ '' ] and self . has_parameters : errors . append ( \"\" ) return errors class NumpyClassDocString ( NumpyDocString ) : def __init__ ( self , docstring , class_name , class_object ) : super ( NumpyClassDocString , self ) . __init__ ( docstring ) self . class_name = class_name methods = dict ( ( name , func ) for name , func in inspect . getmembers ( class_object ) ) self . has_parameters = False if '' in methods : if not inspect . ismethod ( methods [ '' ] ) : return args , varargs , keywords , defaults = inspect . getargspec ( methods [ '' ] ) if ( args and args != [ '' ] ) or varargs or keywords or defaults : self . has_parameters = True def _parse ( self ) : self . _parsed_data = { '' : '' , '' : '' , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : '' , '' : '' , '' : { } , '' : [ ] , '' : [ ] , } return NumpyDocString . _parse ( self ) def __str__ ( self ) : out = [ ] out += self . _str_signature ( ) out += self . _str_summary ( ) out += self . _str_extended_summary ( ) for param_list in ( '' , '' , '' , '' , '' ) : out += self . _str_param_list ( param_list ) out += self . _str_see_also ( ) for s in ( '' , '' , '' ) : out += self . _str_section ( s ) out += self . _str_index ( ) return '' . join ( out ) def get_errors ( self ) : errors = NumpyDocString . get_errors ( self ) if not self [ '' ] and self . has_parameters : errors . append ( \"\" % self . class_name ) return errors class NumpyModuleDocString ( NumpyDocString ) : \"\"\"\"\"\" def _parse ( self ) : self . out = [ ] def __str__ ( self ) : return \"\" . join ( self . _doc . _str ) def get_errors ( self ) : errors = NumpyDocString . get_errors ( self , check_order = False ) return errors def header ( text , style = '' ) : return text + '' + style * len ( text ) + '' class SphinxDocString ( NumpyDocString ) : def _str_header ( self , name , symbol = '' ) : return [ '' + name + '' ] + [ symbol * ( len ( name ) + ) ] def _str_indent ( self , doc , indent = ) : out = [ ] for line in doc : out += [ '' * indent + line ] return out def _str_signature ( self ) : return [ '' % self [ '' ] . replace ( '' , '' ) ] + [ '' ] def _str_summary ( self ) : return self [ '' ] + [ '' ] def _str_extended_summary ( self ) : return self [ '' ] + [ '' ] def _str_param_list ( self , name ) : out = [ ] if self [ name ] : out += self . _str_header ( name ) out += [ '' ] for param , param_type , desc in self [ name ] : out += self . _str_indent ( [ '' % ( param , param_type ) ] ) out += [ '' ] out += self . _str_indent ( desc , ) out += [ '' ] return out def _str_section ( self , name ) : out = [ ] if self [ name ] : out += self . _str_header ( name ) out += [ '' ] content = self . _str_indent ( self [ name ] ) out += content out += [ '' ] return out def _str_index ( self ) : idx = self [ '' ] out = [ ] out += [ '' % idx . get ( '' , '' ) ] for section , references in six . iteritems ( idx ) : if section == '' : continue out += [ '' % ( section , '' . join ( references ) ) ] return out def __str__ ( self , indent = ) : out = [ ] out += self . _str_summary ( ) out += self . _str_extended_summary ( ) for param_list in ( '' , '' , '' , '' ) : out += self . _str_param_list ( param_list ) for s in ( '' , '' , '' ) : out += self . _str_section ( s ) out = self . _str_indent ( out , indent ) return '' . join ( out ) class FunctionDoc ( object ) : def __init__ ( self , func ) : self . _f = func def __str__ ( self ) : out = '' doclines = inspect . getdoc ( self . _f ) or '' try : doc = SphinxDocString ( doclines ) except Exception as e : print ( '' * ) print ( \"\" % ( e , self . _f ) ) print ( '' * ) return out if doc [ '' ] : out += '' % header ( '' % doc [ '' ] . replace ( '' , '' ) , '' ) ", "answer": "else :"}, {"prompt": " from hermes . server import run_server ", "answer": "from hermes . chatroom import Chatroom "}, {"prompt": " from click import confirm , prompt , UsageError import xdg from functools import partial from os . path import expanduser , expandvars , join , normpath , split , exists , isdir from os import makedirs from datetime import date , datetime import sys from khal . log import logger from . settings import settings def validate_int ( input , min_value , max_value ) : try : number = int ( input ) except ValueError : raise UsageError ( '' ) if min_value <= number <= max_value : return number else : raise UsageError ( '' . format ( min_value , max_value ) ) def choose_datetime_format ( ) : while True : ordering_choices = [ ( '' , [ '' , '' , '' ] ) , ( '' , [ '' , '' , '' ] ) , ( '' , [ '' , '' , '' ] ) , ] separator_choices = [ '' , '' , '' ] validate = partial ( validate_int , min_value = , max_value = ) print ( \"\" \"\" ) print ( '' . join ( [ '' . format ( num , one ) for num , ( one , _ ) in enumerate ( ordering_choices ) ] ) ) ordering_no = prompt ( \"\" , value_proc = validate ) print ( ) print ( \"\" ) print ( '' . join ( [ '' . format ( num , one ) for num , one in enumerate ( separator_choices ) ] ) ) prompt_text = \"\" separator = separator_choices [ prompt ( prompt_text , value_proc = validate ) ] dateformat = separator . join ( ordering_choices [ ordering_no ] [ ] ) today = date . today ( ) text = ( \"\" \"\" . format ( dateformat , today . strftime ( dateformat ) ) ) if confirm ( text ) : break return dateformat def choose_time_format ( ) : choices = [ '' , '' ] while True : print ( \"\" ) print ( \"\" ) validate = partial ( validate_int , min_value = , max_value = ) prompt_text = \"\" timeformat = choices [ prompt ( prompt_text , default = , value_proc = validate ) ] now = datetime . now ( ) text = ( \"\" \"\" . format ( timeformat , now . strftime ( timeformat ) ) ) if confirm ( text ) : break return timeformat def find_vdirs ( ) : print ( \"\" \"\" ) if not confirm ( \"\" , default = '' ) : return None try : from vdirsyncer . cli import config except ImportError : print ( \"\" \"\" ) return None vdir_config = config . load_config ( ) vdirs = list ( ) for storage in vdir_config . storages . values ( ) : if storage [ '' ] == '' : ", "answer": "vdirs . append ( ( storage [ '' ] , storage [ '' ] , '' ) )"}, {"prompt": " from os_client_config import cloud_config from os_client_config import config from os_client_config import exceptions from os_client_config . tests import base import fixtures class TestEnviron ( base . TestCase ) : def setUp ( self ) : super ( TestEnviron , self ) . setUp ( ) self . useFixture ( fixtures . EnvironmentVariable ( '' , '' ) ) self . useFixture ( fixtures . EnvironmentVariable ( '' , '' ) ) self . useFixture ( fixtures . EnvironmentVariable ( '' , '' ) ) self . useFixture ( fixtures . EnvironmentVariable ( '' , '' ) ) self . useFixture ( fixtures . EnvironmentVariable ( '' , '' ) ) def test_get_one_cloud ( self ) : c = config . OpenStackConfig ( config_files = [ self . cloud_yaml ] , vendor_files = [ self . vendor_yaml ] ) self . assertIsInstance ( c . get_one_cloud ( ) , cloud_config . CloudConfig ) def test_no_fallthrough ( self ) : c = config . OpenStackConfig ( config_files = [ self . cloud_yaml ] , vendor_files = [ self . vendor_yaml ] ) self . assertRaises ( exceptions . OpenStackConfigException , c . get_one_cloud , '' ) def test_envvar_name_override ( self ) : self . useFixture ( fixtures . EnvironmentVariable ( '' , '' ) ) c = config . OpenStackConfig ( config_files = [ self . cloud_yaml ] , vendor_files = [ self . vendor_yaml ] ) cc = c . get_one_cloud ( '' ) ", "answer": "self . _assert_cloud_details ( cc )"}, {"prompt": " from south . utils import datetime_utils as datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . delete_column ( u'' , '' ) def backwards ( self , orm ) : db . add_column ( u'' , '' , self . gf ( '' ) ( related_name = '' , null = True , to = orm [ '' ] ) , keep_default = False ) models = { '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' , '' : \"\" , '' : \"\" } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) } , '' : { ", "answer": "'' : { '' : \"\" , '' : '' } ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future . utils import surrogateescape surrogateescape . register_surrogateescape ( ) __version__ = '' __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] def message_from_string ( s , * args , ** kws ) : \"\"\"\"\"\" from future . backports . email . parser import Parser return Parser ( * args , ** kws ) . parsestr ( s ) def message_from_bytes ( s , * args , ** kws ) : \"\"\"\"\"\" from future . backports . email . parser import BytesParser return BytesParser ( * args , ** kws ) . parsebytes ( s ) def message_from_file ( fp , * args , ** kws ) : \"\"\"\"\"\" ", "answer": "from future . backports . email . parser import Parser"}, {"prompt": " import datetime from south . db import db from south . v2 import DataMigration from django . db import models from freenasUI . common . system import get_sw_name class Migration ( DataMigration ) : def forwards ( self , orm ) : db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = '' , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) afp = orm . AFP ( ) afp . afp_srv_name = get_sw_name ( ) . lower ( ) afp . afp_srv_guest = False afp . afp_srv_local = True afp . afp_srv_ddp = False afp . save ( ) cifs = orm . CIFS ( ) cifs . cifs_srv_netbiosname = get_sw_name ( ) . lower ( ) cifs . cifs_srv_workgroup = '' cifs . cifs_srv_description = '' % ( get_sw_name ( ) , ) cifs . cifs_srv_doscharset = '' cifs . cifs_srv_unixcharset = '' cifs . cifs_srv_loglevel = '' cifs . cifs_srv_localmaster = True cifs . cifs_srv_timeserver = True cifs . cifs_srv_guest = '' cifs . cifs_srv_largerw = False cifs . cifs_srv_sendfile = True cifs . cifs_srv_easupport = False cifs . cifs_srv_dosattr = True cifs . cifs_srv_nullpw = False cifs . save ( ) ddns = orm . DynamicDNS ( ) ddns . ddns_provider = '' ddns . ddns_username = '' ddns . ddns_password = get_sw_name ( ) . lower ( ) ddns . ddns_wildcard = False ddns . save ( ) ftp = orm . FTP ( ) ftp . ftp_clients = ftp . ftp_ipconnections = ftp . ftp_loginattempt = ftp . ftp_timeout = ftp . ftp_rootlogin = False ftp . ftp_onlyanonymous = False ftp . ftp_onlylocal = False ftp . ftp_filemask = '' ftp . ftp_dirmask = '' ftp . ftp_fxp = ftp . ftp_resume = ", "answer": "ftp . ftp_defaultroot = "}, {"prompt": " import os import shutil import ConfigParser import urllib import data import rule import DFA from ast import literal_eval from pulsar . core . harry import Harry from pulsar . utils . preprocessing import derrick class ModelGenerator ( ) : def __init__ ( self , models_dir , path_conf , pcaps = \"\" , binaries = \"\" , nmf_components = , process = False ) : self . models_dir = models_dir self . path_conf = path_conf self . pcaps = pcaps self . binaries = binaries self . process = process self . nmf_components = nmf_components config = ConfigParser . RawConfigParser ( ) model_conf = os . path . join ( path_conf , \"\" ) config . readfp ( open ( model_conf ) ) self . prisma_dir = config . get ( '' , '' ) self . storage_dir = config . get ( '' , '' ) self . binaries_dir = os . path . abspath ( os . path . join ( self . storage_dir , '' ) ) self . analyses_dir = os . path . abspath ( os . path . join ( self . storage_dir , '' ) ) self . analyses_ival = literal_eval ( config . get ( '' , '' ) ) if self . analyses_ival : self . analyses_ival = range ( self . analyses_ival [ ] , self . analyses_ival [ - ] + ) self . whitespace = config . get ( '' , '' ) self . order = literal_eval ( config . get ( '' , '' ) ) self . ngram = literal_eval ( config . get ( '' , '' ) ) self . dograph = literal_eval ( config . get ( '' , '' ) ) self . minimize = literal_eval ( config . get ( '' , '' ) ) self . subrules = literal_eval ( config . get ( '' , '' ) ) self . colorFieldStates = literal_eval ( config . get ( '' , '' ) ) def generate_model ( self ) : if self . pcaps : self . _generate_model_pcaps ( ) elif isinstance ( self . binaries , list ) : self . _generate_model_binaries ( ) def _generate_model_pcaps ( self ) : for pcap_origin in self . pcaps : pcap = os . path . basename ( pcap_origin ) pcap_noext = pcap . split ( '' ) [ ] pcap_named_dir = os . path . join ( self . models_dir , pcap_noext ) if not os . path . exists ( pcap_named_dir ) : print \"\" . format ( pcap_named_dir ) os . makedirs ( pcap_named_dir ) pcap_path_model = os . path . join ( pcap_named_dir , pcap ) shutil . copyfile ( pcap_origin , pcap_path_model ) self . _extract_derrick ( pcap_noext ) self . _generate_prisma_input ( pcap_noext ) self . _generate_clusters ( pcap_noext ) self . _build_model_files ( pcap_noext ) def _generate_model_binaries ( self ) : if len ( self . binaries ) == : self . binaries = os . listdir ( self . binaries_dir ) pcaps = { b : [ ] for b in self . binaries } if not self . analyses_ival : for path , dirs , files in os . walk ( os . path . abspath ( self . analyses_dir ) ) : ", "answer": "for file in files :"}, {"prompt": " import os . path from sfmigration . common . softwarefactory import SFRedmineMigrator from sfmigration . common import utils from sfmigration . issues . github import GithubImporter logger = utils . logger def get_values ( config_file = '' ) : if not os . path . isfile ( config_file ) : logger . error ( \"\" ) raise source_github = { '' : '' , '' : '' , '' : '' , '' : '' } for key in source_github . iterkeys ( ) : source_github [ key ] = utils . get_config_value ( config_file , '' , key ) dest_redmine = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , ", "answer": "'' : '' , '' : [ ] ,"}, {"prompt": " \"\"\"\"\"\" import abc import os import random import re import shutil import socket import ssl import subprocess import sys import tempfile import types import uuid from oslo_concurrency import processutils as utils import six from proliantutils import exception from proliantutils . ilo import common from proliantutils import log if six . PY3 : def b ( x ) : return bytes ( x , '' ) else : def b ( x ) : return x LOG = log . get_logger ( __name__ ) SUPPORTED_FIRMWARE_UPDATE_COMPONENTS = [ '' , '' , '' , '' , '' ] RAW_FIRMWARE_EXTNS = [ '' , '' , '' ] def check_firmware_update_component ( func ) : \"\"\"\"\"\" @ six . wraps ( func ) def wrapper ( self , filename , component_type ) : \"\"\"\"\"\" component_type = component_type and component_type . lower ( ) if ( component_type not in SUPPORTED_FIRMWARE_UPDATE_COMPONENTS ) : msg = ( \"\" \"\" % { '' : component_type } ) LOG . error ( self . _ ( msg ) ) raise exception . InvalidInputError ( msg ) return func ( self , filename , component_type ) return wrapper @ six . add_metaclass ( abc . ABCMeta ) class FirmwareImageControllerBase ( object ) : \"\"\"\"\"\" def __init__ ( self , fw_file ) : self . fw_file = fw_file file_name , file_ext_with_dot = common . get_filename_and_extension_of ( fw_file ) self . fw_filename = file_name self . fw_file_ext = file_ext_with_dot class FirmwareImageUploader ( FirmwareImageControllerBase ) : \"\"\"\"\"\" HTTP_UPLOAD_HEADER = ( \"\" \"\" \"\" \"\" \"\" ) def upload_file_to ( self , addressinfo , timeout ) : \"\"\"\"\"\" self . hostname , self . port = addressinfo self . timeout = timeout filename = self . fw_file firmware = open ( filename , '' ) . read ( ) boundary = b ( '' + str ( random . randint ( , ) ) + '' ) while boundary in firmware : boundary = b ( '' + str ( random . randint ( , ) ) + '' ) parts = [ b ( \"\" ) + boundary + b ( \"\"\"\"\"\" \"\"\"\"\"\" ) , b ( \"\" ) + boundary + b ( '''''' '''''' ) + b ( filename ) + b ( '''''' ) , firmware , b ( \"\" ) + boundary + b ( \"\" ) , ] total_bytes = sum ( [ len ( x ) for x in parts ] ) sock = self . _get_socket ( ) sock . write ( b ( self . HTTP_UPLOAD_HEADER % ( total_bytes , boundary . decode ( '' ) ) ) ) for part in parts : sock . write ( part ) data = '' try : while True : d = sock . read ( ) data += d . decode ( '' ) if not d : break except socket . sslerror : e = sys . exc_info ( ) [ ] if not data : raise exception . IloConnectionError ( \"\" \"\" % { '' : self . hostname , '' : self . port , '' : str ( e ) } ) cookie_match = re . search ( '' , data ) if not cookie_match : raise exception . IloError ( \"\" \"\" % filename ) return cookie_match . group ( ) def _get_socket ( self , sslversion = ssl . PROTOCOL_TLSv1 ) : \"\"\"\"\"\" err = None sock = None try : for res in socket . getaddrinfo ( self . hostname , self . port , , socket . SOCK_STREAM ) : af , socktype , proto , canonname , sa = res try : sock = socket . socket ( af , socktype , proto ) sock . settimeout ( self . timeout ) sock . connect ( sa ) except socket . timeout : if sock is not None : sock . close ( ) err = exception . IloConnectionError ( \"\" % { '' : self . hostname , '' : self . port } ) except socket . error : if sock is not None : sock . close ( ) e = sys . exc_info ( ) [ ] err = exception . IloConnectionError ( \"\" % { '' : self . hostname , '' : self . port , '' : str ( e ) } ) except Exception : raise exception . IloConnectionError ( \"\" % self . hostname ) if err is not None : raise err try : return ssl . wrap_socket ( sock , ssl_version = sslversion ) except socket . sslerror : e = sys . exc_info ( ) [ ] msg = ( getattr ( e , '' , None ) or getattr ( e , '' , None ) ) if ( '' in msg ) and ( sslversion == ssl . PROTOCOL_TLSv1 ) : return self . _get_socket ( ssl . PROTOCOL_SSLv3 ) raise exception . IloConnectionError ( \"\" \"\" % { '' : self . hostname , '' : self . port , '' : str ( e ) } ) class FirmwareImageExtractor ( FirmwareImageControllerBase ) : \"\"\"\"\"\" def extract ( self ) : \"\"\"\"\"\" target_file = self . fw_file common . add_exec_permission_to ( target_file ) temp_dir = tempfile . mkdtemp ( ) extract_path = os . path . join ( temp_dir , self . fw_filename ) try : self . _do_extract ( target_file , extract_path ) except exception . ImageExtractionFailed : shutil . rmtree ( temp_dir , ignore_errors = True ) raise firmware_file_path = _get_firmware_file_in_new_path ( extract_path ) shutil . rmtree ( temp_dir , ignore_errors = True ) if not firmware_file_path : raise exception . InvalidInputError ( \"\" % target_file ) return firmware_file_path , True ", "answer": "def get_fw_extractor ( fw_file ) :"}, {"prompt": " from traitsui . toolkit import toolkit_object ", "answer": "PyMimeData = toolkit_object ( '' ) "}, {"prompt": " from django . contrib import admin from django . forms import models , ValidationError from django . utils . translation import get_language , ugettext_lazy as _ from models import TaxBoundry , TaxRate , Taxable ADDRESS_FIELDS = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ) ZIP_FIELDS = ( '' , '' , '' , '' ) RATE_FIELDS = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ) class TaxBoundryOptions ( admin . ModelAdmin ) : fieldsets = ( ( None , { '' : ( '' , '' , '' ) } ) , ( '' , { '' : ( '' , ) , '' : ZIP_FIELDS , } ) , ( '' , { '' : ( '' , ) , '' : ADDRESS_FIELDS , } ) , ( '' , { '' : RATE_FIELDS , } ) ) list_display = ( '' , '' , '' , '' , '' , '' , '' , ) class TaxBoundryForm ( models . ModelForm ) : def clean ( self ) : type = self . cleaned_data [ '' ] if type in ( '' , '' ) : for field in ADDRESS_FIELDS : self . cleaned_data [ field ] = None if type == '' : self . cleaned_data [ '' ] = None self . cleaned_data [ '' ] = None low = self . cleaned_data [ '' ] high = self . cleaned_data [ '' ] if high is None or low is None : raise ValidationError ( _ ( \"\" ) ) elif type == '' : low = self . cleaned_data [ '' ] high = self . cleaned_data [ '' ] low_ext = self . cleaned_data [ '' ] high_ext = self . cleaned_data [ '' ] ", "answer": "if high is None or low is None or low_ext is None or high_ext is None :"}, {"prompt": " from setuptools import setup , find_packages tests_require = [ '' , '' , '' , '' ] setup ( name = '' , version = '' , description = \"\" , author = \"\" , author_email = \"\" , license = \"\" , packages = find_packages ( ) , include_package_data = True , zip_safe = False , exclude = [ '' ] , install_requires = [ '' , ", "answer": "'' ,"}, {"prompt": " from twisted . internet import defer from synapse . api . errors import LimitExceededError , SynapseError , AuthError from synapse . crypto . event_signing import add_hashes_and_signatures from synapse . api . constants import Membership , EventTypes from synapse . types import UserID , RoomAlias , Requester from synapse . push . action_generator import ActionGenerator from synapse . util . logcontext import PreserveLoggingContext import logging logger = logging . getLogger ( __name__ ) VISIBILITY_PRIORITY = ( \"\" , \"\" , \"\" , \"\" , ) class BaseHandler ( object ) : \"\"\"\"\"\" def __init__ ( self , hs ) : self . store = hs . get_datastore ( ) self . auth = hs . get_auth ( ) self . notifier = hs . get_notifier ( ) self . state_handler = hs . get_state_handler ( ) self . distributor = hs . get_distributor ( ) self . ratelimiter = hs . get_ratelimiter ( ) self . clock = hs . get_clock ( ) self . hs = hs self . signing_key = hs . config . signing_key [ ] self . server_name = hs . hostname self . event_builder_factory = hs . get_event_builder_factory ( ) @ defer . inlineCallbacks def filter_events_for_clients ( self , user_tuples , events , event_id_to_state ) : \"\"\"\"\"\" forgotten = yield defer . gatherResults ( [ self . store . who_forgot_in_room ( room_id , ) for room_id in frozenset ( e . room_id for e in events ) ] , consumeErrors = True ) event_id_forgotten = frozenset ( row [ \"\" ] for rows in forgotten for row in rows ) def allowed ( event , user_id , is_peeking ) : state = event_id_to_state [ event . event_id ] visibility_event = state . get ( ( EventTypes . RoomHistoryVisibility , \"\" ) , None ) if visibility_event : visibility = visibility_event . content . get ( \"\" , \"\" ) else : visibility = \"\" if visibility not in VISIBILITY_PRIORITY : visibility = \"\" if visibility == \"\" : return True if event . type == EventTypes . RoomHistoryVisibility : prev_content = event . unsigned . get ( \"\" , { } ) prev_visibility = prev_content . get ( \"\" , None ) if prev_visibility not in VISIBILITY_PRIORITY : prev_visibility = \"\" new_priority = VISIBILITY_PRIORITY . index ( visibility ) old_priority = VISIBILITY_PRIORITY . index ( prev_visibility ) if old_priority < new_priority : visibility = prev_visibility membership_event = state . get ( ( EventTypes . Member , user_id ) , None ) if membership_event : if membership_event . event_id in event_id_forgotten : membership = None else : membership = membership_event . membership else : membership = None if membership == Membership . JOIN : return True if visibility == \"\" : return False elif visibility == \"\" : return membership == Membership . INVITE else : return not is_peeking defer . returnValue ( { user_id : [ event for event in events if allowed ( event , user_id , is_peeking ) ] for user_id , is_peeking in user_tuples } ) @ defer . inlineCallbacks def _filter_events_for_client ( self , user_id , events , is_peeking = False ) : \"\"\"\"\"\" types = ( ( EventTypes . RoomHistoryVisibility , \"\" ) , ( EventTypes . Member , user_id ) , ) event_id_to_state = yield self . store . get_state_for_events ( frozenset ( e . event_id for e in events ) , types = types ) res = yield self . filter_events_for_clients ( [ ( user_id , is_peeking ) ] , events , event_id_to_state ) defer . returnValue ( res . get ( user_id , [ ] ) ) def ratelimit ( self , requester ) : time_now = self . clock . time ( ) allowed , time_allowed = self . ratelimiter . send_message ( requester . user . to_string ( ) , time_now , msg_rate_hz = self . hs . config . rc_messages_per_second , burst_count = self . hs . config . rc_message_burst_count , ) if not allowed : raise LimitExceededError ( retry_after_ms = int ( * ( time_allowed - time_now ) ) , ) ", "answer": "@ defer . inlineCallbacks"}, {"prompt": " import sys import unittest from StringIO import StringIO class CrashMailTests ( unittest . TestCase ) : def _getTargetClass ( self ) : from superlance . crashmail import CrashMail return CrashMail def _makeOne ( self , * opts ) : return self . _getTargetClass ( ) ( * opts ) def setUp ( self ) : import tempfile self . tempdir = tempfile . mkdtemp ( ) def tearDown ( self ) : import shutil shutil . rmtree ( self . tempdir ) def _makeOnePopulated ( self , programs , any , response = None ) : import os sendmail = '' % os . path . join ( self . tempdir , '' ) email = '' header = '' prog = self . _makeOne ( programs , any , email , sendmail , header ) prog . stdin = StringIO ( ) prog . stdout = StringIO ( ) prog . stderr = StringIO ( ) return prog def test_runforever_not_process_state_exited ( self ) : programs = { '' : , '' : , '' : } groups = { } any = None prog = self . _makeOnePopulated ( programs , any ) prog . stdin . write ( '' ) prog . stdin . seek ( ) prog . runforever ( test = True ) self . assertEqual ( prog . stderr . getvalue ( ) , '' ) def test_runforever_expected_exit ( self ) : programs = [ '' ] any = None prog = self . _makeOnePopulated ( programs , any ) payload = ( '' '' ) prog . stdin . write ( '' % len ( payload ) ) prog . stdin . write ( payload ) prog . stdin . seek ( ) prog . runforever ( test = True ) self . assertEqual ( prog . stderr . getvalue ( ) , '' ) def test_runforever_unexpected_exit ( self ) : programs = [ '' ] any = None prog = self . _makeOnePopulated ( programs , any ) payload = ( '' '' ) prog . stdin . write ( '' % len ( payload ) ) prog . stdin . write ( payload ) prog . stdin . seek ( ) prog . runforever ( test = True ) output = prog . stderr . getvalue ( ) lines = output . split ( '' ) self . assertEqual ( lines [ ] , '' ) self . assertEqual ( lines [ ] , '' ) self . assertEqual ( lines [ ] , '' ) self . assertEqual ( lines [ ] , '' ) self . failUnless ( '' in lines [ ] ) self . assertEqual ( lines [ ] , '' ) self . failUnless ( ", "answer": "'' in lines [ ] )"}, {"prompt": " import argparse parent_parser = argparse . ArgumentParser ( add_help = False ) config_group = parent_parser . add_argument_group ( title = \"\" ) config_group . add_argument ( '' , '' , help = \"\" , default = '' ) config_group . add_argument ( '' , '' , help = \"\" , default = '' ) log_group = parent_parser . add_argument_group ( title = \"\" ) log_group . add_argument ( '' , '' , help = \"\" , default = '' , dest = '' ) log_group . add_argument ( '' , '' , help = \"\" , default = None ) ", "answer": "log_group . add_argument ( '' , '' , help = \"\" , default = '' )"}, {"prompt": " import unittest import numpy as np import deltasigma as ds class TestDSQuantize ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : t = np . arange ( - , , ) t = t . reshape ( ( , t . shape [ ] ) ) y = t for _ in range ( ) : y = np . concatenate ( ( y , t ) , axis = ) n = np . array ( [ , , ] ) self . re1_first = ds . ds_quantize ( y , n ) self . re1_second = ds . ds_quantize ( y [ , : ] , n = ) self . re2 = np . array ( [ [ - , - , - , - , - , - , - , - , - , - , - , ", "answer": "- , - , - , - , , , , , , , , , ,"}, {"prompt": " from db . redis . user_activity_graph import UserActivityGraph ", "answer": "def add_activity ( client , actuser , actto , acttype , actdict ) :"}, {"prompt": " __author__ = '' import websocket import threading import struct class Session ( object ) : def __init__ ( self ) : self . running = False self . thread = None self . ws = None self . host = '' self . port = self . inbound = [ ] def connect ( self , host , port ) : if not self . is_connected ( ) : if type ( port ) == int : port = str ( port ) url = '' + host + '' + port + '' try : self . ws = websocket . WebSocket ( ) self . ws . connect ( url , origin = '' ) self . running = True self . inbound = [ ] self . thread = threading . Thread ( name = '' , target = self . run ) self . thread . start ( ) return True except Exception as ex : print ( '' + url ) return False def disconnect ( self ) : if self . is_connected ( ) : self . running = False self . thread = None try : if self . ws . connected : self . ws . close ( ) except : pass return True return False def is_connected ( self ) : return self . running and self . ws . connected def run ( self ) : while self . is_connected ( ) and self . thread == threading . current_thread ( ) : try : if self . ws . connected : data = self . ws . recv ( ) self . inbound . append ( data ) except Exception as ex : print ( '' + str ( self . ws . connected ) + '' + str ( ex ) ) return def read ( self ) : if self . is_connected ( ) : if len ( self . inbound ) > : data = self . inbound [ ] self . inbound = self . inbound [ : ] return data return None def write ( self , data ) : if self . is_connected ( ) : if type ( data ) == bytearray : data = bytes ( data ) if len ( data ) > : ", "answer": "try :"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from __future__ import unicode_literals from django . utils . six . moves import urllib_parse from django . http import HttpResponseRedirect , HttpResponseForbidden from django . conf import settings from django . contrib . auth import REDIRECT_FIELD_NAME ", "answer": "from django . contrib . auth . views import login , logout"}, {"prompt": " \"\"\"\"\"\" import pybde from dfvfs import dependencies from dfvfs . file_io import file_object_io from dfvfs . lib import bde ", "answer": "from dfvfs . lib import errors"}, {"prompt": " from __future__ import unicode_literals import spotify from spotify import ffi , lib __all__ = [ '' , ] class Offline ( object ) : \"\"\"\"\"\" def __init__ ( self , session ) : self . _session = session @ property def tracks_to_sync ( self ) : \"\"\"\"\"\" return lib . sp_offline_tracks_to_sync ( self . _session . _sp_session ) @ property def num_playlists ( self ) : \"\"\"\"\"\" return lib . sp_offline_num_playlists ( self . _session . _sp_session ) @ property def sync_status ( self ) : \"\"\"\"\"\" sp_offline_sync_status = ffi . new ( '' ) syncing = lib . sp_offline_sync_get_status ( self . _session . _sp_session , sp_offline_sync_status ) if syncing : return spotify . OfflineSyncStatus ( sp_offline_sync_status ) @ property def time_left ( self ) : \"\"\"\"\"\" return lib . sp_offline_time_left ( self . _session . _sp_session ) class OfflineSyncStatus ( object ) : \"\"\"\"\"\" ", "answer": "def __init__ ( self , sp_offline_sync_status ) :"}, {"prompt": " from importlib import import_module from django . conf import settings from django . test . utils import override_settings from django . utils . translation import LANGUAGE_SESSION_KEY from cms import api from cms . test_utils . testcases import CMSTestCase from cms . utils import i18n @ override_settings ( LANGUAGE_CODE = '' , LANGUAGES = ( ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ) , CMS_LANGUAGES = { : [ { '' : '' , '' : '' , '' : True } , { '' : '' , '' : '' , '' : False } , ] , '' : { '' : True , '' : False , } , } , SITE_ID = , ) class TestLanguages ( CMSTestCase ) : def test_language_code ( self ) : self . assertEqual ( i18n . get_language_code ( '' ) , '' ) self . assertEqual ( i18n . get_current_language ( ) , '' ) def test_get_languages_default_site ( self ) : result = i18n . get_languages ( ) self . assertEqual ( , len ( result ) ) lang = result [ ] self . assertEqual ( lang [ '' ] , '' ) self . assertEqual ( i18n . get_language_code ( lang [ '' ] ) , '' ) self . assertEqual ( lang [ '' ] , True ) lang = result [ ] self . assertEqual ( lang [ '' ] , '' ) self . assertEqual ( i18n . get_language_code ( lang [ '' ] ) , '' ) ", "answer": "self . assertEqual ( lang [ '' ] , False )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import socket import struct import gnlpy . netlink as netlink IPVS_MASQUERADING = IPVS_LOCAL = IPVS_TUNNELING = IPVS_ROUTING = IPVS_METHODS = set ( [ IPVS_MASQUERADING , IPVS_LOCAL , IPVS_TUNNELING , IPVS_ROUTING ] ) IpvsStatsAttrList = netlink . create_attr_list_type ( '' , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ) IpvsStatsAttrList64 = netlink . create_attr_list_type ( '' , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ( '' , netlink . U64Type ) , ) IpvsServiceAttrList = netlink . create_attr_list_type ( '' , ( '' , netlink . U16Type ) , ( '' , netlink . U16Type ) , ( '' , netlink . BinaryType ) , ( '' , netlink . Net16Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . NulStringType ) , ( '' , netlink . BinaryType ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , IpvsStatsAttrList ) , ( '' , netlink . NulStringType ) , ( '' , IpvsStatsAttrList64 ) , ) IpvsDestAttrList = netlink . create_attr_list_type ( '' , ( '' , netlink . BinaryType ) , ( '' , netlink . Net16Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . I32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , IpvsStatsAttrList ) , ( '' , netlink . U16Type ) , ( '' , IpvsStatsAttrList64 ) , ) IpvsDaemonAttrList = netlink . create_attr_list_type ( '' , ( '' , netlink . U32Type ) , ( '' , netlink . NulStringType ) , ( '' , netlink . U32Type ) , ) IpvsInfoAttrList = netlink . create_attr_list_type ( '' , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ) IpvsCmdAttrList = netlink . create_attr_list_type ( '' , ( '' , IpvsServiceAttrList ) , ( '' , IpvsDestAttrList ) , ( '' , IpvsDaemonAttrList ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ( '' , netlink . U32Type ) , ) IpvsMessage = netlink . create_genl_message_type ( '' , '' , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , ( '' , IpvsCmdAttrList ) , required_modules = [ '' ] , ) def verbose ( f ) : def g ( self , * args , ** kwargs ) : if self . verbose : s_args = [ repr ( a ) for a in args ] s_args . extend ( [ '' . format ( k , repr ( v ) ) for k , v in kwargs . items ( ) ] ) print ( '' . format ( f . __name__ , '' . join ( s_args ) ) ) return f ( self , * args , ** kwargs ) return g def _validate_ip ( ip ) : try : socket . inet_pton ( _to_af ( ip ) , ip ) return True except socket . error : return False def _to_af ( ip ) : return socket . AF_INET6 if '' in ip else socket . AF_INET def _to_af_union ( ip ) : af = _to_af ( ip ) return af , socket . inet_pton ( af , ip ) . ljust ( , str ( '' ) ) def _from_af_union ( af , addr ) : n = if af == socket . AF_INET else return socket . inet_ntop ( af , addr [ : n ] ) def _to_proto_num ( proto ) : if proto is None : return None if proto . lower ( ) == '' : return socket . IPPROTO_TCP elif proto . lower ( ) == '' : return socket . IPPROTO_UDP else : assert False , '' % proto def _from_proto_num ( n ) : if n is None : return None if n == socket . IPPROTO_TCP : return '' elif n == socket . IPPROTO_UDP : return '' else : assert False , '' % n class Dest ( object ) : \"\"\"\"\"\" def __init__ ( self , d = { } , validate = False ) : self . ip_ = d . get ( '' , None ) self . weight_ = d . get ( '' , None ) self . port_ = d . get ( '' , None ) self . fwd_method_ = d . get ( '' , IPVS_TUNNELING ) def __repr__ ( self ) : return '' % ( self . ip ( ) , self . weight ( ) ) def ip ( self ) : return self . ip_ def weight ( self ) : return self . weight_ def port ( self ) : return self . port_ def fwd_method ( self ) : return self . fwd_method_ def validate ( self ) : assert _validate_ip ( self . ip_ ) assert isinstance ( self . weight_ , int ) assert self . weight_ >= - assert self . fwd_method_ in IPVS_METHODS def to_dict ( self ) : return { '' : self . ip_ , '' : self . weight_ , } def to_attr_list ( self ) : af , addr = _to_af_union ( self . ip_ ) return IpvsDestAttrList ( addr_family = af , addr = addr , port = self . port_ , fwd_method = self . fwd_method_ ) def __eq__ ( self , other ) : return isinstance ( other , Dest ) and self . to_dict ( ) == other . to_dict ( ) def __ne__ ( self , other ) : return not self . __eq__ ( other ) @ staticmethod def from_attr_list ( lst , default_af = None ) : return Dest ( d = { '' : _from_af_union ( lst . get ( '' , default_af ) , lst . get ( '' ) ) , '' : lst . get ( '' ) , '' : lst . get ( '' ) , '' : lst . get ( '' ) } , validate = True , ", "answer": ")"}, {"prompt": " from django . conf import settings from django . test import TestCase from django . contrib . sites . models import Site ", "answer": "from django . core . urlresolvers import reverse"}, {"prompt": " from __future__ import unicode_literals import logging from json import dumps from urllib import urlencode from urllib2 import Request , urlopen from datetime import datetime , timedelta from flask_protorpc . proto import message_from_json , message_to_json from werkzeug import exceptions from client . orgs import orgs from client . repos import repos from client . users import users from client . events import events from client . issues import issues from client . gitdata import gitdata from client . pullreqs import pullreqs __all__ = [ '' ] class Github : def __init__ ( self , app , config , access_token , username = None , password = None ) : if not app : raise ValueError ( '' ) if not access_token : raise ValueError ( '' ) self . app = app self . config = config self . access_token = access_token self . _username = username self . _password = password self . orgs = orgs . Orgs ( self ) self . repos = repos . Repos ( self ) self . users = users . Users ( self ) self . events = events . Events ( self ) self . issues = issues . Issues ( self ) self . gitdata = gitdata . GitData ( self ) self . pullreqs = pullreqs . PullRequests ( self ) def set_auth_type ( self ) : return '' def auth ( self ) : return ( self . username ( ) , self . password ( ) ) def request ( self , http_verb , path , data = None ) : verb = http_verb . upper ( ) methodmap = dict ( GET = self . get , PUT = self . put , HEAD = self . head , POST = self . post , PATCH = self . patch , DELETE = self . delete ) if verb in methodmap : return methodmap [ verb ] ( self . _url ( path ) ) else : raise ValueError ( '' ) def call ( self , path = None , query = None , data = None , method = '' ) : if method == '' and ( data is None or len ( data ) < ) : data = '' result = '' status = request = Request ( self . _url ( self . app . base_url + path , query ) , data = data , headers = { '' : '' , '' : '' + self . access_token } ) rate_limit = rate_limit_remaining = user_scopes = [ ] accepted_scopes = [ ] try : response = urlopen ( request ) result = response . read ( ) response . close ( ) status = response . code rate_limit = int ( response . headers . dict . get ( '' , ) ) rate_limit_remaining = int ( response . headers . dict . get ( '' , ) ) user_scopes = response . headers . dict . get ( '' , '' ) . split ( '' ) accepted_scopes = response . headers . dict . get ( '' , '' ) . split ( '' ) print '' % ( rate_limit ) print '' % ( rate_limit_remaining ) print '' % ( user_scopes ) print '' % ( accepted_scopes ) except : import traceback print '' % traceback . format_exc ( ) if status == : raise exceptions . Unauthorized ( '''''' % result ) elif status == : raise exceptions . MethodNotAllowed ( '''''' ) elif status == : raise exceptions . NotFound ( '''''' % result ) elif status > : raise exceptions . BadRequest ( '' % ( status , result ) ) return '' + result + '' def head ( self , path , query = None , msg_type = None ) : response = self . call ( path , query = query , method = '' ) return self . _remote ( response , msg_type ) def get ( self , path , query = None , msg_type = None ) : response = self . call ( path , query = query , method = '' ) return self . _remote ( response , msg_type ) def post ( self , path , query = None , data = None , msg_type = None ) : response = self . call ( path , query = query , data = self . msg ( data ) , method = '' ) return self . _remote ( response , msg_type ) def patch ( self , path , query = None , data = None , msg_type = None ) : ", "answer": "response = self . call ( path , query = query , data = self . msg ( data ) , method = '' )"}, {"prompt": " from south . utils import datetime_utils as datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( u'' , '' , self . gf ( '' ) ( default = ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( u'' , '' ) models = { u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } )"}, {"prompt": " from django . utils . translation import ugettext_lazy as _ from django . utils . translation import ungettext_lazy from horizon import tables from openstack_dashboard import api ", "answer": "class CreateRoleLink ( tables . LinkAction ) :"}, {"prompt": " '''''' import unittest import time from pyglet import media from pyglet . media import procedural class TEST_CASE ( unittest . TestCase ) : def test_method ( self ) : source = procedural . WhiteNoise ( ) player = media . Player ( ) player . queue ( source ) player . play ( ) start_time = time . time ( ) stage = while player . source : ", "answer": "if stage == and time . time ( ) - start_time > :"}, {"prompt": " import logging import re import django . contrib . auth . forms from django import forms from django . contrib . auth . models import User , Group from django . forms import ValidationError from django . forms . util import ErrorList from django . utils . translation import get_language , ugettext as _ , ugettext_lazy as _t from desktop import conf as desktop_conf from desktop . lib . django_util import get_username_re_rule , get_groupname_re_rule from desktop . settings import LANGUAGES from useradmin . models import GroupPermission , HuePermission from useradmin . models import get_default_user_group from useradmin . password_policy import get_password_validators LOG = logging . getLogger ( __name__ ) def get_server_choices ( ) : if desktop_conf . LDAP . LDAP_SERVERS . get ( ) : return [ ( ldap_server_record_key , ldap_server_record_key ) for ldap_server_record_key in desktop_conf . LDAP . LDAP_SERVERS . get ( ) ] else : return [ ] def validate_dn ( dn ) : if not dn : raise ValidationError ( _ ( '' ) ) def validate_username ( username_pattern ) : validator = re . compile ( r\"\" % get_username_re_rule ( ) ) if not username_pattern : raise ValidationError ( _ ( '' ) ) if len ( username_pattern ) > : raise ValidationError ( _ ( '' ) ) if not validator . match ( username_pattern ) : raise ValidationError ( _ ( \"\" ) ) def validate_groupname ( groupname_pattern ) : validator = re . compile ( r\"\" % get_groupname_re_rule ( ) ) if not groupname_pattern : raise ValidationError ( _ ( '' ) ) if len ( groupname_pattern ) > : raise ValidationError ( _ ( '' ) ) if not validator . match ( groupname_pattern ) : raise ValidationError ( _ ( \"\" ) ) def validate_first_name ( first_name ) : if first_name and len ( first_name ) > : raise ValidationError ( _ ( '' ) ) def validate_last_name ( last_name ) : if last_name and len ( last_name ) > : raise ValidationError ( _ ( '' ) ) class UserChangeForm ( django . contrib . auth . forms . UserChangeForm ) : \"\"\"\"\"\" GENERIC_VALIDATION_ERROR = _ ( \"\" ) username = forms . RegexField ( label = _t ( \"\" ) , max_length = , regex = '' % ( get_username_re_rule ( ) , ) , ", "answer": "help_text = _t ( \"\" ) ,"}, {"prompt": " from __future__ import print_function from bcc import BPF import argparse from time import strftime import ctypes as ct examples = \"\"\"\"\"\" parser = argparse . ArgumentParser ( description = \"\" , formatter_class = argparse . RawDescriptionHelpFormatter , epilog = examples ) parser . add_argument ( \"\" , \"\" , help = \"\" ) args = parser . parse_args ( ) debug = bpf_text = \"\"\"\"\"\" TASK_COMM_LEN = DNAME_INLINE_LEN = class Data ( ct . Structure ) : _fields_ = [ ( \"\" , ct . c_ulonglong ) , ( \"\" , ct . c_ulonglong ) , ( \"\" , ct . c_char * TASK_COMM_LEN ) , ( \"\" , ct . c_char * DNAME_INLINE_LEN ) ] if args . pid : bpf_text = bpf_text . replace ( '' , '' % args . pid ) else : bpf_text = bpf_text . replace ( '' , '' ) if debug : ", "answer": "print ( bpf_text )"}, {"prompt": " \"\"\"\"\"\" from six import iteritems import googleapiclient try : import oauth2client except ImportError : raise RuntimeError ( '' '' '' '' '' ) from googleapiclient import channel from googleapiclient import discovery from googleapiclient import errors from googleapiclient import http ", "answer": "from googleapiclient import mimeparse"}, {"prompt": " \"\"\"\"\"\" from django import VERSION as DJANGO_VERSION import os try : from local_settings import ROOT_PATH , DEPLOYMENT_PREFIX , DEBUG , ADMINS , MANAGERS , DATABASES except ImportError : ROOT_PATH = os . getcwd ( ) DEPLOYMENT_PREFIX = '' DEBUG = True ADMINS = ( ) MANAGERS = ADMINS DATABASES = { '' : { '' : '' , '' : os . path . join ( ROOT_PATH , '' ) , } } TEMPLATE_DEBUG = DEBUG try : from random import choice from local_settings import GIT_BINARY , SECRET_KEY except ImportError : GIT_BINARY = '' SECRET_KEY = '' . join ( [ chr ( choice ( range ( ) ) ) for _ in range ( ) ] ) try : from subprocess import check_output commit_log = check_output ( [ GIT_BINARY , '' , '' ] ) ", "answer": "COMMIT_TAG = commit_log . split ( '' ) [ ] . split ( ) [ ]"}, {"prompt": " \"\"\"\"\"\" from flask import request , current_app from flask_mail import Message from logging import Handler , ERROR from . . ext import mail def loader_meta ( app = None ) : \"\"\"\"\"\" from . views import core app . register_blueprint ( core ) from . ext import admin admin . init_app ( app ) from flask_bootstrap import Bootstrap bootstrap = Bootstrap ( ) bootstrap . init_app ( app ) from flask import render_template app . errorhandler ( ) ( lambda e : ( render_template ( '' ) , ) ) if not app . debug and app . config . get ( '' ) : mailhandler = FlaskMailHandler ( ERROR ) app . logger . addHandler ( mailhandler ) ", "answer": "loader_meta . priority = "}, {"prompt": " COMMIT = \"\" def check_description ( document ) : actual = \"\" for row in document . findAll ( \"\" ) : cells = row . findAll ( \"\" ) if len ( cells ) >= and cells [ ] . has_key ( \"\" ) and cells [ ] [ \"\" ] == \"\" and cells [ ] . a and cells [ ] . a . string and cells [ ] . a . string . endswith ( \"\" ) and cells [ ] . i and cells [ ] . i . string : actual = cells [ ] . i . string break testing . expect . check ( u\"\" , actual ) with frontend . signin ( ) : frontend . page ( \"\" , params = { \"\" : \"\" , ", "answer": "\"\" : COMMIT } ,"}, {"prompt": " class SimpleEngagementCalculator ( object ) : def calculate_user_engagement_score ( self , user , start_date , end_date ) : return ROOT_URLCONF = None ", "answer": "DATABASE_ENGINE = ''"}, {"prompt": " __author__ = '' import unittest import rdflib from rdflib . plugins . sparql . processor import SPARQLResult import pandas as pd from mock import patch ", "answer": "from niquery . query import QueryBase , SelectQuery , AskQuery"}, {"prompt": " import sys from gm_custom import git_push_remotes argc = len ( sys . argv ) if argc < : ", "answer": "print"}, {"prompt": " \"\"\"\"\"\" import sys _PYTHON3 = sys . version_info >= ( , , ) if _PYTHON3 : long = int unicode = str class Error ( Exception ) : pass __all__ = [ \"\" , \"\" ] def deepcopy ( x ) : \"\"\"\"\"\" try : return _deepcopy_dispatch [ type ( x ) ] ( x ) except KeyError : raise Error ( '' + '' % type ( x ) ) _deepcopy_dispatch = d = { } def _deepcopy_atomic ( x ) : return x ", "answer": "for x in ( type ( None ) , int , long , float ,"}, {"prompt": " import requests import json import sys import os import conn import extra_functions import storage_volume os . system ( '' ) if extra_functions . volume_check ( ) == False : storage_volume . post ( ) headers = conn . headers auth = conn . auth url = conn . url + '' payload = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : ", "answer": "}"}, {"prompt": " \"\"\"\"\"\" from shutit_module import ShutItModule , ShutItException , ShutItFailException import shutit_util import urllib import shutit_global import os import signal import sys import logging from distutils import spawn def stop_all ( shutit , run_order = - ) : \"\"\"\"\"\" cfg = shutit . cfg if cfg [ '' ] [ '' ] >= : print ( '' + shutit_util . colour ( '' , '' ) ) shutit_util . util_raw_input ( ) for module_id in shutit_util . module_ids ( shutit , rev = True ) : shutit_module_obj = shutit . shutit_map [ module_id ] if run_order == - or shutit_module_obj . run_order <= run_order : if shutit_util . is_installed ( shutit , shutit_module_obj ) : if not shutit_module_obj . stop ( shutit ) : shutit . fail ( '' + module_id , shutit_pexpect_child = shutit . get_shutit_pexpect_session_from_id ( '' ) . shutit_pexpect_child ) def start_all ( shutit , run_order = - ) : \"\"\"\"\"\" cfg = shutit . cfg if cfg [ '' ] [ '' ] >= : print ( '' + shutit_util . colour ( '' , '' ) ) shutit_util . util_raw_input ( ) for module_id in shutit_util . module_ids ( shutit ) : shutit_module_obj = shutit . shutit_map [ module_id ] if run_order == - or shutit_module_obj . run_order <= run_order : if shutit_util . is_installed ( shutit , shutit_module_obj ) : if not shutit_module_obj . start ( shutit ) : shutit . fail ( '' + module_id , shutit_pexpect_child = shutit . get_shutit_pexpect_session_from_id ( '' ) . shutit_pexpect_child ) def is_ready ( shutit , shutit_module_obj ) : \"\"\"\"\"\" cfg = shutit . cfg if shutit_module_obj . module_id in cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] : shutit . log ( '' , level = logging . DEBUG ) return True ready = shutit_module_obj . check_ready ( shutit ) if ready : cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] . append ( shutit_module_obj . module_id ) return True else : return False def init_shutit_map ( shutit ) : \"\"\"\"\"\" cfg = shutit . cfg modules = shutit . shutit_modules if len ( [ mod for mod in modules if mod . run_order > ] ) < : shutit . log ( modules , level = logging . DEBUG ) path = '' . join ( cfg [ '' ] [ '' ] ) shutit . log ( '' , code = , level = logging . INFO ) if path == '' : shutit . fail ( '' ) elif path == '' : shutit . fail ( '' ) else : shutit . fail ( '' + path + '' ) shutit . log ( '' , level = logging . DEBUG ) if cfg [ '' ] [ '' ] >= : shutit . log ( '' , level = logging . DEBUG ) for module in modules : shutit . log ( module . module_id , level = logging . DEBUG ) shutit . log ( '' , level = logging . DEBUG ) run_orders = { } has_core_module = False for module in modules : assert isinstance ( module , ShutItModule ) if module . module_id in shutit . shutit_map : shutit . fail ( '' + module . module_id + '' ) if module . run_order in run_orders : shutit . fail ( '' + str ( module . run_order ) + '' + module . module_id + '' + run_orders [ module . run_order ] . module_id + '' ) if module . run_order == : has_core_module = True shutit . shutit_map [ module . module_id ] = run_orders [ module . run_order ] = module if not has_core_module : shutit . fail ( '' ) if cfg [ '' ] [ '' ] >= : print ( shutit_util . colour ( '' , '' ) ) shutit_util . util_raw_input ( ) def conn_target ( shutit ) : \"\"\"\"\"\" conn_module = None cfg = shutit . cfg for mod in shutit . conn_modules : if mod . module_id == cfg [ '' ] [ '' ] : conn_module = mod break if conn_module is None : shutit . fail ( '' + cfg [ '' ] [ '' ] ) if cfg [ '' ] [ '' ] >= : print ( '' + shutit . shutit_main_dir + '' + shutit_util . colour ( '' , '' ) ) shutit_util . util_raw_input ( ) conn_module . get_config ( shutit ) conn_module . build ( shutit ) def finalize_target ( shutit ) : \"\"\"\"\"\" cfg = shutit . cfg shutit . pause_point ( '' + shutit . shutit_main_dir + '' , print_input = False , level = ) for mod in shutit . conn_modules : if mod . module_id == cfg [ '' ] [ '' ] : conn_module = mod break conn_module . finalize ( shutit ) def resolve_dependencies ( shutit , to_build , depender ) : \"\"\"\"\"\" shutit . log ( '' , level = logging . DEBUG ) cfg = shutit . cfg for dependee_id in depender . depends_on : dependee = shutit . shutit_map . get ( dependee_id ) if ( dependee and dependee not in to_build and cfg [ dependee_id ] [ '' ] ) : to_build . append ( dependee ) cfg [ dependee_id ] [ '' ] = True return True def check_dependee_exists ( depender , dependee , dependee_id ) : \"\"\"\"\"\" cfg = shutit_global . shutit . cfg if dependee == None : return ( '' + dependee_id + '' + str ( cfg [ '' ] [ '' ] ) + '' + depender . module_id + '' ) def check_dependee_build ( depender , dependee , dependee_id ) : \"\"\"\"\"\" cfg = shutit_global . shutit . cfg if not ( cfg [ dependee . module_id ] [ '' ] or shutit_util . is_to_be_built_or_is_installed ( shutit_global . shutit , dependee ) ) : return ( '' + depender . module_id + '' + dependee_id + '' ) def check_dependee_order ( depender , dependee , dependee_id ) : \"\"\"\"\"\" if dependee . run_order > depender . run_order : return ( '' + depender . module_id + '' + str ( depender . run_order ) + '' + '' + dependee_id + '' + str ( dependee . run_order ) + '' + '' ) def make_dep_graph ( depender ) : \"\"\"\"\"\" digraph = '' for dependee_id in depender . depends_on : digraph = ( digraph + '' + depender . module_id + '' + dependee_id + '' ) return digraph def check_deps ( shutit ) : \"\"\"\"\"\" cfg = shutit . cfg shutit . log ( '' , level = logging . DEBUG ) shutit . pause_point ( '' , print_input = False , level = ) to_build = [ shutit . shutit_map [ module_id ] for module_id in shutit . shutit_map if module_id in cfg and cfg [ module_id ] [ '' ] ] for module in to_build : resolve_dependencies ( shutit , to_build , module ) def err_checker ( errs , triples ) : \"\"\"\"\"\" new_triples = [ ] for err , triple in zip ( errs , triples ) : if not err : new_triples . append ( triple ) continue found_errs . append ( err ) return new_triples found_errs = [ ] triples = [ ] for depender in to_build : for dependee_id in depender . depends_on : triples . append ( ( depender , shutit . shutit_map . get ( dependee_id ) , dependee_id ) ) triples = err_checker ( [ check_dependee_exists ( depender , dependee , dependee_id ) for depender , dependee , dependee_id in triples ] , triples ) triples = err_checker ( [ check_dependee_build ( depender , dependee , dependee_id ) for depender , dependee , dependee_id in triples ] , triples ) triples = err_checker ( [ check_dependee_order ( depender , dependee , dependee_id ) for depender , dependee , dependee_id in triples ] , triples ) if found_errs : return [ ( err , ) for err in found_errs ] shutit . log ( '' , level = logging . DEBUG ) for module_id in shutit_util . module_ids ( shutit ) : module = shutit . shutit_map [ module_id ] if cfg [ module_id ] [ '' ] : shutit . log ( module_id + '' + str ( module . run_order ) , level = logging . DEBUG ) shutit . log ( '' , level = logging . DEBUG ) return [ ] def check_conflicts ( shutit ) : \"\"\"\"\"\" cfg = shutit . cfg shutit . log ( '' , level = logging . DEBUG ) errs = [ ] shutit . pause_point ( '' , print_input = False , level = ) for module_id in shutit_util . module_ids ( shutit ) : if not cfg [ module_id ] [ '' ] : continue conflicter = shutit . shutit_map [ module_id ] for conflictee in conflicter . conflicts_with : conflictee_obj = shutit . shutit_map . get ( conflictee ) if conflictee_obj == None : continue if ( ( cfg [ conflicter . module_id ] [ '' ] or shutit_util . is_to_be_built_or_is_installed ( shutit , conflicter ) ) and ( cfg [ conflictee_obj . module_id ] [ '' ] or shutit_util . is_to_be_built_or_is_installed ( shutit , conflictee_obj ) ) ) : errs . append ( ( '' + conflicter . module_id + '' + conflictee_obj . module_id , ) ) return errs def check_ready ( shutit , throw_error = True ) : \"\"\"\"\"\" cfg = shutit . cfg shutit . log ( '' , level = logging . DEBUG ) errs = [ ] shutit . pause_point ( '' , print_input = False , level = ) for module_id in shutit_util . module_ids ( shutit ) : module = shutit . shutit_map [ module_id ] shutit . log ( '' + module_id , level = logging . DEBUG ) if cfg [ module_id ] [ '' ] and module . module_id not in cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] and not shutit_util . is_installed ( shutit , module ) : shutit . log ( '' + module_id , level = logging . DEBUG ) shutit . login ( prompt_prefix = module_id , command = '' ) revert_dir = os . getcwd ( ) cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] = os . path . dirname ( module . __module_file ) shutit . chdir ( cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] ) if not is_ready ( shutit , module ) and throw_error : errs . append ( ( module_id + '' , shutit . get_shutit_pexpect_session_from_id ( '' ) ) ) shutit . logout ( ) shutit . chdir ( revert_dir ) return errs def do_remove ( shutit , loglevel = logging . DEBUG ) : \"\"\"\"\"\" cfg = shutit . cfg shutit . log ( '' , level = loglevel ) shutit . pause_point ( '' , print_input = False , level = ) for module_id in shutit_util . module_ids ( shutit ) : module = shutit . shutit_map [ module_id ] shutit . log ( '' + module_id , level = logging . DEBUG ) if cfg [ module_id ] [ '' ] : shutit . log ( '' + module_id , level = logging . DEBUG ) shutit . login ( prompt_prefix = module_id , command = '' ) if not module . remove ( shutit ) : shutit . log ( shutit_util . print_modules ( shutit ) , level = logging . DEBUG ) shutit . fail ( module_id + '' , shutit_pexpect_child = shutit . get_shutit_pexpect_session_from_id ( '' ) . pexpect_child ) else : if cfg [ '' ] [ '' ] in ( '' , '' ) : shutit . send ( '' + cfg [ '' ] [ '' ] + '' + module . module_id + '' + cfg [ '' ] [ '' ] + '' + module . module_id + '' + cfg [ '' ] [ '' ] + '' + module . module_id + '' , loglevel = loglevel ) if module . module_id in cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] : cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] . remove ( module . module_id ) cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] . append ( module . module_id ) shutit . logout ( ) def build_module ( shutit , module , loglevel = logging . DEBUG ) : \"\"\"\"\"\" cfg = shutit . cfg shutit . log ( '' + module . module_id + '' + str ( module . run_order ) , level = logging . INFO ) cfg [ '' ] [ '' ] = ( cfg [ '' ] [ '' ] + '' + module . module_id + '' + str ( module . run_order ) ) if not module . build ( shutit ) : shutit . fail ( module . module_id + '' , shutit_pexpect_child = shutit . get_shutit_pexpect_session_from_id ( '' ) . pexpect_child ) else : if cfg [ '' ] [ '' ] in ( '' , '' ) : shutit . send ( '' + cfg [ '' ] [ '' ] + '' + module . module_id + '' + cfg [ '' ] [ '' ] + '' + module . module_id + '' + cfg [ '' ] [ '' ] + '' + module . module_id + '' , loglevel = loglevel ) cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] . append ( module . module_id ) if module . module_id in cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] : cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] . remove ( module . module_id ) shutit . pause_point ( '' + module . module_id , print_input = True , level = ) cfg [ '' ] [ '' ] = ( cfg [ '' ] [ '' ] + '' + module . module_id ) if cfg [ module . module_id ] [ '' ] or cfg [ '' ] [ '' ] >= : shutit . log ( shutit_util . build_report ( shutit , '' + module . module_id ) , level = logging . DEBUG ) if ( not cfg [ module . module_id ] [ '' ] and cfg [ '' ] [ '' ] >= ) : print ( \"\" + \"\" + module . module_id + \"\" ) cfg [ module . module_id ] [ '' ] = ( shutit_util . util_raw_input ( default = '' ) == '' ) if cfg [ module . module_id ] [ '' ] or cfg [ '' ] [ '' ] : shutit . log ( module . module_id + '' , level = logging . INFO ) stop_all ( shutit , module . run_order ) shutit . do_repository_work ( str ( module . module_id ) + '' + str ( module . run_order ) , password = cfg [ '' ] [ '' ] , docker_executable = cfg [ '' ] [ '' ] , force = True ) start_all ( shutit , module . run_order ) if cfg [ '' ] [ '' ] >= : print ( \"\" ) if shutit_util . util_raw_input ( default = '' ) == '' : cfg [ '' ] [ '' ] = def do_build ( shutit ) : \"\"\"\"\"\" cfg = shutit . cfg shutit . log ( '' , level = logging . DEBUG ) shutit . log ( shutit_util . print_config ( cfg ) , level = logging . DEBUG ) if cfg [ '' ] [ '' ] >= : print ( '' + shutit_util . colour ( '' , '' ) ) shutit_util . util_raw_input ( ) module_id_list = shutit_util . module_ids ( shutit ) if cfg [ '' ] [ '' ] : module_id_list_build_only = filter ( lambda x : cfg [ x ] [ '' ] , module_id_list ) for module_id in module_id_list : module = shutit . shutit_map [ module_id ] shutit . log ( '' + module . module_id , level = logging . INFO ) if cfg [ module . module_id ] [ '' ] : if cfg [ '' ] [ '' ] not in module . ok_delivery_methods : shutit . fail ( '' + module . module_id + '' + str ( module . ok_delivery_methods ) + '' ) if shutit_util . is_installed ( shutit , module ) : cfg [ '' ] [ '' ] = ( cfg [ '' ] [ '' ] + '' + module . module_id + '' + str ( module . run_order ) ) else : if cfg [ '' ] [ '' ] and module_id == module_id_list_build_only [ - ] : cfg [ '' ] [ '' ] = ( cfg [ '' ] [ '' ] + '' + module . module_id + '' + str ( module . run_order ) + '' ) else : revert_dir = os . getcwd ( ) cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] = os . path . dirname ( module . __module_file ) shutit . chdir ( cfg [ '' ] [ cfg [ '' ] [ '' ] ] [ '' ] ) shutit . login ( prompt_prefix = module_id , command = '' ) build_module ( shutit , module ) shutit . logout ( ) shutit . chdir ( revert_dir ) if shutit_util . is_installed ( shutit , module ) : shutit . log ( '' , level = logging . DEBUG ) if not module . start ( shutit ) : shutit . fail ( module . module_id + '' , shutit_pexpect_child = shutit . get_shutit_pexpect_session_from_id ( '' ) . pexpect_child ) def do_test ( shutit ) : \"\"\"\"\"\" cfg = shutit . cfg if not cfg [ '' ] [ '' ] : shutit . log ( '' , level = logging . DEBUG ) return shutit . log ( '' , level = logging . DEBUG ) if cfg [ '' ] [ '' ] >= : print '' + shutit_util . colour ( '' , '' ) shutit_util . util_raw_input ( ) stop_all ( shutit ) start_all ( shutit ) for module_id in shutit_util . module_ids ( shutit , rev = True ) : if shutit_util . is_installed ( shutit , shutit . shutit_map [ module_id ] ) : shutit . log ( '' + module_id , level = logging . DEBUG ) shutit . login ( prompt_prefix = module_id , command = '' ) if not shutit . shutit_map [ module_id ] . test ( shutit ) : shutit . fail ( module_id + '' , shutit_pexpect_child = shutit . get_shutit_pexpect_session_from_id ( '' ) . pexpect_child ) shutit . logout ( ) def do_finalize ( shutit ) : \"\"\"\"\"\" cfg = shutit . cfg if cfg [ '' ] [ '' ] >= : print ( '' + shutit_util . colour ( '' , '' ) ) shutit_util . util_raw_input ( ) stop_all ( shutit ) shutit . log ( '' , level = logging . DEBUG ) if cfg [ '' ] [ '' ] >= : print ( '' + '' + shutit_util . colour ( '' , '' ) ) shutit_util . util_raw_input ( ) for module_id in shutit_util . module_ids ( shutit , rev = True ) : if shutit_util . is_installed ( shutit , shutit . shutit_map [ module_id ] ) : shutit . login ( prompt_prefix = module_id , command = '' ) if not shutit . shutit_map [ module_id ] . finalize ( shutit ) : shutit . fail ( module_id + '' , shutit_pexpect_child = shutit . get_shutit_pexpect_session_from_id ( '' ) . pexpect_child ) shutit . logout ( ) def setup_shutit_path ( cfg ) : if not cfg [ '' ] [ '' ] : return res = shutit_util . util_raw_input ( prompt = '' ) if res in [ '' , '' ] : with open ( os . path . join ( cfg [ '' ] , '' ) , '' ) as f : f . write ( '' ) return path_to_shutit = '' for d in [ '' , '' , '' , '' ] : path = os . path . abspath ( d + '' ) if not os . path . isfile ( path ) : continue path_to_shutit = path while path_to_shutit == '' : d = shutit_util . util_raw_input ( prompt = '' ) path = os . path . abspath ( d + '' ) if not os . path . isfile ( path ) : continue path_to_shutit = path if path_to_shutit != '' : bashrc = os . path . expanduser ( '' ) with open ( bashrc , \"\" ) as myfile : myfile . write ( '' + os . path . dirname ( path_to_shutit ) + '' ) shutit_util . util_raw_input ( prompt = '' ) shutit_util . handle_exit ( ) def main ( ) : \"\"\"\"\"\" if sys . version_info . major == : if sys . version_info . minor < : shutit_global . shutit . fail ( '' ) shutit = shutit_global . shutit cfg = shutit . cfg shutit . log ( '' , transient = True , newline = False ) shutit_util . parse_args ( shutit ) if cfg [ '' ] [ '' ] : shutit_util . create_skeleton ( shutit ) cfg [ '' ] [ '' ] = True return shutit . log ( '' , transient = True ) shutit_util . load_configs ( shutit ) if shutit_util . determine_interactive ( ) and spawn . find_executable ( '' ) is None : setup_shutit_path ( cfg ) shutit_util . load_mod_from_file ( shutit , os . path . join ( shutit . shutit_main_dir , '' ) ) shutit_util . load_shutit_modules ( shutit ) shutit . log ( '' , level = logging . INFO ) if cfg [ '' ] [ '' ] : shutit_util . list_modules ( shutit ) shutit_util . handle_exit ( ) init_shutit_map ( shutit ) shutit_util . config_collection ( shutit ) shutit . log ( '' , level = logging . INFO ) conn_target ( shutit ) shutit . log ( '' , level = logging . INFO ) if cfg [ '' ] [ '' ] > and cfg [ '' ] [ '' ] : errs = do_interactive_modules ( shutit ) else : errs = [ ] errs . extend ( check_deps ( shutit ) ) if cfg [ '' ] [ '' ] : digraph = '' digraph += '' . join ( [ make_dep_graph ( module ) for module_id , module in shutit . shutit_map . items ( ) if module_id in cfg and cfg [ module_id ] [ '' ] ] ) digraph += '' f = file ( cfg [ '' ] [ '' ] + '' , '' ) f . write ( digraph ) f . close ( ) digraph_all = '' digraph_all += '' . join ( [ make_dep_graph ( module ) for module_id , module in shutit . shutit_map . items ( ) ] ) digraph_all += '' f = file ( cfg [ '' ] [ '' ] + '' , '' ) f . write ( digraph_all ) f . close ( ) shutit . log ( '' + digraph_all ) shutit . log ( '' ) shutit . log ( '' ) shutit . log ( '' + digraph ) shutit . log ( '' + digraph ) shutit . log ( '' ) shutit . log ( '' ) shutit_util . handle_exit ( ) shutit_util . config_collection_for_built ( shutit ) if cfg [ '' ] [ '' ] or cfg [ '' ] [ '' ] <= logging . DEBUG : shutit . log ( shutit_util . print_config ( cfg , history = cfg [ '' ] [ '' ] ) ) cfg [ '' ] [ '' ] = True f = file ( cfg [ '' ] [ '' ] + '' , '' ) f . write ( shutit_util . print_config ( cfg , history = cfg [ '' ] [ '' ] ) ) f . close ( ) shutit . log ( '' ) shutit . log ( '' + cfg [ '' ] [ '' ] ) shutit . log ( '' ) shutit . log ( '' + cfg [ '' ] [ '' ] + '' + cfg [ '' ] [ '' ] + '' + cfg [ '' ] [ '' ] + '' ) shutit . log ( '' ) shutit . log ( '' + cfg [ '' ] [ '' ] + '' + cfg [ '' ] [ '' ] + '' + cfg [ '' ] [ '' ] + '' ) shutit . log ( '' ) shutit . log ( '' + cfg [ '' ] [ '' ] + '' ) shutit . log ( '' ) if cfg [ '' ] [ '' ] : return errs . extend ( check_conflicts ( shutit ) ) errs . extend ( check_ready ( shutit , throw_error = False ) ) if errs : shutit . log ( shutit_util . print_modules ( shutit ) , level = logging . ERROR ) child = None for err in errs : shutit . log ( err [ ] , level = logging . ERROR ) if not child and len ( err ) > : child = err [ ] shutit . fail ( \"\" , shutit_pexpect_child = child ) shutit . record_config ( ) do_remove ( shutit ) do_build ( shutit ) do_test ( shutit ) do_finalize ( shutit ) finalize_target ( shutit ) shutit . log ( shutit_util . build_report ( shutit , '' ) , level = logging . DEBUG ) if cfg [ '' ] [ '' ] != '' : shutit . log ( cfg [ '' ] [ '' ] , level = logging . INFO ) if cfg [ '' ] [ '' ] >= : shutit . log ( '' + '' + cfg [ '' ] [ '' ] + '' , code = '' , level = logging . DEBUG ) cfg [ '' ] [ '' ] = True shutit . log ( '' , level = logging . INFO ) shutit_util . handle_exit ( ) def do_phone_home ( msg = None , question = '' ) : \"\"\"\"\"\" if msg is None : msg = { } if shutit_global . cfg [ '' ] [ '' ] == : return msg . update ( { '' : '' , '' : os . getcwd ( ) , '' : os . environ . get ( '' , '' ) } ) if question != '' and shutit_util . util_raw_input ( prompt = question + '' ) not in ( '' , '' , '' ) : return try : urllib . urlopen ( \"\" + urllib . urlencode ( msg ) ) except Exception as e : shutit_global . shutit . log ( '' + str ( e . message ) , level = logging . ERROR ) def do_interactive_modules ( shutit ) : cfg = shutit . cfg errs = [ ] while True : shutit_util . list_modules ( shutit , long_output = False , sort_order = '' ) module_id = shutit_util . util_raw_input ( prompt = '' ) if module_id : try : _ = cfg [ module_id ] except : print '' continue cfg [ module_id ] [ '' ] = not cfg [ module_id ] [ '' ] if not shutit_util . config_collection_for_built ( shutit , throw_error = False ) : cfg [ module_id ] [ '' ] = not cfg [ module_id ] [ '' ] shutit_util . util_raw_input ( prompt = '' ) continue if cfg [ module_id ] [ '' ] : newcfg_list = [ ] while True : print shutit_util . print_config ( cfg , module_id = module_id ) name = shutit_util . util_raw_input ( prompt = '' ) if name : doing_list = False while True : if doing_list : val_type = shutit_util . util_raw_input ( prompt = '' ) if val_type not in ( '' , '' , '' ) : continue else : val_type = shutit_util . util_raw_input ( prompt = '' ) if val_type not in ( '' , '' , '' , '' ) : continue if val_type == '' : val = shutit_util . util_raw_input ( prompt = '' ) if doing_list : newcfg_list . append ( val ) else : break elif val_type == '' : val = shutit_util . util_raw_input ( prompt = '' ) if doing_list : if val == '' : newcfg_list . append ( True ) elif val == '' : newcfg_list . append ( False ) else : print '' continue else : break elif val_type == '' : doing_list = True newcfg_list = [ ] elif val_type == '' : break if doing_list : cfg [ module_id ] [ name ] = newcfg_list else : cfg [ module_id ] [ name ] = val else : break else : pass else : break return errs def setup_signals ( ) : signal . signal ( signal . SIGINT , shutit_util . ctrl_c_signal_handler ) signal . signal ( signal . SIGQUIT , shutit_util . ctrl_quit_signal_handler ) shutit_version = '' if __name__ == '' : ", "answer": "setup_signals ( )"}, {"prompt": " from __future__ import absolute_import from . about_dialog import AboutDialog from . application_window import ApplicationWindow from . beep import beep from . clipboard import clipboard , Clipboard from . confirmation_dialog import confirm , ConfirmationDialog from . constant import OK , CANCEL , YES , NO from . dialog import Dialog from . directory_dialog import DirectoryDialog from . file_dialog import FileDialog from . filter import Filter from . gui import GUI from . heading_text import HeadingText from . image_cache import ImageCache from . image_resource import ImageResource from . key_pressed_event import KeyPressedEvent from . message_dialog import error , information , warning , MessageDialog from . progress_dialog import ProgressDialog from . python_editor import PythonEditor from . python_shell import PythonShell from . sorter import Sorter from . splash_screen import SplashScreen from . split_application_window import SplitApplicationWindow from . split_dialog import SplitDialog from . split_panel import SplitPanel from . system_metrics import SystemMetrics from . window import Window from . widget import Widget from traits . etsconfig . api import ETSConfig if ETSConfig . toolkit == '' : from . expandable_panel import ExpandablePanel from . image_widget import ImageWidget from . layered_panel import LayeredPanel from . mdi_application_window import MDIApplicationWindow from . mdi_window_menu import MDIWindowMenu ", "answer": "from . multi_toolbar_window import MultiToolbarWindow"}, {"prompt": " \"\"\"\"\"\" from six . moves import urllib from novaclient import api_versions from novaclient import base class Service ( base . Resource ) : def __repr__ ( self ) : return \"\" % self . binary def _add_details ( self , info ) : dico = '' in info and info [ '' ] or info for ( k , v ) in dico . items ( ) : setattr ( self , k , v ) class ServiceManager ( base . ManagerWithFind ) : resource_class = Service def list ( self , host = None , binary = None ) : \"\"\"\"\"\" url = \"\" filters = [ ] if host : filters . append ( ( \"\" , host ) ) if binary : filters . append ( ( \"\" , binary ) ) if filters : ", "answer": "url = \"\" % ( url , urllib . parse . urlencode ( filters ) )"}, {"prompt": " \"\"\"\"\"\" import functools import logging import sys import types import unittest from nose2 import exceptions , util from nose2 . events import Plugin from nose2 . compat import unittest as ut2 log = logging . getLogger ( __name__ ) __unittest = True class Generators ( Plugin ) : \"\"\"\"\"\" alwaysOn = True configSection = '' def registerInSubprocess ( self , event ) : event . pluginClasses . append ( self . __class__ ) def unpack ( self , generator ) : for index , func_args in enumerate ( generator ) : try : func , args = func_args if not isinstance ( args , tuple ) : args = ( args , ) yield index , ( func , args ) except ValueError : func , args = func_args [ ] , func_args [ : ] yield index , ( func , args ) def loadTestsFromTestCase ( self , event ) : \"\"\"\"\"\" log . debug ( '' , event . testCase ) testCaseClass = event . testCase for name in dir ( testCaseClass ) : method = getattr ( testCaseClass , name ) if ( name . startswith ( self . session . testMethodPrefix ) and hasattr ( getattr ( testCaseClass , name ) , '' ) and util . isgenerator ( method ) ) : instance = testCaseClass ( name ) event . extraTests . extend ( self . _testsFromGenerator ( event , name , method ( instance ) , testCaseClass ) ) def loadTestsFromTestClass ( self , event ) : testCaseClass = event . testCase for name in dir ( testCaseClass ) : method = getattr ( testCaseClass , name ) if ( name . startswith ( self . session . testMethodPrefix ) and hasattr ( getattr ( testCaseClass , name ) , '' ) and util . isgenerator ( method ) ) : instance = testCaseClass ( ) event . extraTests . extend ( self . _testsFromGeneratorMethod ( event , name , method , instance ) ) def getTestCaseNames ( self , event ) : \"\"\"\"\"\" log . debug ( '' , event . testCase ) names = filter ( event . isTestMethod , dir ( event . testCase ) ) klass = event . testCase for name in names : method = getattr ( klass , name ) if util . isgenerator ( method ) : event . excludedNames . append ( name ) def getTestMethodNames ( self , event ) : return self . getTestCaseNames ( event ) def loadTestsFromName ( self , event ) : \"\"\"\"\"\" original_name = name = event . name module = event . module try : result = util . test_from_name ( name , module ) except ( AttributeError , ImportError ) : event . handled = True return event . loader . failedLoadTests ( name , sys . exc_info ( ) ) if result is None : return parent , obj , name , index = result if not util . isgenerator ( obj ) : return if ( index is None and not isinstance ( parent , type ) and not isinstance ( obj , types . FunctionType ) ) : log . debug ( \"\" , obj ) return if ( parent and isinstance ( parent , type ) and issubclass ( parent , unittest . TestCase ) ) : instance = parent ( obj . __name__ ) tests = list ( self . _testsFromGenerator ( event , obj . __name__ , obj ( instance ) , parent ) ) elif ( parent and isinstance ( parent , type ) ) : method = obj instance = parent ( ) tests = list ( self . _testsFromGeneratorMethod ( event , name , method , instance ) ) else : tests = list ( self . _testsFromGeneratorFunc ( event , obj ) ) if index is not None : try : tests = [ tests [ index - ] ] except IndexError : raise exceptions . TestNotFoundError ( original_name ) suite = event . loader . suiteClass ( ) suite . addTests ( tests ) event . handled = True return suite def loadTestsFromModule ( self , event ) : \"\"\"\"\"\" module = event . module def is_test ( obj ) : return ( obj . __name__ . startswith ( self . session . testMethodPrefix ) and util . isgenerator ( obj ) ) tests = [ ] for name in dir ( module ) : obj = getattr ( module , name ) if isinstance ( obj , types . FunctionType ) and is_test ( obj ) : tests . extend ( self . _testsFromGeneratorFunc ( event , obj ) ) event . extraTests . extend ( tests ) def _testsFromGenerator ( self , event , name , generator , testCaseClass ) : try : for index , ( func , args ) in self . unpack ( generator ) : method_name = util . name_from_args ( name , index , args ) setattr ( testCaseClass , method_name , None ) instance = testCaseClass ( method_name ) delattr ( testCaseClass , method_name ) def method ( func = func , args = args ) : return func ( * args ) method = functools . update_wrapper ( method , func ) setattr ( instance , method_name , method ) yield instance except Exception as e : test_name = '' % ( testCaseClass . __module__ , testCaseClass . __name__ , name ) yield event . loader . failedLoadTests ( test_name , e ) def _testsFromGeneratorFunc ( self , event , obj ) : extras = list ( obj ( ) ) name = '' % ( obj . __module__ , obj . __name__ ) args = { } setUp = getattr ( obj , '' , None ) tearDown = getattr ( obj , '' , None ) if setUp is not None : args [ '' ] = setUp if tearDown is not None : args [ '' ] = tearDown def createTest ( name ) : return util . transplant_class ( GeneratorFunctionCase , obj . __module__ ) ( name , ** args ) for test in self . _testsFromGenerator ( event , name , extras , createTest ) : yield test def _testsFromGeneratorMethod ( self , event , name , method , instance ) : extras = list ( method ( instance ) ) name = \"\" % ( instance . __class__ . __module__ , instance . __class__ . __name__ , method . __name__ ) args = { } setUp = getattr ( instance , '' , None ) ", "answer": "tearDown = getattr ( instance , '' , None )"}, {"prompt": " import numpy as np from decoder_utils import load_data , load_nnet , decode , int_to_char , collapse_seq , load_char_map if __name__ == '' : print '' fnum = data_dict , alis , keys = load_data ( fnum ) print '' rnn = load_nnet ( ) data , labels = data_dict [ keys [ ] ] , np . array ( alis [ keys [ ] ] , dtype = np . int32 ) probs = rnn . costAndGrad ( data , labels ) ", "answer": "probs = np . log ( probs . astype ( np . float64 ) + )"}, {"prompt": " \"\"\"\"\"\" from django . core import mail from django . core . mail . backends . base import BaseEmailBackend class EmailBackend ( BaseEmailBackend ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : super ( EmailBackend , self ) . __init__ ( * args , ** kwargs ) if not hasattr ( mail , '' ) : mail . outbox = [ ] def send_messages ( self , messages ) : \"\"\"\"\"\" msg_count = for message in messages : message . message ( ) msg_count += ", "answer": "mail . outbox . extend ( messages )"}, {"prompt": " \"\"\"\"\"\" import pytest import flask from flask . _compat import text_type from werkzeug . http import parse_cache_control_header from jinja2 import TemplateNotFound def test_blueprint_specific_error_handling ( ) : frontend = flask . Blueprint ( '' , __name__ ) backend = flask . Blueprint ( '' , __name__ ) sideend = flask . Blueprint ( '' , __name__ ) @ frontend . errorhandler ( ) def frontend_forbidden ( e ) : return '' , @ frontend . route ( '' ) def frontend_no ( ) : flask . abort ( ) @ backend . errorhandler ( ) def backend_forbidden ( e ) : return '' , @ backend . route ( '' ) def backend_no ( ) : flask . abort ( ) @ sideend . route ( '' ) def sideend_no ( ) : flask . abort ( ) app = flask . Flask ( __name__ ) app . register_blueprint ( frontend ) app . register_blueprint ( backend ) app . register_blueprint ( sideend ) @ app . errorhandler ( ) def app_forbidden ( e ) : return '' , c = app . test_client ( ) assert c . get ( '' ) . data == b'' assert c . get ( '' ) . data == b'' assert c . get ( '' ) . data == b'' def test_blueprint_specific_user_error_handling ( ) : class MyDecoratorException ( Exception ) : pass class MyFunctionException ( Exception ) : pass blue = flask . Blueprint ( '' , __name__ ) @ blue . errorhandler ( MyDecoratorException ) def my_decorator_exception_handler ( e ) : assert isinstance ( e , MyDecoratorException ) return '' def my_function_exception_handler ( e ) : assert isinstance ( e , MyFunctionException ) return '' blue . register_error_handler ( MyFunctionException , my_function_exception_handler ) @ blue . route ( '' ) def blue_deco_test ( ) : raise MyDecoratorException ( ) @ blue . route ( '' ) def blue_func_test ( ) : raise MyFunctionException ( ) app = flask . Flask ( __name__ ) app . register_blueprint ( blue ) c = app . test_client ( ) assert c . get ( '' ) . data == b'' assert c . get ( '' ) . data == b'' def test_blueprint_url_definitions ( ) : bp = flask . Blueprint ( '' , __name__ ) @ bp . route ( '' , defaults = { '' : } ) def foo ( bar , baz ) : return '' % ( bar , baz ) @ bp . route ( '' ) def bar ( bar ) : return text_type ( bar ) app = flask . Flask ( __name__ ) app . register_blueprint ( bp , url_prefix = '' , url_defaults = { '' : } ) app . register_blueprint ( bp , url_prefix = '' , url_defaults = { '' : } ) c = app . test_client ( ) assert c . get ( '' ) . data == b'' assert c . get ( '' ) . data == b'' assert c . get ( '' ) . data == b'' assert c . get ( '' ) . data == b'' def test_blueprint_url_processors ( ) : bp = flask . Blueprint ( '' , __name__ , url_prefix = '' ) @ bp . url_defaults def add_language_code ( endpoint , values ) : values . setdefault ( '' , flask . g . lang_code ) @ bp . url_value_preprocessor def pull_lang_code ( endpoint , values ) : flask . g . lang_code = values . pop ( '' ) @ bp . route ( '' ) def index ( ) : return flask . url_for ( '' ) @ bp . route ( '' ) def about ( ) : return flask . url_for ( '' ) app = flask . Flask ( __name__ ) app . register_blueprint ( bp ) c = app . test_client ( ) assert c . get ( '' ) . data == b'' assert c . get ( '' ) . data == b'' def test_templates_and_static ( test_apps ) : from blueprintapp import app c = app . test_client ( ) rv = c . get ( '' ) assert rv . data == b'' rv = c . get ( '' ) assert rv . data == b'' rv = c . get ( '' ) assert rv . data == b'' rv = c . get ( '' ) assert rv . data . strip ( ) == b'' rv . close ( ) rv = c . get ( '' ) assert rv . data . strip ( ) == b'' rv . close ( ) max_age_default = app . config [ '' ] try : expected_max_age = if app . config [ '' ] == expected_max_age : expected_max_age = app . config [ '' ] = expected_max_age rv = c . get ( '' ) cc = parse_cache_control_header ( rv . headers [ '' ] ) ", "answer": "assert cc . max_age == expected_max_age"}, {"prompt": " try : import unittest2 as unittest except ImportError : import unittest from isso import wsgi class TestWSGIUtilities ( unittest . TestCase ) : def test_urlsplit ( self ) : examples = [ ( \"\" , ( '' , , False ) ) , ( \"\" , ( '' , , True ) ) , ( \"\" , ( '' , , False ) ) , ( \"\" , ( '' , , False ) ) , ( \"\" , ( '' , , True ) ) ] for ( hostname , result ) in examples : self . assertEqual ( wsgi . urlsplit ( hostname ) , result ) def test_urljoin ( self ) : examples = [ ( ( \"\" , , False ) , \"\" ) , ( ( \"\" , , True ) , \"\" ) , ( ( \"\" , , True ) , \"\" ) ] for ( split , result ) in examples : ", "answer": "self . assertEqual ( wsgi . urljoin ( * split ) , result )"}, {"prompt": " from __future__ import unicode_literals from django . conf . urls import patterns urlpatterns = patterns ( '' , ( r'' , lambda r : None , { } , \"\" ) , ( r'' , lambda r : None , { } , \"\" ) , ", "answer": ") "}, {"prompt": " \"\"\"\"\"\" import unittest from pycopia . SMI import SMI class SMITests ( unittest . TestCase ) : def setUp ( self ) : SMI . load_modules ( \"\" , \"\" , \"\" , \"\" , \"\" ) mods = list ( SMI . get_modules ( ) ) self . mod = mods [ - ] def test_get_modules ( self ) : \"\"\"\"\"\" print ( self . mod ) def test_get_scalars ( self ) : print ( \"\" ) scalars = list ( self . mod . get_scalars ( ) ) scalar = scalars [ ] print ( scalar ) def test_get_rows ( self ) : print ( \"\" ) rows = list ( self . mod . get_rows ( SMI . SMI_STATUS_CURRENT ) ) print ( rows [ ] ) def test_types ( self ) : print ( \"\" ) tcmib = SMI . get_module ( \"\" ) smi_types = tcmib . get_types ( ) for smi_type in smi_types : print ( \"\" , smi_type , smi_type . snmptype ) def test_index ( self ) : print ( \"\" ) rtpmib = SMI . get_module ( \"\" ) rtpsess = rtpmib . get_node ( \"\" ) rtpsess_index = rtpsess . get_index ( ) for ind in rtpsess_index : print ( rtpmib . get_node ( ind . name ) . value ) def test_augments ( self ) : print ( \"\" ) snmpmib = SMI . get_module ( \"\" ) taenode = snmpmib . get_node ( \"\" ) taenode_index = taenode . get_index ( ) print ( repr ( taenode_index ) ) comm = snmpmib . get_node ( \"\" ) comm_index = comm . get_index ( ) print ( repr ( comm_index ) ) newoid = comm . OID print ( newoid ) def test_ipmib ( self ) : ipmod = SMI . get_module ( \"\" ) eslist = ipmod . get_scalars ( ) for es in eslist : print ( es . name , es . syntax ) ", "answer": "n = ipmod . get_node ( \"\" )"}, {"prompt": " from ooni import nettest from ooni . utils import log from twisted . internet import defer , protocol , reactor from twisted . python import usage import os def which ( program ) : def is_exe ( fpath ) : ", "answer": "return os . path . isfile ( fpath ) and os . access ( fpath , os . X_OK )"}, {"prompt": " '''''' from dossier . web . run import default_app ", "answer": "_ , application = default_app ( ) "}, {"prompt": " from __future__ import absolute_import import json import six __all__ = ( '' , '' , '' , '' , '' , '' , '' , ) class ConnectionRequest ( object ) : \"\"\"\"\"\" __slots__ = ( '' , '' , '' , '' , '' , '' , '' , '' , '' ) ", "answer": "def __init__ ( self , peer , headers , host , path , params , version , origin , protocols , extensions ) :"}, {"prompt": " \"\"\"\"\"\" from django . http import HttpResponse class HttpCreated ( HttpResponse ) : status_code = ", "answer": "def __init__ ( self , * args , ** kwargs ) :"}, {"prompt": " from test . testlib import * from git import * class TestHead ( object ) : def setup ( self ) : self . repo = Repo ( GIT_REPO ) @ patch_object ( Git , '' ) def test_repr ( self , git ) : git . return_value = fixture ( '' ) head = self . repo . heads [ ] assert_equal ( '' % head . name , repr ( head ) ) assert_true ( git . called ) assert_equal ( git . call_args , ( ( '' , '' ) , { '' : '' , '' : '' } ) ) @ patch_object ( Git , '' ) ", "answer": "def test_ref_with_path_component ( self , git ) :"}, {"prompt": " import os import time import unittest import eventlet import mock import six from swift . common import exceptions , utils from swift . common . storage_policy import POLICIES from swift . common . utils import Timestamp from swift . obj import ssync_sender , diskfile , ssync_receiver from test . unit import patch_policies , make_timestamp_iter from test . unit . obj . common import FakeReplicator , BaseTest class NullBufferedHTTPConnection ( object ) : def __init__ ( * args , ** kwargs ) : pass def putrequest ( * args , ** kwargs ) : pass def putheader ( * args , ** kwargs ) : pass def endheaders ( * args , ** kwargs ) : pass def getresponse ( * args , ** kwargs ) : pass def close ( * args , ** kwargs ) : pass class FakeResponse ( object ) : def __init__ ( self , chunk_body = '' ) : self . status = self . close_called = False if chunk_body : self . fp = six . StringIO ( '' % ( len ( chunk_body ) , chunk_body ) ) def read ( self , * args , ** kwargs ) : return '' def close ( self ) : self . close_called = True class FakeConnection ( object ) : def __init__ ( self ) : self . sent = [ ] self . closed = False def send ( self , data ) : self . sent . append ( data ) def close ( self ) : self . closed = True @ patch_policies ( ) class TestSender ( BaseTest ) : def setUp ( self ) : super ( TestSender , self ) . setUp ( ) self . testdir = os . path . join ( self . tmpdir , '' ) utils . mkdirs ( os . path . join ( self . testdir , '' ) ) self . daemon = FakeReplicator ( self . testdir ) self . sender = ssync_sender . Sender ( self . daemon , None , None , None ) def test_call_catches_MessageTimeout ( self ) : def connect ( self ) : exc = exceptions . MessageTimeout ( , '' ) exc . cancel ( ) raise exc with mock . patch . object ( ssync_sender . Sender , '' , connect ) : node = dict ( replication_ip = '' , replication_port = , device = '' ) job = dict ( partition = '' , policy = POLICIES . legacy ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] success , candidates = self . sender ( ) self . assertFalse ( success ) self . assertEqual ( candidates , { } ) error_lines = self . daemon . logger . get_lines_for_level ( '' ) self . assertEqual ( , len ( error_lines ) ) self . assertEqual ( '' , error_lines [ ] ) def test_call_catches_ReplicationException ( self ) : def connect ( self ) : raise exceptions . ReplicationException ( '' ) with mock . patch . object ( ssync_sender . Sender , '' , connect ) : node = dict ( replication_ip = '' , replication_port = , device = '' ) job = dict ( partition = '' , policy = POLICIES . legacy ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] success , candidates = self . sender ( ) self . assertFalse ( success ) self . assertEqual ( candidates , { } ) error_lines = self . daemon . logger . get_lines_for_level ( '' ) self . assertEqual ( , len ( error_lines ) ) self . assertEqual ( '' , error_lines [ ] ) def test_call_catches_other_exceptions ( self ) : node = dict ( replication_ip = '' , replication_port = , device = '' ) job = dict ( partition = '' , policy = POLICIES . legacy ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] self . sender . connect = '' success , candidates = self . sender ( ) self . assertFalse ( success ) self . assertEqual ( candidates , { } ) error_lines = self . daemon . logger . get_lines_for_level ( '' ) for line in error_lines : self . assertTrue ( line . startswith ( '' ) ) def test_call_catches_exception_handling_exception ( self ) : job = node = None self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] self . sender . connect = '' success , candidates = self . sender ( ) self . assertFalse ( success ) self . assertEqual ( candidates , { } ) error_lines = self . daemon . logger . get_lines_for_level ( '' ) for line in error_lines : self . assertTrue ( line . startswith ( '' ) ) def test_call_calls_others ( self ) : self . sender . suffixes = [ '' ] self . sender . connect = mock . MagicMock ( ) self . sender . missing_check = mock . MagicMock ( ) self . sender . updates = mock . MagicMock ( ) self . sender . disconnect = mock . MagicMock ( ) success , candidates = self . sender ( ) self . assertTrue ( success ) self . assertEqual ( candidates , { } ) self . sender . connect . assert_called_once_with ( ) self . sender . missing_check . assert_called_once_with ( ) self . sender . updates . assert_called_once_with ( ) self . sender . disconnect . assert_called_once_with ( ) def test_call_calls_others_returns_failure ( self ) : self . sender . suffixes = [ '' ] self . sender . connect = mock . MagicMock ( ) self . sender . missing_check = mock . MagicMock ( ) self . sender . updates = mock . MagicMock ( ) self . sender . disconnect = mock . MagicMock ( ) self . sender . failures = success , candidates = self . sender ( ) self . assertFalse ( success ) self . assertEqual ( candidates , { } ) self . sender . connect . assert_called_once_with ( ) self . sender . missing_check . assert_called_once_with ( ) self . sender . updates . assert_called_once_with ( ) self . sender . disconnect . assert_called_once_with ( ) def test_connect ( self ) : node = dict ( replication_ip = '' , replication_port = , device = '' , index = ) job = dict ( partition = '' , policy = POLICIES [ ] ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] with mock . patch ( '' ) as mock_conn_class : mock_conn = mock_conn_class . return_value mock_resp = mock . MagicMock ( ) mock_resp . status = mock_conn . getresponse . return_value = mock_resp self . sender . connect ( ) mock_conn_class . assert_called_once_with ( '' ) expectations = { '' : [ mock . call ( '' , '' ) , ] , '' : [ mock . call ( '' , '' ) , mock . call ( '' , ) , mock . call ( '' , ) , mock . call ( '' , ) , ] , '' : [ mock . call ( ) ] , } for method_name , expected_calls in expectations . items ( ) : mock_method = getattr ( mock_conn , method_name ) self . assertEqual ( expected_calls , mock_method . mock_calls , '' % ( method_name , mock_method . mock_calls , expected_calls ) ) def test_connect_handoff ( self ) : node = dict ( replication_ip = '' , replication_port = , device = '' ) job = dict ( partition = '' , policy = POLICIES [ ] , frag_index = ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] with mock . patch ( '' ) as mock_conn_class : mock_conn = mock_conn_class . return_value mock_resp = mock . MagicMock ( ) mock_resp . status = mock_conn . getresponse . return_value = mock_resp self . sender . connect ( ) mock_conn_class . assert_called_once_with ( '' ) expectations = { '' : [ mock . call ( '' , '' ) , ] , '' : [ mock . call ( '' , '' ) , mock . call ( '' , ) , mock . call ( '' , ) , mock . call ( '' , '' ) , ] , '' : [ mock . call ( ) ] , } for method_name , expected_calls in expectations . items ( ) : mock_method = getattr ( mock_conn , method_name ) self . assertEqual ( expected_calls , mock_method . mock_calls , '' % ( method_name , mock_method . mock_calls , expected_calls ) ) def test_connect_handoff_no_frag ( self ) : node = dict ( replication_ip = '' , replication_port = , device = '' ) job = dict ( partition = '' , policy = POLICIES [ ] ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] with mock . patch ( '' ) as mock_conn_class : mock_conn = mock_conn_class . return_value mock_resp = mock . MagicMock ( ) mock_resp . status = mock_conn . getresponse . return_value = mock_resp self . sender . connect ( ) mock_conn_class . assert_called_once_with ( '' ) expectations = { '' : [ mock . call ( '' , '' ) , ] , '' : [ mock . call ( '' , '' ) , mock . call ( '' , ) , mock . call ( '' , '' ) , mock . call ( '' , '' ) , ] , '' : [ mock . call ( ) ] , } for method_name , expected_calls in expectations . items ( ) : mock_method = getattr ( mock_conn , method_name ) self . assertEqual ( expected_calls , mock_method . mock_calls , '' % ( method_name , mock_method . mock_calls , expected_calls ) ) def test_connect_handoff_none_frag ( self ) : node = dict ( replication_ip = '' , replication_port = , device = '' ) job = dict ( partition = '' , policy = POLICIES [ ] , frag_index = None ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] with mock . patch ( '' ) as mock_conn_class : mock_conn = mock_conn_class . return_value mock_resp = mock . MagicMock ( ) mock_resp . status = mock_conn . getresponse . return_value = mock_resp self . sender . connect ( ) mock_conn_class . assert_called_once_with ( '' ) expectations = { '' : [ mock . call ( '' , '' ) , ] , '' : [ mock . call ( '' , '' ) , mock . call ( '' , ) , mock . call ( '' , '' ) , mock . call ( '' , '' ) , ] , '' : [ mock . call ( ) ] , } for method_name , expected_calls in expectations . items ( ) : mock_method = getattr ( mock_conn , method_name ) self . assertEqual ( expected_calls , mock_method . mock_calls , '' % ( method_name , mock_method . mock_calls , expected_calls ) ) def test_connect_handoff_replicated ( self ) : node = dict ( replication_ip = '' , replication_port = , device = '' ) job = dict ( partition = '' , policy = POLICIES [ ] ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] with mock . patch ( '' ) as mock_conn_class : mock_conn = mock_conn_class . return_value mock_resp = mock . MagicMock ( ) mock_resp . status = mock_conn . getresponse . return_value = mock_resp self . sender . connect ( ) mock_conn_class . assert_called_once_with ( '' ) expectations = { '' : [ mock . call ( '' , '' ) , ] , '' : [ mock . call ( '' , '' ) , mock . call ( '' , ) , mock . call ( '' , '' ) , mock . call ( '' , '' ) , ] , '' : [ mock . call ( ) ] , } for method_name , expected_calls in expectations . items ( ) : mock_method = getattr ( mock_conn , method_name ) self . assertEqual ( expected_calls , mock_method . mock_calls , '' % ( method_name , mock_method . mock_calls , expected_calls ) ) def test_call ( self ) : def patch_sender ( sender ) : sender . connect = mock . MagicMock ( ) sender . missing_check = mock . MagicMock ( ) sender . updates = mock . MagicMock ( ) sender . disconnect = mock . MagicMock ( ) node = dict ( replication_ip = '' , replication_port = , device = '' ) job = { '' : '' , '' : '' , '' : POLICIES . legacy , '' : , } available_map = dict ( [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] ) sender = ssync_sender . Sender ( self . daemon , node , job , [ ] , remote_check_objs = None ) patch_sender ( sender ) sender . available_map = available_map success , candidates = sender ( ) self . assertTrue ( success ) self . assertEqual ( { } , candidates ) sender = ssync_sender . Sender ( self . daemon , node , job , [ '' ] , remote_check_objs = None ) patch_sender ( sender ) sender . available_map = available_map success , candidates = sender ( ) self . assertTrue ( success ) self . assertEqual ( available_map , candidates ) wanted = '' sender = ssync_sender . Sender ( self . daemon , node , job , [ '' ] , remote_check_objs = None ) patch_sender ( sender ) sender . send_map = { wanted : [ ] } sender . available_map = available_map success , candidates = sender ( ) self . assertTrue ( success ) self . assertEqual ( available_map , candidates ) wanted = '' remote_check_objs = set ( available_map . keys ( ) ) sender = ssync_sender . Sender ( self . daemon , node , job , [ '' ] , remote_check_objs = remote_check_objs ) patch_sender ( sender ) sender . send_map = { wanted : [ ] } sender . available_map = available_map success , candidates = sender ( ) self . assertTrue ( success ) expected_map = dict ( [ ( '' , '' ) , ( '' , '' ) ] ) self . assertEqual ( expected_map , candidates ) def test_call_and_missing_check_metadata_legacy_response ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if device == '' and partition == '' and suffixes == [ '' ] and policy == POLICIES . legacy : yield ( '' '' , '' , { '' : Timestamp ( ) , '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , suffixes ) ) self . sender . connection = FakeConnection ( ) self . sender . node = { } self . sender . job = { '' : '' , '' : '' , '' : POLICIES . legacy , '' : , } self . sender . suffixes = [ '' ] self . sender . response = FakeResponse ( chunk_body = ( '' '' '' '' '' ) ) self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . connect = mock . MagicMock ( ) self . sender . df_mgr . get_diskfile_from_hash = mock . MagicMock ( ) self . sender . disconnect = mock . MagicMock ( ) success , candidates = self . sender ( ) self . assertTrue ( success ) found_post = found_put = False for chunk in self . sender . connection . sent : if '' in chunk : found_post = True if '' in chunk : found_put = True self . assertFalse ( found_post ) self . assertTrue ( found_put ) self . assertEqual ( self . sender . failures , ) def test_call_and_missing_check ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if device == '' and partition == '' and suffixes == [ '' ] and policy == POLICIES . legacy : yield ( '' '' , '' , { '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , suffixes ) ) self . sender . connection = FakeConnection ( ) self . sender . node = { } self . sender . job = { '' : '' , '' : '' , '' : POLICIES . legacy , '' : , } self . sender . suffixes = [ '' ] self . sender . response = FakeResponse ( chunk_body = ( '' '' '' ) ) self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . connect = mock . MagicMock ( ) self . sender . updates = mock . MagicMock ( ) self . sender . disconnect = mock . MagicMock ( ) success , candidates = self . sender ( ) self . assertTrue ( success ) self . assertEqual ( candidates , dict ( [ ( '' , { '' : Timestamp ( ) } ) ] ) ) self . assertEqual ( self . sender . failures , ) def test_call_and_missing_check_with_obj_list ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if device == '' and partition == '' and suffixes == [ '' ] and policy == POLICIES . legacy : yield ( '' '' , '' , { '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , suffixes ) ) job = { '' : '' , '' : '' , '' : POLICIES . legacy , '' : , } self . sender = ssync_sender . Sender ( self . daemon , None , job , [ '' ] , [ '' ] ) self . sender . connection = FakeConnection ( ) self . sender . response = FakeResponse ( chunk_body = ( '' '' ) ) self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . connect = mock . MagicMock ( ) self . sender . updates = mock . MagicMock ( ) self . sender . disconnect = mock . MagicMock ( ) success , candidates = self . sender ( ) self . assertTrue ( success ) self . assertEqual ( candidates , dict ( [ ( '' , { '' : Timestamp ( ) } ) ] ) ) self . assertEqual ( self . sender . failures , ) def test_call_and_missing_check_with_obj_list_but_required ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if device == '' and partition == '' and suffixes == [ '' ] and policy == POLICIES . legacy : yield ( '' '' , '' , { '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , suffixes ) ) job = { '' : '' , '' : '' , '' : POLICIES . legacy , '' : , } self . sender = ssync_sender . Sender ( self . daemon , { } , job , [ '' ] , [ '' ] ) self . sender . connection = FakeConnection ( ) self . sender . response = FakeResponse ( chunk_body = ( '' '' '' ) ) self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . connect = mock . MagicMock ( ) self . sender . updates = mock . MagicMock ( ) self . sender . disconnect = mock . MagicMock ( ) success , candidates = self . sender ( ) self . assertTrue ( success ) self . assertEqual ( candidates , { } ) def test_connect_send_timeout ( self ) : self . daemon . node_timeout = self . daemon . conn_timeout = node = dict ( replication_ip = '' , replication_port = , device = '' ) job = dict ( partition = '' , policy = POLICIES . legacy ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] def putrequest ( * args , ** kwargs ) : eventlet . sleep ( ) with mock . patch . object ( ssync_sender . bufferedhttp . BufferedHTTPConnection , '' , putrequest ) : success , candidates = self . sender ( ) self . assertFalse ( success ) self . assertEqual ( candidates , { } ) error_lines = self . daemon . logger . get_lines_for_level ( '' ) for line in error_lines : self . assertTrue ( line . startswith ( '' ) ) def test_connect_receive_timeout ( self ) : self . daemon . node_timeout = node = dict ( replication_ip = '' , replication_port = , device = '' , index = ) job = dict ( partition = '' , policy = POLICIES . legacy ) self . sender = ssync_sender . Sender ( self . daemon , node , job , None ) self . sender . suffixes = [ '' ] class FakeBufferedHTTPConnection ( NullBufferedHTTPConnection ) : def getresponse ( * args , ** kwargs ) : eventlet . sleep ( ) with mock . patch . object ( ssync_sender . bufferedhttp , '' , FakeBufferedHTTPConnection ) : success , candidates = self . sender ( ) self . assertFalse ( success ) self . assertEqual ( candidates , { } ) error_lines = self . daemon . logger . get_lines_for_level ( '' ) for line in error_lines : self . assertTrue ( line . startswith ( '' ) ) def test_connect_bad_status ( self ) : self . daemon . node_timeout = node = dict ( replication_ip = '' , replication_port = , device = '' , index = ) job = dict ( partition = '' , policy = POLICIES . legacy ) class FakeBufferedHTTPConnection ( NullBufferedHTTPConnection ) : def getresponse ( * args , ** kwargs ) : response = FakeResponse ( ) response . status = response . read = lambda : '' return response missing_check_fn = '' with mock . patch ( missing_check_fn ) as mock_missing_check : with mock . patch . object ( ssync_sender . bufferedhttp , '' , FakeBufferedHTTPConnection ) : self . sender = ssync_sender . Sender ( self . daemon , node , job , [ '' ] ) success , candidates = self . sender ( ) self . assertFalse ( success ) self . assertEqual ( candidates , { } ) error_lines = self . daemon . logger . get_lines_for_level ( '' ) for line in error_lines : self . assertTrue ( line . startswith ( '' ) ) self . assertIn ( '' , line ) self . assertFalse ( mock_missing_check . called ) def test_readline_newline_in_buffer ( self ) : self . sender . response_buffer = '' self . assertEqual ( self . sender . readline ( ) , '' ) self . assertEqual ( self . sender . response_buffer , '' ) def test_readline_buffer_exceeds_network_chunk_size_somehow ( self ) : self . daemon . network_chunk_size = self . sender . response_buffer = '' self . assertEqual ( self . sender . readline ( ) , '' ) self . assertEqual ( self . sender . response_buffer , '' ) def test_readline_at_start_of_chunk ( self ) : self . sender . response = FakeResponse ( ) self . sender . response . fp = six . StringIO ( '' ) self . assertEqual ( self . sender . readline ( ) , '' ) def test_readline_chunk_with_extension ( self ) : self . sender . response = FakeResponse ( ) self . sender . response . fp = six . StringIO ( '' ) self . assertEqual ( self . sender . readline ( ) , '' ) def test_readline_broken_chunk ( self ) : self . sender . response = FakeResponse ( ) self . sender . response . fp = six . StringIO ( '' ) self . assertRaises ( exceptions . ReplicationException , self . sender . readline ) self . assertTrue ( self . sender . response . close_called ) def test_readline_terminated_chunk ( self ) : self . sender . response = FakeResponse ( ) self . sender . response . fp = six . StringIO ( '' ) self . assertRaises ( exceptions . ReplicationException , self . sender . readline ) self . assertTrue ( self . sender . response . close_called ) def test_readline_all ( self ) : self . sender . response = FakeResponse ( ) self . sender . response . fp = six . StringIO ( '' ) self . assertEqual ( self . sender . readline ( ) , '' ) self . assertEqual ( self . sender . readline ( ) , '' ) self . assertEqual ( self . sender . readline ( ) , '' ) def test_readline_all_trailing_not_newline_termed ( self ) : self . sender . response = FakeResponse ( ) self . sender . response . fp = six . StringIO ( '' ) self . assertEqual ( self . sender . readline ( ) , '' ) self . assertEqual ( self . sender . readline ( ) , '' ) self . assertEqual ( self . sender . readline ( ) , '' ) self . assertEqual ( self . sender . readline ( ) , '' ) def test_missing_check_timeout ( self ) : self . sender . connection = FakeConnection ( ) self . sender . connection . send = lambda d : eventlet . sleep ( ) self . sender . daemon . node_timeout = self . assertRaises ( exceptions . MessageTimeout , self . sender . missing_check ) def test_missing_check_has_empty_suffixes ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if ( device != '' or partition != '' or policy != POLICIES . legacy or suffixes != [ '' , '' ] ) : yield raise Exception ( '' % ( device , partition , policy , suffixes ) ) self . sender . connection = FakeConnection ( ) self . sender . job = { '' : '' , '' : '' , '' : POLICIES . legacy , } self . sender . suffixes = [ '' , '' ] self . sender . response = FakeResponse ( chunk_body = ( '' '' ) ) self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . missing_check ( ) self . assertEqual ( '' . join ( self . sender . connection . sent ) , '' '' ) self . assertEqual ( self . sender . send_map , { } ) self . assertEqual ( self . sender . available_map , { } ) def test_missing_check_has_suffixes ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if ( device == '' and partition == '' and policy == POLICIES . legacy and suffixes == [ '' , '' ] ) : yield ( '' '' , '' , { '' : Timestamp ( ) } ) yield ( '' '' , '' , { '' : Timestamp ( ) , '' : Timestamp ( ) } ) yield ( '' '' , '' , { '' : Timestamp ( ) , '' : Timestamp ( ) , '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , policy , suffixes ) ) self . sender . connection = FakeConnection ( ) self . sender . job = { '' : '' , '' : '' , '' : POLICIES . legacy , } self . sender . suffixes = [ '' , '' ] self . sender . response = FakeResponse ( chunk_body = ( '' '' ) ) self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . missing_check ( ) self . assertEqual ( '' . join ( self . sender . connection . sent ) , '' '' '' '' '' '' '' ) self . assertEqual ( self . sender . send_map , { } ) candidates = [ ( '' , dict ( ts_data = Timestamp ( ) ) ) , ( '' , dict ( ts_data = Timestamp ( ) , ts_meta = Timestamp ( ) ) ) , ( '' , dict ( ts_data = Timestamp ( ) , ts_meta = Timestamp ( ) , ts_ctype = Timestamp ( ) ) ) ] self . assertEqual ( self . sender . available_map , dict ( candidates ) ) def test_missing_check_far_end_disconnect ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if ( device == '' and partition == '' and policy == POLICIES . legacy and suffixes == [ '' ] ) : yield ( '' '' , '' , { '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , policy , suffixes ) ) self . sender . connection = FakeConnection ( ) self . sender . job = { '' : '' , '' : '' , '' : POLICIES . legacy , } self . sender . suffixes = [ '' ] self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . response = FakeResponse ( chunk_body = '' ) exc = None try : self . sender . missing_check ( ) except exceptions . ReplicationException as err : exc = err self . assertEqual ( str ( exc ) , '' ) self . assertEqual ( '' . join ( self . sender . connection . sent ) , '' '' '' ) self . assertEqual ( self . sender . available_map , dict ( [ ( '' , dict ( ts_data = Timestamp ( ) ) ) ] ) ) def test_missing_check_far_end_disconnect2 ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if ( device == '' and partition == '' and policy == POLICIES . legacy and suffixes == [ '' ] ) : yield ( '' '' , '' , { '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , policy , suffixes ) ) self . sender . connection = FakeConnection ( ) self . sender . job = { '' : '' , '' : '' , '' : POLICIES . legacy , } self . sender . suffixes = [ '' ] self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . response = FakeResponse ( chunk_body = '' ) exc = None try : self . sender . missing_check ( ) except exceptions . ReplicationException as err : exc = err self . assertEqual ( str ( exc ) , '' ) self . assertEqual ( '' . join ( self . sender . connection . sent ) , '' '' '' ) self . assertEqual ( self . sender . available_map , dict ( [ ( '' , { '' : Timestamp ( ) } ) ] ) ) def test_missing_check_far_end_unexpected ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if ( device == '' and partition == '' and policy == POLICIES . legacy and suffixes == [ '' ] ) : yield ( '' '' , '' , { '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , policy , suffixes ) ) self . sender . connection = FakeConnection ( ) self . sender . job = { '' : '' , '' : '' , '' : POLICIES . legacy , } self . sender . suffixes = [ '' ] self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . response = FakeResponse ( chunk_body = '' ) exc = None try : self . sender . missing_check ( ) except exceptions . ReplicationException as err : exc = err self . assertEqual ( str ( exc ) , \"\" ) self . assertEqual ( '' . join ( self . sender . connection . sent ) , '' '' '' ) self . assertEqual ( self . sender . available_map , dict ( [ ( '' , { '' : Timestamp ( ) } ) ] ) ) def test_missing_check_send_map ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if ( device == '' and partition == '' and policy == POLICIES . legacy and suffixes == [ '' ] ) : yield ( '' '' , '' , { '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , policy , suffixes ) ) self . sender . connection = FakeConnection ( ) self . sender . job = { '' : '' , '' : '' , '' : POLICIES . legacy , } self . sender . suffixes = [ '' ] self . sender . response = FakeResponse ( chunk_body = ( '' '' '' ) ) self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . missing_check ( ) self . assertEqual ( '' . join ( self . sender . connection . sent ) , '' '' '' ) self . assertEqual ( self . sender . send_map , { '' : { '' : True , '' : True } } ) self . assertEqual ( self . sender . available_map , dict ( [ ( '' , { '' : Timestamp ( ) } ) ] ) ) def test_missing_check_extra_line_parts ( self ) : def yield_hashes ( device , partition , policy , suffixes = None , ** kwargs ) : if ( device == '' and partition == '' and policy == POLICIES . legacy and suffixes == [ '' ] ) : yield ( '' '' , '' , { '' : Timestamp ( ) } ) else : raise Exception ( '' % ( device , partition , policy , suffixes ) ) self . sender . connection = FakeConnection ( ) self . sender . job = { '' : '' , '' : '' , '' : POLICIES . legacy , } self . sender . suffixes = [ '' ] self . sender . response = FakeResponse ( chunk_body = ( '' '' '' ) ) self . sender . daemon . _diskfile_mgr . yield_hashes = yield_hashes self . sender . missing_check ( ) self . assertEqual ( self . sender . send_map , { '' : { '' : True } } ) self . assertEqual ( self . sender . available_map , dict ( [ ( '' , { '' : Timestamp ( ) } ) ] ) ) def test_updates_timeout ( self ) : self . sender . connection = FakeConnection ( ) self . sender . connection . send = lambda d : eventlet . sleep ( ) self . sender . daemon . node_timeout = self . assertRaises ( exceptions . MessageTimeout , self . sender . updates ) def test_updates_empty_send_map ( self ) : self . sender . connection = FakeConnection ( ) self . sender . send_map = { } self . sender . response = FakeResponse ( chunk_body = ( ", "answer": "''"}, {"prompt": " import numpy as np from numpy . testing import assert_allclose from nose . tools import raises from menpo . shape import PointCloud from menpo . transform import ( Homogeneous , Scale , TransformChain , NonUniformScale , UniformScale , Translation , Similarity , Rotation , AlignmentUniformScale , AlignmentRotation ) def homog_compose_before_nonuniformscale_test ( ) : homog = Homogeneous ( np . array ( [ [ , , ] , [ , , ] , [ , , ] ] ) ) s = NonUniformScale ( [ , ] ) res = homog . compose_before ( s ) assert ( type ( res ) == Homogeneous ) assert_allclose ( res . h_matrix , np . array ( [ [ , , ] , [ , , ] , [ , , ] ] ) ) def homog_compose_after_uniformscale_test ( ) : homog = Homogeneous ( np . array ( [ [ , , ] , [ , , ] , [ , , ] ] ) ) s = UniformScale ( , ) res = homog . compose_after ( s ) assert ( type ( res ) == Homogeneous ) assert_allclose ( res . h_matrix , np . array ( [ [ , , ] , [ , , ] , [ , , ] ] ) ) ", "answer": "def rotation_compose_before_homog_test ( ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import positions . fields def add_test_data ( apps , schema_editor ) : MigrationTest = apps . get_model ( \"\" , \"\" ) ", "answer": "test_record = MigrationTest . objects . create ( name = '' , age = , favorite_color = '' )"}, {"prompt": " PREFIX = '' FILES = '' INDEXES = [ '' ] ", "answer": "PRE_LOAD = [ ( '' , '' ) ] "}, {"prompt": " import os from django . core . files . storage import get_storage_class from django . utils . dateparse import parse_datetime from onadata . apps . viewer . models . data_dictionary import DataDictionary from onadata . apps . viewer . models . export import Export from onadata . libs . utils . export_tools import generate_export from test_base import TestBase class TestExport ( TestBase ) : def setUp ( self ) : self . _create_user_and_login ( ) self . fixture_dir = os . path . join ( ", "answer": "self . this_directory , '' , '' )"}, {"prompt": " \"\"\"\"\"\" import re from jinja2 . ext import Extension from jinja2 . lexer import Token , describe_token from jinja2 import TemplateSyntaxError _tag_re = re . compile ( r'' ) _ws_normalize_re = re . compile ( r'' ) class StreamProcessContext ( object ) : def __init__ ( self , stream ) : self . stream = stream self . token = None self . stack = [ ] def fail ( self , message ) : raise TemplateSyntaxError ( message , self . token . lineno , self . stream . name , self . stream . filename ) def _make_dict_from_listing ( listing ) : rv = { } for keys , value in listing : for key in keys : rv [ key ] = value return rv class HTMLCompress ( Extension ) : isolated_elements = set ( [ '' , '' , '' , '' ] ) void_elements = set ( [ '' , '' , '' , '' , '' , '' , '' , '' ] ) block_elements = set ( [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) breaking_rules = _make_dict_from_listing ( [ ( [ '' ] , set ( [ '' ] ) ) , ( [ '' ] , set ( [ '' ] ) ) , ( [ '' , '' ] , set ( [ '' , '' , '' , '' , '' , '' ] ) ) , ( [ '' ] , set ( [ '' , '' , '' , '' ] ) ) , ( [ '' , '' , '' ] , set ( [ '' , '' , '' ] ) ) , ( [ '' , '' ] , set ( [ '' , '' , '' ] ) ) ] ) def is_isolated ( self , stack ) : for tag in reversed ( stack ) : if tag in self . isolated_elements : return True return False def is_breaking ( self , tag , other_tag ) : breaking = self . breaking_rules . get ( other_tag ) return breaking and ( tag in breaking or ( '' in breaking and tag in self . block_elements ) ) def enter_tag ( self , tag , ctx ) : while ctx . stack and self . is_breaking ( tag , ctx . stack [ - ] ) : self . leave_tag ( ctx . stack [ - ] , ctx ) if tag not in self . void_elements : ctx . stack . append ( tag ) def leave_tag ( self , tag , ctx ) : if not ctx . stack : ctx . fail ( '' '' % tag ) if tag == ctx . stack [ - ] : ctx . stack . pop ( ) return for idx , other_tag in enumerate ( reversed ( ctx . stack ) ) : if other_tag == tag : for num in xrange ( idx + ) : ctx . stack . pop ( ) elif not self . breaking_rules . get ( other_tag ) : break def normalize ( self , ctx ) : pos = buffer = [ ] def write_data ( value ) : if not self . is_isolated ( ctx . stack ) : value = _ws_normalize_re . sub ( '' , value . strip ( ) ) buffer . append ( value ) for match in _tag_re . finditer ( ctx . token . value ) : ", "answer": "closes , tag , sole = match . groups ( )"}, {"prompt": " import pytest from rc . poller import supported_pollers from rc import redis_clients from rc . redis_cluster import RedisCluster @ pytest . mark . parametrize ( '' , supported_pollers ) ", "answer": "def test_all_pollers ( redis_hosts , poller , monkeypatch ) :"}, {"prompt": " import operator import sys from . libmp import int_types , mpf_hash , bitcount , from_man_exp , HASH_MODULUS new = object . __new__ def create_reduced ( p , q , _cache = { } ) : key = p , q if key in _cache : return _cache [ key ] x , y = p , q while y : x , y = y , x % y if x != : p //= x q //= x v = new ( mpq ) v . _mpq_ = p , q if q <= and abs ( key [ ] ) < : _cache [ key ] = v return v class mpq ( object ) : \"\"\"\"\"\" __slots__ = [ \"\" ] def __new__ ( cls , p , q = ) : if type ( p ) is tuple : p , q = p elif hasattr ( p , '' ) : p , q = p . _mpq_ return create_reduced ( p , q ) def __repr__ ( s ) : return \"\" % s . _mpq_ def __str__ ( s ) : return \"\" % s . _mpq_ def __int__ ( s ) : a , b = s . _mpq_ return a // b def __nonzero__ ( s ) : return bool ( s . _mpq_ [ ] ) __bool__ = __nonzero__ def __hash__ ( s ) : a , b = s . _mpq_ if sys . version >= \"\" : inverse = pow ( b , HASH_MODULUS - , HASH_MODULUS ) if not inverse : h = sys . hash_info . inf else : h = ( abs ( a ) * inverse ) % HASH_MODULUS if a < : h = - h if h == - : h = - return h else : if b == : return hash ( a ) if not ( b & ( b - ) ) : return mpf_hash ( from_man_exp ( a , - bitcount ( b ) ) ) return hash ( ( a , b ) ) def __eq__ ( s , t ) : ttype = type ( t ) if ttype is mpq : return s . _mpq_ == t . _mpq_ if ttype in int_types : a , b = s . _mpq_ if b != : return False return a == t return NotImplemented def __ne__ ( s , t ) : ttype = type ( t ) if ttype is mpq : return s . _mpq_ != t . _mpq_ if ttype in int_types : a , b = s . _mpq_ if b != : return True return a != t return NotImplemented def _cmp ( s , t , op ) : ttype = type ( t ) if ttype in int_types : a , b = s . _mpq_ return op ( a , t * b ) if ttype is mpq : a , b = s . _mpq_ c , d = t . _mpq_ return op ( a * d , b * c ) return NotImplementedError def __lt__ ( s , t ) : return s . _cmp ( t , operator . lt ) def __le__ ( s , t ) : return s . _cmp ( t , operator . le ) def __gt__ ( s , t ) : return s . _cmp ( t , operator . gt ) def __ge__ ( s , t ) : return s . _cmp ( t , operator . ge ) def __abs__ ( s ) : a , b = s . _mpq_ if a >= : return s v = new ( mpq ) v . _mpq_ = - a , b return v def __neg__ ( s ) : a , b = s . _mpq_ v = new ( mpq ) v . _mpq_ = - a , b return v def __pos__ ( s ) : return s def __add__ ( s , t ) : ttype = type ( t ) if ttype is mpq : a , b = s . _mpq_ c , d = t . _mpq_ return create_reduced ( a * d + b * c , b * d ) if ttype in int_types : a , b = s . _mpq_ v = new ( mpq ) v . _mpq_ = a + b * t , b return v return NotImplemented __radd__ = __add__ def __sub__ ( s , t ) : ttype = type ( t ) if ttype is mpq : a , b = s . _mpq_ c , d = t . _mpq_ return create_reduced ( a * d - b * c , b * d ) if ttype in int_types : a , b = s . _mpq_ v = new ( mpq ) v . _mpq_ = a - b * t , b return v return NotImplemented def __rsub__ ( s , t ) : ttype = type ( t ) if ttype is mpq : a , b = s . _mpq_ c , d = t . _mpq_ return create_reduced ( b * c - a * d , b * d ) if ttype in int_types : a , b = s . _mpq_ v = new ( mpq ) v . _mpq_ = b * t - a , b return v return NotImplemented def __mul__ ( s , t ) : ttype = type ( t ) if ttype is mpq : ", "answer": "a , b = s . _mpq_"}, {"prompt": " from twisted . application import service , internet from twisted . internet import reactor from twisted . spread import pb import cache_classes ", "answer": "class Receiver ( pb . Root ) :"}, {"prompt": " \"\"\"\"\"\" from zope . interface import classProvides from twisted . internet import error as neterror from twisted . python import failure from snapy import netsnmp from snapy . twisted import Session as SnmpSession from nagcat import errors , query , util class SNMPCommon ( query . Query ) : \"\"\"\"\"\" def __init__ ( self , nagcat , conf ) : super ( SNMPCommon , self ) . __init__ ( nagcat , conf ) protocol = conf . get ( '' , '' ) if protocol not in ( '' , '' , '' ) : raise errors . ConfigError ( conf , \"\" % conf [ '' ] ) if protocol == '' : self . conf [ '' ] = '' % conf [ '' ] else : self . conf [ '' ] = '' % ( protocol , self . addr , int ( conf . get ( '' , ) ) ) self . conf [ '' ] = str ( conf . get ( '' , '' ) ) if self . conf [ '' ] not in ( '' , '' ) : raise errors . ConfigError ( conf , \"\" % conf [ '' ] ) self . conf [ '' ] = conf . get ( '' , None ) if not self . conf [ '' ] : raise errors . ConfigError ( conf , \"\" ) def check_oid ( self , conf , key ) : \"\"\"\"\"\" try : oid = netsnmp . OID ( conf [ key ] ) except netsnmp . OIDValueError , ex : raise errors . ConfigError ( conf , str ( ex ) ) return oid _use_bulk = True @ staticmethod def use_bulk ( value ) : \"\"\"\"\"\" SNMPCommon . _use_bulk = bool ( value ) class SNMPQuery ( SNMPCommon ) : \"\"\"\"\"\" classProvides ( query . IQuery ) name = \"\" def __init__ ( self , nagcat , conf ) : super ( SNMPQuery , self ) . __init__ ( nagcat , conf ) if '' in conf : if ( \"\" in conf or \"\" in conf or \"\" in conf ) : raise errors . ConfigError ( conf , \"\" ) self . conf [ '' ] = self . check_oid ( conf , '' ) conf [ '' ] = False self . query_oid = nagcat . new_query ( conf , qcls = SNMPCombined ) self . addDependency ( self . query_oid ) elif ( \"\" in conf and \"\" in conf and \"\" in conf ) : if \"\" in conf : raise errors . ConfigError ( conf , \"\" ) self . conf [ '' ] = self . check_oid ( conf , '' ) self . conf [ '' ] = self . check_oid ( conf , '' ) self . conf [ '' ] = conf [ '' ] conf [ '' ] = True base = conf . copy ( ) base [ '' ] = self . conf [ '' ] self . query_base = nagcat . new_query ( base , qcls = SNMPCombined ) self . addDependency ( self . query_base ) key = conf . copy ( ) key [ '' ] = self . conf [ '' ] self . query_key = nagcat . new_query ( key , qcls = SNMPCombined ) self . addDependency ( self . query_key ) else : raise errors . ConfigError ( conf , \"\" ) if \"\" in conf : self . conf [ '' ] = self . check_oid ( conf , '' ) scale = conf . copy ( ) scale [ '' ] = self . conf [ '' ] self . query_scale = nagcat . new_query ( scale , qcls = SNMPCombined ) self . addDependency ( self . query_scale ) else : self . query_scale = None def _start ( self ) : \"\"\"\"\"\" try : if \"\" in self . conf : return self . _get_result ( ) else : return self . _get_result_set ( ) except : return errors . Failure ( ) def _do_scale ( self , scale , value ) : \"\"\"\"\"\" try : scale = util . MathString ( scale ) value = util . MathString ( value ) except util . MathError : raise errors . TestCritical ( \"\" ) return value * scale def _get_result ( self ) : \"\"\"\"\"\" result = self . query_oid . result if isinstance ( result , failure . Failure ) : return result oid = self . conf [ '' ] result = dict ( self . query_oid . result ) if oid not in result : raise errors . TestCritical ( \"\" % ( oid , ) ) result = result [ oid ] if self . query_scale : oid = self . conf [ '' ] scale = dict ( self . query_scale . result ) if oid not in result : raise errors . TestCritical ( \"\" % ( oid , ) ) scale = scale [ oid ] result = self . _do_scale ( scale , result ) return str ( result ) def _get_result_set ( self ) : \"\"\"\"\"\" class Return ( Exception ) : pass def filter_result ( result , root ) : if isinstance ( result , failure . Failure ) : raise Return ( result ) new = { } for key , value in result : if key . startswith ( self . conf [ root ] ) : new [ key ] = value if not new : raise errors . TestCritical ( \"\" % ( root , ) ) return new try : base = filter_result ( self . query_base . result , \"\" ) keys = filter_result ( self . query_key . result , \"\" ) if self . query_scale : scale = filter_result ( self . query_scale . result , \"\" ) except Return , ex : return ex . args [ ] final = None for oid , value in keys . iteritems ( ) : if value == self . conf [ \"\" ] : index = oid [ len ( self . conf [ \"\" ] ) : ] final = self . conf [ '' ] + index if self . query_scale : final_scale = self . conf [ '' ] + index break if final is None : raise errors . TestCritical ( \"\" % self . conf [ \"\" ] ) if final not in base : raise errors . TestCritical ( \"\" % ( final , ) ) result = base [ final ] if self . query_scale : if final_scale not in scale : raise errors . TestCritical ( \"\" % ( final_scale , ) ) scale = scale [ final_scale ] result = self . _do_scale ( scale , result ) return str ( result ) class SNMPCombined ( SNMPCommon ) : \"\"\"\"\"\" name = \"\" def __init__ ( self , nagcat , conf ) : \"\"\"\"\"\" super ( SNMPCombined , self ) . __init__ ( nagcat , conf ) self . oids = set ( ) self . update ( conf ) self . conf [ '' ] = conf [ '' ] if self . conf [ '' ] == \"\" : self . conf [ '' ] = self . oids try : self . client = SnmpSession ( version = self . conf [ '' ] , community = self . conf [ '' ] , timeout = , retrys = int ( self . conf [ '' ] ) , peername = self . conf [ '' ] , _use_bulk = self . _use_bulk ) except netsnmp . SnmpError , ex : raise errors . InitError ( \"\" % ex ) def update ( self , conf ) : \"\"\"\"\"\" super ( SNMPCombined , self ) . update ( conf ) self . oids . add ( self . check_oid ( conf , '' ) ) def _start ( self ) : try : self . client . open ( ) if self . conf [ '' ] : deferred = self . client . walk ( self . oids , strict = True ) else : deferred = self . client . get ( self . oids ) except : return errors . Failure ( ) deferred . addBoth ( self . _handle_close ) ", "answer": "deferred . addErrback ( self . _handle_error )"}, {"prompt": " from __future__ import absolute_import import sys import pip from pip . compat import stdlib_pkgs from pip . basecommand import Command from pip . operations . freeze import freeze from pip . wheel import WheelCache DEV_PKGS = ( '' , '' , '' , '' ) class FreezeCommand ( Command ) : \"\"\"\"\"\" name = '' usage = \"\"\"\"\"\" summary = '' log_streams = ( \"\" , \"\" ) def __init__ ( self , * args , ** kw ) : super ( FreezeCommand , self ) . __init__ ( * args , ** kw ) self . cmd_opts . add_option ( '' , '' , dest = '' , action = '' , default = None , metavar = '' , help = \"\" \"\" ) self . cmd_opts . add_option ( '' , '' , dest = '' , action = '' , default = [ ] , metavar = '' , help = '' '' ) self . cmd_opts . add_option ( '' , '' , dest = '' , action = '' , default = False , help = '' '' ) self . cmd_opts . add_option ( '' , dest = '' , action = '' , default = False , help = '' ) self . cmd_opts . add_option ( '' , dest = '' , action = '' , ", "answer": "help = ''"}, {"prompt": " \"\"\"\"\"\" from color_patch_model import ColorPatchModel ", "answer": "from mesa . visualization . modules import CanvasGrid"}, {"prompt": " from namespaces import TABLENS from element import Element def Body ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def CalculationSettings ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def CellAddress ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def CellContentChange ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def CellContentDeletion ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def CellRangeSource ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def ChangeDeletion ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def ChangeTrackTableCell ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def Consolidation ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def ContentValidation ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def ContentValidations ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def CoveredTableCell ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def CutOffs ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotDisplayInfo ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotField ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotFieldReference ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotGroup ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotGroupMember ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotGroups ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotLayoutInfo ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotLevel ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotMember ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotMembers ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotSortInfo ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) def DataPilotSubtotal ( ** args ) : return Element ( qname = ( TABLENS , '' ) , ** args ) ", "answer": "def DataPilotSubtotals ( ** args ) :"}, {"prompt": " from mrq . job import Job import datetime from mrq . queue import Queue import time import pytest def test_sorted_graph ( worker ) : p_queue = \"\" worker . start_deps ( ) assert Queue ( p_queue ) . size ( ) == worker . send_raw_tasks ( p_queue , { \"\" : - , \"\" : , \"\" : , \"\" : , \"\" : } , start = False , block = False ) ", "answer": "time . sleep ( )"}, {"prompt": " from twisted . trial . unittest import TestCase from twisted . python import context class ContextTest ( TestCase ) : ", "answer": "def testBasicContext ( self ) :"}, {"prompt": " from __future__ import unicode_literals from django . contrib . auth . models import AnonymousUser from django . contrib . auth . models import User from django . contrib . sessions . middleware import SessionMiddleware from django . core . exceptions import ImproperlyConfigured from django . core . exceptions import PermissionDenied from django . test import RequestFactory from django . views . generic import DetailView import pytest from machina . apps . forum_permission . middleware import ForumPermissionMiddleware from machina . core . db . models import get_model from machina . core . loading import get_class from machina . test . factories import create_forum from machina . test . factories import UserFactory Forum = get_model ( '' , '' ) PermissionHandler = get_class ( '' , '' ) assign_perm = get_class ( '' , '' ) PermissionRequiredMixin = get_class ( '' , '' ) @ pytest . mark . django_db class TestPermissionRequiredMixin ( object ) : @ pytest . fixture ( autouse = True ) def setup ( self ) : self . user = UserFactory . create ( ) self . factory = RequestFactory ( ) self . perm_handler = PermissionHandler ( ) self . forum = create_forum ( ) assign_perm ( '' , self . user , self . forum ) self . mixin = PermissionRequiredMixin ( ) def get_request ( self , url = '' ) : request = self . factory . get ( '' ) middleware = SessionMiddleware ( ) middleware . process_request ( request ) request . session . save ( ) return request def test_should_raise_if_the_permission_required_attribute_is_set_with_an_incorrect_value ( self ) : self . mixin . object = self . forum self . mixin . permission_required = request = self . get_request ( ) request . user = self . user ForumPermissionMiddleware ( ) . process_request ( request ) with pytest . raises ( ImproperlyConfigured ) : self . mixin . check_permissions ( request ) def test_should_redirect_anonymous_users_to_login_url_if_access_is_not_granted ( self ) : self . mixin . object = self . forum self . mixin . permission_required = '' request = self . get_request ( ) request . user = AnonymousUser ( ) ForumPermissionMiddleware ( ) . process_request ( request ) response = self . mixin . dispatch ( request ) assert response . status_code == def test_should_return_http_response_forbiden_to_logged_in_users_if_access_is_not_granted ( self ) : self . mixin . object = self . forum self . mixin . permission_required = [ '' , ] request = self . get_request ( ) request . user = self . user ForumPermissionMiddleware ( ) . process_request ( request ) with pytest . raises ( PermissionDenied ) : self . mixin . dispatch ( request ) def test_should_return_a_valid_response_if_access_is_granted ( self ) : class ForumTestView ( PermissionRequiredMixin , DetailView ) : permission_required = [ '' , ] def get_queryset ( self ) : return Forum . objects . all ( ) forum_view = ForumTestView ( ) request = self . get_request ( ) request . user = self . user ForumPermissionMiddleware ( ) . process_request ( request ) ", "answer": "response = forum_view . dispatch ( request , pk = self . forum . pk )"}, {"prompt": " import logging import re import os from urlparse import urlsplit , urlunsplit log = logging . getLogger ( __name__ ) def atoi ( text ) : return int ( text ) if text . isdigit ( ) else text def natural_keys ( text ) : return [ atoi ( c ) for c in re . split ( r'' , text ) ] ETHERNET_RE = re . compile ( r'' ) MANAGEMENT_RE = re . compile ( r'' ) INTERFACE_NO_RE = re . compile ( r'' ) def expand_range ( interfaces ) : '''''' items = set ( ) prefix = None for group in [ x . strip ( ) for x in interfaces . split ( '' ) ] : ranges = [ x . strip ( ) for x in group . split ( '' ) ] if len ( ranges ) == : interface = ranges [ ] . lower ( ) match = ETHERNET_RE . match ( interface ) if match : intf_no = interface [ len ( match . groups ( ) [ ] ) : ] for token in intf_no . split ( '' ) : if int ( token ) < : log . warning ( '' '' '' % group ) raise TypeError ( '' '' '' % group ) prefix = '' items . add ( '' % ( prefix , intf_no ) ) else : match = MANAGEMENT_RE . match ( interface ) if match : intf_no = interface [ len ( match . groups ( ) [ ] ) : ] for token in intf_no . split ( '' ) : if int ( token ) < : log . warning ( '' '' '' % group ) raise TypeError ( '' '' '' % group ) prefix = '' items . add ( '' % ( prefix , intf_no ) ) else : match = INTERFACE_NO_RE . match ( interface ) if match : for token in interface . split ( '' ) : if int ( token ) < : log . warning ( '' '' '' % group ) raise TypeError ( '' '' '' % group ) items . add ( '' % ( prefix , interface ) ) else : log . warning ( '' '' % group ) raise TypeError ( '' '' % group ) elif len ( ranges ) == : [ start , end ] = [ x . lower ( ) for x in ranges ] items_len = len ( items ) for regex , intf_type in [ ( ETHERNET_RE , '' ) , ( MANAGEMENT_RE , '' ) , ( INTERFACE_NO_RE , prefix ) ] : ", "answer": "match_start = regex . match ( start )"}, {"prompt": " ROOT_URLCONF = '' SECRET_KEY = '' DATABASES = { '' : { '' : '' , '' : '' , } , } INSTALLED_APPS = ( '' , '' , '' , '' , ) MIGRATION_MODULES = { '' : '' , } TEMPLATES = [ { '' : '' , '' : { '' : ( '' , ) , ", "answer": "} ,"}, {"prompt": " from math import sqrt class Rocket ( ) : def __init__ ( self , x = , y = ) : self . x = x self . y = y def move_rocket ( self , x_increment = , y_increment = ) : self . x += x_increment self . y += y_increment def get_distance ( self , other_rocket ) : distance = sqrt ( ( self . x - other_rocket . x ) ** + ( self . y - other_rocket . y ) ** ) return distance ", "answer": "class Shuttle ( Rocket ) :"}, {"prompt": " \"\"\"\"\"\" import datetime import time import webapp2 from google . appengine . ext import blobstore from simian import settings from simian . auth import gaeserver from simian . mac import common from simian . mac import models from simian . mac . common import gae_util from simian . mac . common import mail class AuthSessionCleanup ( webapp2 . RequestHandler ) : \"\"\"\"\"\" def get ( self ) : \"\"\"\"\"\" asd = gaeserver . AuthSessionSimianServer ( ) expired_sessions_count = asd . ExpireAll ( ) class MarkComputersInactive ( webapp2 . RequestHandler ) : \"\"\"\"\"\" def get ( self ) : \"\"\"\"\"\" count = models . Computer . MarkInactive ( ) class UpdateAverageInstallDurations ( webapp2 . RequestHandler ) : \"\"\"\"\"\" def get ( self ) : \"\"\"\"\"\" pkgs , unused_dt = models . ReportsCache . GetInstallCounts ( ) for p in models . PackageInfo . all ( ) : if not p . plist : continue if p . munki_name not in pkgs : continue elif not pkgs [ p . munki_name ] . get ( '' , None ) : continue lock = '' % p . filename if not gae_util . ObtainLock ( lock , timeout = ) : continue old_desc = p . plist [ '' ] avg_duration_text = models . PackageInfo . AVG_DURATION_TEXT % ( pkgs [ p . munki_name ] [ '' ] , pkgs [ p . munki_name ] [ '' ] ) p . description = '' % ( p . description , avg_duration_text ) if p . plist [ '' ] != old_desc : p . put ( ) gae_util . ReleaseLock ( lock ) delay = for track in common . TRACKS : delay += models . Catalog . Generate ( track , delay = delay ) class VerifyPackages ( webapp2 . RequestHandler ) : \"\"\"\"\"\" def get ( self ) : \"\"\"\"\"\" for p in models . PackageInfo . all ( ) : if p . blobstore_key and blobstore . BlobInfo . get ( p . blobstore_key ) : continue elif p . mtime < ( datetime . datetime . utcnow ( ) - datetime . timedelta ( days = ) ) : subject = '' % p . filename body = ( '' '' % ( settings . SERVER_HOSTNAME , p . filename ) ) mail . SendMail ( [ settings . EMAIL_ADMIN_LIST ] , subject , body ) for b in blobstore . BlobInfo . all ( ) : key = b . key ( ) max_attempts = for i in xrange ( , max_attempts + ) : p = models . PackageInfo . all ( ) . filter ( '' , key ) . get ( ) if p : break elif i == max_attempts : if not b . filename and not b . size : b . delete ( ) break subject = '' % b . filename body = ( '' '' '' % ( b . filename , key ) ) ", "answer": "mail . SendMail ( [ settings . EMAIL_ADMIN_LIST ] , subject , body )"}, {"prompt": " import click from platformio . commands . lib import lib_update as cmd_lib_update from platformio . commands . platforms import platforms_update as cmd_platforms_update @ click . command ( \"\" , short_help = \"\" ) @ click . pass_context def cli ( ctx ) : ctx . invoke ( cmd_platforms_update ) ", "answer": "click . echo ( )"}, {"prompt": " from __future__ import print_function ", "answer": "try :"}, {"prompt": " from pyramid . events import subscriber , BeforeRender from social . apps . pyramid_app . utils import backends from example . models import DBSession , User def login_user ( backend , user , user_social_auth ) : backend . strategy . session_set ( '' , user . id ) def login_required ( request ) : return getattr ( request , '' , None ) is not None def get_user ( request ) : user_id = request . session . get ( '' ) if user_id : user = DBSession . query ( User ) . filter ( User . id == user_id ) . first ( ) else : user = None return user ", "answer": "@ subscriber ( BeforeRender )"}, {"prompt": " from os import kill , system , path , chdir from signal import alarm , signal , SIGALRM , SIGKILL import time import subprocess from re import sub , compile , search from sys import argv REAVER = '' PIXIEWPS = '' WASH = '' AIRMON = '' MACCHANGER = '' GIT = '' INFO = '' ALERTA = '' INPUT = '' DATA = '' OPCION = '' USE_REAVER = False USE_PIXIEWPS = False WASH_TIME = WASH_CHANNEL = '' REAVER_TIME = CHOICES_YES = [ '' , '' , '' , '' , '' ] CHOICES_NOPE = [ '' , '' , '' , '' ] PROMPT_APS = False OUTPUT = False OUTPUT_FILE = '' PRINT_REAVER = True PRINT_PIXIE = True GET_PASSWORD = False FOREVER = False OVERRIDE = False def banner ( ) : \"\"\"\"\"\" print print \"\" print \"\" print \"\" print \"\" print \"\" print \"\" print print \"\" print \"\" print \"\" print \"\" print \"\" print def arg_parser ( ) : \"\"\"\"\"\" global PRINT_PIXIE global PRINT_REAVER global USE_REAVER global USE_PIXIEWPS global WASH_TIME global REAVER_TIME global WASH_CHANNEL global PROMPT_APS global OUTPUT_FILE global OUTPUT global GET_PASSWORD global FOREVER global OVERRIDE H = [ '' , '' ] binary_flags = [ '' , '' , '' , '' ] for arg in argv [ : ] : if arg in H : help ( ) exit ( ) elif argv [ argv . index ( arg ) - ] in binary_flags : continue elif arg == '' or arg == '' : PRINT_PIXIE = False PRINT_REAVER = False elif arg == '' or arg == '' : USE_REAVER = True elif arg == '' or arg == '' : USE_PIXIEWPS = True elif arg == '' or arg == '' : try : WASH_TIME = int ( argv [ argv . index ( arg ) + ] ) except ValueError : help ( ) elif arg == '' or arg == '' : try : REAVER_TIME = int ( argv [ argv . index ( arg ) + ] ) except ValueError : help ( ) elif arg == '' or arg == '' : try : WASH_CHANNEL = int ( argv [ argv . index ( arg ) + ] ) except ValueError : help ( ) elif arg == '' or arg == '' : PROMPT_APS = True elif arg == '' or arg == '' : OUTPUT = True OUTPUT_FILE = argv [ argv . index ( arg ) + ] elif arg == '' or arg == '' : GET_PASSWORD = True elif arg == '' or arg == '' : FOREVER = True elif arg == '' or arg == '' : OVERRIDE = True else : help ( ) def help ( ) : \"\"\"\"\"\" print print \"\" print \"\" print print '' print '' print '' print '' print '' print '' print '' print '' print '' print '' print '' print '' print '' print '' print '' print '' print '' print exit ( ) class Engine ( ) : \"\"\"\"\"\" def __init__ ( self ) : self . REAVER = True self . PIXIEWPS = True self . WASH = True self . AIRMON = True self . MACCHANGER = True self . GIT = True def start ( self ) : \"\"\"\"\"\" chdir ( '' ) if not c . check_iface ( ) : c . set_iface ( \"\" ) else : print INFO + \"\" % c . IFACE_MON choice = raw_input ( \"\" % INPUT ) if choice in CHOICES_YES : pass elif choice in CHOICES_NOPE : c . set_iface ( \"\" ) c . set_iface ( \"\" ) if FOREVER : while True : attack = Attack ( ) attack . get_wps_aps ( ) else : attack = Attack ( ) attack . get_wps_aps ( ) engine . exit_limpio ( ) def parse_wash ( self , linea ) : \"\"\"\"\"\" linea = linea . split ( '' ) bssid = linea [ ] canal = linea [ ] essid = linea [ - ] return [ bssid , canal , essid ] def parse_reaver ( self , output , pin_encontrado = False ) : \"\"\"\"\"\" if pin_encontrado : password = '' for linea in output : if '' in linea : password = sub ( '' , '' , linea ) return password if password == '' : return '' E_NONCE = '' R_NONCE = '' PKR = '' PKE = '' HASH1 = '' HASH2 = '' AUTHKEY = '' MANUFACTURER = '' MODEL = '' NUMBER = '' uberlista = [ ] lista_final = [ ] is_complete = False has_something = False if output == '' : return '' for linea in output : if '' in linea : has_something = True elif '' in linea : lista_final = output [ : output . index ( linea ) + ] is_complete = True break elif '' in linea : return '' if has_something and not is_complete : return '' elif has_something == False : return '' for linea in lista_final : if '' in linea : E_NONCE = sub ( '' , '' , linea ) elif '' in linea : R_NONCE = sub ( '' , '' , linea ) elif '' in linea : PKR = sub ( '' , '' , linea ) elif '' in linea : PKE = sub ( '' , '' , linea ) elif '' in linea : HASH1 = sub ( '' , '' , linea ) elif '' in linea : HASH2 = sub ( '' , '' , linea ) elif '' in linea : AUTHKEY = sub ( '' , '' , linea ) elif '' in linea : MANUFACTURER = sub ( '' , '' , linea ) elif '' in linea : MODEL = sub ( '' , '' , linea ) elif '' in linea : NUMBER = sub ( '' , '' , linea ) elif '' in linea : ESSID = sub ( '' , '' , linea ) ESSID = ESSID . split ( '' ) [ - ] [ : - ] elif '' in linea : BSSID = sub ( '' , '' , linea ) else : pass uberlista = [ PKE . strip ( ) , PKR . strip ( ) , HASH1 . strip ( ) , HASH2 . strip ( ) , AUTHKEY . strip ( ) , MANUFACTURER . strip ( ) , MODEL . strip ( ) , NUMBER . strip ( ) , E_NONCE . strip ( ) , R_NONCE . strip ( ) , ESSID . strip ( ) , BSSID . strip ( ) ] return uberlista def check ( self , check_again = False ) : \"\"\"\"\"\" if c . get_uid ( ) != '' : print ALERTA + '' exit ( ) if c . program_exists ( MACCHANGER ) : self . MACCHANGER = True elif not check_again : print ALERTA + '' print '' print '' print '' print '' self . MACCHANGER = False if c . program_exists ( REAVER ) : version = c . check_reaver_version ( ) if version == '' : self . REAVER = True else : print ALERTA + \"\" self . REAVER = False elif not check_again : print ALERTA + '' self . REAVER = False if c . program_exists ( PIXIEWPS ) : self . PIXIEWPS = True elif not check_again : print ALERTA + '' self . PIXIEWPS = False if c . program_exists ( WASH ) : self . WASH = True elif not check_again : print ALERTA + '' self . WASH = False if c . program_exists ( GIT ) : self . GIT = True elif not check_again : self . GIT = False if self . REAVER and self . AIRMON and self . WASH and self . PIXIEWPS and check_again : print INFO + \"\" raw_input ( \"\" % INPUT ) print INFO + \"\" elif check_again : print print ALERTA + \"\" print \"\" print \"\" print exit ( ) if self . REAVER and self . WASH and self . PIXIEWPS : pass else : print ALERTA + \"\" print INPUT + \"\" print \"\" print \"\" print \"\" print \"\" print \"\" print \"\" choice = raw_input ( \"\" % INPUT ) if choice in CHOICES_YES : c . get_binarios ( ) else : exit ( ) engine . start ( ) def run ( self , cmd , shell = False , kill_tree = True , timeout = - ) : \"\"\"\"\"\" class Alarm ( Exception ) : pass def alarm_handler ( signum , frame ) : raise Alarm if timeout != - : signal ( SIGALRM , alarm_handler ) alarm ( timeout ) proc = subprocess . Popen ( cmd , shell = shell , stdout = subprocess . PIPE ) output = [ ] try : for line in iter ( proc . stdout . readline , '' ) : output . append ( line ) if timeout != - : alarm ( ) except Alarm : pids = [ proc . pid ] if kill_tree : pids . extend ( self . get_process_children ( proc . pid ) ) for pid in pids : try : kill ( pid , SIGKILL ) except OSError : pass return output return output def get_process_children ( self , pid ) : \"\"\"\"\"\" proc = subprocess . Popen ( '' % pid , shell = True , stdout = subprocess . PIPE ) stdout = proc . communicate ( ) [ ] return [ int ( p ) for p in stdout . split ( ) ] def mac_changer ( self ) : \"\"\"\"\"\" print INFO + \"\" system ( '' % c . IFACE_MON ) system ( '' % c . IFACE_MON ) system ( '' % c . IFACE_MON ) system ( '' % c . IFACE_MON ) mac = subprocess . check_output ( [ '' , '' , c . IFACE_MON ] ) mac = mac . split ( '' ) [ ] mac = sub ( '' , '' , mac . strip ( ) ) mac = sub ( '' , '' , mac ) system ( '' % c . IFACE_MON ) system ( '' % c . IFACE_MON ) system ( '' % c . IFACE_MON ) system ( '' % c . IFACE_MON ) print INFO + \"\" % ( INPUT , mac . upper ( ) ) def exit_limpio ( self ) : \"\"\"\"\"\" if path . isfile ( '' ) or path . isfile ( '' ) : print OPCION + \"\" print \"\" choice = raw_input ( \"\" % INPUT ) if choice in CHOICES_YES : system ( '' ) if c . IS_MON : c . set_iface ( \"\" ) if USE_REAVER : system ( '' ) exit ( ) class Config ( ) : \"\"\"\"\"\" IFACE_MON = '' IFACE = '' IS_MON = False def program_exists ( self , programa ) : \"\"\"\"\"\" cmd = \"\" + programa output = subprocess . Popen ( cmd , shell = True , stdout = subprocess . PIPE ) output = output . communicate ( ) [ ] if output != \"\" : return True else : return False def get_uid ( self ) : \"\"\"\"\"\" uid = subprocess . check_output ( [ '' , '' ] ) . strip ( ) return uid def check_iface ( self ) : \"\"\"\"\"\" proc = subprocess . Popen ( '' , shell = True , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) . communicate ( ) [ ] . strip ( ) . split ( '' ) mon = '' for linea in proc : if '' in linea : mon = linea [ : ] . strip ( ) if mon != '' : self . IFACE_MON , self . IFACE = mon , mon self . IS_MON = True return True else : return False def get_iface ( self ) : \"\"\"\"\"\" if self . IS_MON : proc = subprocess . Popen ( '' , shell = True , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) . communicate ( ) [ ] . strip ( ) . split ( '' ) for linea in proc : if '' in linea : mon = linea [ : ] . strip ( ) self . IFACE_MON = mon return mon else : proc = subprocess . Popen ( '' , shell = True , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) . communicate ( ) [ ] . strip ( ) . split ( '' ) ifaces = [ ] for linea in proc : if '' in linea : ifaces . append ( linea [ : ] . strip ( ) ) if len ( ifaces ) == and ifaces [ ] == '' : print ALERTA + \"\" print \"\" print \"\" print \"\" exit ( ) elif len ( ifaces ) > : print INPUT + \"\" for i in ifaces : print str ( ifaces . index ( i ) ) + \"\" + i while True : try : choice = int ( raw_input ( INPUT ) ) self . IFACE = ifaces [ choice ] return ifaces [ choice ] break except IndexError : print ALERTA + \"\" % ( len ( ifaces ) - ) except ValueError : print ALERTA + \"\" % ( len ( ifaces ) - ) except KeyboardInterrupt : print print ALERTA + \"\" print engine . exit_limpio ( ) else : self . IFACE = ifaces [ ] return ifaces [ ] def set_iface ( self , status ) : \"\"\"\"\"\" if self . IS_MON : print INFO + '' % self . get_iface ( ) system ( '' % ( self . IFACE_MON ) ) system ( '' % ( self . IFACE_MON ) ) system ( '' % ( self . IFACE_MON ) ) self . IS_MON = False print INFO + '' else : print INFO + '' % ( self . get_iface ( ) ) system ( '' % ( self . IFACE ) ) system ( '' % ( self . IFACE ) ) system ( '' % ( self . IFACE ) ) self . IFACE_MON = self . IFACE self . IS_MON = True print INFO + \"\" % self . IFACE def data_file ( self , data ) : \"\"\"\"\"\" ", "answer": "system ( '' % OUTPUT_FILE )"}, {"prompt": " from rally . common import logging from rally . plugins . openstack import scenario from rally . plugins . openstack . scenarios . keystone import utils as kutils from rally . task import validation class KeystoneBasic ( kutils . KeystoneScenario ) : \"\"\"\"\"\" @ validation . required_openstack ( admin = True ) @ scenario . configure ( context = { \"\" : [ \"\" ] } ) @ logging . log_deprecated_args ( \"\" , \"\" , [ \"\" ] , once = True ) def create_user ( self , name_length = , ** kwargs ) : \"\"\"\"\"\" self . _user_create ( ** kwargs ) @ validation . required_openstack ( admin = True ) @ scenario . configure ( context = { \"\" : [ \"\" ] } ) @ logging . log_deprecated_args ( \"\" , \"\" , [ \"\" ] , once = True ) def create_delete_user ( self , name_length = , ** kwargs ) : \"\"\"\"\"\" user = self . _user_create ( ** kwargs ) self . _resource_delete ( user ) @ validation . required_openstack ( admin = True ) @ scenario . configure ( context = { \"\" : [ \"\" ] } ) def create_user_set_enabled_and_delete ( self , enabled = True , ** kwargs ) : \"\"\"\"\"\" user = self . _user_create ( enabled = enabled , ** kwargs ) self . _update_user_enabled ( user , not enabled ) self . _resource_delete ( user ) @ validation . required_openstack ( admin = True ) @ scenario . configure ( context = { \"\" : [ \"\" ] } ) @ logging . log_deprecated_args ( \"\" , \"\" , [ \"\" ] , once = True ) def create_tenant ( self , name_length = , ** kwargs ) : \"\"\"\"\"\" self . _tenant_create ( ** kwargs ) @ validation . number ( \"\" , minval = ) @ validation . required_openstack ( admin = True ) @ scenario . configure ( context = { \"\" : [ \"\" ] } ) @ logging . log_deprecated_args ( \"\" , \"\" , [ \"\" ] , once = True ) def create_tenant_with_users ( self , users_per_tenant , name_length = , ** kwargs ) : \"\"\"\"\"\" tenant = self . _tenant_create ( ** kwargs ) self . _users_create ( tenant , users_per_tenant = users_per_tenant ) @ validation . required_openstack ( admin = True ) ", "answer": "@ scenario . configure ( context = { \"\" : [ \"\" ] } )"}, {"prompt": " import sys if sys . version_info < ( , ) : import unittest2 as unittest else : import unittest import mock import tempfile import logging from kafka import KafkaClient , MultiProcessConsumer import beaver from beaver . config import BeaverConfig from beaver . transports import create_transport from beaver . unicode_dammit import unicode_dammit from fixtures import Fixture , ZookeeperFixture , KafkaFixture try : from beaver . transports . kafka_transport import KafkaTransport skip = False except ImportError , e : if e . message == '' : skip = True else : raise @ unittest . skipIf ( skip , '' ) class KafkaTests ( unittest . TestCase ) : @ classmethod def setUpClass ( cls ) : cls . logger = logging . getLogger ( __name__ ) empty_conf = tempfile . NamedTemporaryFile ( delete = True ) cls . beaver_config = BeaverConfig ( mock . Mock ( config = empty_conf . name ) ) output_file = Fixture . download_official_distribution ( ) Fixture . extract_distribution ( output_file ) cls . zk = ZookeeperFixture . instance ( ) cls . server = KafkaFixture . instance ( , cls . zk . host , cls . zk . port ) @ classmethod def tearDownClass ( cls ) : cls . server . close ( ) cls . zk . close ( ) def test_builtin_kafka ( cls ) : cls . beaver_config . set ( '' , '' ) cls . beaver_config . set ( '' , ) cls . beaver_config . set ( '' , cls . server . host + \"\" + str ( cls . server . port ) ) transport = create_transport ( cls . beaver_config , logger = cls . logger ) cls . assertIsInstance ( transport , beaver . transports . kafka_transport . KafkaTransport ) data = { } lines = [ ] n = for i in range ( n ) : lines . append ( '' + str ( i ) + '' ) new_lines = [ ] for line in lines : message = unicode_dammit ( line ) if len ( message ) == : continue new_lines . append ( message ) data [ '' ] = new_lines data [ '' ] = [ ] transport . callback ( \"\" , ** data ) messages = cls . _consume_messages ( cls . server . host , cls . server . port ) cls . assertEqual ( n , messages . __len__ ( ) ) for message in messages : ", "answer": "cls . assertIn ( '' , message . message . value ) ;"}, {"prompt": " \"\"\"\"\"\" from dronekit import connect , VehicleMode , LocationGlobal , LocationGlobalRelative from pymavlink import mavutil import time import math import argparse ", "answer": "parser = argparse . ArgumentParser ( description = '' )"}, {"prompt": " from datetime import timedelta from django . core . paginator import Paginator from django . http import Http404 from django . utils . translation import ugettext as _ from molly . utils import haversine from molly . utils . views import BaseView , ZoomableView from molly . utils . breadcrumbs import * from molly . maps import Map from molly . apps . library . forms import SearchForm from molly . apps . library . models import LibrarySearchQuery , LibrarySearchError class IndexView ( BaseView ) : \"\"\"\"\"\" def get_metadata ( self , request ) : return { '' : _ ( '' ) , '' : _ ( \"\" ) , } def initial_context ( self , request ) : return { '' : SearchForm ( ) } @ BreadcrumbFactory def breadcrumb ( self , request , context ) : return Breadcrumb ( self . conf . local_name , None , _ ( '' ) , lazy_reverse ( '' ) ) def handle_GET ( self , request , context ) : return self . render ( request , context , '' , expires = timedelta ( days = ) ) class SearchDetailView ( BaseView ) : \"\"\"\"\"\" def get_metadata ( self , request ) : return { '' : False , } def initial_context ( self , request ) : return { '' : SearchForm ( request . GET ) , } @ BreadcrumbFactory def breadcrumb ( self , request , context ) : if '' in context or context [ '' ] . is_valid ( ) : title = _ ( '' ) else : title = _ ( '' ) return Breadcrumb ( self . conf . local_name , lazy_parent ( '' ) , title , lazy_reverse ( '' ) , ) def handle_GET ( self , request , context ) : search_form = context [ '' ] if not ( request . GET and search_form . is_valid ( ) ) : return self . render ( request , context , '' ) try : query = LibrarySearchQuery ( search_form . cleaned_data [ '' ] , search_form . cleaned_data [ '' ] , search_form . cleaned_data [ '' ] ) except LibrarySearchQuery . InconsistentQuery , e : return self . handle_error ( request , context , e . msg ) try : results = self . conf . provider . library_search ( query ) except LibrarySearchError as e : return self . handle_error ( request , context , e . message ) paginator = Paginator ( results , ) try : page_index = int ( request . GET [ '' ] ) except ( ValueError , KeyError ) : page_index = else : page_index = min ( max ( , page_index ) , paginator . num_pages ) page = paginator . page ( page_index ) if hasattr ( self . conf , '' ) : self . conf . additional_metadata_provider . annotate ( page . object_list ) page . object_list = list ( page . object_list ) context . update ( { '' : query . removed , '' : paginator , '' : page , } ) return self . render ( request , context , '' , expires = timedelta ( hours = ) ) def handle_error ( self , request , context , message ) : context [ '' ] = message return self . render ( request , context , '' ) AVAIL_COLORS = [ '' , '' , '' , '' , '' ] class ItemDetailView ( ZoomableView ) : \"\"\"\"\"\" def initial_context ( self , request , control_number ) : context = super ( ItemDetailView , self ) . initial_context ( request ) item = self . conf . provider . control_number_search ( control_number ) if item is None : raise Http404 ( ) context . update ( { '' : item , '' : control_number , } ) return context @ BreadcrumbFactory def breadcrumb ( self , request , context , control_number ) : return Breadcrumb ( self . conf . local_name , lazy_parent ( '' ) , _ ( '' ) , lazy_reverse ( '' , args = [ control_number ] ) , ) def handle_GET ( self , request , context , control_number ) : user_location = request . session . get ( '' ) points = [ ] point_libraries = [ ] lbs = context [ '' ] . libraries . items ( ) for library , books in lbs : library . entity = library . get_entity ( ) if user_location : lbs = sorted ( lbs , key = lambda ( l , b ) : ( haversine ( user_location , l . entity . location ) if l . entity and l . entity . location else float ( '' ) ) ) for library , books in lbs : if library . entity != None and library . entity . location != None : colour = AVAIL_COLORS [ max ( b [ '' ] for b in books ) ] points . append ( ( library . entity . location [ ] , library . entity . location [ ] , colour , library . entity . title ) ) point_libraries . append ( library ) if len ( points ) > : ", "answer": "context [ '' ] = Map ("}, {"prompt": " \"\"\"\"\"\" import base64 import urllib2 import uuid from googleads import dfp ADVERTISER_ID = '' ICON_URL = ( '' '' ) APP_ICON_SMALL = ( '' '' ) def main ( client , advertiser_id ) : creative_service = client . GetService ( '' , version = '' ) creative_template_id = '' image_data = urllib2 . urlopen ( ICON_URL ) . read ( ) image_data = base64 . b64encode ( image_data ) app_icon_data = urllib2 . urlopen ( APP_ICON_SMALL ) . read ( ) app_icon_data = base64 . b64encode ( app_icon_data ) creative = { '' : '' , '' : '' % uuid . uuid4 ( ) , '' : advertiser_id , '' : { '' : '' , '' : '' , '' : False } , '' : creative_template_id , '' : ( '' '' ) , '' : [ { '' : '' , '' : '' , '' : { '' : image_data , '' : '' % uuid . uuid4 ( ) } } , { '' : '' , '' : '' , '' : { '' : app_icon_data , '' : '' % uuid . uuid4 ( ) } } , { '' : '' , '' : '' , '' : '' } , { '' : '' , '' : '' , '' : '' } , { '' : '' , '' : '' , '' : '' } , { '' : '' , '' : '' , '' : '' } , { '' : '' , '' : '' , '' : '' } , { '' : '' , '' : '' , '' : '' } , { '' : '' , '' : '' , '' : '' } ] } creative = creative_service . createCreatives ( [ creative ] ) [ ] print ( '' '' ", "answer": "% ( creative [ '' ] , creative [ '' ] , creative [ '' ] ) )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function , absolute_import import inspect from functools import wraps , partial from llvmlite import ir from numba import types , cgutils from numba . pythonapi import box , unbox , NativeValue from numba import njit from numba . six import exec_ from . import _box _getter_code_template = \"\"\"\"\"\" _setter_code_template = \"\"\"\"\"\" _method_code_template = \"\"\"\"\"\" def _generate_property ( field , template , fname ) : \"\"\"\"\"\" source = template . format ( field ) glbls = { } exec_ ( source , glbls ) return njit ( glbls [ fname ] ) _generate_getter = partial ( _generate_property , template = _getter_code_template , fname = '' ) _generate_setter = partial ( _generate_property , template = _setter_code_template , fname = '' ) def _generate_method ( name , func ) : \"\"\"\"\"\" argspec = inspect . getargspec ( func ) assert not argspec . varargs , '' assert not argspec . keywords , '' assert not argspec . defaults , '' args = '' . join ( argspec . args [ : ] ) source = _method_code_template . format ( method = name , args = args ) glbls = { } exec_ ( source , glbls ) method = njit ( glbls [ '' ] ) @ wraps ( func ) def wrapper ( * args , ** kwargs ) : return method ( * args , ** kwargs ) return wrapper _cache_specialized_box = { } def _specialize_box ( typ ) : \"\"\"\"\"\" if typ in _cache_specialized_box : return _cache_specialized_box [ typ ] dct = { '' : ( ) , '' : typ } for field in typ . struct : if not field . startswith ( '' ) : getter = _generate_getter ( field ) setter = _generate_setter ( field ) dct [ field ] = property ( getter , setter ) for field , impdct in typ . jitprops . items ( ) : if not field . startswith ( '' ) : getter = None setter = None if '' in impdct : getter = _generate_getter ( field ) if '' in impdct : setter = _generate_setter ( field ) dct [ field ] = property ( getter , setter ) for name , func in typ . methods . items ( ) : if not name . startswith ( '' ) : getter = _generate_method ( name , func ) dct [ name ] = getter subcls = type ( typ . classname , ( _box . Box , ) , dct ) _cache_specialized_box [ typ ] = subcls for k , v in dct . items ( ) : if isinstance ( v , property ) : prop = getattr ( subcls , k ) if prop . fget is not None : fget = prop . fget fast_fget = fget . compile ( ( typ , ) ) fget . disable_compile ( ) setattr ( subcls , k , property ( fast_fget , prop . fset , prop . fdel ) ) return subcls @ box ( types . ClassInstanceType ) def _box_class_instance ( typ , val , c ) : meminfo , dataptr = cgutils . unpack_tuple ( c . builder , val ) box_subclassed = _specialize_box ( typ ) int_addr_boxcls = c . context . get_constant ( types . uintp , id ( box_subclassed ) ) box_cls = c . builder . inttoptr ( int_addr_boxcls , c . pyapi . pyobj ) box = c . pyapi . call_function_objargs ( box_cls , ( ) ) llvoidptr = ir . IntType ( ) . as_pointer ( ) addr_meminfo = c . builder . bitcast ( meminfo , llvoidptr ) addr_data = c . builder . bitcast ( dataptr , llvoidptr ) ", "answer": "def set_member ( member_offset , value ) :"}, {"prompt": " from exceptions import Exception from mox import IsA from rack import context from rack import db from rack import exception from rack . openstack . common import jsonutils from rack . resourceoperator import manager from rack import test from rack . tests . api import fakes import uuid import webob GID = unicode ( uuid . uuid4 ( ) ) NETWORK_ID1 = unicode ( uuid . uuid4 ( ) ) NETWORK_ID2 = unicode ( uuid . uuid4 ( ) ) RO_HOST_NAME = \"\" NEUTRON_NW_ID = \"\" def fake_create_db ( context , values ) : values [ \"\" ] = NETWORK_ID1 return values def fake_group_get_by_gid ( context , gid ) : return { \"\" : gid , \"\" : \"\" } def fake_select_destinations ( context , request_spec , filter_properties ) : return { \"\" : RO_HOST_NAME } def fake_network_get_all ( context , gid ) : return _return_base_network_list ( context , gid ) def fake_network_get_all_empty_list ( contextm , gid ) : return [ ] def fake_raise_exception ( ) : raise Exception ( ) def _return_base_network_list ( context , gid ) : return [ { \"\" : NETWORK_ID1 , \"\" : \"\" + NETWORK_ID1 , \"\" : gid , \"\" : context . user_id , \"\" : context . project_id , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } , { \"\" : NETWORK_ID2 , \"\" : None , \"\" : gid , \"\" : context . user_id , \"\" : context . project_id , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } ] def fake_network_get_by_network_id ( context , gid , network_id ) : network_dict = _return_base_network_list ( context , gid ) [ ] network_dict [ \"\" ] = [ ] return network_dict def fake_network_delete ( context , gid , network_id ) : return { \"\" : NEUTRON_NW_ID , \"\" : \"\" } def get_request ( url , method , body = None ) : req = webob . Request . blank ( url ) req . headers [ '' ] = '' req . method = method if body is not None : req . body = jsonutils . dumps ( body ) return req class FakeContext ( context . RequestContext ) : def elevated ( self ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : self . _elevated = super ( FakeContext , self ) . elevated ( ) return self . _elevated class NetworksTest ( test . NoDBTestCase ) : def setUp ( self ) : super ( NetworksTest , self ) . setUp ( ) self . stubs . Set ( db , \"\" , fake_group_get_by_gid ) self . user_id = '' self . project_id = '' self . context = FakeContext ( self . user_id , self . project_id ) ", "answer": "self . app = fakes . wsgi_app ( )"}, {"prompt": " __productname__ = '' __version__ = \"\" __copyright__ = \"\" __author__ = \"\" __author_email__ = \"\" __description__ = \"\" __license__ = \"\" __homepage__ = \"\" from imapfw . init import Imapfw ", "answer": "from imapfw import runtime "}, {"prompt": " from __future__ import unicode_literals import posixpath from django . conf import settings ", "answer": "JQUERY_URL = getattr ("}, {"prompt": " \"\"\"\"\"\" import httpretty from six . moves import cStringIO from six . moves . urllib import parse as urlparse from bravado . client import SwaggerClient from tests . functional . conftest import register_spec , API_DOCS_URL , register_get def test_form_params_in_request ( httprettified , swagger_dict ) : param1_spec = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } param2_spec = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } path_spec = swagger_dict [ '' ] [ '' ] path_spec [ '' ] = path_spec . pop ( '' ) path_spec [ '' ] [ '' ] = [ param1_spec , param2_spec ] register_spec ( swagger_dict ) httpretty . register_uri ( httpretty . POST , \"\" ) resource = SwaggerClient . from_url ( API_DOCS_URL ) . api_test resource . testHTTP ( param_id = , param_name = '' ) . result ( ) content_type = httpretty . last_request ( ) . headers [ '' ] assert '' == content_type body = urlparse . parse_qs ( httpretty . last_request ( ) . body ) assert { b'' : [ b'' ] , b'' : [ b'' ] } == body def test_file_upload_in_request ( httprettified , swagger_dict ) : param1_spec = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } param2_spec = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } path_spec = swagger_dict [ '' ] [ '' ] path_spec [ '' ] = path_spec . pop ( '' ) path_spec [ '' ] [ '' ] = [ param1_spec , param2_spec ] path_spec [ '' ] [ '' ] = [ '' ] register_spec ( swagger_dict ) httpretty . register_uri ( httpretty . POST , \"\" ) resource = SwaggerClient . from_url ( API_DOCS_URL ) . api_test resource . testHTTP ( param_id = , file_name = cStringIO ( '' ) ) . result ( ) content_type = httpretty . last_request ( ) . headers [ '' ] assert content_type . startswith ( '' ) assert b\"\" in httpretty . last_request ( ) . body assert b\"\" in httpretty . last_request ( ) . body def test_parameter_in_path_of_request ( httprettified , swagger_dict ) : path_param_spec = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } paths_spec = swagger_dict [ '' ] paths_spec [ '' ] = paths_spec . pop ( '' ) paths_spec [ '' ] [ '' ] [ '' ] . append ( path_param_spec ) register_spec ( swagger_dict ) register_get ( '' ) resource = SwaggerClient . from_url ( API_DOCS_URL ) . api_test assert resource . testHTTP ( test_param = \"\" , param_id = \"\" ) . result ( ) is None def test_default_value_not_in_request ( httprettified , swagger_dict ) : swagger_dict [ '' ] [ '' ] [ '' ] [ '' ] [ ] [ '' ] = '' register_spec ( swagger_dict ) register_get ( \"\" ) resource = SwaggerClient . from_url ( API_DOCS_URL ) . api_test resource . testHTTP ( ) . result ( ) assert '' not in httpretty . last_request ( ) . querystring def test_array_with_collection_format_in_path_of_request ( httprettified , swagger_dict ) : path_param_spec = { '' : '' , '' : '' , '' : '' , '' : { '' : '' ", "answer": "} ,"}, {"prompt": " import os import sys from setuptools import setup if sys . version_info < ( , ) : ", "answer": "tests_require = [ '' ]"}, {"prompt": " from django . contrib import admin from custom_comments . articles . models import Article class ArticleAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' , '' ) ", "answer": "list_filter = ( '' , )"}, {"prompt": " import pytest ", "answer": "@ pytest . yield_fixture ( )"}, {"prompt": " import django if django . VERSION >= ( , ) : from django . contrib . auth import get_user_model User = get_user_model ( ) else : try : from django . contrib . auth . models import User except ImportError : ", "answer": "raise ImportError ( u\"\" )"}, {"prompt": " import os import sys import ast from . loaders import EnvFileConfigurationLoader , IniFileConfigurationLoader , EnvVarConfigurationLoader from . exceptions import InvalidConfigurationFile , InvalidPath , InvalidConfigurationCast , UnknownConfiguration from . casts import Boolean , Option , List , Tuple MAGIC_FRAME_DEPTH = class ConfigurationDiscovery ( object ) : default_filetypes = ( EnvFileConfigurationLoader , IniFileConfigurationLoader ) def __init__ ( self , starting_path , filetypes = None , root_path = \"\" ) : \"\"\"\"\"\" self . starting_path = os . path . realpath ( os . path . abspath ( starting_path ) ) self . root_path = os . path . realpath ( root_path ) if not self . starting_path . startswith ( self . root_path ) : raise InvalidPath ( '' ) if filetypes is None : filetypes = self . default_filetypes self . filetypes = filetypes self . _config_files = None def _scan_path ( self , path ) : ", "answer": "config_files = [ ]"}, {"prompt": " from copy import deepcopy import numpy as np from six import string_types from sklearn import decomposition as sk_decomp from sklearn import cluster as sk_cluster from sklearn . metrics import pairwise_distances from os . path import exists , join from os import makedirs from nibabel import nifti1 from neurosynth . analysis import meta class Clusterable ( object ) : '''''' def __init__ ( self , dataset , mask = None , features = None , feature_threshold = None , min_voxels = None , min_studies = None ) : self . dataset = dataset self . masker = deepcopy ( dataset . masker ) if features is not None : ids = dataset . get_studies ( features = features , frequency_threshold = feature_threshold ) data = dataset . get_image_data ( ids , dense = False ) else : data = dataset . image_table . data if min_studies is not None : av = self . masker . unmask ( data . sum ( ) >= min_studies , output = '' ) self . masker . add ( { '' : av } ) if min_voxels is not None : data = data [ : , np . array ( data . sum ( ) >= min_voxels ) . squeeze ( ) ] if mask is not None : self . masker . add ( { '' : mask } ) self . data = data [ self . masker . get_mask ( [ '' , '' ] ) , : ] . toarray ( ) def transform ( self , transformer , transpose = False ) : '''''' data = self . data . T if transpose else self . data data = transformer . fit_transform ( data ) self . data = data . T if transpose else data return self def magic ( dataset , method = '' , roi_mask = None , coactivation_mask = None , features = None , feature_threshold = , min_voxels_per_study = None , min_studies_per_voxel = None , reduce_reference = '' , n_components = , distance_metric = '' , clustering_algorithm = '' , n_clusters = , clustering_kwargs = { } , output_dir = None , filename = None , coactivation_images = False , coactivation_threshold = ) : '''''' roi = Clusterable ( dataset , roi_mask , min_voxels = min_voxels_per_study , min_studies = min_studies_per_voxel , features = features , feature_threshold = feature_threshold ) if method == '' : reference = Clusterable ( dataset , coactivation_mask , min_voxels = min_voxels_per_study , min_studies = min_studies_per_voxel , features = features , feature_threshold = feature_threshold ) elif method == '' : reference = deepcopy ( roi ) feature_data = dataset . feature_table . data n_studies = len ( feature_data ) reference . data = reference . data . dot ( feature_data . values ) / n_studies elif method == '' : reference = roi if reduce_reference is not None : if isinstance ( reduce_reference , string_types ) : reduce_reference = { '' : sk_decomp . RandomizedPCA , '' : sk_decomp . FastICA } [ reduce_reference ] ( n_components ) transpose = ( method == '' ) reference = reference . transform ( reduce_reference , transpose = transpose ) if method == '' : distances = pairwise_distances ( roi . data , reference . data , metric = distance_metric ) else : distances = reference . data if isinstance ( clustering_algorithm , string_types ) : clustering_algorithm = { '' : sk_cluster . KMeans , '' : sk_cluster . MiniBatchKMeans } [ clustering_algorithm ] ( n_clusters , ** clustering_kwargs ) labels = clustering_algorithm . fit_predict ( distances ) + header = roi . masker . get_header ( ) header [ '' ] = labels . max ( ) header [ '' ] = labels . min ( ) voxel_labels = roi . masker . unmask ( labels ) img = nifti1 . Nifti1Image ( voxel_labels , None , header ) if output_dir is not None : if not exists ( output_dir ) : makedirs ( output_dir ) if filename is None : ", "answer": "filename = '' % n_clusters"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " \"\"\"\"\"\" import logging from networking_bagpipe . agent import bagpipe_bgp_agent from neutron_lib import constants as n_const from neutron . agent . l2 import agent_extension from neutron . plugins . ml2 . drivers . openvswitch . agent . common import constants as ovs_agt_constants from neutron . plugins . ml2 . drivers . openvswitch . agent . openflow . native import br_tun as native_br_tun from neutron . plugins . ml2 . drivers . openvswitch . agent . openflow . ovs_ofctl import br_tun as ofctl_br_tun LOG = logging . getLogger ( __name__ ) class OVSBridgeIntercept ( ofctl_br_tun . OVSTunnelBridge , native_br_tun . OVSTunnelBridge ) : \"\"\"\"\"\" def __init__ ( self , bridge ) : \"\"\"\"\"\" self . bridge = bridge self . intercept_method ( \"\" ) def intercept_method ( self , method_name ) : method = getattr ( self . bridge . __class__ , method_name , None ) if method is not None : setattr ( self , method_name , lambda * args , ** kwargs : method ( self , * args , ** kwargs ) ) def __getattr__ ( self , name ) : return getattr ( self . bridge , name ) class BagpipeBgpvpnAgentExtension ( agent_extension . AgentCoreResourceExtension ) : def initialize ( self , connection , driver_type ) : if driver_type != ovs_agt_constants . EXTENSION_DRIVER_TYPE : raise Exception ( \"\" \"\" ) self . bagpipe_bgp_agent = bagpipe_bgp_agent . BaGPipeBGPAgent ( n_const . AGENT_TYPE_OVS , ", "answer": "connection ,"}, {"prompt": " from os . path import dirname , join , abspath __dir__ = dirname ( abspath ( __file__ ) ) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ) MANAGERS = ADMINS DATABASE_ENGINE = '' ", "answer": "DATABASE_NAME = ''"}, {"prompt": " import xml_models from saasu_client import DEFAULT_GET_URL from saasu_client . models . base import BaseModel , CollectionField __all__ = [ '' , '' , '' , '' , '' ] class ServiceInvoiceItem ( BaseModel ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals from bs4 import BeautifulSoup from django . conf import settings from django . contrib import admin from django . test import override_settings from cms . api import add_plugin , create_page from cms . utils . plugins import build_plugin_tree from cmsplugin_cascade . bootstrap3 . container import ( BootstrapContainerPlugin , BootstrapRowPlugin , BootstrapColumnPlugin ) from cmsplugin_cascade . bootstrap3 . accordion import ( BootstrapAccordionPlugin , BootstrapAccordionPanelPlugin ) from cmsplugin_cascade . bootstrap3 import settings from cms . test_utils . testcases import CMSTestCase from . utils import get_request_context BS3_BREAKPOINT_KEYS = list ( tp [ ] for tp in settings . CMSPLUGIN_CASCADE [ '' ] [ '' ] ) class AccordionPluginTest ( CMSTestCase ) : def setUp ( self ) : page = create_page ( '' , '' , '' , published = True , in_navigation = True ) self . placeholder = page . placeholders . get ( slot = '' ) self . request = self . get_request ( language = '' , page = page ) self . admin_site = admin . sites . AdminSite ( ) def build_accordion_plugins ( self ) : container_model = add_plugin ( self . placeholder , BootstrapContainerPlugin , '' , glossary = { '' : BS3_BREAKPOINT_KEYS } ) container_plugin = container_model . get_plugin_class_instance ( self . admin_site ) self . assertIsInstance ( container_plugin , BootstrapContainerPlugin ) row_model = add_plugin ( self . placeholder , BootstrapRowPlugin , '' , target = container_model , glossary = { } ) row_plugin = row_model . get_plugin_class_instance ( ) self . assertIsInstance ( row_plugin , BootstrapRowPlugin ) column_model = add_plugin ( self . placeholder , BootstrapColumnPlugin , '' , target = row_model , glossary = { '' : '' , '' : '' , '' : '' , '' : '' } ) column_plugin = column_model . get_plugin_class_instance ( ) self . assertIsInstance ( column_plugin , BootstrapColumnPlugin ) accordion_model = add_plugin ( self . placeholder , BootstrapAccordionPlugin , '' , target = column_model ) accordion_plugin = accordion_model . get_plugin_class_instance ( self . admin_site ) self . assertIsInstance ( accordion_plugin , BootstrapAccordionPlugin ) ", "answer": "accordion_plugin . cms_plugin_instance = accordion_model . cmsplugin_ptr"}, {"prompt": " import ClientConstants as CC import ClientFiles import HydrusConstants as HC import HydrusData import HydrusGlobals import HydrusServerResources import os from twisted . web . static import File as FileResource local_booru_css = FileResource ( os . path . join ( HC . STATIC_DIR , '' ) , defaultType = '' ) class HydrusResourceCommandBooru ( HydrusServerResources . HydrusResourceCommand ) : def _recordDataUsage ( self , request ) : path = request . path [ : ] if request . method == '' : method = HC . GET else : method = HC . POST if ( HC . LOCAL_BOORU , method , path ) in HC . BANDWIDTH_CONSUMING_REQUESTS : num_bytes = request . hydrus_request_data_usage HydrusGlobals . client_controller . pub ( '' , { CC . LOCAL_BOORU_SERVICE_KEY : [ HydrusData . ServiceUpdate ( HC . SERVICE_UPDATE_REQUEST_MADE , num_bytes ) ] } ) def _callbackCheckRestrictions ( self , request ) : self . _checkServerBusy ( ) self . _checkUserAgent ( request ) self . _domain . CheckValid ( request . getClientIP ( ) ) return request class HydrusResourceCommandBooruFile ( HydrusResourceCommandBooru ) : def _threadDoGETJob ( self , request ) : share_key = request . hydrus_args [ '' ] hash = request . hydrus_args [ '' ] local_booru_manager = HydrusGlobals . client_controller . GetManager ( '' ) local_booru_manager . CheckFileAuthorised ( share_key , hash ) client_files_manager = HydrusGlobals . client_controller . GetClientFilesManager ( ) path = client_files_manager . GetFilePath ( hash ) response_context = HydrusServerResources . ResponseContext ( , path = path ) return response_context class HydrusResourceCommandBooruGallery ( HydrusResourceCommandBooru ) : def _threadDoGETJob ( self , request ) : share_key = request . hydrus_args [ '' ] local_booru_manager = HydrusGlobals . client_controller . GetManager ( '' ) local_booru_manager . CheckShareAuthorised ( share_key ) ( name , text , timeout , media_results ) = local_booru_manager . GetGalleryInfo ( share_key ) body = '''''' if name == '' : body += '''''' else : body += '''''' + name + '''''' body += '''''' ( thumbnail_width , thumbnail_height ) = HC . options [ '' ] body += '''''' + str ( thumbnail_width ) + '''''' + str ( thumbnail_height ) + '''''' body += '''''' body += '''''' + HydrusData . ConvertTimestampToPrettyExpires ( timeout ) + '''''' if name != '' : body += '''''' + name + '''''' if text != '' : newline = '''''' body += '''''' + text . replace ( os . linesep , newline ) . replace ( '' , newline ) + '''''' body += '''''' for media_result in media_results : hash = media_result . GetHash ( ) mime = media_result . GetMime ( ) body += '''''' + share_key . encode ( '' ) + '''''' + hash . encode ( '' ) + '''''' + share_key . encode ( '' ) + '''''' + hash . encode ( '' ) + '''''' body += '''''' response_context = HydrusServerResources . ResponseContext ( , mime = HC . TEXT_HTML , body = body ) return response_context class HydrusResourceCommandBooruPage ( HydrusResourceCommandBooru ) : def _threadDoGETJob ( self , request ) : share_key = request . hydrus_args [ '' ] hash = request . hydrus_args [ '' ] local_booru_manager = HydrusGlobals . client_controller . GetManager ( '' ) local_booru_manager . CheckFileAuthorised ( share_key , hash ) ( name , text , timeout , media_result ) = local_booru_manager . GetPageInfo ( share_key , hash ) body = '''''' if name == '' : body += '''''' else : body += '''''' + name + '''''' body += '''''' body += '''''' body += '''''' + HydrusData . ConvertTimestampToPrettyExpires ( timeout ) + '''''' if name != '' : body += '''''' + name + '''''' if text != '' : newline = '''''' body += '''''' + text . replace ( os . linesep , newline ) . replace ( '' , newline ) + '''''' body += '''''' mime = media_result . GetMime ( ) if mime in HC . IMAGES : ( width , height ) = media_result . GetResolution ( ) body += '''''' + str ( width ) + '''''' + str ( height ) + '''''' + share_key . encode ( '' ) + '''''' + hash . encode ( '' ) + '''''' elif mime in HC . VIDEO : ( width , height ) = media_result . GetResolution ( ) body += '''''' + str ( width ) + '''''' + str ( height ) + '''''' + share_key . encode ( '' ) + '''''' + hash . encode ( '' ) + '''''' + share_key . encode ( '' ) + '''''' + hash . encode ( '' ) + '''''' + HC . mime_string_lookup [ mime ] + '''''' elif mime == HC . APPLICATION_FLASH : ( width , height ) = media_result . GetResolution ( ) body += '''''' + str ( width ) + '''''' + str ( height ) + '''''' + share_key . encode ( '' ) + '''''' + hash . encode ( '' ) + '''''' + share_key . encode ( '' ) + '''''' + hash . encode ( '' ) + '''''' + HC . mime_string_lookup [ mime ] + '''''' else : body += '''''' + share_key . encode ( '' ) + '''''' + hash . encode ( '' ) + '''''' + HC . mime_string_lookup [ mime ] + '''''' body += '''''' response_context = HydrusServerResources . ResponseContext ( , mime = HC . TEXT_HTML , body = body ) return response_context class HydrusResourceCommandBooruThumbnail ( HydrusResourceCommandBooru ) : def _threadDoGETJob ( self , request ) : share_key = request . hydrus_args [ '' ] hash = request . hydrus_args [ '' ] local_booru_manager = HydrusGlobals . client_controller . GetManager ( '' ) local_booru_manager . CheckFileAuthorised ( share_key , hash ) media_result = local_booru_manager . GetMediaResult ( share_key , hash ) mime = media_result . GetMime ( ) if mime in HC . MIMES_WITH_THUMBNAILS : path = ClientFiles . GetThumbnailPath ( hash , full_size = False ) elif mime in HC . AUDIO : path = os . path . join ( HC . STATIC_DIR , '' ) elif mime == HC . APPLICATION_PDF : path = os . path . join ( HC . STATIC_DIR , '' ) else : path = os . path . join ( HC . STATIC_DIR , '' ) response_context = HydrusServerResources . ResponseContext ( , path = path ) return response_context class HydrusResourceCommandLocalFile ( HydrusServerResources . HydrusResourceCommand ) : def _threadDoGETJob ( self , request ) : hash = request . hydrus_args [ '' ] client_files_manager = HydrusGlobals . client_controller . GetClientFilesManager ( ) path = client_files_manager . GetFilePath ( hash ) ", "answer": "response_context = HydrusServerResources . ResponseContext ( , path = path )"}, {"prompt": " import logging from twisted . internet import reactor , defer from smpp . twisted . client import SMPPClientTransceiver , SMPPClientService from smpp . twisted . config import SMPPClientConfig class SMPP ( object ) : def __init__ ( self , config = None ) : if config is None : config = SMPPClientConfig ( host = '' , port = , username = '' , password = '' ) self . config = config @ defer . inlineCallbacks def run ( self ) : ", "answer": "try :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import unittest from ctypes import POINTER import comtypes from comtypes . client import CreateObject , GetModule GetModule ( '' ) from comtypes . gen . Accessibility import IAccessible class TestCase ( unittest . TestCase ) : def setUp ( self ) : self . ie = CreateObject ( '' ) def tearDown ( self ) : self . ie . Quit ( ) del self . ie def test ( self ) : ie = self . ie ie . navigate2 ( \"\" , ) sp = ie . Document . Body . QueryInterface ( comtypes . IServiceProvider ) ", "answer": "pacc = sp . QueryService ( IAccessible . _iid_ , IAccessible )"}, {"prompt": " import json from kraken import plugins from kraken_examples . bob_guide_rig import BobGuideRig from kraken . core . profiler import Profiler ", "answer": "from kraken . helpers . utility_methods import logHierarchy"}, {"prompt": " import __builtin__ import itertools def element_ancestry ( element ) : \"\"\"\"\"\" return itertools . chain ( ( element , ) , element . parents ) def search_ancestry ( element , predicate ) : \"\"\"\"\"\" for obj in element_ancestry ( element ) : try : ", "answer": "transform = predicate ( obj )"}, {"prompt": " import requests import collections import sys import time import json Entry = collections . namedtuple ( \"\" , \"\" ) ROW_TYPES = { } def row_type_for_columns ( name , column_names ) : column_names = tuple ( column_names ) row_type = ROW_TYPES . get ( ( name , column_names ) ) if row_type is None : row_type = collections . namedtuple ( name , column_names ) ", "answer": "ROW_TYPES [ ( name , column_names ) ] = row_type"}, {"prompt": " import dateutil . parser , datetime from bson . objectid import ObjectId from gluon . custom_import import track_changes from oauth import OAuth2 from oauth . storage import web2pyStorage as storage from oauth . exceptions import * track_changes ( True ) CODES = { '' : } MESSAGES = { '' : '' } def validate_access_token ( f ) : \"\"\"\"\"\" from oauth . storage import web2pyStorage as storage storage = storage ( ) storage . connect ( ) oauth = OAuth2 ( storage ) response . headers [ '' ] = json_headers ( ) response . view = json_service ( ) header = request . env [ '' ] token = oauth . validate_access_params ( request . get_vars , request . post_vars , header ) return f def parse_to_date ( default , arg ) : try : if default : return dateutil . parser . parse ( default ) if not arg else dateutil . parser . parse ( arg ) else : return None if not arg else dateutil . parser . parse ( arg ) except ValueError : return default def json_service ( ) : return '' def json_headers ( ) : return '' ", "answer": "def encode_model ( obj , recursive = False ) :"}, {"prompt": " class MyClass ( object ) : def __init__ ( self ) : ", "answer": "self . my_function ( )"}, {"prompt": " import os , time , sys , subprocess import git import utils , meta HIPPO_DIR = \"\" HIPPO_BASE = \"\" COMMANDS = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] class Hippo : \"\"\"\"\"\" def __init__ ( self , datadir , base ) : self . datadir , self . base = datadir , base self . gitdir = os . path . join ( self . datadir , \"\" ) self . manifest = os . path . join ( self . datadir , \"\" ) def repo ( self ) : \"\"\"\"\"\" return git . Repo ( self . gitdir ) def refresh_manifest ( self ) : r = self . repo ( ) paths = set ( ) for ( path , stage ) , entry in r . index . entries . iteritems ( ) : for i in utils . allpaths ( os . path . join ( self . base , path ) ) : paths . add ( i ) m = meta . Metadata ( ) data = m . make_manifest ( paths ) f = open ( self . manifest , \"\" ) f . write ( data ) f . close ( ) def apply_manifest ( self ) : data = open ( self . manifest ) . read ( ) m = meta . Metadata ( ) m . apply_manifest ( data ) def _git ( self ) : os . environ [ \"\" ] = self . base os . environ [ \"\" ] = os . path . join ( self . datadir , \"\" ) return git . Git ( self . base ) def init ( self , args ) : g = self . _git ( ) utils . touch ( self . manifest ) g . init ( ) g . add ( self . manifest ) def add ( self , args ) : g = self . _git ( ) g . add ( * args ) def commit ( self , args ) : self . refresh_manifest ( ) os . environ [ \"\" ] = self . base os . environ [ \"\" ] = os . path . join ( self . datadir , \"\" ) tail = \"\" if args : tail = \"\" + \"\" . join ( args ) p = subprocess . Popen ( \"\" + tail , shell = True ) p . wait ( ) def _cmd ( self , cmd , args ) : g = self . _git ( ) print getattr ( g , cmd ) ( * args ) , def refresh ( self , args ) : self . refresh_manifest ( ) def status ( self , args ) : self . refresh_manifest ( ) ", "answer": "args . append ( \"\" )"}, {"prompt": " \"\"\"\"\"\" import io import sys PY3 = sys . version_info [ ] == if PY3 : StringIO = io . StringIO BytesIO = io . BytesIO import codecs open_with_encoding = codecs . open range = range ifilter = filter raw_input = input import configparser CONFIGPARSER_BOOLEAN_STATES = configparser . ConfigParser . BOOLEAN_STATES else : import __builtin__ import cStringIO StringIO = BytesIO = cStringIO . StringIO open_with_encoding = io . open range = xrange from itertools import ifilter raw_input = raw_input import ConfigParser as configparser CONFIGPARSER_BOOLEAN_STATES = configparser . ConfigParser . _boolean_states def EncodeAndWriteToStdout ( s , encoding ) : \"\"\"\"\"\" if PY3 : sys . stdout . buffer . write ( codecs . encode ( s , encoding ) ) else : sys . stdout . write ( s . encode ( encoding ) ) def unicode ( s ) : \"\"\"\"\"\" if PY3 : return s else : ", "answer": "return __builtin__ . unicode ( s , '' )"}, {"prompt": " from driver_base import DriverBase import socket import sys import time import os os . sys . path . insert ( , os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) ) import log class CMDTYPE : SETUP_DATA = PIXEL_DATA = BRIGHTNESS = class RETURN_CODES : SUCCESS = ERROR = ERROR_SIZE = ERROR_UNSUPPORTED = class DriverNetwork ( DriverBase ) : \"\"\"\"\"\" def __init__ ( self , num = , width = , height = , host = \"\" , port = ) : super ( DriverNetwork , self ) . __init__ ( num , width , height ) self . _host = host self . _port = port def _generateHeader ( self , cmd , size ) : packet = bytearray ( ) packet . append ( cmd ) packet . append ( size & ) packet . append ( size >> ) return packet def _connect ( self ) : try : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s . connect ( ( self . _host , self . _port ) ) return s except socket . gaierror : error = \"\" . format ( self . _host ) log . error ( error ) raise IOError ( error ) def update ( self , data ) : try : s = self . _connect ( ) count = self . bufByteCount packet = self . _generateHeader ( CMDTYPE . PIXEL_DATA , count ) packet . extend ( data ) s . sendall ( packet ) resp = ord ( s . recv ( ) ) s . close ( ) if resp != RETURN_CODES . SUCCESS : log . warning ( \"\" , resp ) except Exception as e : log . exception ( e ) error = \"\" log . error ( error ) raise IOError ( error ) def setMasterBrightness ( self , brightness ) : packet = self . _generateHeader ( CMDTYPE . BRIGHTNESS , ) packet . append ( brightness ) s = self . _connect ( ) s . sendall ( packet ) resp = ord ( s . recv ( ) ) if resp != RETURN_CODES . SUCCESS : return False else : return True MANIFEST = [ { \"\" : \"\" , \"\" : DriverNetwork , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : [ { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : , \"\" : , \"\" : \"\" } , { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : , \"\" : , \"\" : \"\" } , { ", "answer": "\"\" : \"\" ,"}, {"prompt": " from model import * from data_api import * import sys X = prepare_experiment_data ( dataset = \"\" , CV = ) params = cPickle . load ( open ( sys . argv [ ] , \"\" ) ) R = range ( ) ", "answer": "networks = createNetworks ( entity_matrix = X [ \"\" ] , embedding_matrix = params [ \"\" ] , k = , only_metric = False )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Tangible ( )"}, {"prompt": " '''''' import rpyc import logging from sqlalchemy import Column , ForeignKey from sqlalchemy . orm import synonym , relationship from sqlalchemy . types import Unicode , Boolean , Integer from models import dbsession , algorithm_association_table , plugin_association_table from models . BaseObject import BaseObject from models . Algorithm import Algorithm from rpyc . utils . ssh import SshContext from tempfile import NamedTemporaryFile class WeaponSystem ( BaseObject ) : '''''' name = Column ( Unicode ( ) , unique = True , nullable = False ) initialized = Column ( Boolean , default = False , nullable = False ) ssh_user = Column ( Unicode ( ) , nullable = False ) ssh_key = Column ( Unicode ( ) , nullable = False ) ip_address = Column ( Unicode ( ) , unique = True , nullable = False ) ssh_port = Column ( Integer , default = , nullable = False ) service_port = Column ( Integer , default = , nullable = False ) cpu_count = Column ( Integer , default = ) gpu_count = Column ( Integer , default = ) algorithms = relationship ( \"\" , secondary = algorithm_association_table , backref = \"\" ) plugins = relationship ( \"\" , secondary = plugin_association_table , backref = \"\" ) @ classmethod def by_id ( cls , weapon_id ) : '''''' return dbsession . query ( cls ) . filter_by ( id = weapon_id ) . first ( ) @ classmethod def by_uuid ( cls , weapon_uuid ) : '''''' return dbsession . query ( cls ) . filter_by ( uuid = unicode ( weapon_uuid ) ) . first ( ) @ classmethod def get_all ( cls ) : '''''' return dbsession . query ( cls ) . all ( ) @ classmethod def get_uninitialized ( cls ) : '''''' return dbsession . query ( cls ) . filter_by ( initialized = False ) . all ( ) @ classmethod def by_name ( cls , weapon_name ) : '''''' return dbsession . query ( cls ) . filter_by ( name = unicode ( weapon_name ) ) . first ( ) @ classmethod def by_ip_address ( cls , weapon_ip_address ) : '''''' return dbsession . query ( cls ) . filter_by ( ip_address = unicode ( weapon_ip_address ) ) . first ( ) @ classmethod def all_idle ( cls ) : '''''' online_systems = filter ( lambda weapon_system : weapon_system . is_online ( ) , cls . get_all ( ) ) return filter ( lambda weapon_system : not weapon_system . is_busy ( ) , online_systems ) @ classmethod def system_ready ( cls , algo ) : '''''' return filter ( lambda weapon_system : algo in weapon_system . algorithms , cls . all_idle ( ) ) def get_rpc_connection ( self , * args ) : '''''' logging . info ( \"\" ) return self . __connect__ ( ) def is_online ( self ) : ", "answer": "''''''"}, {"prompt": " { '' : array ( [ ( '' , , ) , ( '' , , ) ] , dtype = [ ( '' , '' ) , ( '' , float ) , ( '' , float ) ] ) , '' : { '' : '' , '' : '' , '' : { '' : ( '' , float , float ) , '' : ( '' , '' , '' ) } , '' : } ", "answer": "} "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " \"\"\"\"\"\" from django . db import models class Category ( models . Model ) : ", "answer": "name = models . CharField ( )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Building ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " from django . conf import settings from django . utils . translation import ugettext_lazy as _lazy from django . core . exceptions import ValidationError from rest_framework import fields from olympia . amo . utils import to_language class TranslationSerializerField ( fields . Field ) : \"\"\"\"\"\" default_error_messages = { '' : _lazy ( u'' '' ) , '' : _lazy ( u'' ) } def __init__ ( self , * args , ** kwargs ) : self . min_length = kwargs . pop ( '' , None ) super ( TranslationSerializerField , self ) . __init__ ( * args , ** kwargs ) def fetch_all_translations ( self , obj , source , field ) : translations = field . __class__ . objects . filter ( id = field . id , localized_string__isnull = False ) return dict ( ( to_language ( trans . locale ) , unicode ( trans ) ) for trans in translations ) if translations else None def fetch_single_translation ( self , obj , source , field , requested_language ) : return unicode ( field ) if field else None def get_attribute ( self , obj ) : source = self . source or self . field_name field = fields . get_attribute ( obj , source . split ( '' ) ) if not field : ", "answer": "return None"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) ", "answer": "result . template = \"\""}, {"prompt": " from pyvi import window from pyvi . modes import normal class Editor ( object ) : _command = None active_tab = None def __init__ ( self , tabs = None , config = None , normal = normal ) : self . config = config self . mode = self . normal = normal self . count = None if tabs is None : tabs = self . tabs = [ window . Tab ( self ) ] else : tabs = self . tabs = list ( tabs ) ", "answer": "if tabs :"}, {"prompt": " import os ", "answer": "deltasigma_theme_path = os . path . split ( os . path . split ( __file__ ) [ ] ) [ ] "}, {"prompt": " import re import logging from functools import wraps from inspect import getargspec from flask . wrappers import Response from flask import current_app , request , jsonify from flask_jsonrpc . site import jsonrpc_site from flask_jsonrpc . _compat import ( b , u , text_type , string_types , OrderedDict , NativeStringIO ) from flask_jsonrpc . types import ( Object , Number , Boolean , String , Array , Nil , Any , Type ) from flask_jsonrpc . helpers import ( make_response , jsonify_status_code , extract_raw_data_request , authenticate ) from flask_jsonrpc . exceptions import ( Error , ParseError , InvalidRequestError , MethodNotFoundError , InvalidParamsError , ServerError , RequestPostError , InvalidCredentialsError , OtherError ) default_site = jsonrpc_site KWARG_RE = re . compile ( r'' ) SIG_RE = re . compile ( r'' r'' ) class JSONRPCTypeCheckingUnavailable ( Exception ) : pass def _type_checking_available ( sig = '' , validate = False ) : if not hasattr ( type , '' ) and validate : raise JSONRPCTypeCheckingUnavailable ( '' '' '' . format ( sig ) ) def _validate_arg ( value , expected ) : \"\"\"\"\"\" if type ( value ) == expected : return True return False def _eval_arg_type ( arg_type , T = Any , arg = None , sig = None ) : \"\"\"\"\"\" try : T = eval ( arg_type ) except Exception as e : raise ValueError ( '' . format ( arg_type , arg , sig , text_type ( e ) ) ) else : if type ( T ) not in ( type , Type ) : raise TypeError ( '' . format ( repr ( T ) , arg , sig ) ) return T def _parse_sig ( sig , arg_names , validate = False ) : \"\"\"\"\"\" d = SIG_RE . match ( sig ) if not d : raise ValueError ( '' . format ( sig ) ) d = d . groupdict ( ) ret = [ ( n , Any ) for n in arg_names ] if text_type ( '' ) in d and type ( d [ '' ] ) in string_types and d [ '' ] . strip ( ) : for i , arg in enumerate ( d [ '' ] . strip ( ) . split ( '' ) ) : _type_checking_available ( sig , validate ) if text_type ( '' ) in arg : if not type ( ret ) is OrderedDict : ret = OrderedDict ( ret ) dk = KWARG_RE . match ( arg ) if not dk : raise ValueError ( '' . format ( arg , sig ) ) dk = dk . groupdict ( ) if not sum ( [ ( k in dk and type ( dk [ k ] ) in string_types and bool ( dk [ k ] . strip ( ) ) ) for k in ( '' , '' ) ] ) : raise ValueError ( '' . format ( arg , sig ) ) ret [ dk [ '' ] ] = _eval_arg_type ( dk [ '' ] , None , arg , sig ) else : if type ( ret ) is OrderedDict : raise ValueError ( '' '' . format ( sig ) ) if len ( ret ) < i + : ret . append ( ( text_type ( i ) , _eval_arg_type ( arg , None , arg , sig ) ) ) else : ", "answer": "ret [ i ] = ( ret [ i ] [ ] , _eval_arg_type ( arg , None , arg , sig ) )"}, {"prompt": " \"\"\"\"\"\" from numpy import logical_xor , sum import numpy from numpy . random import randn from kameleon_mcmc . distribution . Distribution import Distribution from kameleon_mcmc . distribution . proposals . DiscreteRandomWalkProposal import DiscreteRandomWalkProposal from kameleon_mcmc . kernel . Kernel import Kernel from kameleon_mcmc . mcmc . samplers . MCMCSampler import MCMCSampler class DiscreteKameleon ( MCMCSampler ) : \"\"\"\"\"\" def __init__ ( self , distribution , kernel , Z , threshold , spread ) : if not isinstance ( distribution , Distribution ) : raise TypeError ( \"\" ) if not isinstance ( kernel , Kernel ) : raise TypeError ( \"\" ) if not type ( Z ) is numpy . ndarray : raise TypeError ( \"\" ) if not len ( Z . shape ) == : raise ValueError ( \"\" ) if not Z . shape [ ] == distribution . dimension : raise ValueError ( \"\" ) if not Z . shape [ ] > : raise ValueError ( \"\" ) if not type ( threshold ) is float : raise TypeError ( \"\" ) if not type ( spread ) is float : raise TypeError ( \"\" ) if not ( spread > and spread < ) : raise ValueError ( \"\" ) MCMCSampler . __init__ ( self , distribution ) self . kernel = kernel self . Z = Z self . threshold = threshold self . spread = spread ", "answer": "def __str__ ( self ) :"}, {"prompt": " from django . conf . urls . defaults import patterns , url import views ", "answer": "urlpatterns = patterns ( '' ,"}, {"prompt": " \"\"\"\"\"\" import logging , time from django . core . management . base import BaseCommand from ... charge import ( recognize_income , extend_subscriptions , create_charges_for_balance , complete_charges ) from ... utils import datetime_or_now LOGGER = logging . getLogger ( __name__ ) class Command ( BaseCommand ) : help = \"\"\"\"\"\" def add_arguments ( self , parser ) : parser . add_argument ( '' , action = '' , dest = '' , default = False , help = '' ) ", "answer": "parser . add_argument ( '' , action = '' ,"}, {"prompt": " import datetime from django . db . models . aggregates import refs_aggregate from django . db . models . constants import LOOKUP_SEP from django . utils import tree class ExpressionNode ( tree . Node ) : \"\"\"\"\"\" ADD = '' SUB = '' MUL = '' DIV = '' MOD = '' BITAND = '' BITOR = '' def __init__ ( self , children = None , connector = None , negated = False ) : if children is not None and len ( children ) > and connector is None : raise TypeError ( '' ) super ( ExpressionNode , self ) . __init__ ( children , connector , negated ) def _combine ( self , other , connector , reversed , node = None ) : if isinstance ( other , datetime . timedelta ) : return DateModifierNode ( [ self , other ] , connector ) if reversed : obj = ExpressionNode ( [ other ] , connector ) obj . add ( node or self , connector ) else : obj = node or ExpressionNode ( [ self ] , connector ) obj . add ( other , connector ) return obj def contains_aggregate ( self , existing_aggregates ) : if self . children : return any ( child . contains_aggregate ( existing_aggregates ) for child in self . children if hasattr ( child , '' ) ) else : return refs_aggregate ( self . name . split ( LOOKUP_SEP ) , existing_aggregates ) def prepare_database_save ( self , unused ) : return self def prepare ( self , evaluator , query , allow_joins ) : return evaluator . prepare_node ( self , query , allow_joins ) def evaluate ( self , evaluator , qn , connection ) : return evaluator . evaluate_node ( self , qn , connection ) def __add__ ( self , other ) : return self . _combine ( other , self . ADD , False ) def __sub__ ( self , other ) : return self . _combine ( other , self . SUB , False ) def __mul__ ( self , other ) : return self . _combine ( other , self . MUL , False ) def __truediv__ ( self , other ) : return self . _combine ( other , self . DIV , False ) def __div__ ( self , other ) : return type ( self ) . __truediv__ ( self , other ) def __mod__ ( self , other ) : return self . _combine ( other , self . MOD , False ) def __and__ ( self , other ) : raise NotImplementedError ( \"\" ) def bitand ( self , other ) : return self . _combine ( other , self . BITAND , False ) ", "answer": "def __or__ ( self , other ) :"}, {"prompt": " import PyV8 import sys from dnlib . jsapi import RootAPI import os import readline histfile = os . path . join ( os . path . expanduser ( \"\" ) , \"\" ) try : readline . read_history_file ( histfile ) except IOError : pass ", "answer": "import atexit"}, {"prompt": " from __future__ import absolute_import __all__ = [ '' ] from flask import current_app from freight import http from freight . exceptions import CheckFailed , CheckPending from . base import Check ERR_CHECK = '' ERR_MISSING_CONTEXT = '' class GitHubContextCheck ( Check ) : def get_options ( self ) : ", "answer": "return {"}, {"prompt": " from nodeconductor . quotas import views def register_in ( router ) : ", "answer": "router . register ( r'' , views . QuotaViewSet ) "}, {"prompt": " from pyswagger import SwaggerApp from pyswagger . getter import UrlGetter from . utils import get_test_data_folder import unittest import os class GetterTestCase ( unittest . TestCase ) : \"\"\"\"\"\" def test_random_name_v2_0 ( self ) : \"\"\"\"\"\" path = get_test_data_folder ( version = '' , which = '' ) path = os . path . join ( path , '' ) app = SwaggerApp . create ( path ) def test_random_name_v1_2 ( self ) : \"\"\"\"\"\" path = get_test_data_folder ( version = '' , which = '' ) path = os . path . join ( path , '' ) app = SwaggerApp . create ( path ) def test_local_path_with_custome_getter ( self ) : \"\"\"\"\"\" cls = UrlGetter path = get_test_data_folder ( version = '' , which = '' ) ", "answer": "path = os . path . join ( path , '' )"}, {"prompt": " from flask import Blueprint , request from apikit import jsonify from apikit import get_limit , get_offset from aleph import authz from aleph . core import url_for from aleph . model import Alert from aleph . views . cache import enable_cache from aleph . views . util import get_document from aleph . search import documents_query , execute_documents_query from aleph . search import records_query , execute_records_query from aleph . search . util import next_params blueprint = Blueprint ( '' , __name__ ) @ blueprint . route ( '' ) def query ( ) : creds = authz . collections ( authz . READ ) , authz . sources ( authz . READ ) enable_cache ( vary_user = True , vary = creds ) query = documents_query ( request . args ) query [ '' ] = get_limit ( default = ) query [ '' ] = get_offset ( ) result = execute_documents_query ( request . args , query ) result [ '' ] = None if authz . logged_in ( ) : result [ '' ] = Alert . exists ( request . args , request . auth_role ) params = next_params ( request . args , result ) if params is not None : result [ '' ] = url_for ( '' , ** params ) ", "answer": "return jsonify ( result )"}, {"prompt": " try : from django . conf . urls import patterns , include , handler500 , url except ImportError : from django . conf . urls . defaults import patterns , include , handler500 , url ", "answer": "from django . conf import settings"}, {"prompt": " from django . conf . urls . defaults import * from django . contrib . comments . urls import urlpatterns urlpatterns += patterns ( '' , ", "answer": "url ( r'' ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) ", "answer": "result . template = \"\""}, {"prompt": " dict_of = lambda o : { k : getattr ( o , k ) for k in dir ( o ) if '' not in k and not callable ( getattr ( o , k ) ) } from django . db import connections def fetch ( query , params = [ ] , db = '' ) : cursor = connections [ db ] . cursor ( ) ", "answer": "cursor . execute ( query , params )"}, {"prompt": " import numpy as np import theano . tensor as T from mozi . datasets . voc import VOC from mozi . model import Sequential from mozi . layers . alexnet import Alexnet from mozi . log import Log from mozi . train_object import TrainObject from mozi . cost import error , entropy from mozi . learning_method import SGD from mozi . env import setenv import os import theano def train ( ) : ", "answer": "data = VOC ( batch_size = , train_valid_test_ratio = [ , , ] )"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os import subprocess from pants . base . exceptions import TaskError from pants . contrib . go . tasks . go_workspace_task import GoWorkspaceTask class GoFmt ( GoWorkspaceTask ) : \"\"\"\"\"\" @ classmethod def register_options ( cls , register ) : super ( GoFmt , cls ) . register_options ( register ) register ( '' , type = bool , fingerprint = True , help = '' ) _GO_SOURCE_EXTENSION = '' def _is_checked ( self , target ) : return target . has_sources ( self . _GO_SOURCE_EXTENSION ) and not target . is_synthetic def execute ( self ) : if self . get_options ( ) . skip : return targets = self . context . targets ( self . _is_checked ) with self . invalidated ( targets ) as invalidation_check : invalid_targets = [ vt . target for vt in invalidation_check . invalid_vts ] sources = self . calculate_sources ( invalid_targets ) if sources : args = [ os . path . join ( self . go_dist . goroot , '' , '' ) , '' ] + list ( sources ) try : ", "answer": "output = subprocess . check_output ( args )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from werkzeug . contrib . cache import SimpleCache from . cache import ImageCache class ImageSimpleCache ( ImageCache ) : \"\"\"\"\"\" timeout = * * * def __init__ ( self ) : \"\"\"\"\"\" super ( ImageSimpleCache , self ) . __init__ ( ) self . cache = SimpleCache ( ) def get ( self , key ) : \"\"\"\"\"\" ", "answer": "return self . cache . get ( key )"}, {"prompt": " import cv2 from webcam_gui import webcam_gui def imgproc ( frame ) : gray = cv2 . cvtColor ( frame , cv2 . COLOR_BGR2GRAY ) cv2 . imshow ( '' , gray ) blur = cv2 . blur ( gray , ( , ) ) edge = cv2 . Canny ( blur , , ) edge = cv2 . blur ( edge , ( , ) ) ", "answer": "cv2 . imshow ( '' , edge )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import sys import time STREAM = sys . stderr BAR_TEMPLATE = '' MILL_TEMPLATE = '' DOTS_CHAR = '' BAR_FILLED_CHAR = '' BAR_EMPTY_CHAR = '' MILL_CHARS = [ '' , '' , '' , '' ] ETA_INTERVAL = ETA_SMA_WINDOW = def bar ( it , label = '' , width = , hide = False , empty_char = BAR_EMPTY_CHAR , filled_char = BAR_FILLED_CHAR ) : \"\"\"\"\"\" def _show ( _i ) : if ( time . time ( ) - bar . etadelta ) > ETA_INTERVAL : bar . etadelta = time . time ( ) bar . ittimes = bar . ittimes [ - ETA_SMA_WINDOW : ] + [ - ( bar . start - time . time ( ) ) / ( _i + ) ] bar . eta = sum ( bar . ittimes ) / float ( len ( bar . ittimes ) ) * ( count - _i ) bar . etadisp = time . strftime ( '' , time . gmtime ( bar . eta ) ) x = int ( width * _i / count ) if not hide : STREAM . write ( BAR_TEMPLATE % ( label , filled_char * x , empty_char * ( width - x ) , _i , count , bar . etadisp ) ) STREAM . flush ( ) count = len ( it ) bar . start = time . time ( ) bar . ittimes = [ ] bar . eta = bar . etadelta = time . time ( ) bar . etadisp = time . strftime ( '' , time . gmtime ( bar . eta ) ) if count : _show ( ) for i , item in enumerate ( it ) : yield item _show ( i + ) if not hide : STREAM . write ( '' ) STREAM . flush ( ) def dots ( it , label = '' , hide = False ) : \"\"\"\"\"\" count = if not hide : STREAM . write ( label ) for item in it : if not hide : STREAM . write ( DOTS_CHAR ) sys . stderr . flush ( ) count += yield item STREAM . write ( '' ) STREAM . flush ( ) def mill ( it , label = '' , hide = False , ) : \"\"\"\"\"\" ", "answer": "def _mill_char ( _i ) :"}, {"prompt": " '''''' __docformat__ = '' __version__ = '' import unittest from pyglet import window class EVENT_MOUSE_ENTER_LEAVE ( unittest . TestCase ) : ", "answer": "def on_mouse_enter ( self , x , y ) :"}, {"prompt": " \"\"\"\"\"\" ", "answer": "import numpy as np"}, {"prompt": " from django . contrib import admin from django . conf . urls . defaults import patterns , url from django . utils . translation import ugettext as _ from django . http import HttpResponseRedirect from django . shortcuts import render_to_response from django . template import RequestContext from wurfl import update from wurfl . models import Update , Patch import operator class UpdateAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' , '' , '' , '' , '' , ) list_filter = ( '' , ) ordering = ( '' , ) def has_add_permission ( self , request ) : return False def update_hybrid_view ( self , request ) : updates = update . hybrid ( ) if any ( map ( operator . attrgetter ( '' ) , updates ) ) : message = _ ( '' ) else : message = _ ( '' ) request . user . message_set . create ( message = message ) return HttpResponseRedirect ( request . path + \"\" ) ", "answer": "def update_wurfl_view ( self , request ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division , print_function from datetime import datetime try : import unittest2 as unittest except ImportError : import unittest import numpy as np import quantities as pq try : from IPython . lib . pretty import pretty except ImportError as err : HAVE_IPYTHON = False else : HAVE_IPYTHON = True from neo . core . segment import Segment from neo . core import ( AnalogSignalArray , Block , Epoch , EpochArray , RecordingChannelGroup , SpikeTrain , Unit ) from neo . core . container import filterdata from neo . test . tools import ( assert_neo_object_is_compliant , assert_same_sub_schema ) from neo . test . generate_datasets import ( fake_neo , get_fake_value , get_fake_values , get_annotations , clone_object , TEST_ANNOTATIONS ) class Test__generate_datasets ( unittest . TestCase ) : def setUp ( self ) : np . random . seed ( ) self . annotations = dict ( [ ( str ( x ) , TEST_ANNOTATIONS [ x ] ) for x in range ( len ( TEST_ANNOTATIONS ) ) ] ) def test__get_fake_values ( self ) : self . annotations [ '' ] = file_datetime = get_fake_value ( '' , datetime , seed = ) rec_datetime = get_fake_value ( '' , datetime , seed = ) index = get_fake_value ( '' , int , seed = ) name = get_fake_value ( '' , str , seed = , obj = Segment ) description = get_fake_value ( '' , str , seed = , obj = '' ) file_origin = get_fake_value ( '' , str ) attrs1 = { '' : file_datetime , '' : rec_datetime , '' : index , '' : name , '' : description , '' : file_origin } attrs2 = attrs1 . copy ( ) attrs2 . update ( self . annotations ) res11 = get_fake_values ( Segment , annotate = False , seed = ) res12 = get_fake_values ( '' , annotate = False , seed = ) res21 = get_fake_values ( Segment , annotate = True , seed = ) res22 = get_fake_values ( '' , annotate = True , seed = ) self . assertEqual ( res11 , attrs1 ) self . assertEqual ( res12 , attrs1 ) self . assertEqual ( res21 , attrs2 ) self . assertEqual ( res22 , attrs2 ) def test__fake_neo__cascade ( self ) : self . annotations [ '' ] = None obj_type = Segment cascade = True res = fake_neo ( obj_type = obj_type , cascade = cascade ) self . assertTrue ( isinstance ( res , Segment ) ) assert_neo_object_is_compliant ( res ) self . assertEqual ( res . annotations , self . annotations ) self . assertEqual ( len ( res . analogsignalarrays ) , ) self . assertEqual ( len ( res . analogsignals ) , ) self . assertEqual ( len ( res . irregularlysampledsignals ) , ) self . assertEqual ( len ( res . spiketrains ) , ) self . assertEqual ( len ( res . spikes ) , ) self . assertEqual ( len ( res . events ) , ) self . assertEqual ( len ( res . epochs ) , ) self . assertEqual ( len ( res . eventarrays ) , ) self . assertEqual ( len ( res . epocharrays ) , ) for child in res . children : del child . annotations [ '' ] del child . annotations [ '' ] self . assertEqual ( res . analogsignalarrays [ ] . annotations , self . annotations ) self . assertEqual ( res . analogsignals [ ] . annotations , self . annotations ) self . assertEqual ( res . irregularlysampledsignals [ ] . annotations , self . annotations ) self . assertEqual ( res . spiketrains [ ] . annotations , self . annotations ) self . assertEqual ( res . spikes [ ] . annotations , self . annotations ) self . assertEqual ( res . events [ ] . annotations , self . annotations ) self . assertEqual ( res . epochs [ ] . annotations , self . annotations ) self . assertEqual ( res . eventarrays [ ] . annotations , self . annotations ) self . assertEqual ( res . epocharrays [ ] . annotations , self . annotations ) def test__fake_neo__nocascade ( self ) : self . annotations [ '' ] = None obj_type = '' cascade = False res = fake_neo ( obj_type = obj_type , cascade = cascade ) self . assertTrue ( isinstance ( res , Segment ) ) assert_neo_object_is_compliant ( res ) self . assertEqual ( res . annotations , self . annotations ) self . assertEqual ( len ( res . analogsignalarrays ) , ) self . assertEqual ( len ( res . analogsignals ) , ) self . assertEqual ( len ( res . irregularlysampledsignals ) , ) self . assertEqual ( len ( res . spiketrains ) , ) self . assertEqual ( len ( res . spikes ) , ) self . assertEqual ( len ( res . events ) , ) self . assertEqual ( len ( res . epochs ) , ) self . assertEqual ( len ( res . eventarrays ) , ) self . assertEqual ( len ( res . epocharrays ) , ) class TestSegment ( unittest . TestCase ) : def setUp ( self ) : self . nchildren = blk = fake_neo ( Block , seed = , n = self . nchildren ) self . unit1 , self . unit2 , self . unit3 , self . unit4 = blk . list_units self . seg1 , self . seg2 = blk . segments self . targobj = self . seg1 self . seed1 = self . seg1 . annotations [ '' ] self . seed2 = self . seg2 . annotations [ '' ] del self . seg1 . annotations [ '' ] del self . seg2 . annotations [ '' ] del self . seg1 . annotations [ '' ] del self . seg2 . annotations [ '' ] self . sigs1 = self . seg1 . analogsignals self . sigs2 = self . seg2 . analogsignals self . sigarrs1 = self . seg1 . analogsignalarrays self . sigarrs2 = self . seg2 . analogsignalarrays self . irsigs1 = self . seg1 . irregularlysampledsignals self . irsigs2 = self . seg2 . irregularlysampledsignals self . spikes1 = self . seg1 . spikes self . spikes2 = self . seg2 . spikes self . trains1 = self . seg1 . spiketrains self . trains2 = self . seg2 . spiketrains self . epcs1 = self . seg1 . epochs self . epcs2 = self . seg2 . epochs self . epcas1 = self . seg1 . epocharrays self . epcas2 = self . seg2 . epocharrays self . evts1 = self . seg1 . events self . evts2 = self . seg2 . events self . evtas1 = self . seg1 . eventarrays self . evtas2 = self . seg2 . eventarrays self . sigs1a = clone_object ( self . sigs1 ) self . sigarrs1a = clone_object ( self . sigarrs1 , n = ) self . irsigs1a = clone_object ( self . irsigs1 ) self . spikes1a = clone_object ( self . spikes1 ) self . trains1a = clone_object ( self . trains1 ) self . epcs1a = clone_object ( self . epcs1 ) self . epcas1a = clone_object ( self . epcas1 ) self . evts1a = clone_object ( self . evts1 ) self . evtas1a = clone_object ( self . evtas1 ) for obj , obja in zip ( self . sigs1 + self . sigarrs1 , self . sigs1a + self . sigarrs1a ) : obja . channel_index = obj . channel_index def test_init ( self ) : seg = Segment ( name = '' , index = ) assert_neo_object_is_compliant ( seg ) self . assertEqual ( seg . name , '' ) self . assertEqual ( seg . file_origin , None ) self . assertEqual ( seg . index , ) def check_creation ( self , seg ) : assert_neo_object_is_compliant ( seg ) seed = seg . annotations [ '' ] targ0 = get_fake_value ( '' , datetime , seed = seed + ) self . assertEqual ( seg . file_datetime , targ0 ) targ1 = get_fake_value ( '' , datetime , seed = seed + ) self . assertEqual ( seg . rec_datetime , targ1 ) targ2 = get_fake_value ( '' , int , seed = seed + ) self . assertEqual ( seg . index , targ2 ) targ3 = get_fake_value ( '' , str , seed = seed + , obj = Segment ) self . assertEqual ( seg . name , targ3 ) targ4 = get_fake_value ( '' , str , seed = seed + , obj = Segment ) self . assertEqual ( seg . description , targ4 ) targ5 = get_fake_value ( '' , str ) self . assertEqual ( seg . file_origin , targ5 ) targ6 = get_annotations ( ) targ6 [ '' ] = seed self . assertEqual ( seg . annotations , targ6 ) self . assertTrue ( hasattr ( seg , '' ) ) self . assertTrue ( hasattr ( seg , '' ) ) self . assertTrue ( hasattr ( seg , '' ) ) self . assertTrue ( hasattr ( seg , '' ) ) self . assertTrue ( hasattr ( seg , '' ) ) self . assertTrue ( hasattr ( seg , '' ) ) self . assertTrue ( hasattr ( seg , '' ) ) self . assertTrue ( hasattr ( seg , '' ) ) self . assertTrue ( hasattr ( seg , '' ) ) self . assertEqual ( len ( seg . analogsignals ) , self . nchildren ** ) self . assertEqual ( len ( seg . analogsignalarrays ) , self . nchildren ) self . assertEqual ( len ( seg . irregularlysampledsignals ) , self . nchildren ** ) self . assertEqual ( len ( seg . epochs ) , self . nchildren ) self . assertEqual ( len ( seg . epocharrays ) , self . nchildren ) self . assertEqual ( len ( seg . events ) , self . nchildren ) self . assertEqual ( len ( seg . eventarrays ) , self . nchildren ) self . assertEqual ( len ( seg . spikes ) , self . nchildren ** ) self . assertEqual ( len ( seg . spiketrains ) , self . nchildren ** ) def test__creation ( self ) : self . check_creation ( self . seg1 ) self . check_creation ( self . seg2 ) def test__merge ( self ) : seg1a = fake_neo ( Block , seed = self . seed1 , n = self . nchildren ) . segments [ ] assert_same_sub_schema ( self . seg1 , seg1a ) seg1a . spikes . append ( self . spikes2 [ ] ) seg1a . epocharrays . append ( self . epcas2 [ ] ) seg1a . annotate ( seed = self . seed2 ) seg1a . merge ( self . seg2 ) self . check_creation ( self . seg2 ) assert_same_sub_schema ( self . sigs1a + self . sigs2 , seg1a . analogsignals ) assert_same_sub_schema ( self . sigarrs1a + self . sigarrs2 , seg1a . analogsignalarrays ) assert_same_sub_schema ( self . irsigs1a + self . irsigs2 , seg1a . irregularlysampledsignals ) assert_same_sub_schema ( self . epcs1 + self . epcs2 , seg1a . epochs ) assert_same_sub_schema ( self . epcas1 + self . epcas2 , seg1a . epocharrays ) assert_same_sub_schema ( self . evts1 + self . evts2 , seg1a . events ) assert_same_sub_schema ( self . evtas1 + self . evtas2 , seg1a . eventarrays ) assert_same_sub_schema ( self . spikes1 + self . spikes2 , seg1a . spikes ) assert_same_sub_schema ( self . trains1 + self . trains2 , seg1a . spiketrains ) def test__children ( self ) : blk = Block ( name = '' ) blk . segments = [ self . seg1 ] blk . create_many_to_one_relationship ( force = True ) assert_neo_object_is_compliant ( self . seg1 ) assert_neo_object_is_compliant ( blk ) childobjs = ( '' , '' , '' , '' , '' , '' , '' , '' , '' ) childconts = ( '' , '' , '' , '' , '' , '' , '' , '' , '' ) self . assertEqual ( self . seg1 . _container_child_objects , ( ) ) self . assertEqual ( self . seg1 . _data_child_objects , childobjs ) self . assertEqual ( self . seg1 . _single_parent_objects , ( '' , ) ) self . assertEqual ( self . seg1 . _multi_child_objects , ( ) ) self . assertEqual ( self . seg1 . _multi_parent_objects , ( ) ) self . assertEqual ( self . seg1 . _child_properties , ( ) ) self . assertEqual ( self . seg1 . _single_child_objects , childobjs ) self . assertEqual ( self . seg1 . _container_child_containers , ( ) ) self . assertEqual ( self . seg1 . _data_child_containers , childconts ) self . assertEqual ( self . seg1 . _single_child_containers , childconts ) self . assertEqual ( self . seg1 . _single_parent_containers , ( '' , ) ) self . assertEqual ( self . seg1 . _multi_child_containers , ( ) ) self . assertEqual ( self . seg1 . _multi_parent_containers , ( ) ) self . assertEqual ( self . seg1 . _child_objects , childobjs ) self . assertEqual ( self . seg1 . _child_containers , childconts ) self . assertEqual ( self . seg1 . _parent_objects , ( '' , ) ) self . assertEqual ( self . seg1 . _parent_containers , ( '' , ) ) totchildren = ( self . nchildren * * + self . nchildren + * ( self . nchildren ** ) + * ( self . nchildren ** ) ) self . assertEqual ( len ( self . seg1 . _single_children ) , totchildren ) self . assertEqual ( len ( self . seg1 . data_children ) , totchildren ) self . assertEqual ( len ( self . seg1 . children ) , totchildren ) self . assertEqual ( len ( self . seg1 . data_children_recur ) , totchildren ) self . assertEqual ( len ( self . seg1 . children_recur ) , totchildren ) self . assertEqual ( len ( self . seg1 . _multi_children ) , ) self . assertEqual ( len ( self . seg1 . container_children ) , ) self . assertEqual ( len ( self . seg1 . container_children_recur ) , ) children = ( self . sigs1a + self . sigarrs1a + self . epcs1a + self . epcas1a + self . evts1a + self . evtas1a + self . irsigs1a + self . spikes1a + self . trains1a ) assert_same_sub_schema ( list ( self . seg1 . _single_children ) , children ) assert_same_sub_schema ( list ( self . seg1 . data_children ) , children ) assert_same_sub_schema ( list ( self . seg1 . data_children_recur ) , children ) assert_same_sub_schema ( list ( self . seg1 . children ) , children ) assert_same_sub_schema ( list ( self . seg1 . children_recur ) , children ) self . assertEqual ( len ( self . seg1 . parents ) , ) self . assertEqual ( self . seg1 . parents [ ] . name , '' ) def test__size ( self ) : targ1 = { \"\" : self . nchildren , \"\" : self . nchildren , \"\" : self . nchildren ** , \"\" : self . nchildren ** , \"\" : self . nchildren ** , \"\" : self . nchildren ** , \"\" : self . nchildren , \"\" : self . nchildren , \"\" : self . nchildren } self . assertEqual ( self . targobj . size , targ1 ) def test__filter_none ( self ) : targ = [ ] res0 = self . targobj . filter ( ) res1 = self . targobj . filter ( { } ) res2 = self . targobj . filter ( [ ] ) res3 = self . targobj . filter ( [ { } ] ) res4 = self . targobj . filter ( [ { } , { } ] ) res5 = self . targobj . filter ( [ { } , { } ] ) res6 = self . targobj . filter ( targdict = { } ) res7 = self . targobj . filter ( targdict = [ ] ) res8 = self . targobj . filter ( targdict = [ { } ] ) res9 = self . targobj . filter ( targdict = [ { } , { } ] ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) assert_same_sub_schema ( res3 , targ ) assert_same_sub_schema ( res4 , targ ) assert_same_sub_schema ( res5 , targ ) assert_same_sub_schema ( res6 , targ ) assert_same_sub_schema ( res7 , targ ) assert_same_sub_schema ( res8 , targ ) assert_same_sub_schema ( res9 , targ ) def test__filter_annotation_single ( self ) : targ = ( self . sigs1a + self . sigarrs1a + [ self . epcs1a [ ] , self . epcas1a [ ] ] + [ self . evts1a [ ] , self . evtas1a [ ] ] + self . irsigs1a + self . spikes1a + self . trains1a ) res0 = self . targobj . filter ( j = ) res1 = self . targobj . filter ( { '' : } ) res2 = self . targobj . filter ( targdict = { '' : } ) res3 = self . targobj . filter ( [ { '' : } ] ) res4 = self . targobj . filter ( targdict = [ { '' : } ] ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) assert_same_sub_schema ( res3 , targ ) assert_same_sub_schema ( res4 , targ ) def test__filter_single_annotation_nores ( self ) : targ = [ ] res0 = self . targobj . filter ( j = ) res1 = self . targobj . filter ( { '' : } ) res2 = self . targobj . filter ( targdict = { '' : } ) res3 = self . targobj . filter ( [ { '' : } ] ) res4 = self . targobj . filter ( targdict = [ { '' : } ] ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) assert_same_sub_schema ( res3 , targ ) assert_same_sub_schema ( res4 , targ ) def test__filter_attribute_single ( self ) : targ = [ self . epcs1a [ ] ] res0 = self . targobj . filter ( name = self . epcs1a [ ] . name ) res1 = self . targobj . filter ( { '' : self . epcs1a [ ] . name } ) res2 = self . targobj . filter ( targdict = { '' : self . epcs1a [ ] . name } ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) def test__filter_attribute_single_nores ( self ) : targ = [ ] res0 = self . targobj . filter ( name = self . epcs2 [ ] . name ) res1 = self . targobj . filter ( { '' : self . epcs2 [ ] . name } ) res2 = self . targobj . filter ( targdict = { '' : self . epcs2 [ ] . name } ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) def test__filter_multi ( self ) : targ = ( self . sigs1a + self . sigarrs1a + [ self . epcs1a [ ] , self . epcas1a [ ] ] + [ self . evts1a [ ] , self . evtas1a [ ] ] + self . irsigs1a + self . spikes1a + self . trains1a + [ self . epcs1a [ ] ] ) res0 = self . targobj . filter ( name = self . epcs1a [ ] . name , j = ) res1 = self . targobj . filter ( { '' : self . epcs1a [ ] . name , '' : } ) res2 = self . targobj . filter ( targdict = { '' : self . epcs1a [ ] . name , '' : } ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) def test__filter_multi_nores ( self ) : targ = [ ] res0 = self . targobj . filter ( [ { '' : } , { } ] ) res1 = self . targobj . filter ( { } , ttype = ) res2 = self . targobj . filter ( [ { } ] , ttype = ) res3 = self . targobj . filter ( { '' : self . epcs1a [ ] . name } , j = ) res4 = self . targobj . filter ( targdict = { '' : self . epcs1a [ ] . name } , j = ) res5 = self . targobj . filter ( name = self . epcs1a [ ] . name , targdict = { '' : } ) res6 = self . targobj . filter ( name = self . epcs2 [ ] . name , j = ) res7 = self . targobj . filter ( { '' : self . epcs2 [ ] . name , '' : } ) res8 = self . targobj . filter ( targdict = { '' : self . epcs2 [ ] . name , '' : } ) res9 = self . targobj . filter ( { '' : self . epcs2 [ ] . name } , j = ) res10 = self . targobj . filter ( targdict = { '' : self . epcs2 [ ] . name } , j = ) res11 = self . targobj . filter ( name = self . epcs2 [ ] . name , targdict = { '' : } ) res12 = self . targobj . filter ( { '' : self . epcs1a [ ] . name } , j = ) res13 = self . targobj . filter ( targdict = { '' : self . epcs1a [ ] . name } , j = ) res14 = self . targobj . filter ( name = self . epcs1a [ ] . name , targdict = { '' : } ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) assert_same_sub_schema ( res3 , targ ) assert_same_sub_schema ( res4 , targ ) assert_same_sub_schema ( res5 , targ ) assert_same_sub_schema ( res6 , targ ) assert_same_sub_schema ( res7 , targ ) assert_same_sub_schema ( res8 , targ ) assert_same_sub_schema ( res9 , targ ) assert_same_sub_schema ( res10 , targ ) assert_same_sub_schema ( res11 , targ ) assert_same_sub_schema ( res12 , targ ) assert_same_sub_schema ( res13 , targ ) assert_same_sub_schema ( res14 , targ ) def test__filter_multi_partres ( self ) : targ = [ self . epcs1a [ ] ] res0 = self . targobj . filter ( name = self . epcs1a [ ] . name , j = ) res1 = self . targobj . filter ( { '' : self . epcs1a [ ] . name , '' : } ) res2 = self . targobj . filter ( targdict = { '' : self . epcs1a [ ] . name , '' : } ) res3 = self . targobj . filter ( [ { '' : } , { '' : } ] ) res4 = self . targobj . filter ( { '' : } , i = ) res5 = self . targobj . filter ( [ { '' : } ] , i = ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) assert_same_sub_schema ( res3 , targ ) assert_same_sub_schema ( res4 , targ ) assert_same_sub_schema ( res5 , targ ) def test__filter_single_annotation_obj_single ( self ) : targ = [ self . epcs1a [ ] ] res0 = self . targobj . filter ( j = , objects = '' ) res1 = self . targobj . filter ( j = , objects = Epoch ) res2 = self . targobj . filter ( j = , objects = [ '' ] ) res3 = self . targobj . filter ( j = , objects = [ Epoch ] ) res4 = self . targobj . filter ( j = , objects = [ Epoch , RecordingChannelGroup ] ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) assert_same_sub_schema ( res3 , targ ) assert_same_sub_schema ( res4 , targ ) def test__filter_single_annotation_obj_multi ( self ) : targ = [ self . epcs1a [ ] , self . epcas1a [ ] ] res0 = self . targobj . filter ( j = , objects = [ '' , EpochArray ] ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_annotation_obj_none ( self ) : targ = [ ] res0 = self . targobj . filter ( j = , objects = RecordingChannelGroup ) res1 = self . targobj . filter ( j = , objects = '' ) res2 = self . targobj . filter ( j = , objects = [ ] ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) def test__filter_single_annotation_norecur ( self ) : targ = [ self . epcs1a [ ] , self . epcas1a [ ] , self . evts1a [ ] , self . evtas1a [ ] ] res0 = self . targobj . filter ( j = , recursive = False ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_attribute_norecur ( self ) : targ = [ self . epcs1a [ ] ] res0 = self . targobj . filter ( name = self . epcs1a [ ] . name , recursive = False ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_annotation_nodata ( self ) : targ = [ ] res0 = self . targobj . filter ( j = , data = False ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_attribute_nodata ( self ) : targ = [ ] res0 = self . targobj . filter ( name = self . epcs1a [ ] . name , data = False ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_annotation_nodata_norecur ( self ) : targ = [ ] res0 = self . targobj . filter ( j = , data = False , recursive = False ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_attribute_nodata_norecur ( self ) : targ = [ ] res0 = self . targobj . filter ( name = self . epcs1a [ ] . name , data = False , recursive = False ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_annotation_container ( self ) : targ = [ self . epcs1a [ ] , self . epcas1a [ ] , self . evts1a [ ] , self . evtas1a [ ] ] res0 = self . targobj . filter ( j = , container = True ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_attribute_container ( self ) : targ = [ self . epcs1a [ ] ] res0 = self . targobj . filter ( name = self . epcs1a [ ] . name , container = True ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_annotation_container_norecur ( self ) : targ = [ self . epcs1a [ ] , self . epcas1a [ ] , self . evts1a [ ] , self . evtas1a [ ] ] res0 = self . targobj . filter ( j = , container = True , recursive = False ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_attribute_container_norecur ( self ) : targ = [ self . epcs1a [ ] ] res0 = self . targobj . filter ( name = self . epcs1a [ ] . name , container = True , recursive = False ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_annotation_nodata_container ( self ) : targ = [ ] res0 = self . targobj . filter ( j = , data = False , container = True ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_attribute_nodata_container ( self ) : targ = [ ] res0 = self . targobj . filter ( name = self . epcs1a [ ] . name , data = False , container = True ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_annotation_nodata_container_norecur ( self ) : targ = [ ] res0 = self . targobj . filter ( j = , data = False , container = True , recursive = False ) assert_same_sub_schema ( res0 , targ ) def test__filter_single_attribute_nodata_container_norecur ( self ) : targ = [ ] res0 = self . targobj . filter ( name = self . epcs1a [ ] . name , data = False , container = True , recursive = False ) assert_same_sub_schema ( res0 , targ ) data = self . targobj . children_recur targ = ( self . sigs1a + self . sigarrs1a + [ self . epcs1a [ ] , self . epcas1a [ ] ] + [ self . evts1a [ ] , self . evtas1a [ ] ] + self . irsigs1a + self . spikes1a + self . trains1a + [ self . epcs1a [ ] ] ) res0 = filterdata ( data , name = self . epcs1a [ ] . name , j = ) res1 = filterdata ( data , { '' : self . epcs1a [ ] . name , '' : } ) res2 = filterdata ( data , targdict = { '' : self . epcs1a [ ] . name , '' : } ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) def test__filterdata_multi_nores ( self ) : data = self . targobj . children_recur targ = [ ] res0 = filterdata ( data , [ { '' : } , { } ] ) res1 = filterdata ( data , { } , ttype = ) res2 = filterdata ( data , [ { } ] , ttype = ) res3 = filterdata ( data , { '' : self . epcs1a [ ] . name } , j = ) res4 = filterdata ( data , targdict = { '' : self . epcs1a [ ] . name } , j = ) res5 = filterdata ( data , name = self . epcs1a [ ] . name , targdict = { '' : } ) res6 = filterdata ( data , name = self . epcs2 [ ] . name , j = ) res7 = filterdata ( data , { '' : self . epcs2 [ ] . name , '' : } ) res8 = filterdata ( data , targdict = { '' : self . epcs2 [ ] . name , '' : } ) res9 = filterdata ( data , { '' : self . epcs2 [ ] . name } , j = ) res10 = filterdata ( data , targdict = { '' : self . epcs2 [ ] . name } , j = ) res11 = filterdata ( data , name = self . epcs2 [ ] . name , targdict = { '' : } ) res12 = filterdata ( data , { '' : self . epcs1a [ ] . name } , j = ) res13 = filterdata ( data , targdict = { '' : self . epcs1a [ ] . name } , j = ) res14 = filterdata ( data , name = self . epcs1a [ ] . name , targdict = { '' : } ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) assert_same_sub_schema ( res3 , targ ) assert_same_sub_schema ( res4 , targ ) assert_same_sub_schema ( res5 , targ ) assert_same_sub_schema ( res6 , targ ) assert_same_sub_schema ( res7 , targ ) assert_same_sub_schema ( res8 , targ ) assert_same_sub_schema ( res9 , targ ) assert_same_sub_schema ( res10 , targ ) assert_same_sub_schema ( res11 , targ ) assert_same_sub_schema ( res12 , targ ) assert_same_sub_schema ( res13 , targ ) assert_same_sub_schema ( res14 , targ ) def test__filterdata_multi_partres ( self ) : data = self . targobj . children_recur targ = [ self . epcs1a [ ] ] res0 = filterdata ( data , name = self . epcs1a [ ] . name , j = ) res1 = filterdata ( data , { '' : self . epcs1a [ ] . name , '' : } ) res2 = filterdata ( data , targdict = { '' : self . epcs1a [ ] . name , '' : } ) res3 = filterdata ( data , [ { '' : } , { '' : } ] ) res4 = filterdata ( data , { '' : } , i = ) res5 = filterdata ( data , [ { '' : } ] , i = ) assert_same_sub_schema ( res0 , targ ) assert_same_sub_schema ( res1 , targ ) assert_same_sub_schema ( res2 , targ ) assert_same_sub_schema ( res3 , targ ) assert_same_sub_schema ( res4 , targ ) assert_same_sub_schema ( res5 , targ ) @ unittest . skipUnless ( HAVE_IPYTHON , \"\" ) def test__pretty ( self ) : ann = get_annotations ( ) ann [ '' ] = self . seed1 ann = pretty ( ann ) . replace ( '' , '' ) res = pretty ( self . seg1 ) sig0 = pretty ( self . sigs1 [ ] ) sig1 = pretty ( self . sigs1 [ ] ) sig2 = pretty ( self . sigs1 [ ] ) sig3 = pretty ( self . sigs1 [ ] ) sig0 = sig0 . replace ( '' , '' ) sig1 = sig1 . replace ( '' , '' ) sig2 = sig2 . replace ( '' , '' ) sig3 = sig3 . replace ( '' , '' ) sigarr0 = pretty ( self . sigarrs1 [ ] ) sigarr1 = pretty ( self . sigarrs1 [ ] ) sigarr0 = sigarr0 . replace ( '' , '' ) sigarr1 = sigarr1 . replace ( '' , '' ) targ = ( \"\" + ( \"\" % ( len ( self . sigs1a ) , len ( self . sigarrs1a ) ) ) + ( \"\" % ( len ( self . epcs1a ) , len ( self . epcas1a ) ) ) + ( \"\" % ( len ( self . evts1a ) , len ( self . evtas1a ) ) ) + ( \"\" % len ( self . irsigs1a ) ) + ( \"\" % ( len ( self . spikes1a ) , len ( self . trains1a ) ) ) + ( \"\" % ( self . seg1 . name , self . seg1 . description ) ) + ( \"\" % ann ) + ( \"\" % len ( self . sigs1a ) ) + ( '' % ( , sig0 ) ) + ( '' % ( , sig1 ) ) + ( '' % ( , sig2 ) ) + ( '' % ( , sig3 ) ) + ( \"\" % len ( self . sigarrs1a ) ) + ( '' % ( , sigarr0 ) ) + ( '' % ( , sigarr1 ) ) ) self . assertEqual ( res , targ ) def test__construct_subsegment_by_unit ( self ) : nb_seg = nb_unit = unit_with_sig = np . array ( [ , , ] ) signal_types = [ '' , '' ] sig_len = rcgs = [ RecordingChannelGroup ( name = '' , channel_indexes = unit_with_sig ) , RecordingChannelGroup ( name = '' , channel_indexes = unit_with_sig ) ] all_unit = [ ] for u in range ( nb_unit ) : un = Unit ( name = '' % u , channel_indexes = np . array ( [ u ] ) ) assert_neo_object_is_compliant ( un ) all_unit . append ( un ) blk = Block ( ) blk . recordingchannelgroups = rcgs for s in range ( nb_seg ) : seg = Segment ( name = '' % s ) for j in range ( nb_unit ) : st = SpikeTrain ( [ , ] , units = '' , t_start = , t_stop = ) st . unit = all_unit [ j ] for t in signal_types : anasigarr = AnalogSignalArray ( np . zeros ( ( sig_len , len ( unit_with_sig ) ) ) , units = '' , sampling_rate = * pq . Hz , channel_indexes = unit_with_sig ) seg . analogsignalarrays . append ( anasigarr ) blk . create_many_to_one_relationship ( ) for unit in all_unit : assert_neo_object_is_compliant ( unit ) for rcg in rcgs : assert_neo_object_is_compliant ( rcg ) assert_neo_object_is_compliant ( blk ) newseg = seg . construct_subsegment_by_unit ( all_unit [ : ] ) assert_neo_object_is_compliant ( newseg ) def test_segment_take_spikes_by_unit ( self ) : result1 = self . seg1 . take_spikes_by_unit ( ) result21 = self . seg1 . take_spikes_by_unit ( [ self . unit1 ] ) result22 = self . seg1 . take_spikes_by_unit ( [ self . unit2 ] ) self . assertEqual ( result1 , [ ] ) assert_same_sub_schema ( result21 , [ self . spikes1a [ ] ] ) assert_same_sub_schema ( result22 , [ self . spikes1a [ ] ] ) def test_segment_take_spiketrains_by_unit ( self ) : result1 = self . seg1 . take_spiketrains_by_unit ( ) result21 = self . seg1 . take_spiketrains_by_unit ( [ self . unit1 ] ) result22 = self . seg1 . take_spiketrains_by_unit ( [ self . unit2 ] ) self . assertEqual ( result1 , [ ] ) assert_same_sub_schema ( result21 , [ self . trains1a [ ] ] ) assert_same_sub_schema ( result22 , [ self . trains1a [ ] ] ) def test_segment_take_analogsignal_by_unit ( self ) : result1 = self . seg1 . take_analogsignal_by_unit ( ) result21 = self . seg1 . take_analogsignal_by_unit ( [ self . unit1 ] ) result22 = self . seg1 . take_analogsignal_by_unit ( [ self . unit2 ] ) self . assertEqual ( result1 , [ ] ) assert_same_sub_schema ( result21 , [ self . sigs1a [ ] ] ) assert_same_sub_schema ( result22 , [ self . sigs1a [ ] ] ) def test_segment_take_analogsignal_by_channelindex ( self ) : ind1 = self . unit1 . channel_indexes [ ] ind2 = self . unit2 . channel_indexes [ ] result1 = self . seg1 . take_analogsignal_by_channelindex ( ) result21 = self . seg1 . take_analogsignal_by_channelindex ( [ ind1 ] ) result22 = self . seg1 . take_analogsignal_by_channelindex ( [ ind2 ] ) self . assertEqual ( result1 , [ ] ) assert_same_sub_schema ( result21 , [ self . sigs1a [ ] ] ) assert_same_sub_schema ( result22 , [ self . sigs1a [ ] ] ) def test_seg_take_slice_of_analogsignalarray_by_unit ( self ) : seg = self . seg1 result1 = seg . take_slice_of_analogsignalarray_by_unit ( ) result21 = seg . take_slice_of_analogsignalarray_by_unit ( [ self . unit1 ] ) result23 = seg . take_slice_of_analogsignalarray_by_unit ( [ self . unit3 ] ) self . assertEqual ( result1 , [ ] ) targ1 = [ self . sigarrs1a [ ] [ : , np . array ( [ True ] ) ] , self . sigarrs1a [ ] [ : , np . array ( [ False ] ) ] ] targ3 = [ self . sigarrs1a [ ] [ : , np . array ( [ False ] ) ] , self . sigarrs1a [ ] [ : , np . array ( [ True ] ) ] ] assert_same_sub_schema ( result21 , targ1 ) ", "answer": "assert_same_sub_schema ( result23 , targ3 )"}, {"prompt": " from eventlet import patcher from eventlet . green import ftplib from eventlet . green import httplib ", "answer": "from eventlet . green import socket"}, {"prompt": " \"\"\"\"\"\" 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 tabs from horizon . utils import memoized from openstack_dashboard import api from openstack_dashboard . utils import filters from openstack_dashboard . dashboards . project . images . images import forms as project_forms from openstack_dashboard . dashboards . project . images . images import tables as project_tables from openstack_dashboard . dashboards . project . images . images import tabs as project_tabs class CreateView ( forms . ModalFormView ) : form_class = project_forms . CreateImageForm form_id = \"\" modal_header = _ ( \"\" ) submit_label = _ ( \"\" ) submit_url = reverse_lazy ( '' ) template_name = '' context_object_name = '' success_url = reverse_lazy ( \"\" ) page_title = _ ( \"\" ) def get_initial ( self ) : initial = { } for name in [ '' , '' , '' , '' , '' , '' , '' , '' ] : tmp = self . request . GET . get ( name ) if tmp : initial [ name ] = tmp return initial class UpdateView ( forms . ModalFormView ) : form_class = project_forms . UpdateImageForm form_id = \"\" modal_header = _ ( \"\" ) submit_label = _ ( \"\" ) submit_url = \"\" template_name = '' success_url = reverse_lazy ( \"\" ) page_title = _ ( \"\" ) @ memoized . memoized_method def get_object ( self ) : try : return api . glance . image_get ( self . request , self . kwargs [ '' ] ) except Exception : msg = _ ( '' ) url = reverse ( '' ) exceptions . handle ( self . request , msg , redirect = url ) def get_context_data ( self , ** kwargs ) : context = super ( UpdateView , self ) . get_context_data ( ** kwargs ) context [ '' ] = self . get_object ( ) args = ( self . kwargs [ '' ] , ) context [ '' ] = reverse ( self . submit_url , args = args ) return context def get_initial ( self ) : image = self . get_object ( ) ", "answer": "properties = getattr ( image , '' , { } )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "import os"}, {"prompt": " from aws import Action service_name = '' prefix = '' CreateIdentityPool = Action ( prefix , '' ) DeleteIdentityPool = Action ( prefix , '' ) DescribeIdentityPool = Action ( prefix , '' ) ListIdentities = Action ( prefix , '' ) ", "answer": "ListIdentityPools = Action ( prefix , '' )"}, {"prompt": " class DrawTree ( object ) : def __init__ ( self , tree , depth = ) : ", "answer": "self . x = - "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " from framework . dependency_management . dependency_resolver import ServiceLocator \"\"\"\"\"\" import string , re import cgi DESCRIPTION = \"\" def run ( PluginInfo ) : ", "answer": "plugin_helper = ServiceLocator . get_component ( \"\" )"}, {"prompt": " from argparse import ArgumentParser import numpy as np ", "answer": "from vsm . corpus import *"}, {"prompt": " from kamaki . cli . config import Config from kamaki . clients import astakos , image , ClientError from kamaki . clients . utils import https https . patch_with_certs ( '' ) cnf = Config ( ) ", "answer": "CLOUD = cnf . get ( '' , '' )"}, {"prompt": " import balanced balanced . configure ( '' ) ", "answer": "card_holds = balanced . CardHold . query "}, {"prompt": " from airy . core . conf import settings from airy . utils . safestring import mark_safe def format ( number , decimal_sep , decimal_pos , grouping = , thousand_sep = '' ) : \"\"\"\"\"\" use_grouping = settings . USE_L10N and settings . USE_THOUSAND_SEPARATOR and grouping if isinstance ( number , int ) and not use_grouping and not decimal_pos : return mark_safe ( unicode ( number ) ) if float ( number ) < : sign = '' else : sign = '' str_number = unicode ( number ) if str_number [ ] == '' : str_number = str_number [ : ] if '' in str_number : int_part , dec_part = str_number . split ( '' ) if decimal_pos : dec_part = dec_part [ : decimal_pos ] else : int_part , dec_part = str_number , '' if decimal_pos : dec_part = dec_part + ( '' * ( decimal_pos - len ( dec_part ) ) ) ", "answer": "if dec_part : dec_part = decimal_sep + dec_part"}, {"prompt": " import alembic . command import click ", "answer": "from warehouse . cli . db import db"}, {"prompt": " \"\"\"\"\"\" from pyjamas . ui . AbsolutePanel import AbsolutePanel from pyjamas . dnd import PickupDragController from pyjamas . dnd . drop import AbsolutePositionDropController \"\"\"\"\"\" class AbsolutePositionExample ( Example ) : CSS_DEMO_ABSOLUTE_POSITION_EXAMPLE = \"\" def __init__ ( self , dragController ) : Example . __init__ ( self , dragController ) self . addStyleName ( self . CSS_DEMO_ABSOLUTE_POSITION_EXAMPLE ) positioningDropTarget = AbsolutePanel ( ) positioningDropTarget . setPixelSize ( , ) self . setWidget ( positioningDropTarget ) self . absposdc = AbsolutePositionDropController ( positioningDropTarget ) dragController . registerDropController ( self . absposdc ) def getDescription ( self ) : return \"\" def getInvolvedClasses ( self ) : return [ AbsolutePositionExample , AbsolutePositionDropController ] def onInitialLoad ( self ) : ", "answer": "self . absposdc . drop ( self . createDraggable ( ) , , )"}, {"prompt": " from __future__ import unicode_literals import json from django import template from django . core . serializers . json import DjangoJSONEncoder from django . http import HttpResponse , HttpResponseForbidden from django . shortcuts import get_object_or_404 from django . template import RequestContext , Template from django . views . debug import ExceptionReporter from django . views . decorators . http import require_POST from django . contrib . contenttypes . models import ContentType from django . shortcuts import render from . forms import ScribbleForm , PreviewForm , FieldScribbleForm from . models import Scribble from . utils import get_variables def build_scribble_context ( scribble ) : \"\" context = { '' : scribble , } return context @ require_POST def preview_scribble ( request , ct_pk ) : \"\" if not request . user . is_authenticated ( ) : return HttpResponseForbidden ( ) content_type = get_object_or_404 ( ContentType , pk = ct_pk ) change_scribble = '' . format ( content_type . app_label , content_type . model ) add_scribble = '' . format ( content_type . app_label , content_type . model ) can_edit = request . user . has_perm ( change_scribble ) can_create = request . user . has_perm ( add_scribble ) if not ( can_edit or can_create ) : return HttpResponseForbidden ( ) results = { '' : False , '' : '' , } form = PreviewForm ( request . POST ) if form . is_valid ( ) : results [ '' ] = True if hasattr ( template , '' ) : scribbler_template = template . engines [ '' ] . from_string ( form . cleaned_data . get ( '' , '' ) ) else : scribbler_template = template . Template ( form . cleaned_data . get ( '' , '' ) ) context = build_scribble_context ( form . instance ) results [ '' ] = scribbler_template . render ( context , request ) results [ '' ] = get_variables ( RequestContext ( request , context ) ) else : if hasattr ( form , '' ) : try : exc_type , exc_value , tb = form . exc_info reporter = ExceptionReporter ( request , exc_type , exc_value , tb ) reporter . get_template_exception_info ( ) results [ '' ] = reporter . template_info except ( ValueError , AttributeError ) : results [ '' ] = form . exc_info else : results [ '' ] = { '' : '' , '' : '' , } content = json . dumps ( results , cls = DjangoJSONEncoder , ensure_ascii = False ) return HttpResponse ( content , content_type = '' ) @ require_POST def create_edit_scribble ( request , scribble_id = None ) : \"\" if not request . user . is_authenticated ( ) : return HttpResponseForbidden ( ) if scribble_id is not None : scribble = get_object_or_404 ( Scribble , pk = scribble_id ) if not request . user . has_perm ( '' ) : return HttpResponseForbidden ( ) else : ", "answer": "scribble = Scribble ( )"}, {"prompt": " import i3ipc import re from argparse import ArgumentParser ", "answer": "def main ( ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Building ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " from urllib import urlencode from django . contrib . gis . geos import Point from molly . maps . osm import fit_to_map from molly . maps . models import GeneratedMap class Map ( object ) : \"\"\"\"\"\" def __init__ ( self , centre_point , points , min_points , zoom , width , height , extra_points = [ ] , paths = [ ] ) : \"\"\"\"\"\" self . centre_point = centre_point self . extra_points = extra_points self . min_points = min_points self . paths = paths self . width = width self . height = height try : self . static_map_hash , ( self . points , self . zoom , lon_center , lat_center ) = fit_to_map ( centre_point = centre_point , extra_points = extra_points , points = points , paths = paths , min_points = min_points , zoom = zoom , width = width , ", "answer": "height = height ,"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models from django . contrib . auth import get_user_model User = get_user_model ( ) class Migration ( SchemaMigration ) : depends_on = ( ( \"\" , \"\" ) , ) def forwards ( self , orm ) : db . create_table ( u'' , ( ( u'' , self . gf ( '' ) ( to = orm [ '' ] , unique = True , primary_key = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( ) ) , ) ) db . send_create_signal ( u'' , [ '' ] ) m2m_table_name = db . shorten_name ( u'' ) ", "answer": "db . create_table ( m2m_table_name , ("}, {"prompt": " import unittest from copperhead import * from recursive_equal import recursive_equal class TupleData ( unittest . TestCase ) : def testTypeTupleScalars ( self ) : source = ( , ) result_type , result_value = runtime . driver . induct ( source ) self . assertEqual ( repr ( result_type ) , \"\" ) def testTypeTupleSequences ( self ) : source = ( [ , ] , [ , ] ) result_type , result_value = runtime . driver . induct ( source ) self . assertEqual ( repr ( result_type ) , \"\" ) def testTypeNestedTuple ( self ) : source = ( , ( , , ( , ) ) , ) result_type , result_value = runtime . driver . induct ( source ) self . assertEqual ( repr ( result_type ) , \"\" ) @ cu def test_tuple ( ( m , n ) , b ) : \"\"\"\"\"\" q , r = m , n s = q , r t , u = s o , p = b return t + o , u + p @ cu def test_tuple_return ( ) : \"\"\"\"\"\" a = , return a @ cu def test_nested_tuple_return ( ) : return ( , ( , ) ) @ cu def test_tuple_seq ( x , y ) : return x , y @ cu def test_containerize ( x ) : def sub ( xi ) : return - xi y = map ( sub , x ) z = x , y return z @ cu def test_tuple_seq_args ( x ) : y , z = x return y , z class TupleExtract ( unittest . TestCase ) : def testTuple ( self ) : source_a = ( , ) source_b = ( , ) golden = ( , ) ", "answer": "self . assertEqual ( test_tuple ( source_a , source_b ) , golden )"}, {"prompt": " \"\"\"\"\"\" __version__ = \"\" from . . StyleProperty import StyleProperty from copy import copy from . . import convert as cvt __all__ = [ '' ] class SubStyle ( StyleProperty ) : \"\"\"\"\"\" def __init__ ( self , styleClass , ** kwargs ) : \"\"\"\"\"\" validator = cvt . Converter ( cvt . toInstance , styleClass , allowNone = False ) doc = kwargs . pop ( '' , None ) if doc is None : doc = \"\" % ( styleClass . __name__ , ) self . styleClass = styleClass self . kwargs = kwargs style = self . styleClass ( ** self . kwargs ) StyleProperty . __init__ ( self , style , validator , doc ) def validate ( self , value ) : \"\"\"\"\"\" if isinstance ( value , dict ) : kw = { } kw . update ( self . kwargs ) kw . update ( value ) value = self . styleClass ( ** kw ) return StyleProperty . validate ( self , value ) def __str__ ( self ) : \"\"\"\"\"\" if self . owner : return \"\" % ( self . styleClass . __name__ , self . owner . __name__ , self . name ) elif self . name : return \"\" % ( self . styleClass . __name__ , self . name ) ", "answer": "else :"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os from pants . base . build_environment import get_buildroot from pants . base . payload import Payload from pants . build_graph . target import Target from pants . task . task import Task from pants_test . tasks . task_test_base import TaskTestBase class DummyLibrary ( Target ) : def __init__ ( self , address , source , * args , ** kwargs ) : ", "answer": "payload = Payload ( )"}, {"prompt": " import math def distance ( pa , pb ) : ax , ay = pa bx , by = pb return math . sqrt ( ( ax - bx ) ** + ( ay - by ) ** ) def index_of_nearest ( p , hot_points , distance_f = distance ) : \"\"\"\"\"\" min_dist = None ", "answer": "nearest_hp_i = None"}, {"prompt": " from setuptools import setup , find_packages version = '' LONG_DESCRIPTION = '''''' setup ( name = '' , version = version , description = \"\" , long_description = LONG_DESCRIPTION , classifiers = [ \"\" , \"\" , \"\" , \"\" , ] , keywords = '' , author = '' , author_email = '' , url = '' , license = '' , packages = find_packages ( ) , include_package_data = True , ", "answer": "zip_safe = False ,"}, {"prompt": " from quadratic_weighted_kappa import * from elementwise import * from auc import auc from average_precision import apk , mapk from edit_distance import levenshtein from custom . kdd_average_precision import kdd_apk , kdd_mapk ", "answer": "from custom . binomial_deviance import capped_log10_likelihood , capped_binomial_deviance "}, {"prompt": " from st2common . rbac . types import PermissionType from st2common . rbac . types import ResourceType from st2common . rbac . types import SystemRole from st2common . persistence . rbac import Role from st2common . persistence . rbac import UserRoleAssignment from st2common . persistence . rbac import PermissionGrant from st2common . models . db . rbac import RoleDB from st2common . models . db . rbac import UserRoleAssignmentDB from st2common . models . db . rbac import PermissionGrantDB __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] def get_all_roles ( exclude_system = False ) : \"\"\"\"\"\" if exclude_system : result = Role . query ( system = False ) else : result = Role . get_all ( ) return result def get_system_roles ( ) : \"\"\"\"\"\" result = Role . query ( system = True ) return result def get_roles_for_user ( user_db ) : \"\"\"\"\"\" role_names = UserRoleAssignment . query ( user = user_db . name ) . only ( '' ) . scalar ( '' ) result = Role . query ( name__in = role_names ) return result def get_role_assignments_for_user ( user_db ) : \"\"\"\"\"\" result = UserRoleAssignment . query ( user = user_db . name ) return result def get_role_by_name ( name ) : \"\"\"\"\"\" result = Role . get ( name = name ) return result def create_role ( name , description = None ) : \"\"\"\"\"\" if name in SystemRole . get_valid_values ( ) : raise ValueError ( '' % ( name ) ) role_db = RoleDB ( name = name , description = description ) role_db = Role . add_or_update ( role_db ) return role_db def delete_role ( name ) : \"\"\"\"\"\" if name in SystemRole . get_valid_values ( ) : raise ValueError ( '' ) role_db = Role . get ( name = name ) result = Role . delete ( role_db ) return result def assign_role_to_user ( role_db , user_db , description = None ) : \"\"\"\"\"\" role_assignment_db = UserRoleAssignmentDB ( user = user_db . name , role = role_db . name , description = description ) role_assignment_db = UserRoleAssignment . add_or_update ( role_assignment_db ) return role_assignment_db def revoke_role_from_user ( role_db , user_db ) : \"\"\"\"\"\" role_assignment_db = UserRoleAssignment . get ( user = user_db . name , role = role_db . name ) result = UserRoleAssignment . delete ( role_assignment_db ) return result def get_all_permission_grants_for_user ( user_db , resource_uid = None , resource_types = None , permission_types = None ) : \"\"\"\"\"\" role_names = UserRoleAssignment . query ( user = user_db . name ) . only ( '' ) . scalar ( '' ) permission_grant_ids = Role . query ( name__in = role_names ) . scalar ( '' ) permission_grant_ids = sum ( permission_grant_ids , [ ] ) permission_grants_filters = { } permission_grants_filters [ '' ] = permission_grant_ids if resource_uid : permission_grants_filters [ '' ] = resource_uid if resource_types : permission_grants_filters [ '' ] = resource_types if permission_types : permission_grants_filters [ '' ] = permission_types permission_grant_dbs = PermissionGrant . query ( ** permission_grants_filters ) return permission_grant_dbs def create_permission_grant_for_resource_db ( role_db , resource_db , permission_types ) : \"\"\"\"\"\" permission_types = _validate_permission_types ( resource_db = resource_db , permission_types = permission_types ) resource_uid = resource_db . get_uid ( ) resource_type = resource_db . get_resource_type ( ) result = create_permission_grant ( role_db = role_db , resource_uid = resource_uid , resource_type = resource_type , permission_types = permission_types ) return result def create_permission_grant ( role_db , resource_uid , resource_type , permission_types ) : \"\"\"\"\"\" permission_grant_db = PermissionGrantDB ( resource_uid = resource_uid , resource_type = resource_type , permission_types = permission_types ) permission_grant_db = PermissionGrant . add_or_update ( permission_grant_db ) role_db . update ( push__permission_grants = permission_grant_db . id ) return permission_grant_db def remove_permission_grant_for_resource_db ( role_db , resource_db , permission_types ) : \"\"\"\"\"\" permission_types = _validate_permission_types ( resource_db = resource_db , permission_types = permission_types ) resource_uid = resource_db . get_uid ( ) resource_type = resource_db . get_resource_type ( ) permission_grant_db = PermissionGrant . get ( resource_uid = resource_uid , resource_type = resource_type , permission_types = permission_types ) role_db . update ( pull__permission_grants = permission_grant_db . id ) ", "answer": "return permission_grant_db"}, {"prompt": " from plyer . platforms . win . libs . batterystatus import battery_status from plyer . facades import Battery class WinBattery ( Battery ) : def _get_state ( self ) : status = { \"\" : None , \"\" : None } query = battery_status ( ) if ( not query ) : return status ", "answer": "status [ \"\" ] = query [ \"\" ] == "}, {"prompt": " from twisted . trial import unittest ", "answer": "from txtorcon import log"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " from PyQt4 . QtCore import * from PyQt4 . QtGui import * from app . widget import tweet_widget class SeperatedTweetWindow ( QDialog ) : def __init__ ( self , account , tweet , avatar , thumbnail , parent = None ) : super ( SeperatedTweetWindow , self ) . __init__ ( parent ) ", "answer": "self . account = account"}, {"prompt": " \"\"\"\"\"\" from world import world , setup_module , teardown_module import create_source_steps as source_create import create_dataset_steps as dataset_create import create_statistical_tst_steps as statistical_tst_create class TestStatisticalTest ( object ) : def setup ( self ) : \"\"\"\"\"\" print \"\" % __name__ def teardown ( self ) : \"\"\"\"\"\" print \"\" % __name__ def test_scenario1 ( self ) : \"\"\"\"\"\" print self . test_scenario1 . __doc__ examples = [ [ '' , '' , '' , '' , '' , '' ] ] for example in examples : print \"\" , example source_create . i_upload_a_file ( self , example [ ] ) source_create . the_source_is_finished ( self , example [ ] ) dataset_create . i_create_a_dataset ( self ) dataset_create . the_dataset_is_finished_in_less_than ( self , example [ ] ) ", "answer": "statistical_tst_create . i_create_a_tst_from_dataset ( self )"}, {"prompt": " from django . conf . urls . defaults import patterns , include , url from django . contrib import admin from django . conf import settings admin . autodiscover ( ) handler404 = '' handler500 = '' urlpatterns = patterns ( '' ) ", "answer": "if settings . DEBUG or settings . SERVE_STATIC :"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " '''''' \"\"\"\"\"\" import ssl import requests ", "answer": "import json"}, {"prompt": " \"\"\"\"\"\" from django . conf . urls import include , url ", "answer": "from django . contrib import admin"}, {"prompt": " import re import os import sys from setuptools import setup name = '' package = '' description = '' url = '' author = '' author_email = '' license = '' def get_version ( package ) : \"\"\"\"\"\" init_py = open ( os . path . join ( package , '' ) ) . read ( ) return re . search ( \"\" , init_py , re . MULTILINE ) . group ( ) def get_packages ( package ) : \"\"\"\"\"\" return [ dirpath for dirpath , dirnames , filenames in os . walk ( package ) if os . path . exists ( os . path . join ( dirpath , '' ) ) ] def get_package_data ( package ) : \"\"\"\"\"\" walk = [ ( dirpath . replace ( package + os . sep , '' , ) , filenames ) for dirpath , dirnames , filenames in os . walk ( package ) if not os . path . exists ( os . path . join ( dirpath , '' ) ) ] filepaths = [ ] for base , filenames in walk : filepaths . extend ( [ os . path . join ( base , filename ) for filename in filenames ] ) return { package : filepaths } version = get_version ( package ) if sys . argv [ - ] == '' : if os . system ( \"\" ) : print ( \"\" ) sys . exit ( ) os . system ( \"\" ) os . system ( \"\" ) print ( \"\" ) print ( \"\" . format ( version ) ) print ( \"\" ) sys . exit ( ) setup ( name = name , version = version , url = url , license = license , description = description , author = author , author_email = author_email , packages = get_packages ( package ) , package_data = get_package_data ( package ) , install_requires = [ ] , classifiers = [ '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from django . utils . text import capfirst , get_text_list from django . contrib . admin . util import flatten_fieldsets from django . http import HttpResponseRedirect from django . utils . encoding import force_unicode import re from copy import deepcopy from django . conf import settings from django import forms from django . contrib import admin from django . db . models import Model from django . forms . util import ErrorList , ValidationError from django . forms . models import BaseInlineFormSet , ModelFormMetaclass from django . utils . translation import ugettext as _ from django . template . loader import find_template from django . template import TemplateDoesNotExist from multilingual . languages import get_default_language from multilingual . utils import GLL MULTILINGUAL_PREFIX = '' MULTILINGUAL_INLINE_PREFIX = '' def gll ( func ) : def wrapped ( cls , request , * args , ** kwargs ) : cls . use_language = request . GET . get ( '' , request . GET . get ( '' , get_default_language ( ) ) ) GLL . lock ( cls . use_language ) resp = func ( cls , request , * args , ** kwargs ) GLL . release ( ) return resp wrapped . __name__ = func . __name__ wrapped . __doc__ = func . __doc__ return wrapped def standard_get_fill_check_field ( stdopts ) : if hasattr ( stdopts , '' ) : opts = stdopts . translation_model . _meta for field in opts . fields : if field . name in ( '' , '' ) : continue if not ( field . blank or field . null ) : return field . name return None def relation_hack ( form , fields , prefix = '' ) : opts = form . instance . _meta localm2m = [ m2m . attname for m2m in opts . local_many_to_many ] externalfk = [ obj . field . related_query_name ( ) for obj in opts . get_all_related_objects ( ) ] externalm2m = [ m2m . get_accessor_name ( ) for m2m in opts . get_all_related_many_to_many_objects ( ) ] for name , db_field in fields : full_name = '' % ( prefix , name ) if full_name in form . fields : value = getattr ( form . instance , name , '' ) if isinstance ( value , Model ) : value = value . pk elif name in localm2m : value = value . all ( ) elif name in externalfk : value = value . all ( ) elif name in externalm2m : value = value . all ( ) form . fields [ full_name ] . initial = value class MultilingualInlineModelForm ( forms . ModelForm ) : def __init__ ( self , data = None , files = None , auto_id = '' , prefix = None , initial = None , error_class = ErrorList , label_suffix = '' , empty_permitted = False , instance = None ) : \"\"\"\"\"\" super ( MultilingualInlineModelForm , self ) . __init__ ( data , files , auto_id , prefix , initial , error_class , label_suffix , empty_permitted , instance ) if self . instance . pk : relation_hack ( self , get_translated_fields ( self . instance ) , MULTILINGUAL_INLINE_PREFIX ) class MultilingualInlineFormSet ( BaseInlineFormSet ) : def get_queryset ( self ) : if self . queryset is not None : ", "answer": "qs = self . queryset"}, {"prompt": " \"\"\"\"\"\" class KeyVal : __guid__ = \"\" def __repr__ ( self ) : ", "answer": "return \"\" % self . __dict__ "}, {"prompt": " import json from poni import tool from helper import * plugin_text = \"\"\"\"\"\" class TestControls ( Helper ) : def test_basic_controls ( self ) : poni = self . repo_and_config ( \"\" , \"\" , plugin_text ) temp = self . temp_file ( ) def cmd_output ( cmd , output ) : assert not poni . run ( [ \"\" , \"\" , cmd , \"\" , temp ] ) assert open ( temp ) . read ( ) == output ", "answer": "os . unlink ( temp )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import __main__ from collections import namedtuple import re import os import sys from jedi import Interpreter from jedi . api . helpers import completion_parts from jedi . parser . user_context import UserContext def setup_readline ( namespace_module = __main__ ) : \"\"\"\"\"\" class JediRL ( object ) : def complete ( self , text , state ) : \"\"\"\"\"\" if state == : ", "answer": "sys . path . insert ( , os . getcwd ( ) )"}, {"prompt": " \"\"\"\"\"\" from . view_chooser import ViewChooser from . workbench_action import WorkbenchAction class ShowViewAction ( WorkbenchAction ) : \"\"\"\"\"\" id = '' name = '' def perform ( self , event ) : \"\"\"\"\"\" chooser = ViewChooser ( window = self . window ) ", "answer": "ui = chooser . edit_traits ( parent = self . window . control , kind = '' )"}, {"prompt": " from wordpress_xmlrpc . base import * class GetPageStatusList ( AuthenticatedMethod ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import print_function \"\"\"\"\"\" \"\"\"\"\"\" import difflib import ConfigParser import os import random import re import string import sys import threading import time import xml . etree . ElementTree as ET from urllib import urlencode from urllib2 import build_opener , install_opener , urlopen , ProxyHandler , Request from urlparse import urlsplit , urlunsplit , parse_qsl from optparse import OptionParser from subprocess import Popen , PIPE from sys import exit NAME = \"\" VERSION = \"\" URL = \"\" INVALID_FILENAME = \"\" . join ( random . sample ( string . letters , ) ) MAX_HELP_OPTION_LENGTH = CASES_FILE = \"\" USER_AGENTS_FILE = \"\" HOME_FILES_FILE = \"\" HEURISTIC_RATIO = SKIP_RETRIEVE_THRESHOLD = BANNER = \"\"\"\"\"\" % ( NAME , VERSION , URL ) ROTATOR_CHARS = \"\" GIT_REPOSITORY = \"\" EXAMPLES = \"\"\"\"\"\" class PROXY_TYPE : HTTP = \"\" HTTPS = \"\" SOCKS4 = \"\" SOCKS5 = \"\" class HTTP_HEADER : COOKIE = \"\" USER_AGENT = \"\" CONTENT_LENGTH = \"\" class AttribDict ( dict ) : def __getattr__ ( self , name ) : return self . get ( name ) def __setattr__ ( self , name , value ) : return self . __setitem__ ( name , value ) kb = AttribDict ( ) args = None def print ( * args , ** kwargs ) : \"\"\"\"\"\" with kb . print_lock : return __builtins__ . print ( * args , ** kwargs ) def get_cases ( args ) : \"\"\"\"\"\" tree = ET . parse ( CASES_FILE ) root = tree . getroot ( ) def _ ( parent , element ) : element . parent = parent for key , value in element . attrib . items ( ) : setattr ( element , key , value ) for child in element . getchildren ( ) : _ ( element , child ) _ ( None , root ) for attr in ( \"\" , \"\" , \"\" ) : if getattr ( args , attr ) : for element in root . findall ( \"\" % attr ) : if element . value . lower ( ) != getattr ( args , attr ) . lower ( ) : element . parent . remove ( element ) if args . type : for _ in ( _ for _ in ( \"\" , \"\" , \"\" ) if _ . lower ( ) != args . type . lower ( ) ) : for element in root . findall ( \"\" % _ ) : element . parent . remove ( element ) def _ ( element , tag ) : while element . parent is not None : if element . parent . tag == tag : return element . parent else : element = element . parent cases = [ ] replacements = { } if args . url : replacements [ \"\" ] = urlsplit ( args . url ) . netloc for element in root . findall ( \"\" ) : case = AttribDict ( ) case . location = element . value case . os = _ ( element , \"\" ) . value case . category = _ ( element , \"\" ) . value case . software = _ ( element , \"\" ) . value case . type = _ ( element , \"\" ) is not None and \"\" or _ ( element , \"\" ) is not None and \"\" or _ ( element , \"\" ) is not None and \"\" for variable in re . findall ( r\"\" , case . location ) : case . location = case . location . replace ( variable , replacements . get ( variable . strip ( \"\" ) , variable ) ) match = re . search ( r\"\" , case . location ) if match and kb . through : original = case . location for replacement in kb . versioned_locations [ match . group ( ) ] : case = AttribDict ( case ) case . location = original . replace ( match . group ( ) , replacement ) cases . append ( case ) else : cases . append ( case ) return cases def load_list ( filepath ) : \"\"\"\"\"\" items = [ ] cases = [ ] with open ( filepath , '' ) as f : items = f . readlines ( ) for item in items : case = AttribDict ( { '' : item . strip ( ) } ) cases . append ( case ) return cases def get_revision ( ) : \"\"\"\"\"\" retval = None filepath = None _ = os . path . dirname ( __file__ ) while True : filepath = os . path . join ( _ , \"\" , \"\" ) if os . path . exists ( filepath ) : break else : filepath = None if _ == os . path . dirname ( _ ) : break else : _ = os . path . dirname ( _ ) while True : if filepath and os . path . isfile ( filepath ) : with open ( filepath , \"\" ) as f : content = f . read ( ) filepath = None if content . startswith ( \"\" ) : filepath = os . path . join ( _ , \"\" , content . replace ( \"\" , \"\" ) ) . strip ( ) else : match = re . match ( r\"\" , content ) retval = match . group ( ) if match else None break else : break if not retval : process = Popen ( \"\" , shell = True , stdout = PIPE , stderr = PIPE ) stdout , _ = process . communicate ( ) match = re . search ( r\"\" , stdout or \"\" ) retval = match . group ( ) if match else None return retval [ : ] if retval else None def check_revision ( ) : \"\"\"\"\"\" global BANNER global VERSION revision = get_revision ( ) if revision : _ = VERSION VERSION = \"\" % ( VERSION , revision ) BANNER = BANNER . replace ( _ , VERSION ) def update ( ) : \"\"\"\"\"\" print ( \"\" ) process = Popen ( \"\" % GIT_REPOSITORY , shell = True , stdout = PIPE , stderr = PIPE ) stdout , stderr = process . communicate ( ) success = not process . returncode if success : updated = \"\" not in stdout process = Popen ( \"\" , shell = True , stdout = PIPE , stderr = PIPE ) stdout , _ = process . communicate ( ) revision = stdout [ : ] if stdout and re . search ( r\"\" , stdout ) else \"\" print ( \"\" % ( \"\" if not updated else \"\" , revision ) ) else : print ( \"\" % repr ( stderr . strip ( ) ) ) print ( \"\" ) def ask_question ( question , default = None , automatic = False ) : \"\"\"\"\"\" question = \"\" % question if automatic : answer = default print ( \"\" % ( question , answer ) ) else : with kb . print_lock : answer = raw_input ( question ) print return answer def prepare_request ( payload ) : \"\"\"\"\"\" _ = re . sub ( r\"\" % args . param , r\"\" % ( payload or \"\" ) , kb . request_params ) request_args = { \"\" : \"\" % ( kb . parsed_target_url . scheme or \"\" , kb . parsed_target_url . netloc , kb . parsed_target_url . path ) } if args . data : request_args [ \"\" ] = _ else : request_args [ \"\" ] += \"\" % _ if args . header : request_args [ \"\" ] = args . header if args . cookie : request_args [ \"\" ] = args . cookie if args . user_agent : request_args [ \"\" ] = args . user_agent request_args [ \"\" ] = args . verbose return request_args def clean_response ( response , filepath ) : \"\"\"\"\"\" response = response . replace ( filepath , \"\" ) regex = re . sub ( r\"\" , \"\" , filepath ) return re . sub ( regex , \"\" , response , re . I ) def request_file ( case , replace_slashes = True ) : \"\"\"\"\"\" global ROTATOR_CHARS if args . replace_slash and replace_slashes : case . location = case . location . replace ( \"\" , args . replace_slash . replace ( \"\" , \"\" ) ) if kb . restrict_os and kb . restrict_os != case . os : if args . verbose : print ( \"\" % case . location ) return None if args . prefix and args . prefix [ len ( args . prefix ) - ] == \"\" : args . prefix = args . prefix [ : - ] _ = \"\" % ( args . prefix , case . location , args . postfix ) if args . verbose : print ( \"\" % _ ) else : with kb . print_lock : sys . stdout . write ( \"\" % ROTATOR_CHARS [ ] ) sys . stdout . flush ( ) ROTATOR_CHARS = ROTATOR_CHARS [ : ] + ROTATOR_CHARS [ ] request_args = prepare_request ( _ ) html = get_page ( ** request_args ) if not html or args . bad_string and html . find ( args . bad_string ) != - : return None matcher = difflib . SequenceMatcher ( None , clean_response ( html , case . location ) , clean_response ( kb . invalid_response , INVALID_FILENAME ) ) if matcher . quick_ratio ( ) < HEURISTIC_RATIO : with kb . value_lock : if not kb . found : print ( \"\" ) if case . os : print ( \"\" % case . os ) if kb . restrict_os is None : answer = ask_question ( \"\" % case . os , default = '' , automatic = args . automatic ) kb . restrict_os = answer . upper ( ) != '' and case . os _ = \"\" . join ( _ for _ in ( case . os , case . category , case . type ) if _ ) if _ : _ = \"\" % ( case . location , _ ) _ = _ . replace ( \"\" % ( case . os , case . os ) , \"\" % case . os ) else : _ = \"\" % case . location print ( \"\" % _ ) if args . verbose : kb . files . append ( _ ) if args . write_files : _ = os . path . join ( \"\" , kb . parsed_target_url . netloc ) if not os . path . exists ( _ ) : os . makedirs ( _ ) with open ( os . path . join ( _ , \"\" % case . location . replace ( args . replace_slash if args . replace_slash else \"\" , \"\" ) ) , \"\" ) as f : content = html with kb . value_lock : if kb . filter_output is None : answer = ask_question ( \"\" , default = '' , automatic = args . automatic ) kb . filter_output = answer . upper ( ) != '' if kb . get ( \"\" ) : matcher = difflib . SequenceMatcher ( None , html or \"\" , kb . original_response or \"\" ) matching_blocks = matcher . get_matching_blocks ( ) if matching_blocks : start = matching_blocks [ ] if start [ ] == start [ ] == and start [ ] > : content = content [ start [ ] : ] if len ( matching_blocks ) > : end = matching_blocks [ - ] if end [ ] > and end [ ] + end [ ] == len ( html ) and end [ ] + end [ ] == len ( kb . original_response ) : content = content [ : - end [ ] ] f . write ( content ) return html return None def try_cases ( cases ) : \"\"\"\"\"\" passwd_files = [ \"\" , \"\" ] if args . replace_slash : for i , v in enumerate ( passwd_files ) : passwd_files [ i ] = v . replace ( \"\" , args . replace_slash ) for case in cases : html = request_file ( case ) if html is None : continue if not kb . found : kb . found = True if case . location in passwd_files and not args . skip_parsing : users = re . finditer ( \"\" , html ) if args . verbose : print ( \"\" % case . location ) for user in users : if args . verbose : print ( \"\" % ( user . group ( \"\" ) , user . group ( \"\" ) ) ) if not kb . home_files : with open ( HOME_FILES_FILE , \"\" ) as f : kb . home_files = filter ( None , ( _ . strip ( ) for _ in f . readlines ( ) ) ) for _ in kb . home_files : if user . group ( \"\" ) == \"\" : continue request_file ( AttribDict ( { \"\" : \"\" , \"\" : \"\" , \"\" : case . os , \"\" : \"\" % ( user . group ( \"\" ) , _ ) , \"\" : \"\" } ) ) if \"\" in case . location and not args . skip_parsing : binlogs = re . findall ( \"\" , html ) location = case . location . rfind ( \"\" ) + if args . verbose : print ( \"\" % case . location ) for _ in binlogs : request_file ( AttribDict ( { \"\" : \"\" , \"\" : \"\" , \"\" : case . os , \"\" : \"\" % ( case . location [ : location ] , _ ) , \"\" : \"\" } ) , False ) def parse_args ( ) : \"\"\"\"\"\" OptionParser . format_epilog = lambda self , formatter : self . epilog parser = OptionParser ( usage = \"\" , epilog = EXAMPLES ) parser . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , metavar = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , action = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , action = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , action = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , metavar = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , action = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , metavar = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , action = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , default = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , default = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , type = \"\" , default = , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , metavar = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , type = \"\" , default = , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , action = \"\" , help = \"\" ) parser . formatter . store_option_strings ( parser ) parser . formatter . store_option_strings = lambda _ : None for option , value in parser . formatter . option_strings . items ( ) : value = re . sub ( r\"\" , r\"\" , value ) value = value . replace ( \"\" , '' ) if len ( value ) > MAX_HELP_OPTION_LENGTH : value = ( \"\" % ( MAX_HELP_OPTION_LENGTH - parser . formatter . indent_increment ) ) % value parser . formatter . option_strings [ option ] = value args = parser . parse_args ( ) [ ] if args . url and not args . url . lower ( ) . startswith ( \"\" ) : args . url = \"\" % args . url if not any ( ( args . url , args . list , args . update ) ) : parser . error ( \"\" ) if args . prefix : args . prefix = args . prefix * args . multiplier return args def main ( ) : \"\"\"\"\"\" global args kb . files = [ ] kb . found = False kb . print_lock = threading . Lock ( ) kb . value_lock = threading . Lock ( ) kb . versioned_locations = { } check_revision ( ) print ( BANNER ) args = parse_args ( ) if args . update : update ( ) exit ( ) with open ( \"\" ) as f : section = None for line in f . xreadlines ( ) : line = line . strip ( ) if re . match ( r\"\" , line ) : section = line . strip ( \"\" ) elif line : if section not in kb . versioned_locations : kb . versioned_locations [ section ] = [ ] kb . versioned_locations [ section ] . append ( line ) cases = get_cases ( args ) if not args . list_file else load_list ( args . list_file ) if not cases : print ( \"\" \"\" ) exit ( ) if args . list : args . list = args . list . lower ( ) _ = ( \"\" , \"\" , \"\" ) if args . list not in _ : print ( \"\" % \"\" . join ( _ ) ) exit ( ) print ( \"\" % args . list ) try : for _ in set ( [ _ [ args . list ] for _ in cases ] ) : print ( _ if re . search ( r\"\" , _ ) else '' % _ ) except KeyError : pass finally : exit ( ) if args . ignore_proxy : _ = ProxyHandler ( { } ) opener = build_opener ( _ ) install_opener ( opener ) elif args . proxy : match = re . search ( r\"\" , args . proxy , re . I ) ", "answer": "if match :"}, {"prompt": " from django . test import TestCase from guardian . checks import check_settings class SystemCheckTestCase ( TestCase ) : def test_checks ( self ) : \"\"\"\"\"\" self . assertFalse ( check_settings ( None ) ) with self . settings ( AUTHENTICATION_BACKENDS = ( ", "answer": "'' , ) ,"}, {"prompt": " from setuptools import setup from Pyrex . Distutils . extension import PyrexExtension from Pyrex . Distutils . build_ext import build_ext import os include_dir = os . path . join ( os . getenv ( '' ) , '' , '' ) setup ( name = '' , ext_modules = [ PyrexExtension ( '' , [ '' ] , pyrex_include_dirs = [ include_dir ] , ) , ", "answer": "] ,"}, {"prompt": " import sys from pathlib import Path from . pycloader import get_module def is_package ( full_name ) : module_path = '' . join ( full_name . split ( '' ) ) for load_path in sys . path : load_path = Path ( load_path ) . absolute ( ) target_path = Path ( '' % ( load_path , module_path ) ) if target_path . exists ( ) : return True return False class Loader ( object ) : def __init__ ( self , path ) : self . path = path def load_module ( self , full_name ) : if full_name in sys . modules : return sys . modules [ full_name ] absolute_file_path = str ( self . path . absolute ( ) ) mod = get_module ( full_name , absolute_file_path ) print ( \"\" ) print ( absolute_file_path ) print ( \"\" ) mod . __file__ = absolute_file_path mod . __loader__ = self mod . __name__ = full_name if is_package ( full_name ) : mod . __path__ = [ ] ", "answer": "mod . __package__ = full_name"}, {"prompt": " \"\"\"\"\"\" _null_key = object ( ) class _LRUNode ( object ) : \"\"\"\"\"\" __slots__ = ( '' , '' , '' , '' , '' , '' ) def __init__ ( self , key , value , cleanup = None ) : self . prev = None self . next_key = _null_key self . key = key self . value = value self . cleanup = cleanup self . size = None def __repr__ ( self ) : if self . prev is None : prev_key = None else : prev_key = self . prev . key return '' % ( self . __class__ . __name__ , self . key , self . next_key , prev_key ) def run_cleanup ( self ) : if self . cleanup is not None : self . cleanup ( self . key , self . value ) self . cleanup = None self . value = None class LRUCache ( object ) : \"\"\"\"\"\" def __init__ ( self , max_cache = , after_cleanup_count = None ) : self . _cache = { } self . _most_recently_used = None self . _least_recently_used = None self . _update_max_cache ( max_cache , after_cleanup_count ) def __contains__ ( self , key ) : return key in self . _cache def __getitem__ ( self , key ) : cache = self . _cache node = cache [ key ] mru = self . _most_recently_used if node is mru : return node . value node_prev = node . prev next_key = node . next_key if next_key is _null_key : self . _least_recently_used = node_prev else : node_next = cache [ next_key ] node_next . prev = node_prev node_prev . next_key = next_key node . next_key = mru . key mru . prev = node self . _most_recently_used = node ", "answer": "node . prev = None"}, {"prompt": " from training . train import TrainModel from lasagne_extensions . nonlinearities import rectify from data_preparation import mnist from models import ADGMSSL import numpy as np def run_adgmssl_mnist ( ) : \"\"\"\"\"\" n_labeled = n_samples = n_batches = mnist_data = mnist . load_semi_supervised ( n_batches = n_batches , n_labeled = n_labeled , n_samples = n_samples , filter_std = , seed = , train_valid_combine = True ) n , n_x = mnist_data [ ] [ ] . shape bs = n / n_batches model = ADGMSSL ( n_x = n_x , n_a = , n_z = , n_y = , a_hidden = [ , ] , z_hidden = [ , ] , xhat_hidden = [ , ] , y_hidden = [ , ] , trans_func = rectify , x_dist = '' ) f_train , f_test , f_validate , train_args , test_args , validate_args = model . build_model ( * mnist_data ) train_args [ '' ] [ '' ] = bs train_args [ '' ] [ '' ] = n_samples train_args [ '' ] [ '' ] = * n train_args [ '' ] [ '' ] = ", "answer": "train_args [ '' ] [ '' ] = "}, {"prompt": " from django . core . management . base import NoArgsCommand ", "answer": "from rapidsms . models import Backend"}, {"prompt": " \"\"\"\"\"\" import __init__ as markdown class Processor : def __init__ ( self , markdown_instance = None ) : if markdown_instance : self . markdown = markdown_instance class Postprocessor ( Processor ) : \"\"\"\"\"\" ", "answer": "def run ( self , text ) :"}, {"prompt": " \"\"\"\"\"\" from contextlib import contextmanager from OpenGL . GL import * @ contextmanager def glSection ( type ) : glBegin ( type ) yield glEnd ( ) @ contextmanager def glMatrix ( ) : glPushMatrix ( ) yield glPopMatrix ( ) @ contextmanager def glModeMatrix ( type ) : glMatrixMode ( type ) glPushMatrix ( ) yield glMatrixMode ( type ) glPopMatrix ( ) @ contextmanager def attributes ( * glBits ) : for bit in glBits : glPushAttrib ( bit ) yield for bit in glBits : glPopAttrib ( ) @ contextmanager def enabled ( * glBits ) : for bit in glBits : glEnable ( bit ) yield for bit in glBits : glDisable ( bit ) @ contextmanager def disabled ( * glBits ) : for bit in glBits : glDisable ( bit ) yield for bit in glBits : glEnable ( bit ) @ contextmanager def overlays2D ( width , height , background_color ) : \"\"\"\"\"\" glDisable ( GL_LIGHTING ) glDisable ( GL_LIGHT0 ) glDisable ( GL_BLEND ) glEnable ( GL_SCISSOR_TEST ) with glModeMatrix ( GL_PROJECTION ) : yield glViewport ( , , width , height ) glDisable ( GL_SCISSOR_TEST ) glMatrixMode ( GL_MODELVIEW ) glLoadIdentity ( ) glEnable ( GL_LIGHTING ) glEnable ( GL_LIGHT0 ) glEnable ( GL_BLEND ) glClearColor ( * background_color ) def setup_overlay2D ( x , y , width , height ) : \"\"\"\"\"\" glMatrixMode ( GL_PROJECTION ) glLoadIdentity ( ) glScissor ( x , y , width , height ) glViewport ( x , y , width , height ) glOrtho ( x , x + width , y , y + height , - , ) glMatrixMode ( GL_MODELVIEW ) cyltrigs = [ , , , ] ; def notGlePolyCylinder ( points , color , radius ) : trigs = [ radius * x for x in cyltrigs ] ; if abs ( points [ ] [ ] - points [ ] [ ] ) > : with glSection ( GL_QUAD_STRIP ) : glNormal3f ( , , ) glVertex ( points [ ] [ ] , , radius ) glVertex ( points [ ] [ ] , , radius ) glNormal3f ( , cyltrigs [ ] , cyltrigs [ ] ) glVertex ( points [ ] [ ] , trigs [ ] , trigs [ ] ) glVertex ( points [ ] [ ] , trigs [ ] , trigs [ ] ) glNormal3f ( , cyltrigs [ ] , cyltrigs [ ] ) glVertex ( points [ ] [ ] , trigs [ ] , trigs [ ] ) glVertex ( points [ ] [ ] , trigs [ ] , trigs [ ] ) glNormal3f ( , cyltrigs [ ] , - cyltrigs [ ] ) glVertex ( points [ ] [ ] , trigs [ ] , - trigs [ ] ) glVertex ( points [ ] [ ] , trigs [ ] , - trigs [ ] ) glNormal3f ( , cyltrigs [ ] , - cyltrigs [ ] ) glVertex ( points [ ] [ ] , trigs [ ] , - trigs [ ] ) glVertex ( points [ ] [ ] , trigs [ ] , - trigs [ ] ) glNormal3f ( , , - ) glVertex ( points [ ] [ ] , , - radius ) glVertex ( points [ ] [ ] , , - radius ) glNormal3f ( , - cyltrigs [ ] , - cyltrigs [ ] ) glVertex ( points [ ] [ ] , - trigs [ ] , - trigs [ ] ) glVertex ( points [ ] [ ] , - trigs [ ] , - trigs [ ] ) glNormal3f ( , - cyltrigs [ ] , - cyltrigs [ ] ) glVertex ( points [ ] [ ] , - trigs [ ] , - trigs [ ] ) glVertex ( points [ ] [ ] , - trigs [ ] , - trigs [ ] ) glNormal3f ( , - cyltrigs [ ] , cyltrigs [ ] ) glVertex ( points [ ] [ ] , - trigs [ ] , trigs [ ] ) glVertex ( points [ ] [ ] , - trigs [ ] , trigs [ ] ) glNormal3f ( , - cyltrigs [ ] , cyltrigs [ ] ) glVertex ( points [ ] [ ] , - trigs [ ] , trigs [ ] ) glVertex ( points [ ] [ ] , - trigs [ ] , trigs [ ] ) glNormal3f ( , , ) glVertex ( points [ ] [ ] , , radius ) glVertex ( points [ ] [ ] , , radius ) elif abs ( points [ ] [ ] - points [ ] [ ] ) > : p1 = points [ ] [ ] p2 = points [ ] [ ] with glSection ( GL_QUAD_STRIP ) : glNormal3f ( , , ) glVertex ( , p1 , radius ) glVertex ( , p2 , radius ) glNormal3f ( cyltrigs [ ] , , cyltrigs [ ] ) glVertex ( trigs [ ] , p1 , trigs [ ] ) glVertex ( trigs [ ] , p2 , trigs [ ] ) glNormal3f ( cyltrigs [ ] , , cyltrigs [ ] ) glVertex ( trigs [ ] , p1 , trigs [ ] ) glVertex ( trigs [ ] , p2 , trigs [ ] ) glNormal3f ( cyltrigs [ ] , , - cyltrigs [ ] ) glVertex ( trigs [ ] , p1 , - trigs [ ] ) glVertex ( trigs [ ] , p2 , - trigs [ ] ) glNormal3f ( cyltrigs [ ] , , - cyltrigs [ ] ) glVertex ( trigs [ ] , p1 , - trigs [ ] ) glVertex ( trigs [ ] , p2 , - trigs [ ] ) glNormal3f ( , , - ) glVertex ( , p1 , - radius ) glVertex ( , p2 , - radius ) glNormal3f ( - cyltrigs [ ] , , - cyltrigs [ ] ) glVertex ( - trigs [ ] , p1 , - trigs [ ] ) glVertex ( - trigs [ ] , p2 , - trigs [ ] ) glNormal3f ( - cyltrigs [ ] , , - cyltrigs [ ] ) glVertex ( - trigs [ ] , p1 , - trigs [ ] ) glVertex ( - trigs [ ] , p2 , - trigs [ ] ) glNormal3f ( - cyltrigs [ ] , , cyltrigs [ ] ) glVertex ( - trigs [ ] , p1 , trigs [ ] ) glVertex ( - trigs [ ] , p2 , trigs [ ] ) glNormal3f ( - cyltrigs [ ] , , cyltrigs [ ] ) glVertex ( - trigs [ ] , p1 , trigs [ ] ) glVertex ( - trigs [ ] , p2 , trigs [ ] ) glNormal3f ( , , ) glVertex ( , p1 , radius ) glVertex ( , p2 , radius ) else : p1 = points [ ] [ ] p2 = points [ ] [ ] with glSection ( GL_QUAD_STRIP ) : glNormal3f ( , , ) glVertex ( , radius , p1 ) glVertex ( , radius , p2 ) glNormal3f ( cyltrigs [ ] , cyltrigs [ ] , ) glVertex ( trigs [ ] , trigs [ ] , p1 ) glVertex ( trigs [ ] , trigs [ ] , p2 ) glNormal3f ( cyltrigs [ ] , cyltrigs [ ] , ) glVertex ( trigs [ ] , trigs [ ] , p1 ) glVertex ( trigs [ ] , trigs [ ] , p2 ) glNormal3f ( cyltrigs [ ] , - cyltrigs [ ] , ) glVertex ( trigs [ ] , - trigs [ ] , p1 ) glVertex ( trigs [ ] , - trigs [ ] , p2 ) glNormal3f ( cyltrigs [ ] , - cyltrigs [ ] , ) glVertex ( trigs [ ] , - trigs [ ] , p1 ) glVertex ( trigs [ ] , - trigs [ ] , p2 ) glNormal3f ( , - , ) glVertex ( , - radius , p1 ) glVertex ( , - radius , p2 ) glNormal3f ( - cyltrigs [ ] , - cyltrigs [ ] , ) glVertex ( - trigs [ ] , - trigs [ ] , p1 ) glVertex ( - trigs [ ] , - trigs [ ] , p2 ) glNormal3f ( - cyltrigs [ ] , - cyltrigs [ ] , ) glVertex ( - trigs [ ] , - trigs [ ] , p1 ) glVertex ( - trigs [ ] , - trigs [ ] , p2 ) glNormal3f ( - cyltrigs [ ] , cyltrigs [ ] , ) glVertex ( - trigs [ ] , trigs [ ] , p1 ) glVertex ( - trigs [ ] , trigs [ ] , p2 ) glNormal3f ( - cyltrigs [ ] , cyltrigs [ ] , ) glVertex ( - trigs [ ] , trigs [ ] , p1 ) glVertex ( - trigs [ ] , trigs [ ] , p2 ) ", "answer": "glNormal3f ( , , )"}, {"prompt": " \"\"\"\"\"\" import sys from logging import warning def getModuleWhiteList ( ) : return ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\"\"\"\"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ", "answer": "\"\" ,"}, {"prompt": " import unittest from test . asserting . config_source import ConfigSourceAssertion from test . asserting . config_source import get_fixture_path from vint . linting . config . config_file_source import ConfigFileSource from vint . linting . level import Level FIXTURE_CONFIG_FILE = get_fixture_path ( '' ) class TestConfigFileSource ( ConfigSourceAssertion , unittest . TestCase ) : class ConcreteConfigFileSource ( ConfigFileSource ) : def get_file_path ( self , env ) : return FIXTURE_CONFIG_FILE def test_get_config_dict ( self ) : expected_config_dict = { '' : { '' : True , '' : Level . WARNING , '' : , } , '' : { '' : { '' : False , } , '' : { '' : True , } , } } config_source = self . initialize_config_source_with_env ( ", "answer": "TestConfigFileSource . ConcreteConfigFileSource )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import django_google_maps . fields class Migration ( migrations . Migration ) : dependencies = [ ", "answer": "]"}, {"prompt": " import os import sys msg = '''''' print ( msg ) msg = '''''' print ( msg ) fd = False compat = True sys . stdout . write ( '' ) if os . path . exists ( '' ) : print ( '' ) fd = True ", "answer": "else :"}, {"prompt": " import os from numpy import * from time import sleep def loadDataSet ( fileName ) : dataMat = [ ] ; labelMat = [ ] fr = open ( fileName ) for line in fr . readlines ( ) : lineArr = line . strip ( ) . split ( '' ) dataMat . append ( [ float ( lineArr [ ] ) , float ( lineArr [ ] ) ] ) labelMat . append ( float ( lineArr [ ] ) ) return dataMat , labelMat def selectJrand ( i , m ) : j = i while ( j == i ) : ", "answer": "j = int ( random . uniform ( , m ) )"}, {"prompt": " import atexit import platform import Queue import sys import threading import uuid from collections import deque from os import getenv from time import sleep , time from traceback import format_exc import click import requests from platformio import __version__ , app , exception , util from platformio . ide . projectgenerator import ProjectGenerator class TelemetryBase ( object ) : MACHINE_ID = str ( uuid . uuid5 ( uuid . NAMESPACE_OID , str ( uuid . getnode ( ) ) ) ) def __init__ ( self ) : self . _params = { } def __getitem__ ( self , name ) : return self . _params . get ( name , None ) def __setitem__ ( self , name , value ) : self . _params [ name ] = value def __delitem__ ( self , name ) : if name in self . _params : del self . _params [ name ] def get_cid ( self ) : cid = app . get_state_item ( \"\" ) if not cid : cid = self . MACHINE_ID app . set_state_item ( \"\" , cid ) return cid def send ( self , hittype ) : raise NotImplementedError ( ) class MeasurementProtocol ( TelemetryBase ) : TRACKING_ID = \"\" PARAMS_MAP = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } def __init__ ( self ) : TelemetryBase . __init__ ( self ) self [ '' ] = self [ '' ] = self . TRACKING_ID self [ '' ] = self . get_cid ( ) self [ '' ] = \"\" % click . get_terminal_size ( ) self . _prefill_screen_name ( ) self . _prefill_appinfo ( ) self . _prefill_custom_data ( ) def __getitem__ ( self , name ) : if name in self . PARAMS_MAP : name = self . PARAMS_MAP [ name ] return TelemetryBase . __getitem__ ( self , name ) def __setitem__ ( self , name , value ) : if name in self . PARAMS_MAP : name = self . PARAMS_MAP [ name ] TelemetryBase . __setitem__ ( self , name , value ) def _prefill_appinfo ( self ) : self [ '' ] = __version__ dpdata = [ ] dpdata . append ( \"\" % __version__ ) if app . get_session_var ( \"\" ) : dpdata . append ( \"\" % app . get_session_var ( \"\" ) ) if getenv ( \"\" ) : dpdata . append ( \"\" % getenv ( \"\" ) ) self [ '' ] = \"\" . join ( dpdata ) def _prefill_custom_data ( self ) : self [ '' ] = util . get_systype ( ) self [ '' ] = \"\" % ( platform . python_version ( ) , platform . platform ( ) ) self [ '' ] = ( if app . get_setting ( \"\" ) or app . get_session_var ( \"\" ) else ) def _prefill_screen_name ( self ) : self [ '' ] = \"\" . join ( [ str ( s ) . lower ( ) for s in sys . argv [ : ] ] ) if not app . get_session_var ( \"\" ) : return ctx_args = app . get_session_var ( \"\" ) . args args = [ str ( s ) . lower ( ) for s in ctx_args if not str ( s ) . startswith ( \"\" ) ] if not args : return if args [ ] in ( \"\" , \"\" , \"\" , \"\" ) : cmd_path = args [ : ] else : cmd_path = args [ : ] self [ '' ] = \"\" . join ( [ p . title ( ) for p in cmd_path ] ) def send ( self , hittype ) : if not app . get_setting ( \"\" ) : return self [ '' ] = hittype if \"\" in self . _params and isinstance ( self [ '' ] , float ) : self [ '' ] = int ( ( time ( ) - self [ '' ] ) * ) MPDataPusher ( ) . push ( self . _params ) @ util . singleton class MPDataPusher ( object ) : MAX_WORKERS = def __init__ ( self ) : self . _queue = Queue . LifoQueue ( ) self . _failedque = deque ( ) self . _http_session = requests . Session ( ) self . _http_offline = False self . _workers = [ ] def push ( self , item ) : if self . _http_offline : if \"\" not in item : item [ '' ] = time ( ) self . _failedque . append ( item ) return self . _queue . put ( item ) self . _tune_workers ( ) def in_wait ( self ) : return self . _queue . unfinished_tasks def get_items ( self ) : items = list ( self . _failedque ) try : while True : items . append ( self . _queue . get_nowait ( ) ) except Queue . Empty : pass return items def _tune_workers ( self ) : for i , w in enumerate ( self . _workers ) : if not w . is_alive ( ) : del self . _workers [ i ] need_nums = min ( self . _queue . qsize ( ) , self . MAX_WORKERS ) active_nums = len ( self . _workers ) if need_nums <= active_nums : return for i in range ( need_nums - active_nums ) : t = threading . Thread ( target = self . _worker ) t . daemon = True t . start ( ) self . _workers . append ( t ) ", "answer": "def _worker ( self ) :"}, {"prompt": " import sys from django . conf import settings from django . contrib import admin from django . contrib . admin . widgets import AdminTextInputWidget from django . core . exceptions import ImproperlyConfigured from django . utils . html import escape from django . utils . translation import ugettext_lazy as _ from fluent_comments import appsettings from . compat import get_model as get_comments_model , BASE_APP if appsettings . USE_THREADEDCOMMENTS : if not hasattr ( settings , '' ) or settings . COMMENTS_APP == '' : raise ImproperlyConfigured ( \"\" ) from threadedcomments . admin import ThreadedCommentsAdmin as CommentsAdminBase else : if BASE_APP == '' : from django . contrib . comments . admin import CommentsAdmin as CommentsAdminBase elif BASE_APP == '' : from django_comments . admin import CommentsAdmin as CommentsAdminBase else : raise NotImplementedError ( ) class FluentCommentsAdmin ( CommentsAdminBase ) : \"\"\"\"\"\" fieldsets = [ ( _ ( '' ) , { '' : ( '' , '' , '' , '' , '' , '' , ) } ) , ( _ ( '' ) , { '' : ( '' , '' , ) } , ) , ( _ ( '' ) , { '' : ( '' , '' ) } ) , ] list_display = ( '' , '' , '' , '' , '' , '' ) readonly_fields = ( '' , '' , '' , '' , ) if appsettings . USE_THREADEDCOMMENTS : fieldsets [ ] [ ] [ '' ] = ( '' , '' , '' , '' , '' , '' , '' , ) fieldsets . insert ( , ( _ ( '' ) , { '' : ( '' , ) } ) ) raw_id_fields = ( '' , ) def get_queryset ( self , request ) : return super ( FluentCommentsAdmin , self ) . get_queryset ( request ) . select_related ( '' ) def object_link ( self , comment ) : try : object = comment . content_object except AttributeError : return '' if sys . version_info [ ] >= : title = str ( object ) else : title = unicode ( object ) if object : return u'' . format ( escape ( object . get_absolute_url ( ) ) , escape ( title ) ) else : return u'' object_link . short_description = _ ( \"\" ) object_link . allow_tags = True def user_name_col ( self , comment ) : if comment . user_name : return comment . user_name elif comment . user_id : if sys . version_info [ ] >= : return str ( comment . user ) else : ", "answer": "return unicode ( comment . user )"}, {"prompt": " __author__ = '' from pypet . tests . testutils . ioutils import run_suite , discover_tests , TEST_IMPORT_ERROR , parse_args tests_include = set ( ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) ) big_suite_1 = discover_tests ( lambda class_name , test_name , tags : class_name in tests_include ) tests_include = set ( ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) ) big_suite_2 = discover_tests ( lambda class_name , test_name , tags : class_name in tests_include ) tests_include = set ( ( '' , '' , '' , '' , '' , '' , '' , '' ) ) big_suite_3 = discover_tests ( lambda class_name , test_name , tags : class_name in tests_include ) tests_include = set ( ( '' , '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " _ID = '' API = '' API_CALL_TIMEOUT = '' API_VERSION = '' API_VERSION_MAXIMUM = '' API_VERSION_MINIMUM = '' AREA = '' AREA_MAX = '' BBOX = '' BOUNDS = '' CFGSLAB = '' CFGVERSION = CHANGESET = '' CHANGESETS = '' CHANGESETS_INLINE_SIZE = '' CHANGESETS_PER_SLAB = '' CHANGESETS_MAX = '' CONFIGURATION_SCHEMA_VERSION = '' CONTENT_TYPE = '' COUCHDB = '' DATASTORE = '' DATASTORE_BACKEND = '' DATASTORE_CONFIG = '' DATASTORE_ENCODING = '' DBHOST = '' DBJOB_ADDELEM = '' DBJOB_QUIT = '' DBNAME = '' DBNAME_SUFFIXES = '' DBPORT = '' DBURL = '' DEFAULT = '' ELEMENT = '' FRONT_END = '' GENERATOR = '' GEODOC = '' GEODOC_LRU_SIZE = '' GEODOC_LRU_THREADS = '' GEOHASH_LENGTH = '' ID = '' JSON = '' K = '' LAT = '' LAT_MAX = + LAT_MIN = - LON = '' LON_MAX = + LON_MIN = - MAXIMUM = '' MAXIMUM_ELEMENTS = '' MAXGHLAT = MAXLAT = '' MAXLON = '' MEMBASE = '' MEMBASE_MAX_VALUE_LENGTH = * * MEMBER = '' MEMBERS = '' MINIMUM = '' MINLAT = '' MINLON = '' ND = '' ", "answer": "NODE = ''"}, {"prompt": " class HttpException ( Exception ) : \"\"\"\"\"\" ", "answer": "def __init__ ( self , msg , res ) :"}, {"prompt": " import os import sys sys . path . insert ( , os . path . abspath ( '' ) ) extensions = [ '' , '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' from kolla . version import version_info as kolla_version release = kolla_version . version_string_with_vcs ( ) version = kolla_version . canonical_version_string ( ) add_function_parentheses = True add_module_names = True pygments_style = '' htmlhelp_basename = '' % project latex_documents = [ ( '' , ", "answer": "'' % project ,"}, {"prompt": " from django . conf . urls import include from django . conf . urls import url ", "answer": "from openstack_dashboard . dashboards . admin . hypervisors . compute import urls as compute_urls"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " import os from awscli . testutils import BaseAWSCommandParamsTest , FileCreator , mock class TestUploadBuild ( BaseAWSCommandParamsTest ) : prefix = '' def setUp ( self ) : super ( TestUploadBuild , self ) . setUp ( ) self . files = FileCreator ( ) def tearDown ( self ) : super ( TestUploadBuild , self ) . tearDown ( ) self . files . remove_all ( ) def test_upload_build ( self ) : self . files . create_file ( '' , '' ) cmdline = self . prefix cmdline += '' cmdline += '' % self . files . rootdir self . parsed_responses = [ { '' : { '' : '' } } , { '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' , '' : '' } } , { } ] stdout , stderr , rc = self . run_cmd ( cmdline , expected_rc = ) self . assertEqual ( len ( self . operations_called ) , ) self . assertEqual ( self . operations_called [ ] [ ] . name , '' ) self . assertEqual ( self . operations_called [ ] [ ] , { '' : '' , '' : '' } ) self . assertEqual ( self . operations_called [ ] [ ] . name , '' ) self . assertEqual ( self . operations_called [ ] [ ] , { '' : '' } ) self . assertEqual ( self . operations_called [ ] [ ] . name , '' ) self . assertEqual ( self . operations_called [ ] [ ] , { '' : mock . ANY , '' : '' , '' : '' } ) self . assertIn ( '' % self . files . rootdir , stdout ) self . assertIn ( '' , stdout ) def test_upload_build_with_empty_directory ( self ) : cmdline = self . prefix cmdline += '' cmdline += '' % self . files . rootdir self . parsed_responses = [ { '' : { '' : '' } } , { '' : { ", "answer": "'' : '' ,"}, {"prompt": " from solum . objects import base class Operation ( base . CrudMixin ) : ", "answer": "VERSION = ''"}, {"prompt": " \"\"\"\"\"\" import socket import dns . ipv4 import dns . ipv6 AF_INET = socket . AF_INET try : AF_INET6 = socket . AF_INET6 except AttributeError : AF_INET6 = def inet_pton ( family , text ) : \"\"\"\"\"\" if family == AF_INET : return dns . ipv4 . inet_aton ( text ) elif family == AF_INET6 : return dns . ipv6 . inet_aton ( text ) else : raise NotImplementedError def inet_ntop ( family , address ) : \"\"\"\"\"\" ", "answer": "if family == AF_INET :"}, {"prompt": " \"\"\"\"\"\" ", "answer": "TokenKinds = ["}, {"prompt": " from . import utils from . import mp_utils from . import features from . features import Features from . import np_divs from . np_divs import estimate_divs from . import sdm from . sdm import SDC , NuSDC , SDR , NuSDR , OneClassSDM try : from numpy . testing import nosetester test = nosetester . NoseTester ( ) . test del nosetester ", "answer": "except ImportError :"}, {"prompt": " import socket , traceback , threading , queue from . log import log class Interop : def __init__ ( self , on_recv , on_connect , on_not_connected ) : self . readWorker = None self . readWorkerStopEvent = None self . readBuffer = bytes ( ) self . socket = None self . on_connect = on_connect self . on_recv = on_recv self . on_not_connected = on_not_connected self . sendWorker = None self . sendQueue = queue . Queue ( ) self . sendDataEvent = None self . sendWorkerStopEvent = None def isConnected ( self ) : isConnected = self . socket != None return isConnected def connect ( self ) : try : host = \"\" port = log ( ) . info ( \"\" % ( host , port ) ) tmpSocket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) tmpSocket . connect ( ( host , port ) ) except OSError : log ( ) . info ( \"\" % ( host , port ) ) tmpSocket . close ( ) return self . socket = tmpSocket self . startPullMessages ( ) self . startSendMessages ( ) self . on_connect ( ) log ( ) . info ( \"\" ) def send ( self , type , msg ) : if not self . isConnected ( ) : self . on_not_connected ( ) if not self . isConnected ( ) : return self . sendQueue . put ( ( type , msg ) , True ) self . sendDataEvent . set ( ) def startSendMessages ( self ) : self . sendDataEvent = threading . Event ( ) self . sendWorkerStopEvent = threading . Event ( ) self . sendWorker = threading . Thread ( target = self . sendMessages ) self . sendWorker . daemon = True self . sendWorker . start ( ) def sendMessages ( self ) : try : while not self . sendWorkerStopEvent . is_set ( ) : while not self . sendQueue . empty ( ) : msgTupple = self . sendQueue . get_nowait ( ) type = msgTupple [ ] msg = msgTupple [ ] msgInBytes = bytes ( type + \"\" + str ( len ( msg ) ) + \"\" + msg , \"\" ) self . socket . sendall ( msgInBytes ) self . sendDataEvent . wait ( ) self . sendDataEvent . clear ( ) except : self . disconnect ( ) def stopSendMessages ( self ) : self . sendWorkerStopEvent . set ( ) self . sendDataEvent . set ( ) def startPullMessages ( self ) : self . readWorkerStopEvent = threading . Event ( ) self . readWorker = threading . Thread ( target = self . pullMessages ) self . readWorker . daemon = True self . readWorker . start ( ) def stopPullMessages ( self ) : ", "answer": "self . readWorkerStopEvent . set ( )"}, {"prompt": " \"\"\"\"\"\" import logging from homeassistant . const import CONF_NAME , DEVICE_DEFAULT_NAME , TEMP_FAHRENHEIT from homeassistant . helpers . entity import Entity _LOGGER = logging . getLogger ( __name__ ) REQUIREMENTS = [ '' '' '' ] def setup_platform ( hass , config , add_devices_callback , discovery_info = None ) : \"\"\"\"\"\" from temperusb . temper import TemperHandler temp_unit = hass . config . temperature_unit name = config . get ( CONF_NAME , DEVICE_DEFAULT_NAME ) temper_devices = TemperHandler ( ) . get_devices ( ) add_devices_callback ( [ TemperSensor ( dev , temp_unit , name + '' + str ( idx ) ) for idx , dev in enumerate ( temper_devices ) ] ) class TemperSensor ( Entity ) : \"\"\"\"\"\" def __init__ ( self , temper_device , temp_unit , name ) : \"\"\"\"\"\" self . temper_device = temper_device self . temp_unit = temp_unit self . current_value = None self . _name = name @ property def name ( self ) : \"\"\"\"\"\" return self . _name @ property def state ( self ) : \"\"\"\"\"\" return self . current_value @ property def unit_of_measurement ( self ) : \"\"\"\"\"\" return self . temp_unit def update ( self ) : \"\"\"\"\"\" try : format_str = ( '' if self . temp_unit == TEMP_FAHRENHEIT ", "answer": "else '' )"}, {"prompt": " from director import atlasdriver from director import consoleapp from PythonQt import QtCore , QtGui from collections import namedtuple ", "answer": "atlasDriver = atlasdriver . init ( )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " \"\"\"\"\"\" \"\"\"\"\"\" import socket import struct import sys PROXY_TYPE_SOCKS4 = PROXY_TYPE_SOCKS5 = PROXY_TYPE_HTTP = _defaultproxy = None _orgsocket = socket . socket class ProxyError ( Exception ) : pass class GeneralProxyError ( ProxyError ) : pass class Socks5AuthError ( ProxyError ) : pass class Socks5Error ( ProxyError ) : pass class Socks4Error ( ProxyError ) : pass class HTTPError ( ProxyError ) : pass _generalerrors = ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) _socks5errors = ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) _socks5autherrors = ( \"\" , \"\" , \"\" , \"\" , \"\" ) _socks4errors = ( \"\" , \"\" , \"\" , \"\" , \"\" ) def setdefaultproxy ( proxytype = None , addr = None , port = None , rdns = True , username = None , password = None ) : \"\"\"\"\"\" global _defaultproxy _defaultproxy = ( proxytype , addr , port , rdns , username , password ) def wrapmodule ( module ) : \"\"\"\"\"\" if _defaultproxy != None : module . socket . socket = socksocket else : raise GeneralProxyError ( ( , \"\" ) ) class socksocket ( socket . socket ) : \"\"\"\"\"\" def __init__ ( self , family = socket . AF_INET , type = socket . SOCK_STREAM , proto = , _sock = None ) : _orgsocket . __init__ ( self , family , type , proto , _sock ) if _defaultproxy != None : self . __proxy = _defaultproxy else : self . __proxy = ( None , None , None , None , None , None ) self . __proxysockname = None self . __proxypeername = None def __recvall ( self , count ) : \"\"\"\"\"\" data = self . recv ( count ) while len ( data ) < count : d = self . recv ( count - len ( data ) ) if not d : raise GeneralProxyError ( ( , \"\" ) ) data = data + d return data def setproxy ( self , proxytype = None , addr = None , port = None , rdns = True , username = None , password = None ) : \"\"\"\"\"\" self . __proxy = ( proxytype , addr , port , rdns , username , password ) def __negotiatesocks5 ( self , destaddr , destport ) : \"\"\"\"\"\" if ( self . __proxy [ ] != None ) and ( self . __proxy [ ] != None ) : self . sendall ( struct . pack ( '' , , , , ) ) else : self . sendall ( struct . pack ( '' , , , ) ) chosenauth = self . __recvall ( ) if chosenauth [ : ] != chr ( ) . encode ( ) : self . close ( ) raise GeneralProxyError ( ( , _generalerrors [ ] ) ) if chosenauth [ : ] == chr ( ) . encode ( ) : pass elif chosenauth [ : ] == chr ( ) . encode ( ) : self . sendall ( chr ( ) . encode ( ) + chr ( len ( self . __proxy [ ] ) ) + self . __proxy [ ] + chr ( len ( self . __proxy [ ] ) ) + self . __proxy [ ] ) authstat = self . __recvall ( ) if authstat [ : ] != chr ( ) . encode ( ) : self . close ( ) raise GeneralProxyError ( ( , _generalerrors [ ] ) ) if authstat [ : ] != chr ( ) . encode ( ) : self . close ( ) raise Socks5AuthError ( ( , _socks5autherrors [ ] ) ) else : self . close ( ) if chosenauth [ ] == chr ( ) . encode ( ) : raise Socks5AuthError ( ( , _socks5autherrors [ ] ) ) else : raise GeneralProxyError ( ( , _generalerrors [ ] ) ) req = struct . pack ( '' , , , ) try : ipaddr = socket . inet_aton ( destaddr ) req = req + chr ( ) . encode ( ) + ipaddr except socket . error : if self . __proxy [ ] : ipaddr = None req = req + chr ( ) . encode ( ) + chr ( len ( destaddr ) ) . encode ( ) + destaddr else : ", "answer": "ipaddr = socket . inet_aton ( socket . gethostbyname ( destaddr ) )"}, {"prompt": " import logging from google . appengine . api import xmpp from django . core . urlresolvers import reverse from . import models from . import decorators as deco from . responses import HttpTextResponse def get_chat_status ( account ) : try : presence = xmpp . get_presence ( account . email ) return '' if presence else '' except Exception as err : logging . error ( '' , err ) return '' % err @ deco . require_methods ( '' ) def incoming_chat ( request ) : \"\"\"\"\"\" try : msg = xmpp . Message ( request . POST ) except xmpp . InvalidMessageError , err : logging . warn ( '' % err ) return HttpTextResponse ( '' ) sts = msg . reply ( '' ) logging . debug ( '' , sts ) return HttpTextResponse ( '' ) def must_invite ( account ) : logging . info ( '' , account . email ) try : ", "answer": "xmpp . send_invite ( account . email )"}, {"prompt": " import os , sys ", "answer": "sys . path . insert ( , os . path . join ( sys . path [ ] , '' ) )"}, {"prompt": " from django import forms class CollectionSelectForm ( forms . Form ) : collections = forms . MultipleChoiceField ( ) def __init__ ( self , group_object = None , extra_fields = None , * args , ** kwargs ) : ", "answer": "super ( CollectionSelectForm , self ) . __init__ ( * args , ** kwargs )"}, {"prompt": " import six import os from gunstar . testing import TestCase from gunstar . app import Application from gunstar . http import RequestHandler PROJECT_PATH = os . path . dirname ( os . path . abspath ( __file__ ) ) class Handler ( RequestHandler ) : def get ( self ) : self . response . write ( '' . format ( self . request . method ) ) def post ( self ) : self . response . write ( '' . format ( self . request . method ) ) def put ( self ) : self . response . write ( '' . format ( self . request . method ) ) def delete ( self ) : self . response . write ( '' . format ( self . request . method ) ) def options ( self ) : self . response . write ( '' . format ( self . request . method ) ) def head ( self ) : self . response . write ( '' . format ( self . request . method ) ) class SessionHandler ( RequestHandler ) : def get ( self ) : if self . session . get ( '' ) : self . response . write ( '' . format ( self . session . get ( '' ) ) ) else : self . session . set ( '' , '' ) self . session . save ( ) self . response . write ( '' ) class SessionHandler2 ( RequestHandler ) : def get ( self ) : self . session . clear ( ) self . session . save ( ) self . response . write ( '' ) class SessionHandler3 ( RequestHandler ) : def get ( self ) : self . render_template ( '' , name = '' ) routes = ( ( '' , Handler , '' ) , ( '' , SessionHandler , '' ) , ( '' , SessionHandler2 , '' ) , ( '' , SessionHandler3 , '' ) , ) class Settings ( object ) : SECRET_KEY = '' TEMPLATE_PATH = os . path . join ( PROJECT_PATH , '' ) class ClientTest ( TestCase ) : def get_app ( self ) : return Application ( routes = routes , config = Settings ) def test_get ( self ) : resp = self . client . get ( '' ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path_qs , '' ) resp = self . client . get ( '' , data = { '' : '' } ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path_qs , '' ) resp = self . client . get ( '' , headers = { '' : '' } ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . headers [ '' ] , '' ) def test_head ( self ) : resp = self . client . head ( '' ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path_qs , '' ) resp = self . client . head ( '' , data = { '' : '' } ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path_qs , '' ) resp = self . client . head ( '' , headers = { '' : '' } ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . headers [ '' ] , '' ) def test_post ( self ) : resp = self . client . post ( '' ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . content_type , '' ) resp = self . client . post ( '' , data = { '' : '' } ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . body , six . b ( '' ) ) self . assertEqual ( resp . request_started . content_type , '' ) resp = self . client . post ( '' , headers = { '' : '' } ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . headers [ '' ] , '' ) self . assertEqual ( resp . request_started . content_type , '' ) resp = self . client . post ( '' , content_type = '' ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . content_type , '' ) def test_put ( self ) : resp = self . client . put ( '' ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . content_type , '' ) resp = self . client . put ( '' , data = { '' : '' } ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . body , six . b ( '' ) ) self . assertEqual ( resp . request_started . content_type , '' ) resp = self . client . put ( '' , headers = { '' : '' } ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . headers [ '' ] , '' ) self . assertEqual ( resp . request_started . content_type , '' ) resp = self . client . put ( '' , content_type = '' ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . content_type , '' ) def test_delete ( self ) : resp = self . client . delete ( '' ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . content_type , '' ) resp = self . client . delete ( '' , data = { '' : '' } ) self . assertEqual ( resp . status_code , ) self . assertEqual ( resp . request_started . method , '' ) self . assertEqual ( resp . request_started . path , '' ) self . assertEqual ( resp . request_started . body , six . b ( '' ) ) self . assertEqual ( resp . request_started . content_type , '' ) resp = self . client . delete ( '' , headers = { '' : '' } ) self . assertEqual ( resp . status_code , ) ", "answer": "self . assertEqual ( resp . request_started . method , '' )"}, {"prompt": " import unittest from bubbles import * class GraphTestCase ( unittest . TestCase ) : def test_basic ( self ) : g = Graph ( ) g . add ( Node ( \"\" ) , \"\" ) g . add ( Node ( \"\" ) , \"\" ) g . add ( Node ( \"\" ) , \"\" ) self . assertEqual ( , len ( g . nodes ) ) g . connect ( \"\" , \"\" ) sources = g . sources ( \"\" ) self . assertEqual ( , len ( sources ) ) self . assertTrue ( isinstance ( sources [ \"\" ] , Node ) ) self . assertEqual ( \"\" , sources [ \"\" ] . opname ) ", "answer": "def test_ports ( self ) :"}, {"prompt": " __author__ = '' import subprocess __child_subprocesses__ = [ ] def create_subprocess ( command , ** kwargs ) : child_process = subprocess . Popen ( command , ** kwargs ) global __child_subprocesses__ ", "answer": "__child_subprocesses__ . append ( child_process )"}, {"prompt": " import solum from solum . common import context from solum . common import trace_data from solum . tests import base solum . TLS . trace = trace_data . TraceData ( ) CONTEXT = context . RequestContext ( auth_token = '' , user = '' , tenant = '' , domain = '' , user_domain = '' , project_domain = '' , is_admin = False , read_only = False , request_id = '' , user_name = '' , roles = '' , auth_url = '' , auth_token_info = '' ) class TestTraceData ( base . BaseTestCase ) : \"\"\"\"\"\" def test_auto_clear ( self ) : \"\"\"\"\"\" solum . TLS . trace . auto_clear = True solum . TLS . trace . auto_clear = False try : solum . TLS . trace . auto_clear = '' except AssertionError : pass else : self . assertTrue ( False ) def test_import_context ( self ) : \"\"\"\"\"\" solum . TLS . trace . clear ( ) solum . TLS . trace . import_context ( CONTEXT ) ", "answer": "self . assertEqual ("}, {"prompt": " \"\"\"\"\"\" import os BASE_DIR = os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = [ ] INSTALLED_APPS = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , ) MIDDLEWARE_CLASSES = ( '' , '' , '' , '' , '' , '' , '' , '' , ) ROOT_URLCONF = '' TEMPLATES = [ { ", "answer": "'' : '' ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) ", "answer": "result . template = \"\""}, {"prompt": " import os from platform import python_version_tuple from setuptools import setup import sys requirements = [ '' , '' , '' ] test_requirements = [ '' , '' ] ( major , minor , rev ) = python_version_tuple ( ) if float ( '' % ( major , minor ) ) < : requirements . append ( '' ) test_requirements . append ( '' ) if hasattr ( sys , '' ) : base_path = '' else : base_path = '' data_files = { '' % base_path : [ '' , '' , '' ] , '' % base_path : [ '' ] , '' % base_path : [ '' ] } with open ( '' , '' ) as handle : for path in data_files : for filename in data_files [ path ] : handle . write ( '' % filename ) setup ( name = '' , version = '' , description = ( \"\" \"\" ) , long_description = ( '' '' '' '' ) , classifiers = [ '' , '' , '' , ] , keywords = '' , author = '' , author_email = '' , url = '' , license = open ( '' ) . read ( ) , packages = [ '' , '' , '' , '' , '' , '' ] , install_requires = requirements , extras_require = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } , test_suite = '' , tests_require = test_requirements , data_files = [ ( key , data_files [ key ] ) for key in data_files . keys ( ) ] , ", "answer": "entry_points = dict ( console_scripts = [ '' ,"}, {"prompt": " \"\"\"\"\"\" from . import ast from . import util from . tiler import ASTPattern , SimplePattern , tile EQUALITY = ( \"\" , \"\" ) INEQUALITY = ( \"\" , ) def canonicalize ( node ) : \"\"\"\"\"\" def replace_func ( pattern , n ) : l_literal = isinstance ( n . left , ast . Literal ) r_literal = isinstance ( n . right , ast . Literal ) if not l_literal and r_literal : n . reverse ( ) elif l_literal and r_literal : if n . left . static and not n . right . static : n . reverse ( ) elif not n . left . static and not n . right . static and n . left . value > n . right . value : n . reverse ( ) elif n . left . static and n . right . static and n . left . value > n . right . value : n . reverse ( ) p = SimplePattern ( \"\" ) return tile ( node , [ p ] , replace_func ) def select_rewrite_expression ( name , exprs ) : \"\"\"\"\"\" if name [ ] == \"\" : values = [ e . right . value for e in exprs ] filter_using = util . mode ( values ) for e in exprs : if e . right . value == filter_using : return e elif name [ ] == \"\" : is_static = name [ ] [ ] == \"\" values = [ e . right . value for e in exprs ] if is_static : filter_using = util . median ( values ) else : filter_using = util . mode ( values ) ", "answer": "for e in exprs :"}, {"prompt": " import sys , inspect from django import VERSION as django_version if django_version >= ( , , ) : import json else : from django . utils import simplejson as json from exceptions import ServiceException def servicemethod ( * args , ** kwargs ) : \"\"\"\"\"\" options = { '' : None , '' : None , '' : True , '' : True } method = ( ( len ( args ) == ) and callable ( args [ ] ) ) and args [ ] or None if method is None : options . update ( { '' : bool ( args ) and args [ ] or kwargs . pop ( '' , None ) , '' : ( len ( args ) >= ) and args [ ] or kwargs . pop ( '' , None ) , '' : kwargs . pop ( '' , True ) , '' : kwargs . pop ( '' , True ) , } ) else : options [ '' ] = method . __name__ method . __servicemethod__ = options def method_with_args_wrapper ( method ) : \"\"\"\"\"\" if options [ '' ] is None : options [ '' ] = method . __name__ method . __servicemethod__ = options if options [ '' ] is not None : options [ '' ] . service . add_method ( method ) return method return method or method_with_args_wrapper class BaseService ( object ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" self . methods = { } self . _store = None def _get_store ( self ) : \"\"\"\"\"\" return self . _store def _set_store ( self , store ) : \"\"\"\"\"\" for method in self . methods . values ( ) : method . __servicemethod__ [ '' ] = store self . _store = store store = property ( _get_store , _set_store ) def _get_method_args ( self , method , request , params ) : \"\"\"\"\"\" idx = if method . __servicemethod__ [ '' ] : params . insert ( idx , method . __servicemethod__ [ '' ] ) idx += if method . __servicemethod__ [ '' ] : params . insert ( idx , request ) return params def add_method ( self , method , name = None , request_arg = True , store_arg = True ) : \"\"\"\"\"\" if hasattr ( method , '' ) : options = method . __servicemethod__ else : options = { '' : name or method . __name__ , '' : self . store , '' : request_arg , '' : store_arg } method . __servicemethod__ = options self . methods [ options [ '' ] ] = method def get_method ( self , name ) : \"\"\"\"\"\" try : return self . methods [ name ] except KeyError : raise ServiceException ( '' % name ) def list_methods ( self ) : \"\"\"\"\"\" return self . methods . keys ( ) ", "answer": "def process_request ( self , request ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals __all__ = ( '' , '' , '' , ) class LayoutDimension ( object ) : \"\"\"\"\"\" def __init__ ( self , min = None , max = None , weight = , preferred = None ) : assert isinstance ( weight , int ) and weight > self . min_specified = min is not None self . max_specified = max is not None self . preferred_specified = preferred is not None if min is None : min = if max is None : max = ** if preferred is None : preferred = min self . min = min self . max = max self . preferred = preferred self . weight = weight if self . preferred < self . min : self . preferred = self . min if self . preferred > self . max : self . preferred = self . max @ classmethod def exact ( cls , amount ) : \"\"\"\"\"\" return cls ( min = amount , max = amount , preferred = amount ) def __repr__ ( self ) : return '' % ( self . min , self . max , self . preferred , self . weight ) def __add__ ( self , other ) : return sum_layout_dimensions ( [ self , other ] ) def sum_layout_dimensions ( dimensions ) : \"\"\"\"\"\" min = sum ( [ d . min for d in dimensions if d . min is not None ] ) max = sum ( [ d . max for d in dimensions if d . max is not None ] ) preferred = sum ( [ d . preferred for d in dimensions ] ) return LayoutDimension ( min = min , max = max , preferred = preferred ) def max_layout_dimensions ( dimensions ) : \"\"\"\"\"\" min_ = max ( [ d . min for d in dimensions if d . min is not None ] ) max_ = max ( [ d . max for d in dimensions if d . max is not None ] ) ", "answer": "preferred = max ( [ d . preferred for d in dimensions ] )"}, {"prompt": " from __future__ import absolute_import , print_function , division import numpy import theano from theano import Op , Apply from theano . tensor import TensorType from theano . gof . type import CDataType from nose . plugins . skip import SkipTest class ProdOp ( Op ) : __props__ = ( ) def make_node ( self , i ) : ", "answer": "return Apply ( self , [ i ] , [ CDataType ( '' , '' ) ( ) ] )"}, {"prompt": " \"\"\"\"\"\" import types import unittest from test import test_support class Old : pass class New ( object ) : pass old = Old ( ) new = New ( ) class TestDescrTestCase ( unittest . TestCase ) : def test_class_dict_is_copy ( self ) : class FooMeta ( type ) : def __new__ ( meta , name , bases , class_dict ) : cls = type . __new__ ( meta , name , bases , class_dict ) self . assert_ ( '' not in class_dict ) cls . foo = '' self . assert_ ( '' not in class_dict ) return cls class Foo ( object ) : __metaclass__ = FooMeta def test_descr___get__ ( self ) : class Foo ( object ) : __slots__ = '' def hello ( self ) : pass def hi ( self ) : pass hi = staticmethod ( hi ) foo = Foo ( ) foo . bar = '' self . assertEqual ( Foo . bar . __get__ ( foo ) , '' ) self . assertEqual ( Foo . bar . __get__ ( None , Foo ) , Foo . bar ) bound = Foo . hello . __get__ ( foo ) self . assert_ ( isinstance ( bound , types . MethodType ) ) self . assert_ ( bound . im_self is foo ) self . assertEqual ( Foo . hello . __get__ ( None , Foo ) , Foo . hello ) bound = Foo . hi . __get__ ( foo ) self . assert_ ( isinstance ( bound , types . MethodType ) ) self . assert_ ( bound . im_self is foo ) unbound = Foo . hi . __get__ ( None , foo ) self . assert_ ( isinstance ( unbound , types . MethodType ) ) self . assert_ ( unbound . im_self is None ) def test_ints ( self ) : class C ( int ) : pass try : foo = int ( None ) except TypeError : pass else : self . assert_ ( False , \"\" ) try : foo = C ( None ) except TypeError : pass else : self . assert_ ( False , \"\" ) def test_raising_custom_attribute_error ( self ) : class RaisesCustomMsg ( object ) : def __get__ ( self , instance , type ) : raise AttributeError ( \"\" ) class CustomAttributeError ( AttributeError ) : pass class RaisesCustomErr ( object ) : def __get__ ( self , instance , type ) : raise CustomAttributeError class Foo ( object ) : custom_msg = RaisesCustomMsg ( ) custom_err = RaisesCustomErr ( ) self . assertRaises ( CustomAttributeError , lambda : Foo ( ) . custom_err ) try : Foo ( ) . custom_msg self . assert_ ( False ) except AttributeError , e : self . assertEquals ( \"\" , str ( e ) ) class SubclassDescrTestCase ( unittest . TestCase ) : def test_subclass_cmp_right_op ( self ) : class B ( int ) : def __ge__ ( self , other ) : return \"\" def __le__ ( self , other ) : return \"\" self . assertEqual ( B ( ) >= , \"\" ) self . assertEqual ( >= B ( ) , \"\" ) class C ( object ) : def __ge__ ( self , other ) : return \"\" def __le__ ( self , other ) : return \"\" self . assertEqual ( C ( ) >= , \"\" ) self . assertEqual ( >= C ( ) , \"\" ) class D ( C ) : def __ge__ ( self , other ) : return \"\" def __le__ ( self , other ) : return \"\" self . assertEqual ( D ( ) >= C ( ) , \"\" ) self . assertEqual ( C ( ) >= D ( ) , \"\" ) class E ( C ) : pass self . assertEqual ( E . __le__ , C . __le__ ) self . assertEqual ( E ( ) >= , \"\" ) self . assertEqual ( >= E ( ) , \"\" ) self . assertEqual ( E ( ) >= C ( ) , \"\" ) self . assertEqual ( C ( ) >= E ( ) , \"\" ) def test_subclass_binop ( self ) : def raises ( exc , expected , callable , * args ) : try : callable ( * args ) except exc , msg : if str ( msg ) != expected : self . assert_ ( False , \"\" % ( str ( msg ) , expected ) ) else : self . assert_ ( False , \"\" % exc ) class B ( object ) : pass class C ( object ) : def __radd__ ( self , o ) : return '' % ( o , ) def __rmul__ ( self , o ) : return '' % ( o , ) mapping = [ ] mapping . append ( ( lambda o : '' + o , TypeError , \"\" , \"\" ) ) if test_support . is_jython : mapping . append ( ( lambda o : u'' + o , TypeError , \"\" , \"\" ) ) else : mapping . append ( ( lambda o : u'' + o , TypeError , '' , \"\" ) ) mapping . append ( ( lambda o : [ , ] + o , TypeError , '' , '' ) ) mapping . append ( ( lambda o : ( '' , '' ) + o , TypeError , '' , \"\" ) ) mapping . append ( ( lambda o : '' * o , TypeError , \"\" , \"\" ) ) mapping . append ( ( lambda o : u'' * o , TypeError , \"\" , \"\" ) ) mapping . append ( ( lambda o : [ , ] * o , TypeError , \"\" , '' ) ) mapping . append ( ( lambda o : ( '' , '' ) * o , TypeError , \"\" , \"\" ) ) for func , bexc , bexc_msg , cresult in mapping : raises ( bexc , bexc_msg , lambda : func ( B ( ) ) ) self . assertEqual ( func ( C ( ) ) , cresult ) class InPlaceTestCase ( unittest . TestCase ) : def test_iadd ( self ) : class Foo ( object ) : def __add__ ( self , other ) : return def __radd__ ( self , other ) : return class Bar ( object ) : pass class Baz ( object ) : def __iadd__ ( self , other ) : return NotImplemented foo = Foo ( ) foo += Bar ( ) self . assertEqual ( foo , ) bar = Bar ( ) ", "answer": "bar += Foo ( )"}, {"prompt": " import sublime import sublime_plugin import os from threading import Thread from . import sublimelint from . lint import persist from . lint . edit import Edit def error_command ( f ) : def run ( self , edit , ** kwargs ) : vid = self . view . id ( ) if vid in persist . errors and persist . errors [ vid ] : f ( self , self . view , persist . errors [ vid ] , ** kwargs ) return run def select_line ( view , line ) : sel = view . sel ( ) point = view . text_point ( line , ) sel . clear ( ) sel . add ( view . line ( point ) ) class sublimelint_next_error ( sublime_plugin . TextCommand ) : @ error_command def run ( self , view , errors , direction = ) : self . view . run_command ( '' ) sel = view . sel ( ) if len ( sel ) == : sel . add ( ( , ) ) line = view . rowcol ( sel [ ] . a ) [ ] errors = list ( errors ) if line in errors : errors . remove ( line ) errors = sorted ( errors + [ line ] ) i = errors . index ( line ) + direction if i >= len ( errors ) : i -= len ( errors ) select_line ( view , errors [ i ] ) view . show_at_center ( sel [ ] ) class sublimelint_all_errors ( sublime_plugin . TextCommand ) : @ error_command def run ( self , view , errors ) : options = [ ] option_to_line = [ ] for lineno , messages in sorted ( errors . items ( ) ) : line = view . substr ( view . full_line ( view . text_point ( lineno , ) ) ) while messages : option_to_line . append ( lineno ) options . append ( [ ( \"\" % ( lineno + , line . strip ( ) ) ) ] + [ m for m in messages [ : ] ] ) messages = messages [ : ] def center_line ( i ) : if i != - : select_line ( view , option_to_line [ i ] ) view . show_at_center ( view . sel ( ) [ ] ) view . window ( ) . show_quick_panel ( options , center_line , sublime . MONOSPACE_FONT ) class sublimelint_report ( sublime_plugin . WindowCommand ) : def run ( self , on = '' ) : output = self . window . new_file ( ) output . set_name ( '' ) output . set_scratch ( True ) if on == '' or on == '' : for view in self . window . views ( ) : self . report ( output , view ) if on == '' or on == '' : for folder in self . window . folders ( ) : self . folder ( output , folder ) def folder ( self , output , folder ) : for root , dirs , files in os . walk ( folder ) : for name in files : path = os . path . join ( root , name ) if os . stat ( path ) . st_size < * : pass def report ( self , output , view ) : def finish_lint ( view , linters ) : if not linters : return with Edit ( output ) as edit : if not any ( l . errors for l in linters ) : return filename = os . path . basename ( linters [ ] . filename or '' ) out = '' . format ( filename ) for linter in linters : if linter . errors : for line , errors in sorted ( linter . errors . items ( ) ) : for error in errors : out += '' . format ( line , error ) edit . insert ( output . size ( ) , out ) args = ( view . id ( ) , finish_lint ) ", "answer": "Thread ( target = sublimelint . SublimeLint . lint , args = args ) . start ( ) "}, {"prompt": " from __future__ import division import numba as nb import numpy as np __all__ = ( '' , '' , '' , '' , '' ) @ nb . jit ( '' , nopython = True , nogil = True , cache = True ) def extract_scaled ( x ) : \"\"\"\"\"\" r = np . float64 ( ( x & ) / ) g = np . float64 ( ( ( x >> ) & ) / ) b = np . float64 ( ( ( x >> ) & ) / ) a = np . float64 ( ( ( x >> ) & ) / ) return r , g , b , a @ nb . jit ( '' , nopython = True , nogil = True , cache = True ) def combine_scaled ( r , g , b , a ) : \"\"\"\"\"\" r2 = np . uint32 ( r * ) g2 = np . uint32 ( g * ) b2 = np . uint32 ( b * ) a2 = np . uint32 ( a * ) return np . uint32 ( ( a2 << ) | ( b2 << ) | ( g2 << ) | r2 ) extract_scaled . disable_compile ( ) combine_scaled . disable_compile ( ) composite_op_lookup = { } def operator ( f ) : \"\"\"\"\"\" f2 = nb . vectorize ( f ) f2 . _compile_for_argtys ( ( nb . types . uint32 , nb . types . uint32 ) ) f2 . _frozen = True composite_op_lookup [ f . __name__ ] = f2 return f2 @ operator def source ( src , dst ) : if src & : return src else : return dst @ operator def over ( src , dst ) : sr , sg , sb , sa = extract_scaled ( src ) dr , dg , db , da = extract_scaled ( dst ) factor = - sa a = sa + da * factor if a == : return np . uint32 ( ) r = ( sr * sa + dr * da * factor ) / a g = ( sg * sa + dg * da * factor ) / a b = ( sb * sa + db * da * factor ) / a return combine_scaled ( r , g , b , a ) @ operator def add ( src , dst ) : sr , sg , sb , sa = extract_scaled ( src ) dr , dg , db , da = extract_scaled ( dst ) a = min ( , sa + da ) if a == : return np . uint32 ( ) r = ( sr * sa + dr * da ) / a g = ( sg * sa + dg * da ) / a ", "answer": "b = ( sb * sa + db * da ) / a"}, {"prompt": " from __future__ import print_function import os import sys import subprocess from os import environ as env from shellpython import config _colorama_intialized = False _colorama_available = True try : import colorama from colorama import Fore , Style except ImportError : _colorama_available = False def _is_colorama_enabled ( ) : return _colorama_available and config . COLORAMA_ENABLED def _print_stdout ( text ) : print ( text ) def _print_stderr ( text ) : print ( text , file = sys . stderr ) _PARAM_PRINT_STDOUT = '' _PARAM_PRINT_STDERR = '' _PARAM_INTERACTIVE = '' _PARAM_NO_THROW = '' def exe ( cmd , params ) : \"\"\"\"\"\" global _colorama_intialized if _is_colorama_enabled ( ) and not _colorama_intialized : _colorama_intialized = True colorama . init ( ) if config . PRINT_ALL_COMMANDS : if _is_colorama_enabled ( ) : _print_stdout ( Fore . GREEN + '' + cmd + Style . RESET_ALL ) else : _print_stdout ( '' + cmd ) if _is_param_set ( params , _PARAM_INTERACTIVE ) : return _create_interactive_result ( cmd , params ) else : return _create_result ( cmd , params ) def _is_param_set ( params , param ) : return True if params . find ( param ) != - else False class ShellpyError ( Exception ) : \"\"\"\"\"\" pass class NonZeroReturnCodeError ( ShellpyError ) : \"\"\"\"\"\" def __init__ ( self , cmd , result ) : self . cmd = cmd self . result = result def __str__ ( self ) : if _is_colorama_enabled ( ) : return '' . format ( red = Fore . RED , end = Style . RESET_ALL , cmd = self . cmd , code = self . result . returncode , ", "answer": "stderr = self . result . stderr )"}, {"prompt": " from jedi import parser from jedi . _compatibility import u try : ", "answer": "import unittest2 as unittest"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " from __future__ import absolute_import , division , print_function import os import sys import subprocess import uuid import mmap from contextlib import closing from functools import partial from distutils . spawn import find_executable import sqlalchemy as sa from sqlalchemy . ext . compiler import compiles from sqlalchemy . sql . elements import Executable , ClauseElement from toolz import merge from multipledispatch import MDNotImplementedError from . . append import append from . . convert import convert from . csv import CSV , infer_header from . . temp import Temp from . aws import S3 from . sql import getbind class CopyFromCSV ( Executable , ClauseElement ) : def __init__ ( self , element , csv , delimiter = '' , header = None , na_value = '' , lineterminator = '' , quotechar = '' , escapechar = '' , encoding = '' , skiprows = , bind = None , ** kwargs ) : if not isinstance ( element , sa . Table ) : raise TypeError ( '' ) self . element = element self . csv = csv self . delimiter = delimiter self . header = ( header if header is not None else ( csv . has_header if csv . has_header is not None else infer_header ( csv . path ) ) ) self . na_value = na_value self . lineterminator = lineterminator self . quotechar = quotechar self . escapechar = escapechar self . encoding = encoding self . skiprows = int ( skiprows or self . header ) self . _bind = getbind ( element , bind ) for k , v in kwargs . items ( ) : setattr ( self , k , v ) @ property def bind ( self ) : return self . _bind @ compiles ( CopyFromCSV , '' ) def compile_from_csv_sqlite ( element , compiler , ** kwargs ) : if not find_executable ( '' ) : raise MDNotImplementedError ( \"\" ) t = element . element if not element . header : csv = element . csv else : csv = Temp ( CSV ) ( '' % uuid . uuid1 ( ) ) assert csv . has_header , '' chunksize = << lineterminator = element . lineterminator . encode ( element . encoding ) with open ( element . csv . path , '' ) as f : with closing ( mmap . mmap ( f . fileno ( ) , , access = mmap . ACCESS_READ ) ) as mf : index = mf . find ( lineterminator ) if index == - : raise ValueError ( \"\" % lineterminator ) mf . seek ( index + len ( lineterminator ) ) with open ( csv . path , '' ) as g : for chunk in iter ( partial ( mf . read , chunksize ) , b'' ) : g . write ( chunk ) fullpath = os . path . abspath ( csv . path ) . encode ( '' ) . decode ( ) cmd = [ '' , '' , repr ( element . na_value ) , '' , element . delimiter , '' , '' % ( fullpath , compiler . preparer . format_table ( t ) ) , element . bind . url . database ] stderr = subprocess . check_output ( cmd , stderr = subprocess . STDOUT , stdin = subprocess . PIPE ) . decode ( sys . getfilesystemencoding ( ) ) if stderr : try : raise OSError ( stderr ) except OSError as e : raise sa . exc . DatabaseError ( '' . join ( cmd ) , [ ] , e ) return '' @ compiles ( CopyFromCSV , '' ) def compile_from_csv_mysql ( element , compiler , ** kwargs ) : if element . na_value : raise ValueError ( '' ) return compiler . process ( sa . text ( \"\"\"\"\"\" . format ( local = getattr ( element , '' , '' ) , table = compiler . preparer . format_table ( element . element ) ) ) . bindparams ( path = os . path . abspath ( element . csv . path ) , encoding = element . encoding or element . bind . execute ( '' ) . scalar ( ) , delimiter = element . delimiter , quotechar = element . quotechar , escapechar = element . escapechar , lineterminator = element . lineterminator , skiprows = int ( element . header ) ) , ** kwargs ) @ compiles ( CopyFromCSV , '' ) def compile_from_csv_postgres ( element , compiler , ** kwargs ) : if len ( element . escapechar ) != : raise ValueError ( '' '' ) ", "answer": "if element . lineterminator != '' :"}, {"prompt": " from . selector import Selector class MatchEngine ( object ) : pseudo_fns = { } selector_class = Selector def __init__ ( self ) : self . register_pseudo ( '' , self . pseudo_not ) self . register_pseudo ( '' , self . pseudo_has ) def register_pseudo ( self , name , fn ) : self . pseudo_fns [ name ] = fn @ staticmethod def pseudo_not ( matcher , node , value ) : return not matcher . match_node ( matcher . parse_selector ( value ) [ ] , node ) @ staticmethod def pseudo_has ( matcher , node , value ) : for node , body in matcher . iter_data ( [ node ] ) : if body : return any ( matcher . match_data ( matcher . parse_selector ( value ) [ ] , body ) ) def parse_selector ( self , selector ) : return self . selector_class . parse ( selector ) def match ( self , selector , data ) : selectors = self . parse_selector ( selector ) nodeids = { } for selector in selectors : for node in self . match_data ( selector , data ) : nodeid = id ( node ) if nodeid not in nodeids : nodeids [ nodeid ] = None yield node def match_data ( self , selector , data ) : for node , body in self . _iter_data ( data ) : match = self . match_node ( selector , node ) if match : next_selector = selector . next_selector if next_selector : if body : for node in self . match_data ( next_selector , body ) : yield node else : yield node if body and not selector . combinator == self . selector_class . CHILD : for node in self . match_data ( selector , body ) : yield node def match_node ( self , selector , node ) : match = all ( self . match_rules ( selector , node ) ) if match and selector . attrs : match &= all ( self . match_attrs ( selector , node ) ) if match and selector . pseudos : match &= all ( self . match_pseudos ( selector , node ) ) return match def match_rules ( self , selector , node ) : if selector . typ : yield self . match_type ( selector . typ , node ) if selector . id_ : yield self . match_id ( selector . id_ , node ) ", "answer": "def match_attrs ( self , selector , node ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals from django . utils . translation import ugettext_lazy as _ from lino . utils . instantiator import Instantiator from lino . api import dd , rt def objects ( ) : Language = Instantiator ( '' , \"\" ) . build yield Language ( '' , ** dd . str2kw ( '' , _ ( \"\" ) ) ) yield Language ( '' , ** dd . str2kw ( '' , _ ( \"\" ) ) ) ", "answer": "yield Language ( '' , ** dd . str2kw ( '' , _ ( \"\" ) ) )"}, {"prompt": " from . context import * from . engine import * from . graph import * ", "answer": "from . pipeline import * "}, {"prompt": " from __future__ import unicode_literals ", "answer": "default_app_config = '' "}, {"prompt": " \"\"\"\"\"\" import logging import re from urllib . parse import urljoin from bs4 import BeautifulSoup import requests LOGGER = logging . getLogger ( __name__ ) class Site ( object ) : \"\"\"\"\"\" def __init__ ( self , url_base , url_archive , paste_tag , target_patterns , paste ) : self . url_base = url_base self . url_archive = url_archive self . paste_tag = paste_tag self . target_patterns = target_patterns self . headers = { '' : '' '' } self . paste = paste def get ( self ) : \"\"\"\"\"\" req = requests . get ( self . url_base + self . url_archive , headers = self . headers ) LOGGER . debug ( '' ) while req . status_code != : LOGGER . error ( '' ) req = requests . get ( self . url_base + self . url_archive ) soup = BeautifulSoup ( req . text , '' ) links = soup . find_all ( self . paste_tag ) LOGGER . debug ( '' , len ( links ) ) return [ self . paste ( urljoin ( self . url_base , link . a . get ( '' ) ) ) for link in links ] def get_paste ( self , paste ) : \"\"\"\"\"\" req = requests . get ( paste . url , headers = self . headers ) LOGGER . debug ( '' ) while req . status_code != : LOGGER . error ( '' ) req = requests . get ( paste . url ) found = [ ] for name , pattern in self . target_patterns : LOGGER . debug ( '' , pattern ) matches = re . findall ( pattern , req . text ) LOGGER . debug ( '' , len ( matches ) ) if matches : found . append ( ( name , len ( matches ) ) ) return found class Paste ( object ) : \"\"\"\"\"\" def __init__ ( self , url ) : _id = url . split ( '' ) [ - ] self . _id = _id class PastebinPaste ( Paste ) : \"\"\"\"\"\" def __init__ ( self , url ) : super ( ) . __init__ ( url ) self . url = '' . format ( self . _id ) class PastiePaste ( Paste ) : \"\"\"\"\"\" def __init__ ( self , url ) : super ( ) . __init__ ( url ) self . url = '' . format ( self . _id ) class SlexyPaste ( Paste ) : \"\"\"\"\"\" def __init__ ( self , url ) : super ( ) . __init__ ( url ) self . url = '' . format ( self . _id ) class Pastebin ( Site ) : \"\"\"\"\"\" def __init__ ( self , target_patterns ) : self . url_base = '' self . url_archive = '' self . paste_tag = lambda tag : tag . name == '' and tag . a and '' not in tag . a [ '' ] and tag . a [ '' ] [ : ] super ( ) . __init__ ( self . url_base , self . url_archive , self . paste_tag , target_patterns , PastebinPaste ) class Pastie ( Site ) : \"\"\"\"\"\" def __init__ ( self , target_patterns ) : self . url_base = '' self . url_archive = '' self . paste_tag = lambda tag : tag . name == '' and tag . a and self . url_base in tag . a [ '' ] super ( ) . __init__ ( self . url_base , self . url_archive , self . paste_tag , target_patterns , ", "answer": "PastiePaste )"}, {"prompt": " import logging logger = logging . getLogger ( __name__ ) from boto . exception import SDBResponseError from nymms . state . State import StateManager from nymms . schemas import StateRecord from nymms . exceptions import OutOfDateState from nymms . providers . sdb import SimpleDBBackend class SDBStateManager ( StateManager ) : def __init__ ( self , region , domain_name , schema_class = StateRecord ) : self . region = region self . domain_name = domain_name super ( SDBStateManager , self ) . __init__ ( schema_class ) @ property def conn ( self ) : return self . backend . conn @ property def domain ( self ) : return self . backend . domain def get_backend ( self ) : return SimpleDBBackend ( self . region , self . domain_name ) def save_state ( self , task_id , result , previous ) : new_state = self . build_new_state ( task_id , result , previous ) expected_value = [ '' , False ] if previous : expected_value = [ '' , previous . last_update . isoformat ( ) ] if previous . last_update > new_state . last_update : logger . warning ( task_id + \"\" \"\" ) logger . warning ( task_id + \"\" , previous . to_primitive ( ) ) logger . warning ( task_id + \"\" , new_state . to_primitive ( ) ) raise OutOfDateState ( new_state , previous ) logger . debug ( task_id + \"\" , new_state . to_primitive ( ) ) try : self . domain . put_attributes ( task_id , new_state . to_primitive ( ) , replace = True , expected_value = expected_value ) ", "answer": "except SDBResponseError as e :"}, {"prompt": " import sys , json , httplib , urllib , base64 if len ( sys . argv ) < : print \"\" ", "answer": "sys . exit ( )"}, {"prompt": " from oslo_serialization import jsonutils from nailgun import consts from nailgun . db . sqlalchemy . models import IPAddr from nailgun . db . sqlalchemy . models import NetworkGroup from nailgun import objects from nailgun . utils import reverse from nailgun . test . base import BaseIntegrationTest class BaseIPAddrTest ( BaseIntegrationTest ) : __test__ = False def setUp ( self ) : self . maxDiff = None super ( BaseIPAddrTest , self ) . setUp ( ) self . cluster = self . env . create ( release_kwargs = { '' : '' } , cluster_kwargs = { '' : False } , nodes_kwargs = [ { '' : [ '' ] } ] ) net_manager = objects . Cluster . get_network_manager ( self . cluster ) net_manager . assign_vips_for_net_groups ( self . cluster ) self . management_net = net_manager . get_network_by_netname ( consts . NETWORKS . management , self . cluster . network_groups ) self . management_vips = self . db . query ( IPAddr ) . filter ( IPAddr . vip_name . isnot ( None ) , IPAddr . network == self . management_net . id ) . all ( ) self . vip_ids = [ v . id for v in self . management_vips ] self . expected_vips = [ { '' : '' , '' : None , '' : '' , '' : False , '' : '' } , { '' : '' , '' : None , '' : '' , '' : False , '' : '' } , { '' : '' , '' : False , '' : None , '' : '' , '' : '' } , { '' : '' , '' : False , '' : None , '' : '' , '' : '' } , ] self . non_existing_id = def _remove_from_response ( self , response , fields ) : list_given = isinstance ( response , list ) if not list_given : response = [ response ] clean_response = [ ] for resp_item in response : resp_item_clone = resp_item . copy ( ) for f in fields : resp_item_clone . pop ( f , None ) clean_response . append ( resp_item_clone ) return clean_response if list_given else clean_response [ ] def _check_ip_intersection ( self , ip_addr ) : handlers_info = { '' : { '' : { '' : self . cluster [ '' ] , '' : self . management_vips [ ] . id } , '' : { '' : True , '' : ip_addr , '' : '' } , } , '' : { '' : { '' : self . cluster [ '' ] } , '' : [ { '' : self . management_vips [ ] . id , '' : ip_addr , '' : True } ] } } resp = self . app . patch ( reverse ( self . handler_name , kwargs = handlers_info [ self . handler_name ] [ '' ] , ) , params = jsonutils . dumps ( handlers_info [ self . handler_name ] [ '' ] ) , headers = self . default_headers , expect_errors = True ) self . assertEqual ( resp . status_code , ) net_group = self . db . query ( NetworkGroup ) . filter_by ( id = self . management_net . id ) . first ( ) err_msg = ( \"\" \"\" . format ( ip_addr , net_group . name , net_group . cidr ) ) self . assertIn ( err_msg , resp . json_body [ '' ] ) def test_update_user_defined_fail_if_ip_addr_intersection ( self ) : intersecting_vip = self . management_vips [ ] . ip_addr self . _check_ip_intersection ( intersecting_vip ) class TestIPAddrList ( BaseIPAddrTest ) : __test__ = True handler_name = '' def check_create_vip ( self , create_data ) : resp = self . app . post ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( create_data ) , headers = self . default_headers ) self . assertEqual ( resp . status_code , ) return resp def test_create_vip_for_cluster ( self ) : create_data = { '' : \"\" , '' : self . management_net . id , '' : '' , '' : True } self . check_create_vip ( create_data ) def test_create_vip_for_cluster_wo_is_user_defined_flag ( self ) : create_data = { '' : \"\" , '' : self . management_net . id , '' : '' , } create_resp = self . check_create_vip ( create_data ) get_resp = self . app . get ( reverse ( '' , kwargs = { '' : self . cluster [ '' ] , '' : create_resp . json_body [ '' ] } ) , headers = self . default_headers ) self . assertTrue ( get_resp . json_body [ '' ] ) def test_vips_list_for_cluster ( self ) : resp = self . app . get ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , headers = self . default_headers ) self . assertEqual ( , resp . status_code ) self . assertItemsEqual ( self . expected_vips , self . _remove_from_response ( resp . json_body , [ '' , '' ] ) , ) def test_vips_list_with_two_clusters ( self ) : self . second_cluster = self . env . create_cluster ( api = False ) self . env . create_ip_addrs_by_rules ( self . second_cluster , { '' : { '' : '' , '' : '' , } } ) resp = self . app . get ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , headers = self . default_headers ) self . assertEqual ( , resp . status_code ) self . assertItemsEqual ( self . expected_vips , self . _remove_from_response ( resp . json_body , [ '' , '' ] ) , ) def test_wrong_cluster ( self ) : resp = self . app . get ( reverse ( self . handler_name , kwargs = { '' : } ) , headers = self . default_headers , expect_errors = True ) self . assertEqual ( , resp . status_code ) def test_update ( self ) : update_data = [ { '' : self . vip_ids [ ] , '' : True , '' : '' } , { '' : self . vip_ids [ ] , '' : '' } ] expected_data = [ { '' : self . vip_ids [ ] , '' : True , '' : self . management_vips [ ] [ \"\" ] , '' : '' , '' : '' } , { '' : self . vip_ids [ ] , '' : False , '' : self . management_vips [ ] [ \"\" ] , '' : '' , '' : '' } ] resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( update_data ) , headers = self . default_headers ) self . assertEqual ( , resp . status_code ) self . assertEqual ( expected_data , self . _remove_from_response ( resp . json_body , [ '' , '' ] ) ) def test_update_fail_with_no_id ( self ) : new_data = [ { '' : '' } ] resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( new_data ) , headers = self . default_headers , expect_errors = True ) self . assertEqual ( , resp . status_code ) self . assertIn ( \"\" , resp . json_body [ \"\" ] ) def test_update_fail_with_non_updatable_field ( self ) : new_data = [ { '' : self . vip_ids [ ] , '' : '' } , { '' : self . vip_ids [ ] , '' : '' , '' : self . non_existing_id } ] resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( new_data ) , headers = self . default_headers , expect_errors = True ) self . assertEqual ( , resp . status_code ) self . assertIn ( \"\" , resp . json_body [ \"\" ] ) def test_update_pass_with_non_updatable_not_changed_field ( self ) : new_data = [ { '' : self . management_vips [ ] . id , '' : '' , '' : self . management_vips [ ] . network } ] resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( new_data ) , headers = self . default_headers , expect_errors = True ) self . assertEqual ( , resp . status_code ) def test_update_fail_with_not_found_id ( self ) : new_data = [ { '' : self . non_existing_id , '' : '' } ] resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( new_data ) , headers = self . default_headers , expect_errors = True ) self . assertIn ( str ( self . non_existing_id ) , resp . json_body [ \"\" ] ) self . assertEqual ( , resp . status_code ) def test_update_fail_on_dict_request ( self ) : new_data = { '' : self . vip_ids [ ] , '' : '' } resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( new_data ) , headers = self . default_headers , expect_errors = True ) self . assertEqual ( , resp . status_code ) def test_update_failing_on_empty_request ( self ) : resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = \"\" , headers = self . default_headers , expect_errors = True ) self . assertEqual ( , resp . status_code ) def test_update_not_failing_on_empty_list_request ( self ) : resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( [ ] ) , headers = self . default_headers , expect_errors = True ) self . assertEqual ( , resp . status_code ) def test_update_fail_on_wrong_fields ( self ) : new_data_suites = [ [ { '' : self . vip_ids [ ] , \"\" : self . non_existing_id , \"\" : \"\" } ] ] for new_data in new_data_suites : resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( new_data ) , headers = self . default_headers , expect_errors = True ) self . assertEqual ( , resp . status_code ) def test_update_fail_on_ip_from_wrong_cluster ( self ) : another_cluster = self . env . create_cluster ( api = False ) new_data_suites = [ [ { '' : self . vip_ids [ ] , \"\" : self . non_existing_id } ] ] for new_data in new_data_suites : resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : another_cluster [ '' ] } ) , params = jsonutils . dumps ( new_data ) , headers = self . default_headers , expect_errors = True ) self . assertEqual ( , resp . status_code ) self . assertIn ( \"\" , resp . json_body . get ( \"\" ) ) def test_all_data_not_changed_on_single_error ( self ) : old_all_addr = [ dict ( a ) for a in self . db . query ( IPAddr ) . all ( ) ] self . db . commit ( ) new_data = [ { '' : self . vip_ids [ ] , '' : True , '' : '' } , { '' : False , '' : '' } ] resp = self . app . patch ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = jsonutils . dumps ( new_data ) , headers = self . default_headers , expect_errors = True ) new_all_addr = [ dict ( a ) for a in self . db . query ( IPAddr ) . all ( ) ] self . assertEqual ( old_all_addr , new_all_addr ) self . assertEqual ( , resp . status_code ) def test_ipaddr_filter_by_network_id ( self ) : resp = self . app . get ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = { \"\" : self . management_vips [ ] [ '' ] } , headers = self . default_headers ) self . assertEqual ( [ dict ( v ) for v in self . management_vips ] , resp . json_body ) self . assertEqual ( , resp . status_code ) def test_ipaddr_filter_by_missing_network_id ( self ) : resp = self . app . get ( reverse ( self . handler_name , kwargs = { '' : self . cluster [ '' ] } ) , params = { \"\" : self . non_existing_id } , headers = self . default_headers ) self . assertEqual ( [ ] , resp . json_body ) self . assertEqual ( , resp . status_code ) def test_ipaddr_filter_by_network_role ( self ) : public_net_vip_names = ( '' , '' ) resp = self . app . get ( reverse ( self . handler_name , ", "answer": "kwargs = {"}, {"prompt": " from south . db import db from south . v2 import SchemaMigration class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_unique ( '' , [ '' , '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = , blank = True ) , keep_default = False ) db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = , blank = True ) , keep_default = False ) db . add_column ( '' , '' , self . gf ( '' ) ( default = '' ) , keep_default = False ) db . alter_column ( '' , '' , self . gf ( '' ) ( auto_now = True ) ) db . alter_column ( '' , '' , self . gf ( '' ) ( auto_now_add = True ) ) def backwards ( self , orm ) : db . delete_unique ( '' , [ '' , '' ] ) db . delete_table ( '' ) db . delete_table ( '' ) db . delete_column ( '' , '' ) db . delete_column ( '' , '' ) db . delete_column ( '' , '' ) db . alter_column ( '' , '' , self . gf ( '' ) ( ) ) db . alter_column ( '' , '' , self . gf ( '' ) ( ) ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' , '' : '' } ) ,"}, {"prompt": " '''''' import sys from pprint import pformat from os . path import join , dirname import time import subprocess import shlex PYTHON_DIR = join ( dirname ( __file__ ) , \"\" ) sys . path . append ( PYTHON_DIR ) from unittest import TestCase ", "answer": "import xmlrpclib"}, {"prompt": " from __future__ import absolute_import , division , print_function import sys import optparse from glue import __version__ from glue . logger import logger def parse ( argv ) : \"\"\"\"\"\" usage = \"\"\"\"\"\" parser = optparse . OptionParser ( usage = usage , version = str ( __version__ ) ) parser . add_option ( '' , '' , action = '' , dest = '' , help = \"\" , default = False ) parser . add_option ( '' , action = '' , dest = '' , help = \"\" , default = False ) parser . add_option ( '' , '' , action = '' , dest = '' , help = \"\" , default = False ) parser . add_option ( '' , '' , type = '' , dest = '' , metavar = '' , help = '' ) parser . add_option ( '' , '' , action = '' , help = \"\" , default = False ) err_msg = verify ( parser , argv ) if err_msg : sys . stderr . write ( '' % err_msg ) parser . print_help ( ) sys . exit ( ) return parser . parse_args ( argv ) def verify ( parser , argv ) : \"\"\"\"\"\" opts , args = parser . parse_args ( argv ) err_msg = None if opts . script and opts . restore : err_msg = \"\" elif opts . script and opts . config : err_msg = \"\" elif opts . script and len ( args ) != : err_msg = \"\" elif opts . restore and len ( args ) != : err_msg = \"\" return err_msg def die_on_error ( msg ) : \"\"\"\"\"\" def decorator ( func ) : def wrapper ( * args , ** kwargs ) : try : return func ( * args , ** kwargs ) except Exception as e : import traceback from glue . external . qt import get_qapp get_qapp ( ) from glue . utils . qt import QMessageBoxPatched as QMessageBox m = \"\" % ( msg , e ) detail = str ( traceback . format_exc ( ) ) if len ( m ) > : detail = \"\" % ( m , detail ) m = m [ : ] + '' qmb = QMessageBox ( QMessageBox . Critical , \"\" , m ) qmb . setDetailedText ( detail ) qmb . show ( ) qmb . raise_ ( ) qmb . exec_ ( ) sys . exit ( ) return wrapper return decorator @ die_on_error ( \"\" ) ", "answer": "def restore_session ( gluefile ) :"}, {"prompt": " import unittest from sqlalchemy . engine import create_engine from sqlalchemy . orm . session import sessionmaker from geeknote import storage import pickle def hacked_init ( self ) : '''''' engine = create_engine ( '' , echo = False ) storage . Base . metadata . create_all ( engine ) Session = sessionmaker ( bind = engine ) self . session = Session ( ) class storageTest ( unittest . TestCase ) : def setUp ( self ) : stor = storage . Storage stor . __init__ = hacked_init self . storage = stor ( ) self . otoken = '' self . userinfo = { '' : '' } self . tags = { u'' : , u'' : , u'' : '' } self . notebooks = { u'' : u'' } self . storage . createUser ( self . otoken , self . userinfo ) def test_create_user_without_token_fail ( self ) : self . assertFalse ( self . storage . createUser ( None , self . userinfo ) ) def test_create_user_without_info_fail ( self ) : self . assertFalse ( self . storage . createUser ( self . otoken , None ) ) def test_remove_user_success ( self ) : self . assertTrue ( self . storage . removeUser ( ) ) def test_get_user_token_success ( self ) : self . assertEquals ( self . storage . getUserToken ( ) , self . otoken ) def test_get_user_info_success ( self ) : self . assertEquals ( self . storage . getUserInfo ( ) , self . userinfo ) def test_get_user_props_success ( self ) : props = [ { u'' : '' } , { u'' : { '' : '' } } ] self . assertEquals ( self . storage . getUserprops ( ) , props ) def test_get_user_props_exists_success ( self ) : self . assertEquals ( self . storage . getUserprop ( '' ) , self . userinfo ) def test_get_user_prop_not_exists ( self ) : self . assertFalse ( self . storage . getUserprop ( '' ) ) def test_set_new_user_prop ( self ) : self . assertFalse ( self . storage . getUserprop ( '' ) ) self . assertTrue ( self . storage . setUserprop ( '' , '' ) ) self . assertEquals ( self . storage . getUserprop ( '' ) , '' ) def test_set_exists_user_prop ( self ) : newmail = { '' : '' } self . assertEquals ( self . storage . getUserprop ( '' ) , self . userinfo ) self . assertTrue ( self . storage . setUserprop ( '' , newmail ) , newmail ) self . assertEquals ( self . storage . getUserprop ( '' ) , newmail ) def test_get_empty_settings ( self ) : self . assertEquals ( self . storage . getSettings ( ) , { } ) def test_set_settings_success ( self ) : self . storage . setSettings ( { '' : '' } ) self . assertEquals ( self . storage . getSettings ( ) , { u'' : u\"\" } ) def test_set_setting_error_type_fail ( self ) : self . assertFalse ( self . storage . setSettings ( '' ) ) def test_set_setting_none_value_fail ( self ) : self . assertFalse ( self . storage . setSettings ( { '' : None } ) ) def test_update_settings_fail ( self ) : self . storage . setSettings ( { '' : '' } ) self . assertTrue ( self . storage . setSettings ( { '' : '' } ) ) self . assertEquals ( self . storage . getSettings ( ) , { u'' : u\"\" } ) def test_get_setting_exist_success ( self ) : self . storage . setSettings ( { '' : '' } ) editor = self . storage . getSetting ( '' ) self . assertEquals ( pickle . loads ( editor ) , '' ) def test_set_setting_true ( self ) : editor = '' self . assertTrue ( self . storage . setSetting ( '' , editor ) ) self . assertEquals ( self . storage . getSetting ( '' ) , editor ) def test_get_setting_not_exist_fail ( self ) : self . assertFalse ( self . storage . getSetting ( '' ) ) def test_set_tags_success ( self ) : self . assertTrue ( self . storage . setTags ( self . tags ) ) def test_set_tags_error_type_fail ( self ) : self . assertFalse ( self . storage . setTags ( '' ) ) def test_set_tags_none_value_fail ( self ) : self . assertFalse ( self . storage . setTags ( { '' : None } ) ) def test_get_tags_success ( self ) : tags = { u'' : u'' , u'' : u'' , u'' : u'' } self . assertTrue ( self . storage . setTags ( self . tags ) ) self . assertEquals ( self . storage . getTags ( ) , tags ) def test_replace_tags_success ( self ) : tags = { u'' : u'' , u'' : u'' , u'' : u'' } self . assertTrue ( self . storage . setTags ( self . tags ) ) self . tags [ u'' ] = self . assertTrue ( self . storage . setTags ( self . tags ) ) self . assertEquals ( self . storage . getTags ( ) , tags ) def test_set_notebooks_success ( self ) : self . assertEquals ( self . storage . getNotebooks ( ) , { } ) self . storage . setNotebooks ( self . notebooks ) self . assertEquals ( self . storage . getNotebooks ( ) , self . notebooks ) def test_replace_notebooks_success ( self ) : newnotebooks = { u'' : u'' } self . storage . setNotebooks ( self . notebooks ) self . storage . setNotebooks ( newnotebooks ) self . assertEquals ( self . storage . getNotebooks ( ) , newnotebooks ) def test_get_empty_search_success ( self ) : self . assertFalse ( self . storage . getSearch ( ) ) def test_get_search_exists_success ( self ) : query = '' self . assertTrue ( self . storage . setSearch ( query ) ) self . assertEquals ( self . storage . getSearch ( ) , query ) def test_set_notebooks_error_type_fail ( self ) : self . assertFalse ( self . storage . setNotebooks ( '' ) ) def test_set_notebooks_none_value_fail ( self ) : self . assertFalse ( self . storage . setNotebooks ( { '' : None } ) ) def test_set_search_true ( self ) : self . assertTrue ( self . storage . setSearch ( '' ) ) class modelsTest ( unittest . TestCase ) : def test_rept_userprop ( self ) : userprop = storage . Userprop ( key = '' , value = '' ) self . assertEquals ( userprop . __repr__ ( ) , \"\" ) def test_repr_setting ( self ) : setting = storage . Setting ( key = '' , value = '' ) ", "answer": "self . assertEquals ( setting . __repr__ ( ) ,"}, {"prompt": " from __future__ import print_function import copy import numpy import theano from theano . tensor import grad from theano . tests import unittest_tools import theano . sandbox . cuda as tcn import warnings if not tcn . cuda_available : from nose . plugins . skip import SkipTest raise SkipTest ( '' ) from pylearn2 . sandbox . cuda_convnet . pool import MaxPool , MaxPoolGrad from pylearn2 . models . mlp import max_pool_c01b as gold_max_pool_c01b if theano . config . mode == '' : mode_with_gpu = theano . compile . mode . get_mode ( '' ) . including ( '' ) mode_without_gpu = theano . compile . mode . get_mode ( '' ) . excluding ( '' ) else : mode_with_gpu = theano . compile . mode . get_default_mode ( ) . including ( '' ) mode_without_gpu = theano . compile . mode . get_default_mode ( ) . excluding ( '' ) mode_with_gpu = copy . copy ( mode_with_gpu ) mode_without_gpu = copy . copy ( mode_without_gpu ) mode_with_gpu . check_py_code = False mode_without_gpu . check_py_code = False def my_rand ( * shape ) : return theano . _asarray ( numpy . random . rand ( * shape ) , dtype = '' ) def test_pool ( ) : shps = [ ( , , , ) , ] shps = [ ( channel , x , y , batch ) for ( batch , channel , x , y ) in shps ] warnings . warn ( \"\" ) for shp in shps : for ds in range ( , min ( , shp [ ] + ) ) : for start in [ ] : for stride in range ( , min ( shp [ ] , ds , ) + ) : va = my_rand ( * shp ) tva = va . flatten ( ) vb = my_rand ( * shp ) tvb = vb . flatten ( ) a = tcn . shared_constructor ( va , '' ) b = tcn . shared_constructor ( vb , '' ) op = MaxPool ( ds = ds , stride = stride ) v = op ( a ) rval = theano . tensor . Rop ( v , a , b ) f = theano . function ( [ ] , rval , mode = mode_with_gpu ) ", "answer": "print ( f . maker . fgraph . toposort ( ) )"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( default = None , max_length = , null = True ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( '' , '' ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { } )"}, {"prompt": " '''''' import os import sys import random from foam . ethzlegacyoptinstuff . legacyoptin . optsmodels import Experiment , ExperimentFLowSpace from foam . ethzlegacyoptinstuff . legacyoptin . flowspaceutils import dotted_ip_to_int , mac_to_int , int_to_dotted_ip , int_to_mac , parseFVexception import logging import zlib import base64 import xmlrpclib from xml . parsers . expat import ExpatError import jsonrpc from flaskext . xmlrpc import XMLRPCHandler , Fault from flask import request import foam . task import foam . lib import foam . api . xmlrpc import foam . version from foam . creds import CredVerifier , Certificate from foam . config import AUTO_SLIVER_PRIORITY , GAPI_REPORTFOAMVERSION from foam . core . configdb import ConfigDB from foam . core . log import KeyAdapter from foam . geni . db import GeniDB , UnknownSlice , UnknownNode import foam . geni . approval import foam . geni . ofeliaapproval import foam . geni . lib import sfa from foam . flowvisor import Connection as FV from pprint import pprint import json import httplib , urllib , base64 THIS_SITE_TAG = ConfigDB . getConfigItemByKey ( \"\" ) . getValue ( ) def _same ( val ) : return \"\" % val class om_ch_translate ( object ) : attr_funcs = { \"\" : ( int_to_mac , mac_to_int , , \"\" , \"\" ) , \"\" : ( int_to_mac , mac_to_int , , \"\" , \"\" ) , \"\" : ( _same , int , , \"\" , \"\" ) , \"\" : ( _same , int , , \"\" , \"\" ) , \"\" : ( int_to_dotted_ip , dotted_ip_to_int , , \"\" , \"\" ) , \"\" : ( int_to_dotted_ip , dotted_ip_to_int , , \"\" , \"\" ) , \"\" : ( _same , int , , \"\" , \"\" ) , \"\" : ( _same , int , , \"\" , \"\" ) , \"\" : ( _same , int , , \"\" , \"\" ) , \"\" : ( _same , int , , \"\" , \"\" ) , } import threading import time class RepeatTimer ( threading . Thread ) : def __init__ ( self , interval , callable_fun , * args , ** kwargs ) : threading . Thread . __init__ ( self ) self . interval = interval self . callable_fun = callable_fun self . args = args self . kwargs = kwargs self . event = threading . Event ( ) def run ( self ) : while not self . event . is_set ( ) : self . callable_fun ( self . args , self . kwargs ) self . event . wait ( self . interval ) def cancel ( self ) : self . event . set ( ) from foam . ethzlegacyoptinstuff . api_exp_to_rspecv3 . expdatatogeniv3rspec import create_ofv3_rspec class AMLegExpAPI ( foam . api . xmlrpc . Dispatcher ) : def __init__ ( self , log ) : super ( AMLegExpAPI , self ) . __init__ ( \"\" , log ) self . _actionLog = KeyAdapter ( \"\" , logging . getLogger ( '' ) ) filedir = '' filename = os . path . join ( filedir , '' ) if os . path . isfile ( filename ) : f = open ( filename , '' ) self . slice_info_dict = json . load ( f ) f . close ( ) else : self . slice_info_dict = { } self . switch_dpid_list = None self . link_list = None self . callback_http_attr_list = [ ] self . callback_cred_attr_list = [ ] def recordAction ( self , action , credentials = [ ] , urn = None ) : cred_ids = [ ] self . _actionLog . info ( \"\" % ( urn , action ) ) for cred in credentials : self . _actionLog . info ( \"\" % ( cred ) ) def priv_CreateSliver ( self , slice_urn , credentials , rspec , users , force_approval = False , options = None ) : user_info = users try : if True : self . recordAction ( \"\" , credentials , slice_urn ) try : self . _log . debug ( \"\" % users ) except Exception , e : self . _log . exception ( \"\" ) user_info [ \"\" ] = None user_info [ \"\" ] = None from foam . app import admin_apih if not admin_apih . vlan_automation_on : sliver = foam . geni . lib . createSliver ( slice_urn , credentials , rspec , user_info ) style = ConfigDB . getConfigItemByKey ( \"\" ) . getValue ( ) if style == foam . geni . approval . NEVER : approve = False elif style == foam . geni . approval . ALWAYS : approve = True else : approve = foam . geni . ofeliaapproval . of_analyzeForApproval ( sliver ) if approve or force_approval : pid = foam . task . approveSliver ( sliver . getURN ( ) , AUTO_SLIVER_PRIORITY ) self . _log . debug ( \"\" % pid ) else : free_vlan_list = self . pub_get_offered_vlans ( ) free_vlan = free_vlan_list [ ] slice_id = slice_urn . split ( \"\" ) [ ] . split ( \"\" ) [ ] . split ( \"\" ) [ ] . split ( \"\" ) [ ] if ( slice_id == \"\" ) or ( slice_id not in self . slice_info_dict ) : self . _log . exception ( \"\" ) raise Exception updated_slice_info_dict = self . slice_info_dict . copy ( ) for sliv_pos , sliver in enumerate ( self . slice_info_dict [ slice_id ] [ '' ] ) : for sfs_pos , sfs in enumerate ( sliver [ '' ] ) : updated_slice_info_dict [ slice_id ] [ '' ] [ sliv_pos ] [ '' ] [ sfs_pos ] [ '' ] = free_vlan updated_slice_info_dict [ slice_id ] [ '' ] [ sliv_pos ] [ '' ] [ sfs_pos ] [ '' ] = free_vlan all_efs = self . create_slice_fs ( updated_slice_info_dict [ slice_id ] [ '' ] ) new_slice_of_rspec = create_ofv3_rspec ( slice_id , updated_slice_info_dict [ slice_id ] [ '' ] , updated_slice_info_dict [ slice_id ] [ '' ] , updated_slice_info_dict [ slice_id ] [ '' ] , updated_slice_info_dict [ slice_id ] [ '' ] , updated_slice_info_dict [ slice_id ] [ '' ] , updated_slice_info_dict [ slice_id ] [ '' ] , updated_slice_info_dict [ slice_id ] [ '' ] , updated_slice_info_dict [ slice_id ] [ '' ] , all_efs ) self . slice_info_dict = updated_slice_info_dict . copy ( ) sliver = foam . geni . lib . createSliver ( slice_urn , credentials , new_slice_of_rspec , user_info ) pid = foam . task . approveSliver ( sliver . getURN ( ) , AUTO_SLIVER_PRIORITY ) self . _log . debug ( \"\" % pid ) data = GeniDB . getSliverData ( sliver . getURN ( ) , True ) foam . task . emailCreateSliver ( data ) return self . successResult ( GeniDB . getManifest ( sliver . getURN ( ) ) ) return except foam . geni . lib . RspecParseError , e : self . _log . info ( str ( e ) ) e . _foam_logged = True raise e except foam . geni . lib . RspecValidationError , e : self . _log . info ( str ( e ) ) e . _foam_logged = True raise e except foam . geni . lib . DuplicateSliver , ds : self . _log . info ( \"\" % ( ds . slice_urn ) ) ds . _foam_logged = True raise ds except foam . geni . lib . UnknownComponentManagerID , ucm : raise Fault ( \"\" , \"\" % ( ucm . cid ) ) except ( foam . geni . lib . UnmanagedComponent , UnknownNode ) , uc : self . _log . info ( \"\" % ( uc . cid ) ) f = Fault ( \"\" , \"\" % ( uc . cid ) ) f . _foam_logged = True raise f except Exception , e : self . _log . exception ( \"\" ) raise e def priv_DeleteSliver ( self , slice_urn , credentials , options = None ) : try : if True : self . recordAction ( \"\" , credentials , slice_urn ) if GeniDB . getSliverURN ( slice_urn ) is None : raise Fault ( \"\" , \"\" % ( slice_urn ) ) return self . errorResult ( , \"\" ) sliver_urn = GeniDB . getSliverURN ( slice_urn ) data = GeniDB . getSliverData ( sliver_urn , True ) foam . geni . lib . deleteSliver ( sliver_urn = sliver_urn ) foam . task . emailGAPIDeleteSliver ( data ) return self . successResult ( True ) return self . successResult ( False ) except UnknownSlice , x : self . _log . info ( \"\" % ( slice_urn ) ) x . _foam_logged = True raise x except Exception , e : self . _log . exception ( \"\" ) raise e def pub_check_fv_set ( self , func , * arg , ** kwargs ) : if ( FV . xmlconn is None ) : self . _log . exception ( \"\" ) raise Exception ( \"\" ) return func ( * arg , ** kwargs ) def pub_check_user ( self , func , * args , ** kwargs ) : '''''' if \"\" not in kwargs : raise Exception ( \"\" % func . func_name ) if not hasattr ( kwargs [ \"\" ] , \"\" ) : raise Exception ( \"\" ) kwargs [ '' ] = kwargs [ '' ] . user return func ( * args , ** kwargs ) def pub_checkFlowVisor ( self , * arg , ** kwargs ) : if ( FV . xmlconn is None ) : self . _log . exception ( \"\" ) raise Exception ( \"\" ) return \"\" def pub_convert_star ( self , fs ) : temp = fs . copy ( ) for ch_name , ( to_str , from_str , width , om_name , of_name ) in om_ch_translate . attr_funcs . items ( ) : ch_start = \"\" % ch_name ch_end = \"\" % ch_name if ch_start not in fs or fs [ ch_start ] == \"\" : temp [ ch_start ] = to_str ( ) if ch_end not in fs or fs [ ch_end ] == \"\" : temp [ ch_end ] = to_str ( ** width - ) return temp def pub_convert_star_int ( self , fs ) : temp = fs . copy ( ) for ch_name , ( to_str , from_str , width , om_name , of_name ) in om_ch_translate . attr_funcs . items ( ) : ch_start = \"\" % ch_name ch_end = \"\" % ch_name if ch_start not in fs or fs [ ch_start ] == \"\" : temp [ ch_start ] = else : temp [ ch_start ] = from_str ( fs [ ch_start ] ) if ch_end not in fs or fs [ ch_end ] == \"\" : temp [ ch_end ] = ** width - else : temp [ ch_end ] = from_str ( fs [ ch_end ] ) return temp def pub_get_direction ( self , direction ) : if ( direction == '' ) : return if ( direction == '' ) : return if ( direction == '' ) : return ", "answer": "return "}, {"prompt": " import os import sys import unittest sys . path . append ( os . path . join ( os . path . dirname ( __file__ ) , \"\" ) ) from conversation_table import ConversationTable class StubConversation ( object ) : pass class TestConversationTable ( unittest . TestCase ) : def test_add_get ( self ) : table = ConversationTable ( ) conversation = StubConversation ( ) table . add_conversation ( \"\" , \"\" , conversation ) self . assertEqual ( table . get_conversation ( \"\" , \"\" ) , conversation ) self . assertTrue ( table . lock . _RLock__count == ) def test_get_without_add ( self ) : table = ConversationTable ( ) self . assertIsNone ( table . get_conversation ( \"\" , \"\" ) ) self . assertTrue ( table . lock . _RLock__count == ) def test_add_delete ( self ) : table = ConversationTable ( ) conversation = StubConversation ( ) ", "answer": "table . add_conversation ( \"\" , \"\" , conversation )"}, {"prompt": " import sys import os import commands import getopt import time import numpy as np from msct_image import Image import sct_utils as sct status , path_sct = commands . getstatusoutput ( '' ) fsloutput = '' class Param : def __init__ ( self ) : self . fname_data = '' self . fname_bvecs = '' self . slicewise = self . output_path = '' self . mat_eddy = '' self . min_norm = self . swapXY = self . cost_function_flirt = '' self . interp = '' self . delete_tmp_files = self . merge_back = self . verbose = self . plot_graph = def main ( ) : start_time = time . time ( ) try : opts , args = getopt . getopt ( sys . argv [ : ] , '' ) except getopt . GetoptError : usage ( ) if not opts : usage ( ) for opt , arg in opts : if opt == '' : usage ( ) elif opt in ( '' ) : param . fname_data = arg elif opt in ( '' ) : param . fname_bvecs = arg elif opt in ( '' ) : param . cost_function_flirt = arg elif opt in ( '' ) : param . plot_graph = int ( arg ) elif opt in ( '' ) : param . mat_eddy = arg elif opt in ( '' ) : param . output_path = arg elif opt in ( '' ) : param . interp = arg elif opt in ( '' ) : param . delete_tmp_files = int ( arg ) elif opt in ( '' ) : param . slicewise = int ( arg ) elif opt in ( '' ) : param . verbose = int ( arg ) if param . fname_data == '' or param . fname_bvecs == '' : print '' usage ( ) if param . output_path == '' : param . output_path = os . getcwd ( ) + '' path_tmp = '' + time . strftime ( \"\" ) sct . run ( '' + path_tmp , param . verbose ) os . chdir ( path_tmp ) eddy_correct ( param ) os . chdir ( '' ) if param . delete_tmp_files == : print '' sct . run ( '' + path_tmp , param . verbose ) elapsed_time = time . time ( ) - start_time print '' + str ( int ( round ( elapsed_time ) ) ) + '' def eddy_correct ( param ) : sct . printv ( '' , param . verbose ) sct . printv ( '' , param . verbose ) sct . printv ( '' , param . verbose ) fname_data = param . fname_data min_norm = param . min_norm cost_function = param . cost_function_flirt verbose = param . verbose sct . printv ( ( '' + param . fname_data ) , verbose ) sct . printv ( ( '' + param . fname_bvecs ) , verbose ) path_data , file_data , ext_data = sct . extract_fname ( fname_data ) if param . mat_eddy == '' : param . mat_eddy = '' if not os . path . exists ( param . mat_eddy ) : os . makedirs ( param . mat_eddy ) mat_eddy = param . mat_eddy schedule_file = path_sct + '' sct . printv ( ( '' + schedule_file ) , verbose ) if param . swapXY == : sct . printv ( '' , verbose ) fname_data_new = '' cmd = fsloutput + '' + fname_data + '' + fname_data_new status , output = sct . run ( cmd , verbose ) sct . printv ( ( '' + fname_data_new ) , verbose ) else : fname_data_new = fname_data sct . printv ( '' , verbose ) nx , ny , nz , nt , px , py , pz , pt = Image ( fname_data ) . dim sct . printv ( '' + str ( nx ) + '' + str ( ny ) + '' + str ( nz ) + '' + str ( nt ) , verbose ) sct . printv ( '' , verbose ) from sct_image import split_data im_to_split = Image ( fname_data_new + '' ) im_split_list = split_data ( im_to_split , ) for im in im_split_list : im . save ( ) if param . slicewise : nb_loops = nz file_suffix = [ ] for iZ in range ( nz ) : file_suffix . append ( '' + str ( iZ ) . zfill ( ) ) else : nb_loops = file_suffix = [ '' ] sct . printv ( '' , verbose ) sct . printv ( '' , verbose ) bvecs = [ ] with open ( param . fname_bvecs ) as f : for line in f : bvecs_new = map ( float , line . split ( ) ) bvecs . append ( bvecs_new ) if not len ( bvecs [ ] [ : ] ) == : sct . printv ( '' , verbose ) sct . printv ( '' , verbose ) bvecs = zip ( * bvecs ) bvecs = np . array ( bvecs ) opposite_gradients_iT = [ ] opposite_gradients_jT = [ ] index_identified = [ ] index_b0 = [ ] for iT in range ( nt - ) : if np . linalg . norm ( bvecs [ iT , : ] ) != : if iT not in index_identified : jT = iT + if np . linalg . norm ( ( bvecs [ iT , : ] + bvecs [ jT , : ] ) ) < min_norm : sct . printv ( ( '' + str ( iT ) + '' + str ( jT ) ) , verbose ) opposite_gradients_iT . append ( iT ) opposite_gradients_jT . append ( jT ) index_identified . append ( iT ) else : index_b0 . append ( iT ) sct . printv ( ( '' + str ( iT ) + '' ) , verbose ) nb_oppositeGradients = len ( opposite_gradients_iT ) sct . printv ( ( '' + str ( * nb_oppositeGradients ) + '' + str ( nb_oppositeGradients ) + '' ) , verbose ) sct . printv ( '' + str ( index_b0 ) , verbose ) for iN in range ( nb_oppositeGradients ) : i_plus = opposite_gradients_iT [ iN ] i_minus = opposite_gradients_jT [ iN ] sct . printv ( ( '' + str ( i_plus ) + '' + str ( i_minus ) + '' + str ( iN ) + '' + str ( nb_oppositeGradients ) + '' ) , verbose ) sct . printv ( '' , verbose ) if param . slicewise : sct . printv ( '' , verbose ) fname_plus = file_data + '' + str ( i_plus ) . zfill ( ) fname_plus_Z = file_data + '' + str ( i_plus ) . zfill ( ) + '' im_plus = Image ( fname_plus + '' ) im_plus_split_list = split_data ( im_plus , ) for im_p in im_plus_split_list : im_p . save ( ) fname_minus = file_data + '' + str ( i_minus ) . zfill ( ) fname_minus_Z = file_data + '' + str ( i_minus ) . zfill ( ) + '' im_minus = Image ( fname_minus + '' ) im_minus_split_list = split_data ( im_minus , ) for im_m in im_minus_split_list : im_m . save ( ) for iZ in range ( nb_loops ) : fname_plus = file_data + '' + str ( i_plus ) . zfill ( ) + file_suffix [ iZ ] fname_minus = file_data + '' + str ( i_minus ) . zfill ( ) + file_suffix [ iZ ] sct . printv ( '' , verbose ) fname_plus_corr = file_data + '' + str ( i_plus ) . zfill ( ) + file_suffix [ iZ ] + '' omat = '' + file_data + '' + str ( i_plus ) . zfill ( ) + file_suffix [ iZ ] + '' cmd = fsloutput + '' + fname_plus + '' + fname_minus + '' + schedule_file + '' + omat + '' + cost_function + '' status , output = sct . run ( cmd , verbose ) file = open ( omat ) Matrix = np . loadtxt ( file ) file . close ( ) M = Matrix [ : , : ] sct . printv ( ( '' + str ( M ) ) , verbose ) sct . printv ( ( '' + omat ) , verbose ) sct . printv ( '' , verbose ) A = ( M - np . identity ( ) ) / Mplus = np . identity ( ) + A omat_plus = mat_eddy + '' + str ( i_plus ) + '' + str ( iZ ) + '' file = open ( omat_plus , '' ) np . savetxt ( omat_plus , Mplus , fmt = '' , delimiter = '' , newline = '' , header = '' , footer = '' , comments = '' ) file . close ( ) sct . printv ( ( '' + omat_plus ) , verbose ) Mminus = np . identity ( ) - A ", "answer": "omat_minus = mat_eddy + '' + str ( i_minus ) + '' + str ( iZ ) + ''"}, {"prompt": " import re from django . core import mail from django . core . urlresolvers import reverse from django_webtest import WebTest from oscar . test . testcases import WebTestCase from oscar . test import factories from oscar . core . compat import get_user_model User = get_user_model ( ) class TestAUserWhoseForgottenHerPassword ( WebTest ) : def test_can_reset_her_password ( self ) : username , email , password = '' , '' , '' User . objects . create_user ( username , email , password ) page = self . app . get ( reverse ( '' ) ) form = page . forms [ '' ] form [ '' ] = email response = form . submit ( ) self . assertEqual ( , response . status_code ) self . assertEqual ( , len ( mail . outbox ) ) email_body = mail . outbox [ ] . body urlfinder = re . compile ( r\"\" ) matches = urlfinder . search ( email_body , re . MULTILINE ) self . assertTrue ( '' in matches . groupdict ( ) ) path = matches . groupdict ( ) [ '' ] reset_page = self . app . get ( path ) form = reset_page . forms [ '' ] form [ '' ] = '' form [ '' ] = '' response = form . submit ( ) self . assertEqual ( , response . status_code ) url = reverse ( '' ) form = self . app . get ( url ) . forms [ '' ] form [ '' ] = email form [ '' ] = '' response = form . submit ( '' ) self . assertEqual ( , response . status_code ) class TestAnAuthenticatedUser ( WebTestCase ) : is_anonymous = False def test_receives_an_email_when_their_password_is_changed ( self ) : page = self . get ( reverse ( '' ) ) form = page . forms [ '' ] form [ '' ] = self . password form [ '' ] = u'' form [ '' ] = u'' page = form . submit ( ) self . assertEqual ( len ( mail . outbox ) , ) self . assertIn ( \"\" , mail . outbox [ ] . body ) def test_cannot_access_reset_password_page ( self ) : response = self . get ( reverse ( '' ) , status = ) self . assertEqual ( , response . status_code ) def test_does_not_receive_an_email_when_their_profile_is_updated_but_email_address_not_changed ( self ) : page = self . get ( reverse ( '' ) ) form = page . forms [ '' ] form [ '' ] = \"\" form . submit ( ) self . assertEqual ( len ( mail . outbox ) , ) def test_receives_an_email_when_their_email_address_is_changed ( self ) : page = self . get ( reverse ( '' ) ) form = page . forms [ '' ] new_email = '' form [ '' ] = new_email page = form . submit ( ) self . assertEqual ( len ( mail . outbox ) , ) self . assertEqual ( mail . outbox [ ] . to [ ] , self . email ) self . assertEqual ( User . objects . get ( id = self . user . id ) . email , new_email ) self . assertIn ( \"\" , mail . outbox [ ] . body ) class TestAnAnonymousUser ( WebTestCase ) : is_anonymous = True def assertCanLogin ( self , email , password ) : url = reverse ( '' ) form = self . app . get ( url ) . forms [ '' ] form [ '' ] = email form [ '' ] = password response = form . submit ( '' ) self . assertRedirectsTo ( response , '' ) def test_can_login ( self ) : email , password = '' , '' User . objects . create_user ( '' , email , password ) self . assertCanLogin ( email , password ) def test_can_login_with_email_containing_capitals_in_local_part ( self ) : email , password = '' , '' User . objects . create_user ( '' , email , password ) self . assertCanLogin ( email , password ) def test_can_login_with_email_containing_capitals_in_host ( self ) : email , password = '' , '' User . objects . create_user ( '' , email , password ) self . assertCanLogin ( email , password ) def test_can_register ( self ) : url = reverse ( '' ) form = self . app . get ( url ) . forms [ '' ] form [ '' ] = '' form [ '' ] = form [ '' ] = '' response = form . submit ( ) self . assertRedirectsTo ( response , '' ) def test_casing_of_local_part_of_email_is_preserved ( self ) : url = reverse ( '' ) form = self . app . get ( url ) . forms [ '' ] form [ '' ] = '' form [ '' ] = form [ '' ] = '' form . submit ( ) user = User . objects . all ( ) [ ] self . assertEqual ( user . email , '' ) class TestAStaffUser ( WebTestCase ) : is_anonymous = True password = '' def setUp ( self ) : self . staff = factories . UserFactory . create ( ", "answer": "password = self . password , is_staff = True )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " import django from django import template from django . template import defaultfilters ", "answer": "from django . utils import safestring"}, {"prompt": " \"\"\"\"\"\" ", "answer": "import logging"}, {"prompt": " THINGS = [ ] def setUpModule ( ) : ", "answer": "THINGS . append ( )"}, {"prompt": " from kafka . structs import * ", "answer": "from kafka . errors import * "}, {"prompt": " \"\"\"\"\"\" from functools import reduce import param try : from itertools import izip as zip except : pass from . dimension import ViewableElement from . element import Element , HoloMap , GridSpace , Collator from . layout import Layout from . overlay import NdOverlay , Overlay from . spaces import DynamicMap from . traversal import unique_dimkeys from . import util class Operation ( param . ParameterizedFunction ) : \"\"\"\"\"\" group = param . String ( default = '' , doc = \"\"\"\"\"\" ) @ classmethod def search ( cls , element , pattern ) : \"\"\"\"\"\" if isinstance ( element , Layout ) : return [ el for cell in element for el in cls . search ( cell , pattern ) ] if isinstance ( element , ( NdOverlay , Overlay ) ) : return [ el for el in element if el . matches ( pattern ) ] elif isinstance ( element , Element ) : return [ element ] if element . matches ( pattern ) else [ ] @ classmethod def get_overlay_label ( cls , overlay , default_label = '' ) : \"\"\"\"\"\" if all ( el . label == overlay . get ( ) . label for el in overlay ) : return overlay . get ( ) . label else : return default_label @ classmethod def get_overlay_bounds ( cls , overlay ) : \"\"\"\"\"\" if all ( el . bounds == overlay . get ( ) . bounds for el in overlay ) : return overlay . get ( ) . bounds else : raise ValueError ( \"\" ) class DynamicOperation ( Operation ) : \"\"\"\"\"\" def __call__ ( self , map_obj , ** params ) : self . p = param . ParamOverrides ( self , params ) callback = self . _dynamic_operation ( map_obj ) if isinstance ( map_obj , DynamicMap ) : return map_obj . clone ( callback = callback , shared_data = False ) else : return self . _make_dynamic ( map_obj , callback ) def _process ( self , element ) : return element def _dynamic_operation ( self , map_obj ) : \"\"\"\"\"\" if not isinstance ( map_obj , DynamicMap ) : def dynamic_operation ( * key ) : return self . _process ( map_obj [ key ] ) return dynamic_operation def dynamic_operation ( * key ) : key = key [ ] if map_obj . mode == '' else key _ , el = util . get_dynamic_item ( map_obj , map_obj . kdims , key ) return self . _process ( el ) return dynamic_operation def _make_dynamic ( self , hmap , dynamic_fn ) : \"\"\"\"\"\" dim_values = zip ( * hmap . data . keys ( ) ) params = util . get_param_values ( hmap ) kdims = [ d ( values = list ( values ) ) for d , values in zip ( hmap . kdims , dim_values ) ] return DynamicMap ( dynamic_fn , ** dict ( params , kdims = kdims ) ) class DynamicFunction ( DynamicOperation ) : \"\"\"\"\"\" function = param . Callable ( default = lambda x : x , doc = \"\"\"\"\"\" ) kwargs = param . Dict ( default = { } , doc = \"\"\"\"\"\" ) def _process ( self , element ) : return self . p . function ( element , ** self . p . kwargs ) class ElementOperation ( Operation ) : \"\"\"\"\"\" dynamic = param . ObjectSelector ( default = '' , objects = [ '' , True , False ] , doc = \"\"\"\"\"\" ) input_ranges = param . ClassSelector ( default = { } , class_ = ( dict , tuple ) , doc = \"\"\"\"\"\" ) def _process ( self , view , key = None ) : \"\"\"\"\"\" raise NotImplementedError def process_element ( self , element , key , ** params ) : \"\"\"\"\"\" self . p = param . ParamOverrides ( self , params ) return self . _process ( element , key ) def __call__ ( self , element , ** params ) : self . p = param . ParamOverrides ( self , params ) dynamic = ( ( self . p . dynamic == '' and isinstance ( element , DynamicMap ) ) or self . p . dynamic is True ) if isinstance ( element , ViewableElement ) : processed = self . _process ( element ) elif isinstance ( element , GridSpace ) : grid_data = ( ( pos , self ( cell , ** params ) ) for pos , cell in element . items ( ) ) processed = GridSpace ( grid_data , label = element . label , kdims = element . kdims ) elif dynamic : ", "answer": "processed = DynamicFunction ( element , function = self , kwargs = params )"}, {"prompt": " from urllib2 import URLError try : from Ft . Lib import UriException except : from urllib2 import URLError as UriException import unittest from rdflib import ConjunctiveGraph , URIRef class SPARQLloadContextsTest ( unittest . TestCase ) : def test_dSet_parsed_as_URL_raises_Exception ( self ) : querystr = \"\"\"\"\"\" graph = ConjunctiveGraph ( ) graph . get_context ( URIRef ( \"\" ) ) . parse ( \"\" ) self . assertRaises ( ( URLError , UriException ) , ", "answer": "graph . query , ( querystr ) , loadContexts = False )"}, {"prompt": " \"\"\"\"\"\" from warnings import warn as _warn from types import MethodType as _MethodType , BuiltinMethodType as _BuiltinMethodType from math import log as _log , exp as _exp , pi as _pi , e as _e from math import sqrt as _sqrt , acos as _acos , cos as _cos , sin as _sin from os import urandom as _urandom from binascii import hexlify as _hexlify __all__ = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] NV_MAGICCONST = * _exp ( - ) / _sqrt ( ) TWOPI = * _pi LOG4 = _log ( ) SG_MAGICCONST = + _log ( ) BPF = RECIP_BPF = ** - BPF import _random class Random ( _random . Random ) : \"\"\"\"\"\" VERSION = def __init__ ( self , x = None ) : \"\"\"\"\"\" self . seed ( x ) self . gauss_next = None def seed ( self , a = None ) : \"\"\"\"\"\" if a is None : try : a = long ( _hexlify ( _urandom ( ) ) , ) except NotImplementedError : import time a = long ( time . time ( ) * ) super ( Random , self ) . seed ( a ) self . gauss_next = None def getstate ( self ) : \"\"\"\"\"\" return self . VERSION , super ( Random , self ) . getstate ( ) , self . gauss_next def setstate ( self , state ) : \"\"\"\"\"\" version = state [ ] if version == : version , internalstate , self . gauss_next = state super ( Random , self ) . setstate ( internalstate ) else : raise ValueError ( \"\" \"\" % ( version , self . VERSION ) ) def __getstate__ ( self ) : return self . getstate ( ) def __setstate__ ( self , state ) : self . setstate ( state ) def __reduce__ ( self ) : return self . __class__ , ( ) , self . getstate ( ) def randrange ( self , start , stop = None , step = , int = int , default = None , maxwidth = L << BPF ) : \"\"\"\"\"\" istart = int ( start ) if istart != start : raise ValueError , \"\" if stop is default : if istart > : if istart >= maxwidth : return self . _randbelow ( istart ) return int ( self . random ( ) * istart ) raise ValueError , \"\" istop = int ( stop ) if istop != stop : raise ValueError , \"\" width = istop - istart if step == and width > : if width >= maxwidth : return int ( istart + self . _randbelow ( width ) ) return int ( istart + int ( self . random ( ) * width ) ) if step == : raise ValueError , \"\" % ( istart , istop , width ) istep = int ( step ) if istep != step : raise ValueError , \"\" if istep > : n = ( width + istep - ) // istep elif istep < : n = ( width + istep + ) // istep else : raise ValueError , \"\" if n <= : raise ValueError , \"\" if n >= maxwidth : return istart + self . _randbelow ( n ) return istart + istep * int ( self . random ( ) * n ) def randint ( self , a , b ) : \"\"\"\"\"\" return self . randrange ( a , b + ) def _randbelow ( self , n , _log = _log , int = int , _maxwidth = L << BPF , _Method = _MethodType , _BuiltinMethod = _BuiltinMethodType ) : \"\"\"\"\"\" try : getrandbits = self . getrandbits except AttributeError : pass else : if type ( self . random ) is _BuiltinMethod or type ( getrandbits ) is _Method : k = int ( + _log ( n - , ) ) r = getrandbits ( k ) while r >= n : r = getrandbits ( k ) return r if n >= _maxwidth : _warn ( \"\" \"\" ) return int ( self . random ( ) * n ) def choice ( self , seq ) : \"\"\"\"\"\" return seq [ int ( self . random ( ) * len ( seq ) ) ] def shuffle ( self , x , random = None , int = int ) : \"\"\"\"\"\" if random is None : random = self . random for i in reversed ( xrange ( , len ( x ) ) ) : j = int ( random ( ) * ( i + ) ) x [ i ] , x [ j ] = x [ j ] , x [ i ] def sample ( self , population , k ) : \"\"\"\"\"\" n = len ( population ) if not <= k <= n : raise ValueError , \"\" random = self . random _int = int result = [ None ] * k if n < * k : pool = list ( population ) for i in xrange ( k ) : j = _int ( random ( ) * ( n - i ) ) result [ i ] = pool [ j ] pool [ j ] = pool [ n - i - ] else : try : n > and ( population [ ] , population [ n // ] , population [ n - ] ) except ( TypeError , KeyError ) : population = tuple ( population ) selected = { } for i in xrange ( k ) : j = _int ( random ( ) * n ) while j in selected : j = _int ( random ( ) * n ) result [ i ] = selected [ j ] = population [ j ] return result def uniform ( self , a , b ) : \"\"\"\"\"\" return a + ( b - a ) * self . random ( ) def normalvariate ( self , mu , sigma ) : \"\"\"\"\"\" random = self . random while : u1 = random ( ) u2 = - random ( ) z = NV_MAGICCONST * ( u1 - ) / u2 zz = z * z / if zz <= - _log ( u2 ) : break return mu + z * sigma def lognormvariate ( self , mu , sigma ) : \"\"\"\"\"\" return _exp ( self . normalvariate ( mu , sigma ) ) def expovariate ( self , lambd ) : \"\"\"\"\"\" random = self . random u = random ( ) while u <= : u = random ( ) return - _log ( u ) / lambd def vonmisesvariate ( self , mu , kappa ) : \"\"\"\"\"\" random = self . random if kappa <= : return TWOPI * random ( ) a = + _sqrt ( + * kappa * kappa ) b = ( a - _sqrt ( * a ) ) / ( * kappa ) r = ( + b * b ) / ( * b ) while : u1 = random ( ) z = _cos ( _pi * u1 ) f = ( + r * z ) / ( r + z ) c = kappa * ( r - f ) u2 = random ( ) if u2 < c * ( - c ) or u2 <= c * _exp ( - c ) : break u3 = random ( ) if u3 > : theta = ( mu % TWOPI ) + _acos ( f ) else : theta = ( mu % TWOPI ) - _acos ( f ) return theta def gammavariate ( self , alpha , beta ) : \"\"\"\"\"\" if alpha <= or beta <= : raise ValueError , '' random = self . random if alpha > : ainv = _sqrt ( * alpha - ) bbb = alpha - LOG4 ccc = alpha + ainv while : u1 = random ( ) if not < u1 < : continue u2 = - random ( ) v = _log ( u1 / ( - u1 ) ) / ainv x = alpha * _exp ( v ) z = u1 * u1 * u2 r = bbb + ccc * v - x if r + SG_MAGICCONST - * z >= or r >= _log ( z ) : return x * beta elif alpha == : u = random ( ) while u <= : u = random ( ) return - _log ( u ) * beta else : while : u = random ( ) b = ( _e + alpha ) / _e p = b * u if p <= : x = p ** ( / alpha ) else : x = - _log ( ( b - p ) / alpha ) u1 = random ( ) if p > : if u1 <= x ** ( alpha - ) : break elif u1 <= _exp ( - x ) : break return x * beta def gauss ( self , mu , sigma ) : \"\"\"\"\"\" random = self . random z = self . gauss_next self . gauss_next = None if z is None : x2pi = random ( ) * TWOPI g2rad = _sqrt ( - * _log ( - random ( ) ) ) z = _cos ( x2pi ) * g2rad self . gauss_next = _sin ( x2pi ) * g2rad return mu + z * sigma def betavariate ( self , alpha , beta ) : \"\"\"\"\"\" y = self . gammavariate ( alpha , ) if y == : return else : return y / ( y + self . gammavariate ( beta , ) ) def paretovariate ( self , alpha ) : \"\"\"\"\"\" u = - self . random ( ) return / pow ( u , / alpha ) def weibullvariate ( self , alpha , beta ) : \"\"\"\"\"\" u = - self . random ( ) return alpha * pow ( - _log ( u ) , / beta ) class WichmannHill ( Random ) : VERSION = def seed ( self , a = None ) : \"\"\"\"\"\" if a is None : try : a = long ( _hexlify ( _urandom ( ) ) , ) except NotImplementedError : import time a = long ( time . time ( ) * ) if not isinstance ( a , ( int , long ) ) : a = hash ( a ) a , x = divmod ( a , ) a , y = divmod ( a , ) a , z = divmod ( a , ) self . _seed = int ( x ) + , int ( y ) + , int ( z ) + self . gauss_next = None def random ( self ) : \"\"\"\"\"\" x , y , z = self . _seed x = ( * x ) % y = ( * y ) % z = ( * z ) % self . _seed = x , y , z return ( x / + y / + z / ) % def getstate ( self ) : \"\"\"\"\"\" return self . VERSION , self . _seed , self . gauss_next def setstate ( self , state ) : \"\"\"\"\"\" version = state [ ] if version == : version , self . _seed , self . gauss_next = state else : raise ValueError ( \"\" \"\" % ( version , self . VERSION ) ) def jumpahead ( self , n ) : \"\"\"\"\"\" if not n >= : raise ValueError ( \"\" ) x , y , z = self . _seed x = int ( x * pow ( , n , ) ) % y = int ( y * pow ( , n , ) ) % ", "answer": "z = int ( z * pow ( , n , ) ) % "}, {"prompt": " r\"\"\"\"\"\" import sys import json def main ( ) : if len ( sys . argv ) == : infile = sys . stdin outfile = sys . stdout elif len ( sys . argv ) == : infile = open ( sys . argv [ ] , '' ) outfile = sys . stdout elif len ( sys . argv ) == : infile = open ( sys . argv [ ] , '' ) outfile = open ( sys . argv [ ] , '' ) else : raise SystemExit ( sys . argv [ ] + \"\" ) try : obj = json . load ( infile , object_pairs_hook = json . OrderedDict , use_decimal = True ) ", "answer": "except ValueError as e :"}, {"prompt": " from django . db import models from django_twofactor . util import decrypt_value , check_raw_seed , get_google_url from base64 import b32encode from socket import gethostname class UserAuthToken ( models . Model ) : user = models . OneToOneField ( \"\" ) encrypted_seed = models . CharField ( max_length = ) created_datetime = models . DateTimeField ( verbose_name = \"\" , auto_now_add = True ) updated_datetime = models . DateTimeField ( verbose_name = \"\" , auto_now = True ) def check_auth_code ( self , auth_code ) : \"\"\"\"\"\" return check_raw_seed ( decrypt_value ( self . encrypted_seed ) , auth_code ) def google_url ( self , name = None ) : \"\"\"\"\"\" if not name : username = self . user . username hostname = gethostname ( ) name = \"\" % ( username , hostname ) return get_google_url ( ", "answer": "decrypt_value ( self . encrypted_seed ) ,"}, {"prompt": " from __future__ import absolute_import , unicode_literals try : import unittest unittest . skip ", "answer": "except AttributeError :"}, {"prompt": " from batcountry import BatCountry from PIL import Image import numpy as np import argparse ap = argparse . ArgumentParser ( ) ap . add_argument ( \"\" , \"\" , required = True , help = \"\" ) ", "answer": "ap . add_argument ( \"\" , \"\" , type = str , default = \"\" ,"}, {"prompt": " from scrapy . exceptions import DropItem from scrapy_sci . status import Status , Reader class DuplicatesPipeline ( object ) : def __init__ ( self ) : self . ids_seen = set ( ) status = Status ( ) for classifier in status . classifiers . keys ( ) : for rf in status . classifiers [ classifier ] [ '' ] : json = Reader . read_reviewed ( rf ) ", "answer": "self . ids_seen . add ( json [ '' ] )"}, {"prompt": " '''''' from django . utils . importlib import import_module from django . db . models import signals from django . conf import settings import logging logger = logging . getLogger ( \"\" ) def post_syncdb_run ( sender , ** kwargs ) : \"\"\"\"\"\" post_syncdb_run . queued = getattr ( post_syncdb_run , \"\" , [ ] ) post_syncdb_run . perms_installed = getattr ( post_syncdb_run , \"\" , False ) app = sender . __name__ . split ( \"\" ) [ ] if app == \"\" : post_syncdb_run . perms_installed = True post_syncdb_run . queued . append ( app ) if post_syncdb_run . perms_installed : for app in post_syncdb_run . queued : logger . debug ( \"\" % app ) try : mod = import_module ( \"\" % app ) except ImportError as exc : msg = exc . args [ ] ", "answer": "if not msg . startswith ( '' ) or \"\" not in msg :"}, {"prompt": " from django . contrib import messages from django . contrib . auth import logout , login , authenticate from django . contrib . auth . decorators import login_required from django . contrib . auth . models import User from django . http import HttpResponseBadRequest , Http404 from django . shortcuts import render , redirect , get_object_or_404 from reddit . forms import UserForm , ProfileForm from reddit . utils . helpers import post_only from users . models import RedditUser def user_profile ( request , username ) : user = get_object_or_404 ( User , username = username ) profile = RedditUser . objects . get ( user = user ) return render ( request , '' , { '' : profile } ) @ login_required def edit_profile ( request ) : user = RedditUser . objects . get ( user = request . user ) if request . method == '' : profile_form = ProfileForm ( instance = user ) elif request . method == '' : profile_form = ProfileForm ( request . POST , instance = user ) if profile_form . is_valid ( ) : profile = profile_form . save ( commit = False ) profile . update_profile_data ( ) profile . save ( ) messages . success ( request , \"\" ) else : raise Http404 return render ( request , '' , { '' : profile_form } ) def user_login ( request ) : \"\"\"\"\"\" if request . user . is_authenticated ( ) : messages . warning ( request , \"\" ) return render ( request , '' ) if request . method == \"\" : username = request . POST . get ( '' ) password = request . POST . get ( '' ) if not username or not password : return HttpResponseBadRequest ( ) user = authenticate ( username = username , password = password ) if user : if user . is_active : login ( request , user ) redirect_url = request . POST . get ( '' ) or '' return redirect ( redirect_url ) else : return render ( request , '' , { '' : \"\" } ) else : return render ( request , '' , { '' : \"\" } ) return render ( request , '' ) @ post_only def user_logout ( request ) : \"\"\"\"\"\" if request . user . is_authenticated ( ) : redirect_page = request . POST . get ( '' , '' ) logout ( request ) messages . success ( request , '' ) return redirect ( redirect_page ) return redirect ( '' ) def register ( request ) : \"\"\"\"\"\" user_form = UserForm ( ) if request . user . is_authenticated ( ) : messages . warning ( request , '' ) return render ( request , '' , { '' : user_form } ) if request . method == \"\" : user_form = UserForm ( request . POST ) if user_form . is_valid ( ) : user = user_form . save ( ) user . set_password ( user . password ) user . save ( ) reddit_user = RedditUser ( ) reddit_user . user = user ", "answer": "reddit_user . save ( )"}, {"prompt": " \"\"\"\"\"\" from copy import deepcopy import json import xml . etree . ElementTree as ET from cafe . engine . models . base import AutoMarshallingModel from cloudcafe . networking . lbaas . common . constants import Constants class CreateHealthMonitor ( AutoMarshallingModel ) : \"\"\"\"\"\" ROOT_TAG = '' def __init__ ( self , type_ , tenant_id , delay , timeout , max_retries , ", "answer": "http_method = None , url_path = None , expected_codes = None ,"}, {"prompt": " from setuptools import setup setup ( name = \"\" , version = \"\" , license = \"\" ", "answer": ") "}, {"prompt": " from novaclient . tests . functional import base class TestVirtualInterfacesNovaClient ( base . ClientTestBase ) : \"\"\"\"\"\" COMPUTE_API_VERSION = \"\" def test_virtual_interface_list ( self ) : server = self . _create_server ( ) ", "answer": "output = self . nova ( '' % server . id )"}, {"prompt": " from gremlinclient . tornado_client . client import ( ", "answer": "Response , GraphDatabase , Pool , submit , create_connection ) "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from __future__ import absolute_import from . utils import jr_split , jp_split from . getter import UrlGetter , LocalGetter import six import os import inspect import logging logger = logging . getLogger ( __name__ ) class SwaggerResolver ( object ) : \"\"\"\"\"\" def __init__ ( self , url_load_hook ) : \"\"\"\"\"\" self . __cache = { } self . __url_load_hook = url_load_hook def resolve ( self , jref , getter = None ) : \"\"\"\"\"\" url , jp = jr_split ( jref ) local_url = self . __url_load_hook ( url ) if self . __url_load_hook else url logger . info ( '' . format ( url , local_url ) ) obj = self . __cache . get ( url , None ) if not obj : if not getter : getter = UrlGetter p = six . moves . urllib . parse . urlparse ( local_url ) if p . scheme == '' and p . path : getter = LocalGetter ( os . path . join ( p . netloc , p . path ) ) if inspect . isclass ( getter ) : getter = getter ( local_url ) obj = six . advance_iterator ( getter ) ", "answer": "self . __cache [ url ] = obj if obj else None"}, {"prompt": " from blog . models import * db . connect ( ) print ( \"\" ) Post . create_table ( True ) p1 = Post ( ) p1 . title = \"\" p1 . url = p1 . create_url ( p1 . title ) p1 . body = \"\" p1 . short_description = \"\" p1 . save ( ) p2 = Post ( ) p2 . title = \"\" p2 . url = p2 . create_url ( p2 . title ) p2 . body = \"\" p2 . short_description = \"\" p2 . save ( ) ", "answer": "p3 = Post ( )"}, {"prompt": " from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import units import six import nova . conf from nova import exception from nova . i18n import _ from nova . i18n import _LW from nova . virt . libvirt import utils lvm_opts = [ cfg . StrOpt ( '' , default = '' , choices = ( '' , '' , '' ) , help = '' ) , cfg . IntOpt ( '' , default = , help = '' ) , ] CONF = nova . conf . CONF CONF . register_opts ( lvm_opts , '' ) LOG = logging . getLogger ( __name__ ) def create_volume ( vg , lv , size , sparse = False ) : \"\"\"\"\"\" vg_info = get_volume_group_info ( vg ) free_space = vg_info [ '' ] def check_size ( vg , lv , size ) : if size > free_space : raise RuntimeError ( _ ( '' '' '' '' ) % { '' : vg , '' : free_space , '' : size , '' : lv } ) if sparse : preallocated_space = * units . Mi check_size ( vg , lv , preallocated_space ) if free_space < size : LOG . warning ( _LW ( '' '' '' '' '' ) , { '' : vg , '' : free_space , '' : size , '' : lv } ) cmd = ( '' , '' , '' % preallocated_space , '' , '' % size , '' , lv , vg ) else : check_size ( vg , lv , size ) cmd = ( '' , '' , '' % size , '' , lv , vg ) utils . execute ( * cmd , run_as_root = True , attempts = ) def get_volume_group_info ( vg ) : \"\"\"\"\"\" out , err = utils . execute ( '' , '' , '' , '' , '' , '' , '' , '' , '' , vg , run_as_root = True ) info = out . split ( '' ) if len ( info ) != : raise RuntimeError ( _ ( \"\" ) % vg ) return { '' : int ( info [ ] ) , '' : int ( info [ ] ) , '' : int ( info [ ] ) - int ( info [ ] ) } def list_volumes ( vg ) : \"\"\"\"\"\" out , err = utils . execute ( '' , '' , '' , '' , vg , run_as_root = True ) return [ line . strip ( ) for line in out . splitlines ( ) ] def volume_info ( path ) : \"\"\"\"\"\" out , err = utils . execute ( '' , '' , '' , '' , '' , path , run_as_root = True ) info = [ line . split ( '' ) for line in out . splitlines ( ) ] if len ( info ) != : raise RuntimeError ( _ ( \"\" ) % path ) return dict ( zip ( * info ) ) def get_volume_size ( path ) : \"\"\"\"\"\" try : out , _err = utils . execute ( '' , '' , path , run_as_root = True ) except processutils . ProcessExecutionError : if not utils . path_exists ( path ) : raise exception . VolumeBDMPathNotFound ( path = path ) else : raise return int ( out ) def _zero_volume ( path , volume_size ) : \"\"\"\"\"\" bs = units . Mi direct_flags = ( '' , ) sync_flags = ( ) remaining_bytes = volume_size while remaining_bytes : zero_blocks = remaining_bytes / bs seek_blocks = ( volume_size - remaining_bytes ) / bs zero_cmd = ( '' , '' % bs , '' , '' % path , '' % seek_blocks , '' % zero_blocks ) zero_cmd += direct_flags zero_cmd += sync_flags if zero_blocks : utils . execute ( * zero_cmd , run_as_root = True ) remaining_bytes %= bs bs /= units . Ki direct_flags = ( ) sync_flags = ( '' , ) def clear_volume ( path ) : \"\"\"\"\"\" volume_clear = CONF . libvirt . volume_clear ", "answer": "if volume_clear == '' :"}, {"prompt": " from load_data import load_color import numpy as np import theano import theano . tensor as tensor from theano . tensor . signal . downsample import max_pool_2d def _relu ( X ) : return X * ( X > ) def conv_layer ( input_variable , filter_shape , pool_shape , stride , random_state ) : np_filters = * ( random_state . rand ( * filter_shape ) . astype ( theano . config . floatX ) - ) filters = theano . shared ( np_filters ) np_biases = np . zeros ( filter_shape [ ] ) . astype ( theano . config . floatX ) biases = theano . shared ( np_biases ) params = [ filters , biases ] conv = tensor . nnet . conv2d ( input_variable , filters , subsample = stride ) conv += biases . dimshuffle ( '' , , '' , '' ) n , n_params = normalization_layer ( conv , filter_shape ) params += n_params out = _relu ( n ) pooled = max_pool_2d ( out , pool_shape , ignore_border = True ) return pooled , params def fc_layer ( input_variable , layer_shape , random_state ) : np_W = * ( random_state . rand ( * layer_shape ) . astype ( theano . config . floatX ) - ) W = theano . shared ( np_W ) np_b = np . zeros ( layer_shape [ ] ) . astype ( theano . config . floatX ) b = theano . shared ( np_b ) params = [ W , b ] l = tensor . dot ( input_variable , W ) + b n , n_params = normalization_layer ( l , layer_shape ) params += n_params out = _relu ( n ) return out , params def normalization_layer ( input_variable , layer_shape ) : if len ( layer_shape ) == : np_G = np . ones ( layer_shape [ ] ) . astype ( theano . config . floatX ) np_B = np . zeros ( layer_shape [ ] ) . astype ( theano . config . floatX ) G = theano . shared ( np_G ) B = theano . shared ( np_B ) normed = ( input_variable - input_variable . mean ( axis = ( , , ) , keepdims = True ) ) / ( input_variable . std ( axis = ( , , ) , keepdims = True ) + ) out = G . dimshuffle ( '' , , '' , '' ) * normed + B . dimshuffle ( '' , , '' , '' ) else : np_G = np . ones ( layer_shape [ ] ) . astype ( theano . config . floatX ) np_B = np . zeros ( layer_shape [ ] ) . astype ( theano . config . floatX ) G = theano . shared ( np_G ) B = theano . shared ( np_B ) normed = ( input_variable - input_variable . mean ( axis = , keepdims = True ) ) / ( input_variable . std ( axis = , keepdims = True ) + ) out = G * normed + B params = [ G , B ] return out , params def softmax_layer ( input_variable , layer_shape , random_state ) : np_W = * ( random_state . rand ( * layer_shape ) . astype ( theano . config . floatX ) - ) W = theano . shared ( np_W ) np_b = np . zeros ( layer_shape [ ] ) . astype ( theano . config . floatX ) b = theano . shared ( np_b ) out = tensor . dot ( input_variable , W ) + b params = [ W , b ] e = tensor . exp ( out - out . max ( axis = , keepdims = True ) ) softmax = e / e . sum ( axis = , keepdims = True ) return softmax , params def softmax_cost ( y_hat_sym , y_sym ) : return - tensor . mean ( tensor . log ( y_hat_sym ) [ tensor . arange ( y_sym . shape [ ] ) , y_sym ] ) def minibatch_indices ( X , minibatch_size , lb = None , ub = None ) : if lb is None : lb = if ub is None : ub = len ( X ) minibatch_indices = np . arange ( lb , ub , minibatch_size ) minibatch_indices = np . asarray ( list ( minibatch_indices ) + [ ub ] ) start_indices = minibatch_indices [ : - ] end_indices = minibatch_indices [ : ] return zip ( start_indices , end_indices ) X_t , y_t = load_color ( ) shp = X_t . shape X_train = X_t [ : ] . reshape ( , - ) . astype ( '' ) mean = X_train . mean ( axis = , keepdims = True ) std = X_train . std ( axis = , keepdims = True ) X_t = ( X_t [ : ] . reshape ( len ( X_t ) , - ) - mean ) / std X_t = X_t . reshape ( * shp ) X = tensor . tensor4 ( '' ) y = tensor . ivector ( '' ) X . tag . test_value = X_t [ : ] . astype ( '' ) y . tag . test_value = y_t [ : ] . astype ( '' ) params = [ ] random_state = np . random . RandomState ( ) filter_shape = ( , , , ) pool_shape = ( , ) stride = ( , ) out , l_params = conv_layer ( X , filter_shape , pool_shape , stride , random_state ) params += l_params filter_shape = ( , filter_shape [ ] , , ) pool_shape = ( , ) stride = ( , ) out , l_params = conv_layer ( out , filter_shape , pool_shape , stride , random_state ) params += l_params filter_shape = ( , filter_shape [ ] , , ) pool_shape = ( , ) stride = ( , ) out , l_params = conv_layer ( out , filter_shape , pool_shape , stride , random_state ) params += l_params shp = out . shape out = out . reshape ( ( shp [ ] , shp [ ] * shp [ ] * shp [ ] ) ) shape = ( , ) out , l_params = fc_layer ( out , shape , random_state ) params += l_params shape = ( shape [ ] , ) out , l_params = fc_layer ( out , shape , random_state ) params += l_params shape = ( shape [ ] , ) out , l_params = softmax_layer ( out , shape , random_state ) params += l_params cost = softmax_cost ( out , y ) grads = tensor . grad ( cost , params ) minibatch_size = learning_rate = momentum = class nesterov_momentum ( object ) : \"\"\"\"\"\" def __init__ ( self , params ) : ", "answer": "self . mem = [ theano . shared ( np . zeros_like ( p . get_value ( ) ) )"}, {"prompt": " from __future__ import unicode_literals from django . test import ( TestCase , ) from django . test . utils import override_settings from cookie_consent . models import ( Cookie , CookieGroup , ) from cookie_consent . cache import ( get_cookie_group , get_cookie , ) class CacheTest ( TestCase ) : def setUp ( self ) : self . cookie_group = CookieGroup . objects . create ( varname = \"\" , name = \"\" , ) self . cookie = Cookie . objects . create ( cookiegroup = self . cookie_group , name = \"\" , ) def test_get_cookie_group ( self ) : self . assertEqual ( get_cookie_group ( \"\" ) , self . cookie_group ) def test_get_cookie ( self ) : cookie_group = get_cookie_group ( \"\" ) self . assertEqual ( get_cookie ( cookie_group , \"\" , \"\" ) , self . cookie ) def test_caching ( self ) : CookieGroup . objects . create ( varname = \"\" , name = \"\" , ) with self . assertNumQueries ( ) : ", "answer": "cookie_group = get_cookie_group ( \"\" )"}, {"prompt": " import sys , os cwd = os . getcwd ( ) parent = os . path . dirname ( cwd ) sys . path . append ( parent ) import appengine_toolkit extensions = [ '' , '' ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' version = appengine_toolkit . __version__ release = appengine_toolkit . __version__ exclude_patterns = [ '' ] ", "answer": "pygments_style = ''"}, {"prompt": " from django . conf . urls import include from django . conf . urls import patterns from django . conf . urls import url urlpatterns = patterns ( '' , url ( r'' , include ( '' ) ) , url ( r'' , '' ) , url ( r'' , '' ) , url ( r'' , '' ) , url ( r'' , '' ) , url ( r'' , '' ) , url ( r'' , '' ) , ", "answer": "url ( r'' , '' ) ,"}, {"prompt": " \"\"\"\"\"\" import os import unittest from dfvfs . lib import definitions from dfvfs . path import compressed_stream_path_spec from dfvfs . path import os_path_spec from dfvfs . resolver import context from dfvfs . vfs import compressed_stream_file_entry from dfvfs . vfs import compressed_stream_file_system class CompressedStreamFileEntryTest ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" self . _resolver_context = context . Context ( ) test_file = os . path . join ( u'' , u'' ) path_spec = os_path_spec . OSPathSpec ( location = test_file ) self . _compressed_stream_path_spec = ( compressed_stream_path_spec . CompressedStreamPathSpec ( compression_method = definitions . COMPRESSION_METHOD_BZIP2 , parent = path_spec ) ) self . _file_system = ( compressed_stream_file_system . CompressedStreamFileSystem ( self . _resolver_context ) ) self . _file_system . Open ( self . _compressed_stream_path_spec ) def tearDown ( self ) : \"\"\"\"\"\" self . _file_system . Close ( ) def testInitialize ( self ) : \"\"\"\"\"\" file_entry = compressed_stream_file_entry . CompressedStreamFileEntry ( self . _resolver_context , self . _file_system , self . _compressed_stream_path_spec ) self . assertIsNotNone ( file_entry ) def testGetFileEntryByPathSpec ( self ) : \"\"\"\"\"\" file_entry = self . _file_system . GetFileEntryByPathSpec ( self . _compressed_stream_path_spec ) self . assertIsNotNone ( file_entry ) def testGetParentFileEntry ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import textwrap import numpy from OpenGL import GL from pygly . shader import Shader , VertexShader , FragmentShader , ShaderProgram from pygly . vertex_buffer import VertexBuffer , BufferAttributes , GenericAttribute , VertexAttribute , TextureCoordAttribute from pygly . vertex_array import VertexArray from pyrr import geometry vertices , indices = geometry . create_quad ( scale = ( , ) , st = True , dtype = '' ) vertices = vertices [ indices ] vertices . dtype = [ ( '' , '' , ( , ) ) , ( '' , '' , ( , ) ) , ] def create ( core_profile = True ) : if core_profile : return CoreQuad ( ) else : return LegacyQuad ( ) class CoreQuad ( object ) : vertex_shader = textwrap . dedent ( \"\"\"\"\"\" ) fragment_shader = textwrap . dedent ( \"\"\"\"\"\" ) def __init__ ( self ) : super ( CoreQuad , self ) . __init__ ( ) global vertices self . shader = ShaderProgram ( VertexShader ( self . vertex_shader ) , FragmentShader ( self . fragment_shader ) ) self . buffer = VertexBuffer ( GL . GL_ARRAY_BUFFER , GL . GL_STATIC_DRAW , data = vertices , ) self . buffer_attributes = BufferAttributes ( ) self . buffer_attributes [ '' ] = GenericAttribute . from_dtype ( self . buffer , vertices . dtype , '' , location = self . shader . attributes [ '' ] ) self . buffer_attributes [ '' ] = GenericAttribute . from_dtype ( self . buffer , vertices . dtype , '' , location = self . shader . attributes [ '' ] ) self . vao = VertexArray ( ) self . vao . bind ( ) self . buffer . bind ( ) self . buffer_attributes . set ( ) self . buffer . unbind ( ) self . vao . unbind ( ) def draw ( self , projection , model_view ) : global vertices self . shader . bind ( ) self . shader . uniforms [ '' ] . value = projection self . shader . uniforms [ '' ] . value = model_view self . shader . uniforms [ '' ] . value = self . vao . bind ( ) GL . glDrawArrays ( GL . GL_TRIANGLES , , len ( vertices ) ) self . vao . unbind ( ) self . shader . unbind ( ) class LegacyQuad ( object ) : vertex_shader = textwrap . dedent ( \"\"\"\"\"\" ) fragment_shader = textwrap . dedent ( \"\"\"\"\"\" ) def __init__ ( self ) : super ( LegacyQuad , self ) . __init__ ( ) global vertices self . use_shaders = True GL . glEnable ( GL . GL_TEXTURE_2D ) self . shader = ShaderProgram ( VertexShader ( self . vertex_shader ) , FragmentShader ( self . fragment_shader ) ) self . buffer = VertexBuffer ( GL . GL_ARRAY_BUFFER , GL . GL_STATIC_DRAW , data = vertices , ) self . buffer_attributes = BufferAttributes ( ) self . buffer_attributes [ '' ] = VertexAttribute . from_dtype ( self . buffer , vertices . dtype , '' ", "answer": ")"}, {"prompt": " import time import sqlalchemy as SA import pushmanager . core . db as db import pushmanager . core . util from pushmanager . core . mail import MailQueue from pushmanager . core . rb import RBQueue from pushmanager . core . requesthandler import RequestHandler class LivePushServlet ( RequestHandler ) : def _arg ( self , key ) : return pushmanager . core . util . get_str_arg ( self . request , key , '' ) def post ( self ) : if not self . current_user : return self . send_error ( ) self . pushid = pushmanager . core . util . get_int_arg ( self . request , '' ) push_query = db . push_pushes . update ( ) . where ( db . push_pushes . c . id == self . pushid ) . values ( { '' : '' , '' : time . time ( ) , } ) request_query = db . push_requests . update ( ) . where ( SA . and_ ( db . push_requests . c . state == '' , SA . exists ( [ ] , SA . and_ ( db . push_pushcontents . c . push == self . pushid , db . push_pushcontents . c . request == db . push_requests . c . id , ) ) ) ) . values ( { '' : '' , '' : time . time ( ) , } ) reset_query = db . push_requests . update ( ) . where ( SA . exists ( [ ] , SA . and_ ( db . push_requests . c . state == '' , db . push_pushcontents . c . push == self . pushid , db . push_pushcontents . c . request == db . push_requests . c . id , ) ) ) . values ( { '' : '' , } ) delete_query = db . push_pushcontents . delete ( ) . where ( SA . exists ( [ ] , SA . and_ ( db . push_pushcontents . c . push == self . pushid , db . push_pushcontents . c . request == db . push_requests . c . id , db . push_requests . c . state == '' , ) ) ) live_query = db . push_requests . select ( ) . where ( SA . and_ ( db . push_requests . c . state == '' , db . push_pushcontents . c . push == self . pushid , db . push_pushcontents . c . request == db . push_requests . c . id ) ) db . execute_transaction_cb ( [ push_query , request_query , reset_query , delete_query , live_query ] , self . on_db_complete , ) def on_db_complete ( self , success , db_results ) : self . check_db_results ( success , db_results ) _ , _ , _ , _ , live_requests = db_results for req in live_requests : if req [ '' ] : review_id = int ( req [ '' ] ) RBQueue . enqueue_review ( review_id ) if req [ '' ] : user_string = '' % ( req [ '' ] , req [ '' ] ) users = [ req [ '' ] ] + req [ '' ] . split ( '' ) else : user_string = req [ '' ] users = [ req [ '' ] ] ", "answer": "msg = ("}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import os import celery import raven from django . conf import settings from raven . contrib . celery import register_signal , register_logger_signal os . environ . setdefault ( '' , '' ) class Celery ( celery . Celery ) : def on_configure ( self ) : try : client = raven . Client ( settings . RAVEN_CONFIG [ '' ] ) register_logger_signal ( client ) register_signal ( client ) except AttributeError : ", "answer": "pass"}, {"prompt": " from . component import * from . context import * from . event import * ", "answer": "from . runner import *"}, {"prompt": " from __future__ import ( print_function , unicode_literals , division , absolute_import ) import requests import json import time import re import six from monkeylearn . settings import ( MAX_BATCH_SIZE , MIN_BATCH_SIZE ) from monkeylearn . exceptions import MonkeyLearnException class MonkeyLearnResponse ( object ) : def __init__ ( self , result , responses ) : self . result = result self . query_limit_remaining = responses [ - ] . headers [ '' ] self . raw_responses = responses class SleepRequestsMixin ( object ) : def make_request ( self , url , method , data = None , sleep_if_throttled = True ) : while True : if data : response = requests . request ( method , url , data = json . dumps ( data ) , headers = { '' : '' + self . token , '' : '' } ) else : response = requests . request ( method , url , headers = { '' : '' + self . token , '' : '' } ) response_json = response . json ( ) if sleep_if_throttled and response . status_code == and '' in response_json [ '' ] : seconds = re . findall ( r'' , response_json [ '' ] ) [ ] time . sleep ( int ( seconds ) ) continue elif ( sleep_if_throttled and response . status_code == and '' in response_json [ '' ] ) : time . sleep ( ) continue return response class HandleErrorsMixin ( object ) : ", "answer": "def check_batch_limits ( self , text_list , batch_size ) :"}, {"prompt": " \"\"\"\"\"\" import time def TestAction ( aname , args , modelResult ) : if aname == '' : ( seconds , ) = args time . sleep ( seconds ) else : ", "answer": "raise NotImplementedError , '' % aname"}, {"prompt": " from IPython . core import ipapi from IPython . core import macro ip = ipapi . get ( ) import os , pprint def export ( filename = None ) : lines = [ '' , '' , '' ] vars = ip . db . keys ( '' ) vars . sort ( ) varstomove = [ ] get = ip . db . get macros = [ ] variables = [ ] for var in vars : k = os . path . basename ( var ) v = get ( var ) if k . startswith ( '' ) : continue if isinstance ( v , macro . Macro ) : macros . append ( ( k , v ) ) if type ( v ) in [ int , str , float ] : variables . append ( ( k , v ) ) if macros : lines . extend ( [ '' , '' ] ) for k , v in macros : lines . append ( \"\" % k ) for line in v . value . splitlines ( ) : lines . append ( '' + repr ( line + '' ) ) lines . extend ( [ '' , '' ] ) if variables : lines . extend ( [ '' , '' , '' ] ) for k , v in variables : varstomove . append ( k ) lines . append ( '' % ( k , repr ( v ) ) ) lines . append ( '' % ( '' . join ( varstomove ) ) ) bkms = ip . db . get ( '' , { } ) if bkms : lines . extend ( [ '' , '' , '' ] ) lines . append ( \"\" % pprint . pformat ( bkms , indent = ) ) aliases = ip . db . get ( '' , { } ) if aliases : ", "answer": "lines . extend ( [ '' , '' , '' ] )"}, {"prompt": " import os import re import fnmatch import testing TESTS = None TESTS_BY_FILENAME = { } def automaticDependencies ( filename ) : this_dirname = os . path . dirname ( filename ) for test in TESTS : other_dirname = os . path . dirname ( test . filename ) if this_dirname . startswith ( other_dirname ) : if os . path . sep not in other_dirname or len ( other_dirname ) < len ( this_dirname ) : yield test RE_DEPENDENCY = re . compile ( r\"\" ) RE_FLAG = re . compile ( r\"\" ) RE_IGNORE = re . compile ( r\"\" ) class Test ( object ) : def __init__ ( self , filename ) : self . filename = filename self . groups = [ ] dirname = filename while True : dirname , basename = os . path . split ( dirname ) if not dirname : break self . groups . insert ( , dirname ) self . dependencies = set ( ) self . flags = set ( ) has_dependency_declarations = [ ] def process_file ( path ) : path = os . path . join ( \"\" , \"\" , path ) if not os . path . isfile ( path ) : return with open ( path ) as source_file : for index , line in enumerate ( source_file ) : match = RE_DEPENDENCY . match ( line ) if match : has_dependency_declarations . append ( True ) dependency = match . group ( ) if dependency == \"\" : pass elif dependency not in TESTS_BY_FILENAME : testing . logger . error ( \"\" % ( filename , index + , dependency ) ) else : self . dependencies . add ( TESTS_BY_FILENAME [ dependency ] ) continue match = RE_FLAG . match ( line ) if match : self . flags . add ( match . group ( ) ) continue match = RE_IGNORE . match ( line ) if not match : break process_file ( filename ) dirname = filename while True : dirname = os . path . dirname ( dirname ) if not dirname : break process_file ( os . path . join ( dirname , \"\" ) ) if not has_dependency_declarations : self . dependencies . update ( automaticDependencies ( filename ) ) TESTS . append ( self ) TESTS_BY_FILENAME [ self . filename ] = self def __str__ ( self ) : return self . filename def __hash__ ( self ) : return hash ( self . filename ) def __eq__ ( self , other ) : return self . filename == str ( other ) def __repr__ ( self ) : return \"\" % ( self . filename , sorted ( [ test . filename for test in self . dependencies ] ) ) def findTests ( ) : global TESTS RE_TEST_FILENAME = re . compile ( r\"\" ) RE_IGNORE_FILENAME = re . compile ( r\"\" ) TESTS = [ ] def traverse ( dirname ) : for filename in sorted ( os . listdir ( dirname ) ) : filename = os . path . join ( dirname , filename ) if os . path . isdir ( filename ) : traverse ( filename ) elif RE_TEST_FILENAME . search ( filename ) : Test ( os . path . relpath ( filename , \"\" ) ) elif not RE_IGNORE_FILENAME . search ( filename ) : testing . logger . warning ( \"\" % filename ) traverse ( \"\" ) def filterPatterns ( patterns ) : RE_LEADING_TESTS = re . compile ( \"\" ) patterns = [ RE_LEADING_TESTS . sub ( \"\" , pattern ) for pattern in patterns ] patterns = [ pattern . rstrip ( \"\" ) for pattern in patterns ] patterns = filter ( None , patterns ) return patterns def selectTests ( patterns , strict , flags_on = set ( ) , flags_off = set ( ) ) : if TESTS is None : findTests ( ) patterns = filterPatterns ( patterns ) if not patterns and not flags_on and not flags_off : return TESTS , set ( ) selected = set ( ) dependencies = set ( ) def select ( test , is_dependency = False ) : if test in selected : return selected . add ( test . filename ) if strict : return if is_dependency : dependencies . add ( test . filename ) for dependency in test . dependencies : select ( dependency , True ) for test in TESTS : if flags_on - test . flags : continue if flags_off & test . flags : continue if patterns : for pattern in patterns : filename = test . filename while filename : if fnmatch . fnmatch ( filename , pattern ) : ", "answer": "select ( test )"}, {"prompt": " \"\"\"\"\"\" CRLF = '' import os import Queue import re quoted_slash = re . compile ( \"\" ) import rfc822 import socket import sys if '' in sys . platform and not hasattr ( socket , '' ) : socket . IPPROTO_IPV6 = try : import cStringIO as StringIO except ImportError : import StringIO DEFAULT_BUFFER_SIZE = - _fileobject_uses_str_type = isinstance ( socket . _fileobject ( None ) . _rbuf , basestring ) import threading import time import traceback def format_exc ( limit = None ) : \"\"\"\"\"\" try : etype , value , tb = sys . exc_info ( ) return '' . join ( traceback . format_exception ( etype , value , tb , limit ) ) finally : etype = value = tb = None from urllib import unquote from urlparse import urlparse import warnings import errno def plat_specific_errors ( * errnames ) : \"\"\"\"\"\" errno_names = dir ( errno ) nums = [ getattr ( errno , k ) for k in errnames if k in errno_names ] return dict . fromkeys ( nums ) . keys ( ) socket_error_eintr = plat_specific_errors ( \"\" , \"\" ) socket_errors_to_ignore = plat_specific_errors ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ) socket_errors_to_ignore . append ( \"\" ) socket_errors_to_ignore . append ( \"\" ) socket_errors_nonblocking = plat_specific_errors ( '' , '' , '' ) comma_separated_headers = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] import logging if not hasattr ( logging , '' ) : logging . statistics = { } def read_headers ( rfile , hdict = None ) : \"\"\"\"\"\" if hdict is None : hdict = { } while True : line = rfile . readline ( ) if not line : raise ValueError ( \"\" ) if line == CRLF : break if not line . endswith ( CRLF ) : raise ValueError ( \"\" ) if line [ ] in '' : v = line . strip ( ) else : try : k , v = line . split ( \"\" , ) except ValueError : raise ValueError ( \"\" ) k = k . strip ( ) . title ( ) v = v . strip ( ) hname = k if k in comma_separated_headers : existing = hdict . get ( hname ) if existing : v = \"\" . join ( ( existing , v ) ) hdict [ hname ] = v return hdict class MaxSizeExceeded ( Exception ) : pass class SizeCheckWrapper ( object ) : \"\"\"\"\"\" def __init__ ( self , rfile , maxlen ) : self . rfile = rfile self . maxlen = maxlen self . bytes_read = def _check_length ( self ) : if self . maxlen and self . bytes_read > self . maxlen : raise MaxSizeExceeded ( ) def read ( self , size = None ) : data = self . rfile . read ( size ) self . bytes_read += len ( data ) self . _check_length ( ) return data def readline ( self , size = None ) : if size is not None : data = self . rfile . readline ( size ) self . bytes_read += len ( data ) self . _check_length ( ) return data res = [ ] while True : data = self . rfile . readline ( ) self . bytes_read += len ( data ) self . _check_length ( ) res . append ( data ) if len ( data ) < or data [ - : ] == \"\" : return '' . join ( res ) def readlines ( self , sizehint = ) : total = lines = [ ] line = self . readline ( ) while line : lines . append ( line ) total += len ( line ) if < sizehint <= total : break line = self . readline ( ) return lines def close ( self ) : self . rfile . close ( ) def __iter__ ( self ) : return self def next ( self ) : data = self . rfile . next ( ) self . bytes_read += len ( data ) self . _check_length ( ) return data class KnownLengthRFile ( object ) : \"\"\"\"\"\" def __init__ ( self , rfile , content_length ) : self . rfile = rfile self . remaining = content_length def read ( self , size = None ) : if self . remaining == : return '' if size is None : size = self . remaining else : size = min ( size , self . remaining ) data = self . rfile . read ( size ) self . remaining -= len ( data ) return data def readline ( self , size = None ) : if self . remaining == : return '' if size is None : size = self . remaining else : size = min ( size , self . remaining ) data = self . rfile . readline ( size ) self . remaining -= len ( data ) return data def readlines ( self , sizehint = ) : total = lines = [ ] line = self . readline ( sizehint ) while line : lines . append ( line ) total += len ( line ) if < sizehint <= total : break line = self . readline ( sizehint ) return lines def close ( self ) : self . rfile . close ( ) def __iter__ ( self ) : return self def __next__ ( self ) : data = next ( self . rfile ) self . remaining -= len ( data ) return data class ChunkedRFile ( object ) : \"\"\"\"\"\" def __init__ ( self , rfile , maxlen , bufsize = ) : self . rfile = rfile self . maxlen = maxlen self . bytes_read = self . buffer = '' self . bufsize = bufsize self . closed = False def _fetch ( self ) : if self . closed : return line = self . rfile . readline ( ) self . bytes_read += len ( line ) if self . maxlen and self . bytes_read > self . maxlen : raise MaxSizeExceeded ( \"\" , self . maxlen ) line = line . strip ( ) . split ( \"\" , ) try : chunk_size = line . pop ( ) chunk_size = int ( chunk_size , ) except ValueError : raise ValueError ( \"\" + repr ( chunk_size ) ) if chunk_size <= : self . closed = True return if self . maxlen and self . bytes_read + chunk_size > self . maxlen : raise IOError ( \"\" ) chunk = self . rfile . read ( chunk_size ) self . bytes_read += len ( chunk ) self . buffer += chunk crlf = self . rfile . read ( ) if crlf != CRLF : raise ValueError ( \"\" \"\" + repr ( crlf ) + \"\" ) def read ( self , size = None ) : data = '' while True : if size and len ( data ) >= size : return data if not self . buffer : self . _fetch ( ) if not self . buffer : return data if size : remaining = size - len ( data ) data += self . buffer [ : remaining ] self . buffer = self . buffer [ remaining : ] else : data += self . buffer def readline ( self , size = None ) : data = '' while True : if size and len ( data ) >= size : return data if not self . buffer : self . _fetch ( ) if not self . buffer : return data newline_pos = self . buffer . find ( '' ) if size : if newline_pos == - : remaining = size - len ( data ) data += self . buffer [ : remaining ] self . buffer = self . buffer [ remaining : ] else : remaining = min ( size - len ( data ) , newline_pos ) data += self . buffer [ : remaining ] self . buffer = self . buffer [ remaining : ] else : if newline_pos == - : data += self . buffer else : data += self . buffer [ : newline_pos ] self . buffer = self . buffer [ newline_pos : ] def readlines ( self , sizehint = ) : total = lines = [ ] line = self . readline ( sizehint ) while line : lines . append ( line ) total += len ( line ) if < sizehint <= total : break line = self . readline ( sizehint ) return lines def read_trailer_lines ( self ) : if not self . closed : raise ValueError ( \"\" ) while True : line = self . rfile . readline ( ) if not line : raise ValueError ( \"\" ) self . bytes_read += len ( line ) if self . maxlen and self . bytes_read > self . maxlen : raise IOError ( \"\" ) if line == CRLF : break if not line . endswith ( CRLF ) : raise ValueError ( \"\" ) yield line def close ( self ) : self . rfile . close ( ) def __iter__ ( self ) : total = line = self . readline ( sizehint ) while line : yield line total += len ( line ) if < sizehint <= total : break line = self . readline ( sizehint ) class HTTPRequest ( object ) : \"\"\"\"\"\" server = None \"\"\"\"\"\" conn = None \"\"\"\"\"\" inheaders = { } \"\"\"\"\"\" outheaders = [ ] \"\"\"\"\"\" ready = False \"\"\"\"\"\" close_connection = False \"\"\"\"\"\" chunked_write = False \"\"\"\"\"\" def __init__ ( self , server , conn ) : self . server = server self . conn = conn self . ready = False self . started_request = False self . scheme = \"\" if self . server . ssl_adapter is not None : self . scheme = \"\" self . response_protocol = '' self . inheaders = { } self . status = \"\" self . outheaders = [ ] self . sent_headers = False self . close_connection = self . __class__ . close_connection self . chunked_read = False self . chunked_write = self . __class__ . chunked_write def parse_request ( self ) : \"\"\"\"\"\" self . rfile = SizeCheckWrapper ( self . conn . rfile , self . server . max_request_header_size ) try : self . read_request_line ( ) except MaxSizeExceeded : self . simple_response ( \"\" , \"\" \"\" ) return try : success = self . read_request_headers ( ) except MaxSizeExceeded : self . simple_response ( \"\" , \"\" \"\" ) return else : if not success : return self . ready = True def read_request_line ( self ) : request_line = self . rfile . readline ( ) self . started_request = True if not request_line : self . ready = False return if request_line == CRLF : request_line = self . rfile . readline ( ) if not request_line : self . ready = False return if not request_line . endswith ( CRLF ) : self . simple_response ( \"\" , \"\" ) return try : method , uri , req_protocol = request_line . strip ( ) . split ( \"\" , ) rp = int ( req_protocol [ ] ) , int ( req_protocol [ ] ) except ( ValueError , IndexError ) : self . simple_response ( \"\" , \"\" ) return self . uri = uri self . method = method scheme , authority , path = self . parse_request_uri ( uri ) if '' in path : self . simple_response ( \"\" , \"\" ) return if scheme : self . scheme = scheme qs = '' if '' in path : path , qs = path . split ( '' , ) try : atoms = [ unquote ( x ) for x in quoted_slash . split ( path ) ] except ValueError , ex : self . simple_response ( \"\" , ex . args [ ] ) return path = \"\" . join ( atoms ) self . path = path self . qs = qs sp = int ( self . server . protocol [ ] ) , int ( self . server . protocol [ ] ) if sp [ ] != rp [ ] : self . simple_response ( \"\" ) return self . request_protocol = req_protocol self . response_protocol = \"\" % min ( rp , sp ) def read_request_headers ( self ) : \"\"\"\"\"\" try : read_headers ( self . rfile , self . inheaders ) except ValueError , ex : self . simple_response ( \"\" , ex . args [ ] ) return False mrbs = self . server . max_request_body_size if mrbs and int ( self . inheaders . get ( \"\" , ) ) > mrbs : self . simple_response ( \"\" , \"\" \"\" ) return False if self . response_protocol == \"\" : if self . inheaders . get ( \"\" , \"\" ) == \"\" : self . close_connection = True else : if self . inheaders . get ( \"\" , \"\" ) != \"\" : self . close_connection = True te = None if self . response_protocol == \"\" : te = self . inheaders . get ( \"\" ) if te : te = [ x . strip ( ) . lower ( ) for x in te . split ( \"\" ) if x . strip ( ) ] self . chunked_read = False if te : for enc in te : if enc == \"\" : self . chunked_read = True else : self . simple_response ( \"\" ) self . close_connection = True return False if self . inheaders . get ( \"\" , \"\" ) == \"\" : msg = self . server . protocol + \"\" try : self . conn . wfile . sendall ( msg ) except socket . error , x : if x . args [ ] not in socket_errors_to_ignore : raise return True def parse_request_uri ( self , uri ) : \"\"\"\"\"\" if uri == \"\" : return None , None , uri i = uri . find ( '' ) if i > and '' not in uri [ : i ] : scheme , remainder = uri [ : i ] . lower ( ) , uri [ i + : ] authority , path = remainder . split ( \"\" , ) return scheme , authority , path if uri . startswith ( '' ) : return None , None , uri else : return None , uri , None def respond ( self ) : \"\"\"\"\"\" mrbs = self . server . max_request_body_size if self . chunked_read : self . rfile = ChunkedRFile ( self . conn . rfile , mrbs ) else : cl = int ( self . inheaders . get ( \"\" , ) ) if mrbs and mrbs < cl : if not self . sent_headers : self . simple_response ( \"\" , \"\" \"\" ) return self . rfile = KnownLengthRFile ( self . conn . rfile , cl ) self . server . gateway ( self ) . respond ( ) if ( self . ready and not self . sent_headers ) : self . sent_headers = True self . send_headers ( ) if self . chunked_write : self . conn . wfile . sendall ( \"\" ) def simple_response ( self , status , msg = \"\" ) : \"\"\"\"\"\" status = str ( status ) buf = [ self . server . protocol + \"\" + status + CRLF , \"\" % len ( msg ) , \"\" ] if status [ : ] in ( \"\" , \"\" ) : self . close_connection = True if self . response_protocol == '' : buf . append ( \"\" ) else : status = \"\" buf . append ( CRLF ) if msg : if isinstance ( msg , unicode ) : msg = msg . encode ( \"\" ) buf . append ( msg ) try : self . conn . wfile . sendall ( \"\" . join ( buf ) ) except socket . error , x : if x . args [ ] not in socket_errors_to_ignore : raise def write ( self , chunk ) : \"\"\"\"\"\" if self . chunked_write and chunk : buf = [ hex ( len ( chunk ) ) [ : ] , CRLF , chunk , CRLF ] self . conn . wfile . sendall ( \"\" . join ( buf ) ) else : self . conn . wfile . sendall ( chunk ) def send_headers ( self ) : \"\"\"\"\"\" hkeys = [ key . lower ( ) for key , value in self . outheaders ] status = int ( self . status [ : ] ) if status == : self . close_connection = True elif \"\" not in hkeys : if status < or status in ( , , ) : pass else : if ( self . response_protocol == '' and self . method != '' ) : self . chunked_write = True self . outheaders . append ( ( \"\" , \"\" ) ) else : self . close_connection = True if \"\" not in hkeys : if self . response_protocol == '' : if self . close_connection : self . outheaders . append ( ( \"\" , \"\" ) ) else : if not self . close_connection : self . outheaders . append ( ( \"\" , \"\" ) ) if ( not self . close_connection ) and ( not self . chunked_read ) : remaining = getattr ( self . rfile , '' , ) if remaining > : self . rfile . read ( remaining ) if \"\" not in hkeys : self . outheaders . append ( ( \"\" , rfc822 . formatdate ( ) ) ) if \"\" not in hkeys : self . outheaders . append ( ( \"\" , self . server . server_name ) ) buf = [ self . server . protocol + \"\" + self . status + CRLF ] for k , v in self . outheaders : buf . append ( k + \"\" + v + CRLF ) buf . append ( CRLF ) self . conn . wfile . sendall ( \"\" . join ( buf ) ) class NoSSLError ( Exception ) : \"\"\"\"\"\" pass class FatalSSLAlert ( Exception ) : \"\"\"\"\"\" pass class CP_fileobject ( socket . _fileobject ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : self . bytes_read = self . bytes_written = socket . _fileobject . __init__ ( self , * args , ** kwargs ) def sendall ( self , data ) : \"\"\"\"\"\" while data : try : bytes_sent = self . send ( data ) data = data [ bytes_sent : ] except socket . error , e : if e . args [ ] not in socket_errors_nonblocking : raise def send ( self , data ) : bytes_sent = self . _sock . send ( data ) self . bytes_written += bytes_sent return bytes_sent def flush ( self ) : if self . _wbuf : buffer = \"\" . join ( self . _wbuf ) self . _wbuf = [ ] self . sendall ( buffer ) def recv ( self , size ) : while True : try : data = self . _sock . recv ( size ) self . bytes_read += len ( data ) return data except socket . error , e : if ( e . args [ ] not in socket_errors_nonblocking and e . args [ ] not in socket_error_eintr ) : raise if not _fileobject_uses_str_type : def read ( self , size = - ) : rbufsize = max ( self . _rbufsize , self . default_bufsize ) buf = self . _rbuf buf . seek ( , ) if size < : self . _rbuf = StringIO . StringIO ( ) while True : data = self . recv ( rbufsize ) if not data : break buf . write ( data ) return buf . getvalue ( ) else : buf_len = buf . tell ( ) if buf_len >= size : buf . seek ( ) rv = buf . read ( size ) self . _rbuf = StringIO . StringIO ( ) self . _rbuf . write ( buf . read ( ) ) return rv self . _rbuf = StringIO . StringIO ( ) while True : left = size - buf_len data = self . recv ( left ) if not data : break n = len ( data ) if n == size and not buf_len : return data if n == left : buf . write ( data ) del data break assert n <= left , \"\" % ( left , n ) buf . write ( data ) buf_len += n del data return buf . getvalue ( ) def readline ( self , size = - ) : buf = self . _rbuf buf . seek ( , ) if buf . tell ( ) > : buf . seek ( ) bline = buf . readline ( size ) if bline . endswith ( '' ) or len ( bline ) == size : self . _rbuf = StringIO . StringIO ( ) self . _rbuf . write ( buf . read ( ) ) return bline del bline if size < : if self . _rbufsize <= : buf . seek ( ) buffers = [ buf . read ( ) ] self . _rbuf = StringIO . StringIO ( ) data = None recv = self . recv while data != \"\" : data = recv ( ) if not data : break buffers . append ( data ) return \"\" . join ( buffers ) buf . seek ( , ) self . _rbuf = StringIO . StringIO ( ) while True : data = self . recv ( self . _rbufsize ) if not data : break nl = data . find ( '' ) if nl >= : nl += buf . write ( data [ : nl ] ) self . _rbuf . write ( data [ nl : ] ) del data break buf . write ( data ) return buf . getvalue ( ) else : buf . seek ( , ) buf_len = buf . tell ( ) if buf_len >= size : buf . seek ( ) rv = buf . read ( size ) self . _rbuf = StringIO . StringIO ( ) self . _rbuf . write ( buf . read ( ) ) return rv self . _rbuf = StringIO . StringIO ( ) while True : data = self . recv ( self . _rbufsize ) if not data : break left = size - buf_len nl = data . find ( '' , , left ) if nl >= : nl += self . _rbuf . write ( data [ nl : ] ) if buf_len : buf . write ( data [ : nl ] ) break else : return data [ : nl ] n = len ( data ) if n == size and not buf_len : return data if n >= left : buf . write ( data [ : left ] ) self . _rbuf . write ( data [ left : ] ) break buf . write ( data ) buf_len += n return buf . getvalue ( ) else : def read ( self , size = - ) : if size < : buffers = [ self . _rbuf ] self . _rbuf = \"\" if self . _rbufsize <= : recv_size = self . default_bufsize else : recv_size = self . _rbufsize while True : data = self . recv ( recv_size ) if not data : break buffers . append ( data ) return \"\" . join ( buffers ) else : data = self . _rbuf buf_len = len ( data ) if buf_len >= size : self . _rbuf = data [ size : ] return data [ : size ] buffers = [ ] if data : buffers . append ( data ) self . _rbuf = \"\" while True : left = size - buf_len recv_size = max ( self . _rbufsize , left ) data = self . recv ( recv_size ) if not data : break buffers . append ( data ) n = len ( data ) if n >= left : self . _rbuf = data [ left : ] buffers [ - ] = data [ : left ] break buf_len += n return \"\" . join ( buffers ) def readline ( self , size = - ) : data = self . _rbuf if size < : if self . _rbufsize <= : assert data == \"\" buffers = [ ] while data != \"\" : data = self . recv ( ) if not data : break buffers . append ( data ) return \"\" . join ( buffers ) nl = data . find ( '' ) if nl >= : nl += self . _rbuf = data [ nl : ] return data [ : nl ] buffers = [ ] if data : buffers . append ( data ) self . _rbuf = \"\" while True : data = self . recv ( self . _rbufsize ) if not data : break buffers . append ( data ) nl = data . find ( '' ) if nl >= : nl += self . _rbuf = data [ nl : ] buffers [ - ] = data [ : nl ] break return \"\" . join ( buffers ) else : nl = data . find ( '' , , size ) if nl >= : nl += self . _rbuf = data [ nl : ] return data [ : nl ] buf_len = len ( data ) if buf_len >= size : self . _rbuf = data [ size : ] return data [ : size ] buffers = [ ] if data : buffers . append ( data ) self . _rbuf = \"\" while True : data = self . recv ( self . _rbufsize ) if not data : break buffers . append ( data ) left = size - buf_len nl = data . find ( '' , , left ) if nl >= : nl += self . _rbuf = data [ nl : ] buffers [ - ] = data [ : nl ] break n = len ( data ) if n >= left : self . _rbuf = data [ left : ] buffers [ - ] = data [ : left ] break buf_len += n return \"\" . join ( buffers ) class HTTPConnection ( object ) : \"\"\"\"\"\" remote_addr = None remote_port = None ssl_env = None rbufsize = DEFAULT_BUFFER_SIZE wbufsize = DEFAULT_BUFFER_SIZE RequestHandlerClass = HTTPRequest def __init__ ( self , server , sock , makefile = CP_fileobject ) : self . server = server self . socket = sock self . rfile = makefile ( sock , \"\" , self . rbufsize ) self . wfile = makefile ( sock , \"\" , self . wbufsize ) self . requests_seen = def communicate ( self ) : \"\"\"\"\"\" request_seen = False try : while True : req = None req = self . RequestHandlerClass ( self . server , self ) req . parse_request ( ) if self . server . stats [ '' ] : self . requests_seen += if not req . ready : return request_seen = True req . respond ( ) if req . close_connection : return except socket . error , e : errnum = e . args [ ] if errnum == '' or errnum == '' : if ( not request_seen ) or ( req and req . started_request ) : if req and not req . sent_headers : try : req . simple_response ( \"\" ) except FatalSSLAlert : return elif errnum not in socket_errors_to_ignore : if req and not req . sent_headers : try : req . simple_response ( \"\" , format_exc ( ) ) except FatalSSLAlert : return return except ( KeyboardInterrupt , SystemExit ) : raise except FatalSSLAlert : return except NoSSLError : if req and not req . sent_headers : self . wfile = CP_fileobject ( self . socket . _sock , \"\" , self . wbufsize ) req . simple_response ( \"\" , \"\" \"\" ) self . linger = True except Exception : if req and not req . sent_headers : try : req . simple_response ( \"\" , format_exc ( ) ) except FatalSSLAlert : return linger = False def close ( self ) : \"\"\"\"\"\" self . rfile . close ( ) if not self . linger : if hasattr ( self . socket , '' ) : self . socket . _sock . close ( ) self . socket . close ( ) else : pass _SHUTDOWNREQUEST = None class WorkerThread ( threading . Thread ) : \"\"\"\"\"\" conn = None \"\"\"\"\"\" server = None \"\"\"\"\"\" ready = False \"\"\"\"\"\" def __init__ ( self , server ) : self . ready = False self . server = server self . requests_seen = self . bytes_read = self . bytes_written = self . start_time = None self . work_time = self . stats = { '' : lambda s : self . requests_seen + ( ( self . start_time is None ) and or self . conn . requests_seen ) , '' : lambda s : self . bytes_read + ( ( self . start_time is None ) and or self . conn . rfile . bytes_read ) , '' : lambda s : self . bytes_written + ( ( self . start_time is None ) and or self . conn . wfile . bytes_written ) , '' : lambda s : self . work_time + ( ( self . start_time is None ) and or time . time ( ) - self . start_time ) , '' : lambda s : s [ '' ] ( s ) / ( s [ '' ] ( s ) or ) , '' : lambda s : s [ '' ] ( s ) / ( s [ '' ] ( s ) or ) , } threading . Thread . __init__ ( self ) def run ( self ) : self . server . stats [ '' ] [ self . getName ( ) ] = self . stats try : self . ready = True while True : conn = self . server . requests . get ( ) if conn is _SHUTDOWNREQUEST : return self . conn = conn if self . server . stats [ '' ] : self . start_time = time . time ( ) try : conn . communicate ( ) finally : conn . close ( ) if self . server . stats [ '' ] : self . requests_seen += self . conn . requests_seen self . bytes_read += self . conn . rfile . bytes_read self . bytes_written += self . conn . wfile . bytes_written self . work_time += time . time ( ) - self . start_time self . start_time = None self . conn = None except ( KeyboardInterrupt , SystemExit ) , exc : self . server . interrupt = exc class ThreadPool ( object ) : \"\"\"\"\"\" def __init__ ( self , server , min = , max = - ) : self . server = server self . min = min self . max = max self . _threads = [ ] self . _queue = Queue . Queue ( ) self . get = self . _queue . get def start ( self ) : \"\"\"\"\"\" for i in range ( self . min ) : self . _threads . append ( WorkerThread ( self . server ) ) for worker in self . _threads : worker . setName ( \"\" + worker . getName ( ) ) worker . start ( ) for worker in self . _threads : while not worker . ready : time . sleep ( ) def _get_idle ( self ) : \"\"\"\"\"\" return len ( [ t for t in self . _threads if t . conn is None ] ) idle = property ( _get_idle , doc = _get_idle . __doc__ ) def put ( self , obj ) : self . _queue . put ( obj ) if obj is _SHUTDOWNREQUEST : return def grow ( self , amount ) : \"\"\"\"\"\" for i in range ( amount ) : if self . max > and len ( self . _threads ) >= self . max : break worker = WorkerThread ( self . server ) worker . setName ( \"\" + worker . getName ( ) ) self . _threads . append ( worker ) worker . start ( ) ", "answer": "def shrink ( self , amount ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations from django . conf import settings import utils . models class Migration ( migrations . Migration ) : dependencies = [ migrations . swappable_dependency ( settings . AUTH_USER_MODEL ) , ", "answer": "( '' , '' ) ,"}, {"prompt": " import ctypes import heapq import sys import threading import time import Queue import pyglet _debug = pyglet . options [ '' ] import mt_media import lib_openal as al import lib_alc as alc class OpenALException ( mt_media . MediaException ) : pass def _split_nul_strings ( s ) : nul = False i = while True : if s [ i ] == '' : if nul : break else : nul = True else : nul = False i += s = s [ : i - ] return s . split ( '' ) def get_extensions ( ) : extensions = alc . alcGetString ( context . _device , alc . ALC_EXTENSIONS ) if sys . platform == '' : return ctypes . cast ( extensions , ctypes . c_char_p ) . value . split ( '' ) else : return _split_nul_strings ( extensions ) def have_extension ( extension ) : return extension in get_extensions ( ) format_map = { ( , ) : al . AL_FORMAT_MONO8 , ( , ) : al . AL_FORMAT_MONO16 , ( , ) : al . AL_FORMAT_STEREO8 , ( , ) : al . AL_FORMAT_STEREO16 , } class OpenALWorker ( mt_media . MediaThread ) : _min_write_size = _nap_time = _sleep_time = None def __init__ ( self ) : super ( OpenALWorker , self ) . __init__ ( ) self . players = set ( ) def run ( self ) : while True : self . condition . acquire ( ) if self . stopped : self . condition . release ( ) break sleep_time = - if self . players : player = None write_size = for p in self . players : s = p . get_write_size ( ) if s > write_size : player = p write_size = s if write_size > self . _min_write_size : player . refill ( write_size ) else : sleep_time = self . _nap_time else : sleep_time = self . _sleep_time self . condition . release ( ) if sleep_time != - : self . sleep ( sleep_time ) def add ( self , player ) : self . condition . acquire ( ) self . players . add ( player ) self . condition . notify ( ) self . condition . release ( ) def remove ( self , player ) : self . condition . acquire ( ) self . players . remove ( player ) self . condition . notify ( ) self . condition . release ( ) class OpenALAudioPlayer ( mt_media . AbstractAudioPlayer ) : _min_buffer_size = _ideal_buffer_size = def __init__ ( self , source_group , player ) : super ( OpenALAudioPlayer , self ) . __init__ ( source_group , player ) audio_format = source_group . audio_format try : self . _al_format = format_map [ ( audio_format . channels , audio_format . sample_size ) ] except KeyError : raise OpenALException ( '' ) self . _al_source = al . ALuint ( ) al . alGenSources ( , self . _al_source ) self . _lock = threading . RLock ( ) self . _buffer_cursor = self . _play_cursor = self . _write_cursor = self . _buffer_sizes = [ ] self . _buffer_timestamps = [ ] self . _underrun_timestamp = None self . _events = [ ] self . _playing = False self . _eos = False if not context . have_1_1 : self . _buffer_system_time = time . time ( ) self . refill ( self . _ideal_buffer_size ) def __del__ ( self ) : try : self . delete ( ) except : pass def delete ( self ) : return context . lock ( ) al . alDeleteSources ( , self . _al_source ) context . unlock ( ) self . _al_source = None def play ( self ) : if self . _playing : return self . _playing = True self . _al_play ( ) if not context . have_1_1 : self . _buffer_system_time = time . time ( ) context . worker . add ( self ) def _al_play ( self ) : context . lock ( ) state = al . ALint ( ) al . alGetSourcei ( self . _al_source , al . AL_SOURCE_STATE , state ) if state . value != al . AL_PLAYING : al . alSourcePlay ( self . _al_source ) context . unlock ( ) def stop ( self ) : if not self . _playing : return self . _pause_timestamp = self . get_time ( ) context . lock ( ) al . alSourcePause ( self . _al_source ) context . unlock ( ) self . _playing = False context . worker . remove ( self ) def clear ( self ) : self . _lock . acquire ( ) context . lock ( ) al . alSourceStop ( self . _al_source ) self . _playing = False del self . _events [ : ] self . _underrun_timestamp = None self . _buffer_timestamps = [ None for _ in self . _buffer_timestamps ] context . unlock ( ) self . _lock . release ( ) def _update_play_cursor ( self ) : self . _lock . acquire ( ) context . lock ( ) processed = al . ALint ( ) al . alGetSourcei ( self . _al_source , al . AL_BUFFERS_PROCESSED , processed ) processed = processed . value if processed : buffers = ( al . ALuint * processed ) ( ) al . alSourceUnqueueBuffers ( self . _al_source , len ( buffers ) , buffers ) al . alDeleteBuffers ( len ( buffers ) , buffers ) context . unlock ( ) if processed : if len ( self . _buffer_timestamps ) == processed : self . _underrun_timestamp = self . _buffer_timestamps [ - ] + self . _buffer_sizes [ - ] / float ( self . source_group . audio_format . bytes_per_second ) self . _buffer_cursor += sum ( self . _buffer_sizes [ : processed ] ) del self . _buffer_sizes [ : processed ] del self . _buffer_timestamps [ : processed ] if not context . have_1_1 : ", "answer": "self . _buffer_system_time = time . time ( )"}, {"prompt": " import time from getpass import getpass from textwrap import TextWrapper import tweepy class StreamWatcherListener ( tweepy . StreamListener ) : status_wrapper = TextWrapper ( width = , initial_indent = '' , subsequent_indent = '' ) def on_status ( self , status ) : try : print self . status_wrapper . fill ( status . text ) print '' % ( status . author . screen_name , status . created_at , status . source ) except : pass def on_error ( self , status_code ) : print '' % status_code return True def on_timeout ( self ) : print '' def main ( ) : username = raw_input ( '' ) password = getpass ( '' ) stream = tweepy . Stream ( username , password , StreamWatcherListener ( ) , timeout = None ) valid_modes = [ '' , '' ] while True : mode = raw_input ( '' ) if mode in valid_modes : ", "answer": "break"}, {"prompt": " from django . db import models class SurveyType ( models . Model ) : slug = models . CharField ( max_length = , unique = True ) class Meta : app_label = '' ", "answer": "def __unicode__ ( self ) :"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from django import template"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " \"\"\"\"\"\" import logging import numpy as np from itertools import izip from . import utils from . import config from . import attributes from . metadata import Metadata from . pos import POSReader from . srl import SRLReader from . parse import DependencyReader from . network import Network , ConvolutionalNetwork , ConvolutionalDependencyNetwork def load_network ( md ) : \"\"\"\"\"\" logger = logging . getLogger ( \"\" ) is_srl = md . task . startswith ( '' ) and md . task != '' logger . info ( '' ) if is_srl : net_class = ConvolutionalNetwork elif md . task . endswith ( '' ) : net_class = ConvolutionalDependencyNetwork else : net_class = Network nn = net_class . load_from_file ( md . paths [ md . network ] ) logger . info ( '' ) return nn def create_reader ( md , gold_file = None ) : \"\"\"\"\"\" logger = logging . getLogger ( '' ) logger . info ( '' ) if md . task == '' : tr = POSReader ( md , filename = gold_file ) elif '' in md . task : labeled = md . task . startswith ( '' ) tr = DependencyReader ( md , filename = gold_file , labeled = labeled ) elif md . task . startswith ( '' ) : tr = SRLReader ( md , filename = gold_file , only_boundaries = ( md . task == '' ) , only_classify = ( md . task == '' ) , only_predicates = ( md . task == '' ) ) else : raise ValueError ( \"\" % md . task ) logger . info ( '' ) return tr def _group_arguments ( tokens , predicate_positions , boundaries , labels ) : \"\"\"\"\"\" arg_structs = [ ] for predicate_position , pred_boundaries , pred_labels in izip ( predicate_positions , boundaries , labels ) : structure = { } for token , boundary_tag in izip ( tokens , pred_boundaries ) : if boundary_tag == '' : continue elif boundary_tag == '' : argument_tokens = [ token ] elif boundary_tag == '' : argument_tokens . append ( token ) elif boundary_tag == '' : argument_tokens . append ( token ) tag = pred_labels . pop ( ) structure [ tag ] = argument_tokens else : tag = pred_labels . pop ( ) structure [ tag ] = [ token ] predicate = tokens [ predicate_position ] arg_structs . append ( ( predicate , structure ) ) return arg_structs class SRLAnnotatedSentence ( object ) : \"\"\"\"\"\" def __init__ ( self , tokens , arg_structures ) : \"\"\"\"\"\" self . tokens = tokens self . arg_structures = arg_structures class ParsedSentence ( object ) : \"\"\"\"\"\" def __init__ ( self , tokens , heads , labels , pos = None ) : \"\"\"\"\"\" self . tokens = tokens self . heads = heads self . labels = labels self . pos = pos def __len__ ( self ) : ", "answer": "return len ( self . tokens )"}, {"prompt": " import unittest from depsolver . package import PackageInfo from depsolver . pool import Pool from depsolver . repository import Repository from depsolver . request import _Job , Request from depsolver . requirement import Requirement from depsolver . version import SemanticVersion P = PackageInfo . from_string V = SemanticVersion . from_string R = Requirement . from_string class TestRequest ( unittest . TestCase ) : ", "answer": "def setUp ( self ) :"}, {"prompt": " \"\"\"\"\"\" import nltk from quepy . tagger import Word from quepy . encodingpolicy import assert_valid_encoding _penn_to_morphy_tag = { } def penn_to_morphy_tag ( tag ) : assert_valid_encoding ( tag ) for penn , morphy in _penn_to_morphy_tag . iteritems ( ) : if tag . startswith ( penn ) : return morphy return None def run_nltktagger ( string , nltk_data_path = None ) : \"\"\"\"\"\" ", "answer": "assert_valid_encoding ( string )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import numpy from theano . compat . six . moves import xrange import theano try : grad_not_implemented = theano . gradient . grad_not_implemented except : def grad_not_implemented ( op , idx , ipt ) : return None def any_symbolic ( * args ) : \"\"\"\"\"\" for a in args : if isinstance ( a , theano . Variable ) : return True return False def not_symbolic ( * args ) : return not any_symbolic ( * args ) class Base ( theano . Op ) : \"\"\"\"\"\" def __init__ ( self , module_stride = , ) : self . module_stride = module_stride def _attributes ( self ) : return ( self . module_stride , ) def __eq__ ( self , other ) : return ( type ( self ) == type ( other ) and self . _attributes ( ) == other . _attributes ( ) ) def __hash__ ( self ) : return hash ( ( type ( self ) , self . _attributes ( ) ) ) def __str__ ( self ) : return '' % ( self . __class__ . __name__ , self . module_stride , ) class FilterActs ( Base ) : \"\"\"\"\"\" def make_node ( self , images , filters ) : images = theano . tensor . as_tensor_variable ( images ) filters = theano . tensor . as_tensor_variable ( filters ) ibcast = images . broadcastable fbcast = filters . broadcastable igroups , icolors_per_group , irows , icols , icount = ibcast fmodulesR , fmodulesC , fcolors , frows , fcols = fbcast [ : - ] fgroups , filters_per_group = fbcast [ - : ] hbcast = ( fgroups , filters_per_group , fmodulesR , fmodulesC , icount ) htype = theano . tensor . TensorType ( dtype = images . dtype , broadcastable = hbcast ) if images . dtype != filters . dtype : raise TypeError ( '' , ( images , images . dtype , filters , filters . dtype ) ) return theano . gof . Apply ( self , [ images , filters ] , [ htype ( ) ] ) def perform ( self , node , iargs , ostor ) : images , filters = iargs igroups , icolors_per_group , irows , icols , icount = images . shape fmodulesR , fmodulesC , fcolors , frows , fcols = filters . shape [ : - ] fgroups , filters_per_group = filters . shape [ - : ] hshape = self . infer_shape ( node , ( images . shape , filters . shape ) ) [ ] hidacts = numpy . zeros ( hshape , dtype = images . dtype ) for mR in xrange ( fmodulesR ) : for mC in xrange ( fmodulesC ) : for gg in xrange ( igroups ) : img_r_offset = mR * self . module_stride img_c_offset = mC * self . module_stride rc_images = images [ gg , : , img_r_offset : img_r_offset + frows , img_c_offset : img_c_offset + fcols , : ] rc_filters = filters [ mR , mC , : , : , : , gg , : ] left_arg = rc_filters . reshape ( - , filters_per_group ) . T right_arg = rc_images . reshape ( - , icount ) try : rc_hidacts = numpy . dot ( left_arg , right_arg ) except ValueError as e : if '' in str ( e ) : raise ValueError ( \"\" + str ( left_arg . shape ) + '' + str ( right_arg . shape ) ) else : raise hidacts [ gg , : , mR , mC , : ] = rc_hidacts ostor [ ] [ ] = hidacts print_sizes = if print_sizes : print ( '' , images . shape ) print ( '' , filters . shape ) print ( '' , hidacts . shape ) def grad ( self , inputs , goutputs ) : images , filters = inputs frows = filters . shape [ ] fcols = filters . shape [ ] irows = images . shape [ ] icols = images . shape [ ] hidacts = goutputs [ ] if filters . dtype == '' and hidacts . dtype == '' : filters = theano . tensor . cast ( filters , '' ) gimages = ImgActs ( module_stride = self . module_stride ) ( filters , hidacts , irows , icols ) if images . dtype == '' and hidacts . dtype == '' : images = theano . tensor . cast ( images , '' ) gfilters = WeightActs ( module_stride = self . module_stride ) ( images , hidacts , frows , fcols ) return [ gimages , gfilters ] def infer_shape ( self , node , shapes ) : ishape , fshape = shapes igroups , icolors_per_group , irows , icols , icount = ishape fmodulesR , fmodulesC , fcolors , frows , fcols = fshape [ : - ] fgroups , filters_per_group = fshape [ - : ] if not any_symbolic ( irows , icols ) and irows != icols : raise ValueError ( \"\" , ( irows , icols ) ) if not any_symbolic ( frows , fcols ) and frows != fcols : raise ValueError ( \"\" , ( frows , fcols ) ) if not any_symbolic ( fmodulesR , fmodulesC ) and fmodulesR != fmodulesC : raise ValueError ( '' , ( fmodulesR , fmodulesC ) ) if ( not any_symbolic ( icolors_per_group , fcolors ) and icolors_per_group != fcolors ) : raise ValueError ( \"\" , ", "answer": "( icolors_per_group , fcolors ) )"}, {"prompt": " from __future__ import unicode_literals from django import forms from django . core . exceptions import ObjectDoesNotExist from django . db . models import F from django . utils . translation import ugettext_lazy as _ from machina . conf import settings as machina_settings from machina . core . db . models import get_model from machina . core . loading import get_class Post = get_model ( '' , '' ) Topic = get_model ( '' , '' ) TopicPoll = get_model ( '' , '' ) PermissionHandler = get_class ( '' , '' ) get_anonymous_user_forum_key = get_class ( '' , '' ) class PostForm ( forms . ModelForm ) : class Meta : model = Post fields = [ '' , '' , '' , '' , ] def __init__ ( self , * args , ** kwargs ) : self . user = kwargs . pop ( '' , None ) ", "answer": "self . user_ip = kwargs . pop ( '' , None )"}, {"prompt": " \"\"\"\"\"\" __version__ = '' from _bitarray import _bitarray , bits2bytes , _sysinfo def _btree_insert ( tree , sym , ba ) : \"\"\"\"\"\" v = ba [ ] if len ( ba ) > : if tree [ v ] == [ ] : tree [ v ] = [ [ ] , [ ] ] _btree_insert ( tree [ v ] , sym , ba [ : ] ) else : if tree [ v ] != [ ] : raise ValueError ( \"\" ) tree [ v ] = sym def _mk_tree ( codedict ) : tree = [ [ ] , [ ] ] for sym , ba in codedict . iteritems ( ) : _btree_insert ( tree , sym , ba ) return tree def _check_codedict ( codedict ) : if not isinstance ( codedict , dict ) : raise TypeError ( \"\" ) if len ( codedict ) == : raise ValueError ( \"\" ) for k , v in codedict . iteritems ( ) : if not isinstance ( v , bitarray ) : raise TypeError ( \"\" ) if v . length ( ) == : raise ValueError ( \"\" ) class bitarray ( _bitarray ) : \"\"\"\"\"\" def decode ( self , codedict ) : \"\"\"\"\"\" _check_codedict ( codedict ) return self . _decode ( _mk_tree ( codedict ) ) def encode ( self , codedict , iterable ) : \"\"\"\"\"\" _check_codedict ( codedict ) return self . _encode ( codedict , iterable ) def search ( self , x , limit = - ) : \"\"\"\"\"\" return self . _search ( bitarray ( x ) , limit ) ", "answer": "def __contains__ ( self , other ) :"}, {"prompt": " import pyjd from pyjamas import DOM from pyjamas import Window from pyjamas import Factory from __pyjamas__ import JS , doc from pyjamas . ui . SimplePanel import SimplePanel from pyjamas . ui . Widget import Widget from pyjamas . ui . MouseListener import MouseHandler from pyjamas . ui . RootPanel import RootPanel mousecapturer = None def getMouseCapturer ( ** kwargs ) : global mousecapturer if mousecapturer is None : mousecapturer = GlassWidget ( ** kwargs ) elif not isinstance ( mousecapturer , GlassWidget ) : return None return mousecapturer def show ( mousetarget , ** kwargs ) : global mousecapturer mc = getMouseCapturer ( ** kwargs ) mc . mousetarget = mousetarget if isinstance ( mousetarget , MouseHandler ) : mc . mousehandler = True mc . show ( ) def hide ( ) : global mousecapturer mousecapturer . hide ( ) class GlassWidget ( Widget , MouseHandler ) : def __init__ ( self , ** kwargs ) : self . glassListeners = [ ] self . showing = False self . mousehandler = False if not '' in kwargs : kwargs [ '' ] = \"\" if '' in kwargs : element = kwargs . pop ( '' ) else : element = DOM . createDiv ( ) self . setElement ( element ) Widget . __init__ ( self , ** kwargs ) MouseHandler . __init__ ( self ) self . setzIndex ( ) self . addMouseListener ( self ) def addGlassListener ( self , listener ) : self . glassListeners . append ( listener ) def hide ( self , autoClosed = False ) : self . showing = False self . hideGlass ( ) DOM . removeEventPreview ( self ) RootPanel ( ) . remove ( self ) self . onHideImpl ( self . getElement ( ) ) DOM . releaseCapture ( self . getElement ( ) ) for listener in self . glassListeners : if hasattr ( listener , '' ) : listener . onGlassHide ( self , autoClosed ) else : listener ( self , autoClosed ) def _event_targets_popup ( self , event ) : target = DOM . eventGetTarget ( event ) return target and DOM . isOrHasChild ( self . getElement ( ) , target ) def onEventPreview ( self , event ) : etype = DOM . eventGetType ( event ) if etype == \"\" or etype == \"\" : if DOM . getCaptureElement ( ) is not None : return True elif etype == \"\" or etype == \"\" or etype == \"\" or etype == \"\" : if DOM . getCaptureElement ( ) is not None : return True return self . _event_targets_popup ( event ) def onHideImpl ( self , popup ) : pass def onShowImpl ( self , popup ) : pass def removeGlassListener ( self , listener ) : self . glassListeners . remove ( listener ) def setGlassPosition ( self ) : top = Window . getScrollTop ( ) left = Window . getScrollLeft ( ) height = Window . getClientHeight ( ) width = Window . getClientWidth ( ) el = self . getElement ( ) DOM . setStyleAttribute ( el , \"\" , \"\" ) DOM . setStyleAttribute ( el , \"\" , \"\" % left if left == else \"\" % left ) DOM . setStyleAttribute ( el , \"\" , \"\" % top if top == else \"\" % top ) DOM . setStyleAttribute ( el , \"\" , \"\" % ( top + height ) ) DOM . setStyleAttribute ( el , \"\" , \"\" % ( left + width ) ) if pyjd . is_desktop : DOM . setStyleAttribute ( el , \"\" , \"\" ) DOM . setStyleAttribute ( el , \"\" , \"\" ) def showGlass ( self ) : self . setGlassPosition ( ) doc ( ) . body . appendChild ( self . getElement ( ) ) Window . addWindowResizeListener ( self ) def hideGlass ( self ) : Window . removeWindowResizeListener ( self ) doc ( ) . body . removeChild ( self . getElement ( ) ) def onWindowResized ( self , width , height ) : self . setGlassPosition ( ) def show ( self ) : if self . showing : return self . showing = True self . showGlass ( ) DOM . addEventPreview ( self ) RootPanel ( ) . add ( self ) self . onShowImpl ( self . getElement ( ) ) DOM . setCapture ( self . getElement ( ) ) def adjustMousePos ( self , x , y ) : x += self . getAbsoluteLeft ( ) - self . mousetarget . getAbsoluteLeft ( ) y += self . getAbsoluteTop ( ) - self . mousetarget . getAbsoluteTop ( ) return x , y def onMouseDown ( self , sender , x , y ) : x , y = self . adjustMousePos ( x , y ) if self . mousehandler : self . mousetarget . onBrowserEvent ( DOM . eventGetCurrentEvent ( ) ) else : ", "answer": "self . mousetarget . onMouseDown ( sender , x , y )"}, {"prompt": " from . . utils . access_permissions import BaseAccessPermissions class MediafileAccessPermissions ( BaseAccessPermissions ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from setuptools import setup , find_packages import re import os from os . path import join as opj curdir = os . path . dirname ( os . path . realpath ( __file__ ) ) def read ( fname ) : contents = '' with open ( fname ) as f : contents = f . read ( ) return contents package_name = '' def version ( ) : text = read ( opj ( curdir , package_name , '' ) ) matches = re . findall ( \"\" , text ) return matches [ ] [ ] install_requires = [ '' , '' , ] test_requires = [ '' , '' , ] if __name__ == '' : ", "answer": "setup ("}, {"prompt": " import datetime from django . db import models from django . utils . encoding import python_2_unicode_compatible @ python_2_unicode_compatible class Country ( models . Model ) : name = models . CharField ( max_length = ) def __str__ ( self ) : return self . name @ python_2_unicode_compatible class Person ( models . Model ) : name = models . CharField ( max_length = ) person_country_id = models . IntegerField ( ) person_country = models . ForeignObject ( Country , from_fields = [ '' ] , to_fields = [ '' ] , on_delete = models . CASCADE , ) friends = models . ManyToManyField ( '' , through = '' , symmetrical = False ) class Meta : ordering = ( '' , ) def __str__ ( self ) : return self . name @ python_2_unicode_compatible class Group ( models . Model ) : name = models . CharField ( max_length = ) group_country = models . ForeignKey ( Country , models . CASCADE ) members = models . ManyToManyField ( Person , related_name = '' , through = '' ) class Meta : ordering = ( '' , ) def __str__ ( self ) : return self . name @ python_2_unicode_compatible class Membership ( models . Model ) : membership_country = models . ForeignKey ( Country , models . CASCADE ) date_joined = models . DateTimeField ( default = datetime . datetime . now ) invite_reason = models . CharField ( max_length = , null = True ) person_id = models . IntegerField ( ) group_id = models . IntegerField ( blank = True , null = True ) person = models . ForeignObject ( Person , from_fields = [ '' , '' ] , to_fields = [ '' , '' ] , on_delete = models . CASCADE , ) group = models . ForeignObject ( Group , from_fields = [ '' , '' ] , to_fields = [ '' , '' ] , on_delete = models . CASCADE , ", "answer": ")"}, {"prompt": " from __future__ import absolute_import from django import forms import vobject from contacts_import . backends . importers . base import Importer class vCardImportForm ( forms . Form ) : file = forms . FileField ( ) class vCardImporter ( Importer ) : name = \"\" ", "answer": "form_class = vCardImportForm"}, {"prompt": " from cuddlybuddly . thumbnail . processors import CropToFitProcessor , ResizeProcessor LOADING = False PROCESSORS = { '' : CropToFitProcessor , '' : ResizeProcessor } DEFAULT_PROCESSOR = ResizeProcessor def register_processor ( name , processor , default = False ) : ", "answer": "global PROCESSORS"}, {"prompt": " from django . conf import settings from django . core . urlresolvers import reverse from django . utils . translation import ugettext_lazy as _ from django . utils . translation import ungettext_lazy from horizon import tables import six from openstack_dashboard import api from openstack_dashboard import policy from openstack_dashboard . usage import quotas from openstack_dashboard . utils import filters POLICY_CHECK = getattr ( settings , \"\" , lambda policy , request , target : True ) class DeleteGroup ( policy . PolicyTargetMixin , tables . DeleteAction ) : @ staticmethod def action_present ( count ) : return ungettext_lazy ( u\"\" , u\"\" , count ) @ staticmethod def action_past ( count ) : return ungettext_lazy ( u\"\" , u\"\" , count ) def allowed ( self , request , security_group = None ) : policy_target = self . get_policy_target ( request , security_group ) if api . base . is_service_enabled ( request , \"\" ) : policy = ( ( \"\" , \"\" ) , ) else : policy = ( ( \"\" , \"\" ) , ) if not POLICY_CHECK ( policy , request , policy_target ) : return False if not security_group : return True return security_group . name != '' def delete ( self , request , obj_id ) : api . network . security_group_delete ( request , obj_id ) class CreateGroup ( tables . LinkAction ) : name = \"\" verbose_name = _ ( \"\" ) url = \"\" classes = ( \"\" , ) icon = \"\" def allowed ( self , request , security_group = None ) : if api . base . is_service_enabled ( request , \"\" ) : policy = ( ( \"\" , \"\" ) , ) else : policy = ( ( \"\" , \"\" ) , ) usages = quotas . tenant_quota_usages ( request ) if usages [ '' ] . get ( '' , ) <= : if \"\" not in self . classes : self . classes = [ c for c in self . classes ] + [ \"\" ] self . verbose_name = _ ( \"\" ) else : self . verbose_name = _ ( \"\" ) self . classes = [ c for c in self . classes if c != \"\" ] return POLICY_CHECK ( policy , request , target = { } ) class EditGroup ( policy . PolicyTargetMixin , tables . LinkAction ) : name = \"\" verbose_name = _ ( \"\" ) url = \"\" classes = ( \"\" , ) icon = \"\" def allowed ( self , request , security_group = None ) : policy_target = self . get_policy_target ( request , security_group ) if api . base . is_service_enabled ( request , \"\" ) : policy = ( ( \"\" , \"\" ) , ) else : policy = ( ( \"\" , \"\" ) , ) if not POLICY_CHECK ( policy , request , policy_target ) : return False if not security_group : return True return security_group . name != '' class ManageRules ( policy . PolicyTargetMixin , tables . LinkAction ) : name = \"\" verbose_name = _ ( \"\" ) url = \"\" icon = \"\" def allowed ( self , request , security_group = None ) : policy_target = self . get_policy_target ( request , security_group ) if api . base . is_service_enabled ( request , \"\" ) : policy = ( ( \"\" , \"\" ) , ) else : policy = ( ( \"\" , \"\" ) , ) return POLICY_CHECK ( policy , request , policy_target ) class SecurityGroupsFilterAction ( tables . FilterAction ) : def filter ( self , table , security_groups , filter_string ) : \"\"\"\"\"\" query = filter_string . lower ( ) return [ security_group for security_group in security_groups if query in security_group . name . lower ( ) ] class SecurityGroupsTable ( tables . DataTable ) : name = tables . Column ( \"\" , verbose_name = _ ( \"\" ) ) description = tables . Column ( \"\" , verbose_name = _ ( \"\" ) ) def sanitize_id ( self , obj_id ) : return filters . get_int_or_uuid ( obj_id ) class Meta ( object ) : name = \"\" verbose_name = _ ( \"\" ) table_actions = ( CreateGroup , DeleteGroup , SecurityGroupsFilterAction ) row_actions = ( ManageRules , EditGroup , DeleteGroup ) class CreateRule ( tables . LinkAction ) : name = \"\" verbose_name = _ ( \"\" ) url = \"\" classes = ( \"\" , ) icon = \"\" def allowed ( self , request , security_group_rule = None ) : if api . base . is_service_enabled ( request , \"\" ) : policy = ( ( \"\" , \"\" ) , ) else : policy = ( ( \"\" , \"\" ) , ) return POLICY_CHECK ( policy , request , target = { } ) def get_link_url ( self ) : return reverse ( self . url , args = [ self . table . kwargs [ '' ] ] ) class DeleteRule ( tables . DeleteAction ) : @ staticmethod def action_present ( count ) : return ungettext_lazy ( u\"\" , u\"\" , count ) @ staticmethod def action_past ( count ) : return ungettext_lazy ( u\"\" , u\"\" , count ) def allowed ( self , request , security_group_rule = None ) : if api . base . is_service_enabled ( request , \"\" ) : policy = ( ( \"\" , \"\" ) , ) else : policy = ( ( \"\" , \"\" ) , ) return POLICY_CHECK ( policy , request , target = { } ) def delete ( self , request , obj_id ) : api . network . security_group_rule_delete ( request , obj_id ) def get_success_url ( self , request ) : sg_id = self . table . kwargs [ '' ] return reverse ( \"\" \"\" , args = [ sg_id ] ) def get_remote_ip_prefix ( rule ) : if '' in rule . ip_range : if rule . ip_range [ '' ] is None : range = '' if rule . ethertype == '' else '' else : range = rule . ip_range [ '' ] return range else : return None def get_remote_security_group ( rule ) : return rule . group . get ( '' ) def get_port_range ( rule ) : if rule . from_port is None : return _ ( '' ) ip_proto = rule . ip_protocol ", "answer": "if rule . from_port == rule . to_port :"}, {"prompt": " \"\"\"\"\"\" from os import path import uwhoisd from uwhoisd . utils import make_config_parser HERE = path . dirname ( __file__ ) def create_uwhois ( ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import argparse import sys import os import numpy as np from PIL import Image import urllib , urllib2 import cStringIO import collections import zlib import kanno_cy \"\"\"\"\"\" _xtilesz = _ytilesz = _startslice = _endslice = _prefix = '' _batchsz = _zingestsz = _yingestsz = _xingestsz = def main ( ) : parser = argparse . ArgumentParser ( description = '' ) parser . add_argument ( '' , action = \"\" , help = '' ) parser . add_argument ( '' , action = \"\" , help = '' ) parser . add_argument ( '' , action = \"\" , help = '' ) result = parser . parse_args ( ) for sl in range ( _startslice , _endslice + , _batchsz ) : newdata = np . zeros ( [ _batchsz , _ytilesz , _xtilesz ] , dtype = np . uint32 ) for b in range ( _batchsz ) : if ( sl + b <= _endslice ) : filenm = result . path + '' + _prefix + '' . format ( sl + b ) + '' print filenm tileimage = Image . open ( filenm , '' ) imgdata = np . asarray ( tileimage ) newdata [ b , : , : ] = kanno_cy . pngto32 ( imgdata ) endz = b zlow = sl + zhigh = sl + endz + ", "answer": "ylow = "}, {"prompt": " import copy import logging from oslo_config import cfg from cloudferry . lib . base . action import action from cloudferry . lib . utils import utils CONF = cfg . CONF LOG = logging . getLogger ( __name__ ) class DetachVolumesCompute ( action . Action ) : def run ( self , info , ** kwargs ) : info = copy . deepcopy ( info ) compute_resource = self . cloud . resources [ utils . COMPUTE_RESOURCE ] storage_resource = self . cloud . resources [ utils . STORAGE_RESOURCE ] ", "answer": "for instance in info [ utils . INSTANCES_TYPE ] . itervalues ( ) :"}, {"prompt": " try : from south . db import db ", "answer": "from django . db . models . signals import post_syncdb"}, {"prompt": " import json from appvalidator import validate_app , validate_packaged_app from helper import safe @ safe def test_webapp_new ( ) : \"\"\"\"\"\" with open ( \"\" ) as file_ : out = validate_app ( file_ . read ( ) ) j = json . loads ( out ) assert j [ \"\" ] , \"\" % j @ safe def test_packaged_app_new ( ) : \"\"\"\"\"\" out = validate_packaged_app ( \"\" , listed = False ) j = json . loads ( out ) assert j [ \"\" ] , \"\" % j ", "answer": "@ safe"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import urllib from pyactiveresource import connection from pyactiveresource import formats class Error ( Exception ) : \"\"\"\"\"\" class FakeConnection ( object ) : \"\"\"\"\"\" def __init__ ( self , format = formats . XMLFormat ) : \"\"\"\"\"\" self . format = format self . _request_map = { } self . _debug_only = False def _split_path ( self , path ) : \"\"\"\"\"\" path_only , query_string = urllib . splitquery ( path ) if query_string : query_dict = dict ( [ i . split ( '' ) for i in query_string . split ( '' ) ] ) else : ", "answer": "query_dict = { }"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " import wx from traits . api import Trait , HasTraits , Str , Int from traitsui . api import View , Group from traits . api import Color class Employer ( HasTraits ) : company = Str boss = Str view = View ( '' , '' ) class Person ( HasTraits ) : name = Str ( '' ) age = Int ( ) view = View ( '' , '' , '' , kind = '' ) class ExtraPerson ( Person ) : sex = Trait ( '' , '' ) eye_color = Color extra = Group ( '' , '' ) class LocatedPerson ( Person ) : street = Str city = Str state = Str zip = Int ( ) extra = Group ( '' , '' , '' , '' ) class EmployedPerson ( LocatedPerson ) : ", "answer": "employer = Trait ( Employer ( company = '' , boss = '' ) )"}, {"prompt": " \"\"\"\"\"\" from sys import getrecursionlimit , setrecursionlimit def accessibility ( graph ) : \"\"\"\"\"\" recursionlimit = getrecursionlimit ( ) setrecursionlimit ( max ( len ( graph . nodes ( ) ) * , recursionlimit ) ) accessibility = { } for each in graph : access = { } _dfs ( graph , access , , each ) accessibility [ each ] = list ( access . keys ( ) ) setrecursionlimit ( recursionlimit ) return accessibility def mutual_accessibility ( graph ) : \"\"\"\"\"\" recursionlimit = getrecursionlimit ( ) setrecursionlimit ( max ( len ( graph . nodes ( ) ) * , recursionlimit ) ) mutual_access = { } stack = [ ] low = { } def visit ( node ) : if node in low : return num = len ( low ) low [ node ] = num stack_pos = len ( stack ) stack . append ( node ) for successor in graph . neighbors ( node ) : visit ( successor ) low [ node ] = min ( low [ node ] , low [ successor ] ) if num == low [ node ] : component = stack [ stack_pos : ] del stack [ stack_pos : ] component . sort ( ) for each in component : mutual_access [ each ] = component for item in component : low [ item ] = len ( graph ) for node in graph : visit ( node ) setrecursionlimit ( recursionlimit ) return mutual_access def connected_components ( graph ) : \"\"\"\"\"\" recursionlimit = getrecursionlimit ( ) setrecursionlimit ( max ( len ( graph . nodes ( ) ) * , recursionlimit ) ) visited = { } count = for each in graph : if ( each not in visited ) : _dfs ( graph , visited , count , each ) count = count + setrecursionlimit ( recursionlimit ) return visited def _dfs ( graph , visited , count , node ) : \"\"\"\"\"\" visited [ node ] = count for each in graph [ node ] : if ( each not in visited ) : _dfs ( graph , visited , count , each ) def cut_edges ( graph ) : \"\"\"\"\"\" recursionlimit = getrecursionlimit ( ) setrecursionlimit ( max ( len ( graph . nodes ( ) ) * , recursionlimit ) ) if '' == graph . __class__ . __name__ : return _cut_hyperedges ( graph ) pre = { } low = { } spanning_tree = { } reply = [ ] pre [ None ] = for each in graph : if ( each not in pre ) : spanning_tree [ each ] = None _cut_dfs ( graph , spanning_tree , pre , low , reply , each ) setrecursionlimit ( recursionlimit ) return reply def _cut_hyperedges ( hypergraph ) : \"\"\"\"\"\" edges_ = cut_nodes ( hypergraph . graph ) edges = [ ] for each in edges_ : if ( each [ ] == '' ) : edges . append ( each [ ] ) return edges def cut_nodes ( graph ) : \"\"\"\"\"\" recursionlimit = getrecursionlimit ( ) setrecursionlimit ( max ( len ( graph . nodes ( ) ) * , recursionlimit ) ) if '' == graph . __class__ . __name__ : return _cut_hypernodes ( graph ) pre = { } low = { } reply = { } spanning_tree = { } pre [ None ] = for each in graph : if ( each not in pre ) : spanning_tree [ each ] = None _cut_dfs ( graph , spanning_tree , pre , low , [ ] , each ) for each in graph : if ( spanning_tree [ each ] is not None ) : for other in graph [ each ] : if ( low [ other ] >= pre [ each ] and spanning_tree [ other ] == each ) : reply [ each ] = else : children = for other in graph : if ( spanning_tree [ other ] == each ) : children = children + if ( children >= ) : reply [ each ] = setrecursionlimit ( recursionlimit ) return list ( reply . keys ( ) ) def _cut_hypernodes ( hypergraph ) : \"\"\"\"\"\" nodes_ = cut_nodes ( hypergraph . graph ) nodes = [ ] for each in nodes_ : if ( each [ ] == '' ) : ", "answer": "nodes . append ( each [ ] )"}, {"prompt": " __revision__ = \"\" ", "answer": "from Crypto . Random . OSRNG . winrandom import * "}, {"prompt": " \"\"\"\"\"\" revision = '' down_revision = '' from alembic import op import sqlalchemy as sa def upgrade ( ) : ", "answer": "op . add_column ( '' , sa . Column ( '' , sa . Enum ( ) , server_default = '' , nullable = False ) )"}, {"prompt": " from __future__ import unicode_literals , print_function , division __author__ = \"\" import sys VERSION = \"\" GENERATOR = \"\" % ( VERSION , sys . version ) MIMETYPES = { '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , } FILE_EXT_FOR_MIMETYPE = dict ( [ ( mimetype , ext ) for ext , mimetype in MIMETYPES . items ( ) ] ) ANIM_NS = \"\" DB_NS = \"\" CHART_NS = \"\" CONFIG_NS = \"\" CSS3T_NS = \"\" DC_NS = \"\" DOM_NS = \"\" DR3D_NS = \"\" DRAW_NS = \"\" DRAWOOO_NS = \"\" FIELD_NS = \"\" FO_NS = \"\" FORM_NS = \"\" FORMX_NS = \"\" GRDDL_NS = \"\" KOFFICE_NS = \"\" MANIFEST_NS = \"\" MATH_NS = \"\" META_NS = \"\" NUMBERS_NS = \"\" OFFICE_NS = \"\" OFFICEOOO_NS = \"\" OF_NS = \"\" OOO_NS = \"\" OOOW_NS = \"\" OOOC_NS = \"\" PRESENTATION_NS = \"\" RDFA_NS = \"\" RPT_NS = \"\" SCRIPT_NS = \"\" SMIL_NS = \"\" STYLE_NS = \"\" SVG_NS = \"\" TABLE_NS = \"\" TABLEOOO_NS = \"\" TEXT_NS = \"\" XFORMS_NS = \"\" XHTML_NS = \"\" XLINKS_NS = \"\" XML_NS = \"\" XSD_NS = \"\" XSI_NS = \"\" META_NSMAP = { '' : OFFICE_NS , '' : XLINKS_NS , '' : DC_NS , '' : META_NS , '' : OOO_NS , '' : GRDDL_NS , } MANIFEST_NSMAP = { '' : MANIFEST_NS , } STYLES_NSMAP = { '' : STYLE_NS , '' : TEXT_NS , '' : TABLE_NS , '' : DRAW_NS , '' : FO_NS , '' : XLINKS_NS , '' : DC_NS , '' : META_NS , '' : NUMBERS_NS , '' : SVG_NS , '' : CHART_NS , '' : DR3D_NS , '' : MATH_NS , '' : FORM_NS , '' : SCRIPT_NS , '' : OOO_NS , '' : OOOW_NS , '' : OOOC_NS , '' : OFFICE_NS , '' : DOM_NS , '' : RPT_NS , '' : OF_NS , '' : XHTML_NS , '' : GRDDL_NS , '' : TABLEOOO_NS , '' : CSS3T_NS , } SETTINGS_NSMAP = { '' : OFFICE_NS , '' : XLINKS_NS , '' : CONFIG_NS , '' : OOO_NS , } TEXT_NSMAP = { '' : OFFICE_NS , '' : STYLE_NS , '' : TEXT_NS , '' : TABLE_NS , '' : DRAW_NS , '' : FO_NS , '' : XLINKS_NS , '' : DC_NS , '' : META_NS , '' : NUMBERS_NS , '' : PRESENTATION_NS , '' : SVG_NS , '' : CHART_NS , '' : DR3D_NS , '' : MATH_NS , '' : FORM_NS , '' : SCRIPT_NS , '' : OOO_NS , ", "answer": "'' : OOOW_NS ,"}, {"prompt": " import re import subprocess from subprocess import CalledProcessError from . import base from libqtile . log_utils import logger kb_regex = re . compile ( '' ) class KeyboardLayout ( base . InLoopPollText ) : \"\"\"\"\"\" orientations = base . ORIENTATION_HORIZONTAL defaults = [ ( \"\" , , \"\" ) , ( \"\" , [ \"\" ] , \"\" \"\" \"\" ) , ] def __init__ ( self , ** config ) : base . InLoopPollText . __init__ ( self , ** config ) self . add_defaults ( KeyboardLayout . defaults ) def button_press ( self , x , y , button ) : if button == : self . next_keyboard ( ) def next_keyboard ( self ) : \"\"\"\"\"\" current_keyboard = self . keyboard if current_keyboard in self . configured_keyboards : next_keyboard = self . configured_keyboards [ ( self . configured_keyboards . index ( current_keyboard ) + ) % len ( self . configured_keyboards ) ] else : next_keyboard = self . configured_keyboards [ ] self . keyboard = next_keyboard def poll ( self ) : return self . keyboard . upper ( ) def get_keyboard_layout ( self , setxkbmap_output ) : matches = kb_regex . search ( setxkbmap_output ) if matches is None : return '' return matches . group ( '' ) ", "answer": "@ property"}, {"prompt": " from libcloud . common . types import LibcloudError class Provider ( object ) : \"\"\"\"\"\" DUMMY = CLOUDFILES_US = CLOUDFILES_UK = class ContainerError ( LibcloudError ) : error_type = '' def __init__ ( self , value , driver , container_name ) : self . container_name = container_name super ( ContainerError , self ) . __init__ ( value = value , driver = driver ) def __str__ ( self ) : return '' % ( self . error_type , repr ( self . driver ) , self . container_name ) class ObjectError ( LibcloudError ) : error_type = '' def __init__ ( self , value , driver , object_name ) : self . object_name = object_name super ( ObjectError , self ) . __init__ ( value = value , driver = driver ) def __str__ ( self ) : return '' % ( self . error_type , repr ( self . driver ) , self . object_name ) class ContainerAlreadyExistsError ( ContainerError ) : error_type = '' class ContainerDoesNotExistError ( ContainerError ) : error_type = '' class ContainerIsNotEmptyError ( ContainerError ) : error_type = '' class ObjectDoesNotExistError ( ObjectError ) : ", "answer": "error_type = ''"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " '''''' from crawler . contrib . dpreviews import * from optparse import OptionParser import os import time import pprint import logging logger = logging . getLogger ( __name__ ) logger . addHandler ( logging . StreamHandler ( ) ) logger . setLevel ( logging . DEBUG ) usage = \"\" parser = OptionParser ( usage = usage ) parser . add_option ( '' , \"\" , dest = \"\" , help = \"\" ) ", "answer": "parser . add_option ( \"\" , \"\" , dest = \"\" ,"}, {"prompt": " \"\"\"\"\"\" import sys from setuptools import setup tests_require = [ \"\" ] install_requires = [ '' , '' ] setup ( name = '' , version = '' , url = '' , license = open ( '' ) . read ( ) , author = '' , author_email = '' , description = '' , keywords = [ '' , '' , '' , '' ] , long_description = open ( '' ) . read ( ) , ", "answer": "packages = [ '' ] ,"}, {"prompt": " \"\"\"\"\"\" from core . domain import collection_domain from core . domain import collection_services from core . tests import test_utils import feconf import utils SAMPLE_YAML_CONTENT = ( \"\"\"\"\"\" ) % ( feconf . CURRENT_COLLECTION_SCHEMA_VERSION ) class CollectionDomainUnitTests ( test_utils . GenericTestBase ) : \"\"\"\"\"\" COLLECTION_ID = '' EXPLORATION_ID = '' def setUp ( self ) : super ( CollectionDomainUnitTests , self ) . setUp ( ) self . save_new_valid_collection ( self . COLLECTION_ID , '' , title = '' , category = '' , objective = '' , exploration_id = self . EXPLORATION_ID ) self . collection = collection_services . get_collection_by_id ( self . COLLECTION_ID ) def _assert_validation_error ( self , expected_error_substring ) : \"\"\"\"\"\" with self . assertRaisesRegexp ( utils . ValidationError , expected_error_substring ) : self . collection . validate ( ) def test_initial_validation ( self ) : \"\"\"\"\"\" self . collection . validate ( ) def test_title_validation ( self ) : self . collection . title = self . _assert_validation_error ( '' ) def test_category_validation ( self ) : self . collection . category = self . _assert_validation_error ( '' ) def test_objective_validation ( self ) : self . collection . objective = '' self . _assert_validation_error ( '' ) self . collection . objective = self . _assert_validation_error ( '' ) def test_schema_version_validation ( self ) : self . collection . schema_version = '' self . _assert_validation_error ( '' ) self . collection . schema_version = self . _assert_validation_error ( '' % feconf . CURRENT_COLLECTION_SCHEMA_VERSION ) def test_nodes_validation ( self ) : self . collection . nodes = { } self . _assert_validation_error ( '' ) self . collection . nodes = [ collection_domain . CollectionNode . from_dict ( { '' : '' , '' : [ ] , '' : [ '' ] } ) , collection_domain . CollectionNode . from_dict ( { '' : '' , '' : [ '' ] , '' : [ '' ] } ) ] self . _assert_validation_error ( '' '' ) def test_initial_explorations_validation ( self ) : self . collection . nodes = [ ] self . collection . validate ( strict = False ) self . _assert_validation_error ( ", "answer": "'' )"}, {"prompt": " import pytest import socket from aiohttp . parsers import StreamWriter , CORK from unittest import mock def test_nodelay_default ( loop ) : transport = mock . Mock ( ) s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) transport . get_extra_info . return_value = s proto = mock . Mock ( ) reader = mock . Mock ( ) writer = StreamWriter ( transport , proto , reader , loop ) assert not writer . tcp_nodelay assert not s . getsockopt ( socket . IPPROTO_TCP , socket . TCP_NODELAY ) def test_set_nodelay_no_change ( loop ) : transport = mock . Mock ( ) s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) transport . get_extra_info . return_value = s proto = mock . Mock ( ) reader = mock . Mock ( ) writer = StreamWriter ( transport , proto , reader , loop ) writer . set_tcp_nodelay ( False ) assert not writer . tcp_nodelay assert not s . getsockopt ( socket . IPPROTO_TCP , socket . TCP_NODELAY ) def test_set_nodelay_enable ( loop ) : transport = mock . Mock ( ) s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) transport . get_extra_info . return_value = s proto = mock . Mock ( ) reader = mock . Mock ( ) writer = StreamWriter ( transport , proto , reader , loop ) ", "answer": "writer . set_tcp_nodelay ( True )"}, {"prompt": " from flask import Blueprint , render_template , url_for , redirect , flash , request from flask . ext . login import login_required from flask_login import current_user from comport . public . forms import LoginForm ", "answer": "blueprint = Blueprint ( \"\" , __name__ , url_prefix = '' ,"}, {"prompt": " import random from . . import base from girder . models . token import genToken def setUpModule ( ) : base . startServer ( ) def tearDownModule ( ) : base . stopServer ( ) ", "answer": "class TokensTestCase ( base . TestCase ) :"}, {"prompt": " from funfactory . settings_base import * SITE_TITLE = '' MINIFY_BUNDLES = { '' : { '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , '' , ) } , '' : { '' : ( '' , '' , '' , '' , ) , '' : ( '' , '' , '' , ) , '' : ( '' , ) , } } HMAC_KEYS = { '' : '' , '' : '' , '' : '' } ROOT_URLCONF = '' BROWSERID_CREATE_USER = True SITE_URL = '' LOGIN_URL = '' LOGIN_REDIRECT_URL = '' LOGIN_REDIRECT_URL_FAILURE = '' LOGOUT_REDIRECT_URL = '' def username_algo ( email ) : ", "answer": "from django . contrib . auth . models import User"}, {"prompt": " from Sink import Sink , SinkInfo from pyjamas . ui . MenuBar import MenuBar from pyjamas . ui . MenuItem import MenuItem from pyjamas import Window from pyjamas . ui . HTML import HTML from pyjamas . ui . VerticalPanel import VerticalPanel from pyjamas import DOM from pyjamas . ui . ContextMenuPopupPanel import ContextMenuPopupPanel class Menus ( Sink ) : def __init__ ( self ) : Sink . __init__ ( self ) self . menu = MenuBar ( ) subMenu = MenuBar ( True ) subMenu . addItem ( \"\" , True , self ) subMenu . addItem ( \"\" , True , self ) subMenu . addItem ( \"\" , True , self ) menu0 = MenuBar ( True ) menu0 . addItem ( \"\" , True , self ) menu0 . addItem ( \"\" , True , self ) menu0 . addItem ( \"\" , True , subMenu ) menu1 = MenuBar ( True ) menu1 . addItem ( \"\" , True , self ) menu1 . addItem ( \"\" , True , self ) menu1 . addItem ( \"\" , True , self ) menu1 . addItem ( \"\" , True , self ) menu2 = MenuBar ( True ) menu2 . addItem ( \"\" , self ) menu2 . addItem ( \"\" , self ) menu2 . addItem ( \"\" , True , self ) self . menu . addItem ( MenuItem ( \"\" , menu0 ) ) self . menu . addItem ( MenuItem ( \"\" , menu1 ) ) self . menu . addItem ( MenuItem ( \"\" , menu2 ) ) self . menu . setWidth ( \"\" ) self . panel = VerticalPanel ( ) self . context = HTML ( \"\"\"\"\"\" ) self . panel . add ( self . menu ) self . panel . add ( self . context ) self . initWidget ( self . panel ) self . context . setContextMenu ( self ) def onContextMenu ( self , sender ) : event = DOM . eventGetCurrentEvent ( ) subMenu = MenuBar ( True ) subMenu . addItem ( \"\" , True , self ) subMenu . addItem ( \"\" , True , self ) subMenu . addItem ( \"\" , True , self ) x = DOM . eventGetClientX ( event ) + y = DOM . eventGetClientY ( event ) + popup = ContextMenuPopupPanel ( subMenu ) popup . showAt ( x , y ) def execute ( self ) : Window . alert ( \"\" ) def onShow ( self ) : ", "answer": "pass"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , print_function , absolute_import import numbers import warnings import numpy import pandas from scipy import sparse from scipy . special import expit from collections import defaultdict from sklearn . utils . validation import check_random_state from sklearn . base import BaseEstimator from . commonutils import computeSignalKnnIndices , indices_of_values , check_sample_weight , check_uniform_label from . metrics_utils import bin_to_group_indices , compute_group_weights , compute_bin_indices __author__ = '' def compute_positions ( y_pred , sample_weight ) : \"\"\"\"\"\" order = numpy . argsort ( y_pred ) ordered_weights = sample_weight [ order ] ordered_weights /= float ( numpy . sum ( ordered_weights ) ) efficiencies = ( numpy . cumsum ( ordered_weights ) - * ordered_weights ) return efficiencies [ numpy . argsort ( order ) ] class AbstractLossFunction ( BaseEstimator ) : def fit ( self , X , y , sample_weight ) : \"\"\"\"\"\" pass def negative_gradient ( self , y_pred ) : \"\"\"\"\"\" raise NotImplementedError ( ) def __call__ ( self , y_pred ) : \"\"\"\"\"\" raise NotImplementedError ( ) def update_tree ( self , tree , X , y , y_pred , sample_weight , update_mask , residual ) : \"\"\"\"\"\" terminal_regions = tree . apply ( X ) masked_terminal_regions = terminal_regions . copy ( ) masked_terminal_regions [ ~ update_mask ] = - for leaf , indices_in_leaf in indices_of_values ( masked_terminal_regions ) : if leaf == - : continue tree . value [ leaf , , ] = self . update_tree_leaf ( leaf = leaf , indices_in_leaf = indices_in_leaf , X = X , y = y , y_pred = y_pred , sample_weight = sample_weight , update_mask = update_mask , residual = residual ) def update_fast_tree ( self , fast_tree , X , y , y_pred , sample_weight , update_mask , residual ) : \"\"\"\"\"\" terminal_regions , _ = fast_tree . apply ( X ) terminal_regions [ ~ update_mask ] = - for leaf , indices_in_leaf in indices_of_values ( terminal_regions ) : if leaf == - : continue new_value = self . update_tree_leaf ( leaf = leaf , indices_in_leaf = indices_in_leaf , X = X , y = y , y_pred = y_pred , sample_weight = sample_weight , update_mask = update_mask , residual = residual ) assert len ( fast_tree . nodes_data [ leaf ] ) == fast_tree . nodes_data [ leaf ] = ( new_value , ) def update_tree_leaf ( self , leaf , indices_in_leaf , X , y , y_pred , sample_weight , update_mask , residual ) : raise NotImplementedError ( '' ) class AdaLossFunction ( AbstractLossFunction ) : \"\"\"\"\"\" def __init__ ( self , regularization = ) : self . regularization = regularization def fit ( self , X , y , sample_weight ) : self . y = y self . sample_weight = sample_weight self . y_signed = * y - def __call__ ( self , y_pred ) : return numpy . sum ( self . sample_weight * numpy . exp ( - self . y_signed * y_pred ) ) def negative_gradient ( self , y_pred ) : return self . y_signed * self . sample_weight * numpy . exp ( - self . y_signed * y_pred ) def hessian ( self , y_pred ) : return self . sample_weight * numpy . exp ( - self . y_signed * y_pred ) def update_tree_leaf ( self , leaf , indices_in_leaf , X , y , y_pred , sample_weight , update_mask , residual ) : leaf_ans = y [ indices_in_leaf ] leaf_exp = sample_weight [ indices_in_leaf ] * numpy . exp ( - self . y_signed [ indices_in_leaf ] * y_pred [ indices_in_leaf ] ) w1 = numpy . sum ( leaf_exp [ leaf_ans == ] ) w2 = numpy . sum ( leaf_exp [ leaf_ans == ] ) w_reg = ( w1 + w2 ) * self . regularization return * numpy . log ( ( w1 + w_reg ) / ( w2 + w_reg ) ) class BinomialDevianceLossFunction ( AbstractLossFunction ) : def __init__ ( self , regularization = ) : self . regularization = regularization def fit ( self , X , y , sample_weight ) : self . y = y self . sample_weight = sample_weight self . y_signed = * y - self . adjusted_regularization = numpy . mean ( sample_weight ) * self . regularization def __call__ ( self , y_pred ) : return numpy . sum ( self . sample_weight * numpy . logaddexp ( , - self . y_signed * y_pred ) ) def negative_gradient ( self , y_pred ) : return self . y_signed * self . sample_weight * expit ( - self . y_signed * y_pred ) def hessian ( self , y_pred ) : expits = expit ( self . y_signed * y_pred ) return self . sample_weight * expits * ( - expits ) def update_tree_leaf ( self , leaf , indices_in_leaf , X , y , y_pred , sample_weight , update_mask , residual ) : leaf_y = y [ indices_in_leaf ] y_signed = * leaf_y - leaf_weights = sample_weight [ indices_in_leaf ] residual_abs = expit ( numpy . clip ( - y_signed * y_pred [ indices_in_leaf ] , - , ) ) nominator = numpy . sum ( y_signed * residual_abs * leaf_weights ) denominator = numpy . sum ( residual_abs * ( - residual_abs ) * leaf_weights ) return nominator / ( denominator + self . adjusted_regularization ) class CompositeLossFunction ( AbstractLossFunction ) : \"\"\"\"\"\" def fit ( self , X , y , sample_weight ) : self . y = y self . sample_weight = sample_weight self . y_signed = * y - self . sig_w = ( y == ) * self . sample_weight self . bck_w = ( y == ) * self . sample_weight def __call__ ( self , y_pred ) : result = numpy . sum ( self . sig_w * numpy . logaddexp ( , - y_pred ) ) result += numpy . sum ( self . bck_w * numpy . exp ( * y_pred ) ) return result def negative_gradient ( self , y_pred ) : result = self . sig_w * expit ( - y_pred ) result -= * self . bck_w * numpy . exp ( * y_pred ) return result def hessian ( self , y_pred ) : expits = expit ( self . y_signed * y_pred ) return self . sig_w * expits * ( - expits ) + self . bck_w * * numpy . exp ( * y_pred ) class AbstractMatrixLossFunction ( AbstractLossFunction ) : def __init__ ( self , uniform_variables ) : \"\"\"\"\"\" self . uniform_variables = uniform_variables self . A = None self . A_t = None self . w = None def fit ( self , X , y , sample_weight ) : \"\"\"\"\"\" assert len ( X ) == len ( y ) , \"\" A , w = self . compute_parameters ( X , y ) self . A = sparse . csr_matrix ( A ) self . A_t = sparse . csr_matrix ( self . A . transpose ( ) ) self . A_t_sq = self . A_t . multiply ( self . A_t ) ", "answer": "self . w = numpy . array ( w )"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import yaml_validator class Error ( Exception ) : \"\"\"\"\"\" class Container ( object ) : \"\"\"\"\"\" def __init__ ( self , absolute_paths = None , relative_paths = None ) : \"\"\"\"\"\" self . absolute_paths = absolute_paths if absolute_paths else [ ] self . relative_paths = relative_paths if relative_paths else [ ] self . changelist = '' ", "answer": "class GlobalFilter ( object ) :"}, {"prompt": " \"\"\"\"\"\" from django . db import models from django . test import TestCase from django_any import any_model class RelatedModel ( models . Model ) : name = models . CharField ( max_length = ) class Meta : app_label = '' class BaseModel ( models . Model ) : related = models . ForeignKey ( RelatedModel ) ", "answer": "class Meta :"}, {"prompt": " import sys , os from distutils . core import run_setup from random import choice import re import optparse from django . core . management import execute_from_command_line , call_command from django . core . management . base import CommandError , _make_writeable from django . utils . importlib import import_module from fabric . contrib . console import confirm , prompt from fabric . api import settings from fabric . state import env from fabric . main import find_fabfile import woven TEMPLATE_DIR = os . path . join ( os . path . dirname ( os . path . realpath ( woven . __file__ ) ) , '' , '' ) def copy_helper ( app_or_project , name , directory , dist , template_dir , noadmin ) : \"\"\"\"\"\" import shutil if not re . search ( r'' , name ) : if not re . search ( r'' , name ) : message = '' else : message = '' raise CommandError ( \"\" % ( name , message ) ) top_dir = os . path . join ( directory , dist ) try : os . mkdir ( top_dir ) except OSError , e : raise CommandError ( e ) for d , subdirs , files in os . walk ( template_dir ) : relative_dir = d [ len ( template_dir ) + : ] . replace ( '' , name ) if relative_dir : os . mkdir ( os . path . join ( top_dir , relative_dir ) ) for subdir in subdirs [ : ] : if subdir . startswith ( '' ) : subdirs . remove ( subdir ) for f in files : if not f . endswith ( '' ) : continue path_old = os . path . join ( d , f ) path_new = os . path . join ( top_dir , relative_dir , f . replace ( '' , name ) ) fp_old = open ( path_old , '' ) fp_new = open ( path_new , '' ) if noadmin : fp_new . write ( fp_old . read ( ) . replace ( '' , name ) ) else : fp_new . write ( fp_old . read ( ) . replace ( '' , name ) . replace ( '' , '' ) ) fp_old . close ( ) fp_new . close ( ) try : shutil . copymode ( path_old , path_new ) _make_writeable ( path_new ) except OSError : sys . stderr . write ( style . NOTICE ( \"\" % path_new ) ) def start_distribution ( project_name , template_dir , dist , noadmin ) : \"\"\"\"\"\" directory = os . getcwd ( ) try : import_module ( project_name ) except ImportError : pass else : raise CommandError ( \"\" % project_name ) copy_helper ( '' , project_name , directory , dist , template_dir , noadmin ) main_settings_file = os . path . join ( directory , dist , project_name , '' ) settings_contents = open ( main_settings_file , '' ) . read ( ) fp = open ( main_settings_file , '' ) secret_key = '' . join ( [ choice ( '' ) for i in range ( ) ] ) settings_contents = re . sub ( r\"\" , secret_key + \"\" , settings_contents ) fp . write ( settings_contents ) fp . close ( ) sys . path . append ( os . path . join ( directory , dist ) ) s = import_module ( '' . join ( [ project_name , '' ] ) ) sys . path . pop ( ) if s . DATABASES [ '' ] [ '' ] == '' : if s . DATABASES [ '' ] [ '' ] and not os . path . exists ( s . DATABASES [ '' ] [ '' ] ) : os . mkdir ( os . path . dirname ( s . DATABASES [ '' ] [ '' ] ) ) if s . STATIC_ROOT and os . path . isabs ( s . STATIC_ROOT ) and not os . path . exists ( s . STATIC_ROOT ) : os . mkdir ( s . STATIC_ROOT ) if s . MEDIA_ROOT and os . path . isabs ( s . MEDIA_ROOT ) and not os . path . exists ( s . MEDIA_ROOT ) : os . mkdir ( s . MEDIA_ROOT ) if s . TEMPLATE_DIRS : for t in s . TEMPLATE_DIRS : if not os . path . exists ( t ) and os . path . sep in t : os . mkdir ( t ) if __name__ == \"\" : settings_mod = None inject = False startproject = False orig_cwd = os . getcwd ( ) for arg in sys . argv : if '' in arg : settings_mod = arg . split ( '' ) [ ] . strip ( ) elif arg in [ '' , '' , '' , '' , '' , '' , '' , '' ] : inject = True elif arg == '' : startproject = True inject = True parser = optparse . OptionParser ( usage = \"\" \"\" \"\" ) parser . add_option ( '' , '' , dest = '' , help = '' , default = TEMPLATE_DIR ) parser . add_option ( '' , '' , dest = '' , help = \"\" , default = '' ) parser . add_option ( '' , action = '' , default = False , help = \"\" , ) , parser . add_option ( '' , action = '' , default = False , help = \"\" , ) options , args = parser . parse_args ( ) if len ( args ) not in ( , , ) : parser . print_help ( ) sys . exit ( ) if not options . dist_name : dist = args [ ] else : dist = options . dist_name project_name = args [ ] try : email = args [ ] except IndexError : email = '' start_distribution ( project_name , options . src_dir , dist , noadmin = options . noadmin ) if not os . environ . get ( '' ) and not settings_mod : if startproject : os . chdir ( os . path . join ( orig_cwd , dist ) ) elif not '' in os . listdir ( os . getcwd ( ) ) : with settings ( fabfile = '' ) : env . setup_path = find_fabfile ( ) if not env . setup_path : print '' sys . exit ( ) local_working_dir = os . path . split ( env . setup_path ) [ ] os . chdir ( local_working_dir ) woven_admin = sys . argv [ ] setup = run_setup ( '' , stop_after = \"\" ) settings_mod = '' . join ( [ setup . packages [ ] , '' ] ) os . environ [ '' ] = settings_mod sys . argv . remove ( '' ) sys . argv . insert ( , woven_admin ) if inject : if settings_mod : os . environ [ '' ] = settings_mod ", "answer": "from django . conf import settings"}, {"prompt": " from django import forms from django . forms import fields from django . core . validators import validate_email from . widgets import AutocompleteTextarea class CSVListField ( fields . CharField ) : \"\"\"\"\"\" def to_python ( self , value ) : ", "answer": "if isinstance ( value , list ) :"}, {"prompt": " \"\"\"\"\"\" class QRCode : PAD0 = PAD1 = def __init__ ( self ) : self . typeNumber = self . errorCorrectLevel = ErrorCorrectLevel . H self . qrDataList = [ ] self . modules = [ ] self . moduleCount = def getTypeNumber ( self ) : return self . typeNumber def setTypeNumber ( self , typeNumber ) : self . typeNumber = typeNumber def getErrorCorrectLevel ( self ) : return self . errorCorrectLevel def setErrorCorrectLevel ( self , errorCorrectLevel ) : self . errorCorrectLevel = errorCorrectLevel def clearData ( self ) : self . qrDataList = [ ] def addData ( self , data ) : self . qrDataList . append ( QR8BitByte ( data ) ) def getDataCount ( self ) : return len ( self . qrDataList ) def getData ( self , index ) : return self . qrDataList [ index ] def isDark ( self , row , col ) : return ( self . modules [ row ] [ col ] if self . modules [ row ] [ col ] != None else False ) def getModuleCount ( self ) : return self . moduleCount def make ( self ) : self . _make ( False , self . _getBestMaskPattern ( ) ) def _getBestMaskPattern ( self ) : minLostPoint = pattern = for i in range ( ) : self . _make ( True , i ) lostPoint = QRUtil . getLostPoint ( self ) if i == or minLostPoint > lostPoint : minLostPoint = lostPoint pattern = i return pattern def _make ( self , test , maskPattern ) : self . moduleCount = self . typeNumber * + self . modules = [ [ None ] * self . moduleCount for i in range ( self . moduleCount ) ] self . _setupPositionProbePattern ( , ) self . _setupPositionProbePattern ( self . moduleCount - , ) self . _setupPositionProbePattern ( , self . moduleCount - ) self . _setupPositionAdjustPattern ( ) self . _setupTimingPattern ( ) self . _setupTypeInfo ( test , maskPattern ) if self . typeNumber >= : self . _setupTypeNumber ( test ) data = QRCode . _createData ( self . typeNumber , self . errorCorrectLevel , self . qrDataList ) self . _mapData ( data , maskPattern ) def _mapData ( self , data , maskPattern ) : rows = list ( range ( self . moduleCount ) ) cols = [ col - if col <= else col for col in range ( self . moduleCount - , , - ) ] maskFunc = QRUtil . getMaskFunction ( maskPattern ) byteIndex = bitIndex = for col in cols : rows . reverse ( ) for row in rows : for c in range ( ) : if self . modules [ row ] [ col - c ] == None : dark = False if byteIndex < len ( data ) : dark = ( ( data [ byteIndex ] >> bitIndex ) & ) == if maskFunc ( row , col - c ) : dark = not dark self . modules [ row ] [ col - c ] = dark bitIndex -= if bitIndex == - : byteIndex += bitIndex = def _setupPositionAdjustPattern ( self ) : pos = QRUtil . getPatternPosition ( self . typeNumber ) for row in pos : for col in pos : if self . modules [ row ] [ col ] != None : continue for r in range ( - , ) : for c in range ( - , ) : self . modules [ row + r ] [ col + c ] = ( r == - or r == or c == - or c == or ( r == and c == ) ) def _setupPositionProbePattern ( self , row , col ) : for r in range ( - , ) : for c in range ( - , ) : if ( row + r <= - or self . moduleCount <= row + r or col + c <= - or self . moduleCount <= col + c ) : continue self . modules [ row + r ] [ col + c ] = ( ( <= r and r <= and ( c == or c == ) ) or ( <= c and c <= and ( r == or r == ) ) or ( <= r and r <= and <= c and c <= ) ) def _setupTimingPattern ( self ) : for r in range ( , self . moduleCount - ) : if self . modules [ r ] [ ] != None : continue self . modules [ r ] [ ] = r % == for c in range ( , self . moduleCount - ) : if self . modules [ ] [ c ] != None : continue self . modules [ ] [ c ] = c % == def _setupTypeNumber ( self , test ) : bits = QRUtil . getBCHTypeNumber ( self . typeNumber ) for i in range ( ) : self . modules [ i // ] [ i % + self . moduleCount - - ] = ( not test and ( ( bits >> i ) & ) == ) for i in range ( ) : self . modules [ i % + self . moduleCount - - ] [ i // ] = ( not test and ( ( bits >> i ) & ) == ) def _setupTypeInfo ( self , test , maskPattern ) : data = ( self . errorCorrectLevel << ) | maskPattern bits = QRUtil . getBCHTypeInfo ( data ) for i in range ( ) : mod = not test and ( ( bits >> i ) & ) == if i < : self . modules [ i ] [ ] = mod elif i < : self . modules [ i + ] [ ] = mod else : self . modules [ self . moduleCount - + i ] [ ] = mod for i in range ( ) : mod = not test and ( ( bits >> i ) & ) == if i < : self . modules [ ] [ self . moduleCount - i - ] = mod elif i < : self . modules [ ] [ - i - + ] = mod else : self . modules [ ] [ - i - ] = mod self . modules [ self . moduleCount - ] [ ] = not test @ staticmethod def _createData ( typeNumber , errorCorrectLevel , dataArray ) : rsBlocks = RSBlock . getRSBlocks ( typeNumber , errorCorrectLevel ) buffer = BitBuffer ( ) for data in dataArray : buffer . put ( data . getMode ( ) , ) buffer . put ( data . getLength ( ) , data . getLengthInBits ( typeNumber ) ) data . write ( buffer ) totalDataCount = sum ( rsBlock . getDataCount ( ) for rsBlock in rsBlocks ) if buffer . getLengthInBits ( ) > totalDataCount * : raise Exception ( '' % ( buffer . getLengthInBits ( ) , totalDataCount * ) ) if buffer . getLengthInBits ( ) + <= totalDataCount * : buffer . put ( , ) while buffer . getLengthInBits ( ) % != : buffer . put ( False ) while True : if buffer . getLengthInBits ( ) >= totalDataCount * : break buffer . put ( QRCode . PAD0 , ) if buffer . getLengthInBits ( ) >= totalDataCount * : break buffer . put ( QRCode . PAD1 , ) return QRCode . _createBytes ( buffer , rsBlocks ) @ staticmethod def _createBytes ( buffer , rsBlocks ) : offset = maxDcCount = maxEcCount = dcdata = [ None ] * len ( rsBlocks ) ecdata = [ None ] * len ( rsBlocks ) for r in range ( len ( rsBlocks ) ) : dcCount = rsBlocks [ r ] . getDataCount ( ) ecCount = rsBlocks [ r ] . getTotalCount ( ) - dcCount maxDcCount = max ( maxDcCount , dcCount ) maxEcCount = max ( maxEcCount , ecCount ) dcdata [ r ] = [ ] * dcCount for i in range ( len ( dcdata [ r ] ) ) : dcdata [ r ] [ i ] = & buffer . getBuffer ( ) [ i + offset ] offset += dcCount rsPoly = QRUtil . getErrorCorrectPolynomial ( ecCount ) rawPoly = Polynomial ( dcdata [ r ] , rsPoly . getLength ( ) - ) modPoly = rawPoly . mod ( rsPoly ) ecdata [ r ] = [ ] * ( rsPoly . getLength ( ) - ) for i in range ( len ( ecdata [ r ] ) ) : modIndex = i + modPoly . getLength ( ) - len ( ecdata [ r ] ) ecdata [ r ] [ i ] = modPoly . get ( modIndex ) if modIndex >= else totalCodeCount = sum ( rsBlock . getTotalCount ( ) for rsBlock in rsBlocks ) data = [ ] * totalCodeCount index = for i in range ( maxDcCount ) : for r in range ( len ( rsBlocks ) ) : if i < len ( dcdata [ r ] ) : data [ index ] = dcdata [ r ] [ i ] index += for i in range ( maxEcCount ) : for r in range ( len ( rsBlocks ) ) : if i < len ( ecdata [ r ] ) : data [ index ] = ecdata [ r ] [ i ] index += return data @ staticmethod def getMinimumQRCode ( data , errorCorrectLevel ) : mode = Mode . MODE_8BIT_BYTE qr = QRCode ( ) qr . setErrorCorrectLevel ( errorCorrectLevel ) qr . addData ( data ) length = qr . getData ( ) . getLength ( ) for typeNumber in range ( , ) : if length <= QRUtil . getMaxLength ( typeNumber , mode , errorCorrectLevel ) : qr . setTypeNumber ( typeNumber ) break qr . make ( ) return qr class Mode : MODE_NUMBER = << MODE_ALPHA_NUM = << MODE_8BIT_BYTE = << MODE_KANJI = << class ErrorCorrectLevel : L = M = Q = H = class MaskPattern : PATTERN000 = PATTERN001 = PATTERN010 = PATTERN011 = PATTERN100 = PATTERN101 = PATTERN110 = PATTERN111 = class QRUtil : @ staticmethod def getPatternPosition ( typeNumber ) : return QRUtil . PATTERN_POSITION_TABLE [ typeNumber - ] PATTERN_POSITION_TABLE = [ [ ] , [ , ] , [ , ] , [ , ] , [ , ] , [ , ] , [ , , ] , [ , , ] , [ , , ] , [ , , ] , [ , , ] , [ , , ] , [ , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , , ] , [ , , , , ] , [ , , , , ] , [ , , , , ] , [ , , , , ] , [ , , , , ] , [ , , , , ] , [ , , , , , ] , [ , , , , , ] , [ , , , , , ] , [ , , , , , ] , [ , , , , , ] , [ , , , , , ] , [ , , , , , ] , [ , , , , , , ] , [ , , , , , , ] , [ , , , , , , ] , [ , , , , , , ] , [ , , , , , , ] , [ , , , , , , ] ] MAX_LENGTH = [ [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] ] ] @ staticmethod def getMaxLength ( typeNumber , mode , errorCorrectLevel ) : t = typeNumber - e = { ErrorCorrectLevel . L : , ErrorCorrectLevel . M : , ErrorCorrectLevel . Q : , ErrorCorrectLevel . H : } [ errorCorrectLevel ] m = { Mode . MODE_NUMBER : , Mode . MODE_ALPHA_NUM : , Mode . MODE_8BIT_BYTE : , Mode . MODE_KANJI : } [ mode ] return QRUtil . MAX_LENGTH [ t ] [ e ] [ m ] @ staticmethod def getErrorCorrectPolynomial ( errorCorrectLength ) : a = Polynomial ( [ ] ) for i in range ( errorCorrectLength ) : a = a . multiply ( Polynomial ( [ , QRMath . gexp ( i ) ] ) ) return a @ staticmethod def getMaskFunction ( maskPattern ) : return { MaskPattern . PATTERN000 : lambda i , j : ( i + j ) % == , MaskPattern . PATTERN001 : lambda i , j : i % == , MaskPattern . PATTERN010 : lambda i , j : j % == , MaskPattern . PATTERN011 : lambda i , j : ( i + j ) % == , MaskPattern . PATTERN100 : lambda i , j : ( i // + j // ) % == , MaskPattern . PATTERN101 : lambda i , j : ( i * j ) % + ( i * j ) % == , MaskPattern . PATTERN110 : lambda i , j : ( ( i * j ) % + ( i * j ) % ) % == , MaskPattern . PATTERN111 : ", "answer": "lambda i , j : ( ( i * j ) % + ( i + j ) % ) % == "}, {"prompt": " from django . contrib import admin from models import ErrorReport class ErrorReportAdmin ( admin . ModelAdmin ) : search_fields = ( '' , '' , '' , '' ) date_hierarchy = '' list_display = ( '' , '' , '' , '' , '' , ", "answer": "'' )"}, {"prompt": " import platform import re from awscli . compat import urlopen , URLError from awscli . customizations . codedeploy . systems import System , Ubuntu , Windows , RHEL from socket import timeout MAX_INSTANCE_NAME_LENGTH = MAX_TAGS_PER_INSTANCE = MAX_TAG_KEY_LENGTH = MAX_TAG_VALUE_LENGTH = INSTANCE_NAME_PATTERN = r'' IAM_USER_ARN_PATTERN = r'' INSTANCE_NAME_ARG = { '' : '' , '' : '' , '' : True , '' : ( '' ) } IAM_USER_ARN_ARG = { '' : '' , '' : '' , '' : False , '' : ( '' ) } def validate_region ( params , parsed_globals ) : if parsed_globals . region : params . region = parsed_globals . region else : params . region = params . session . get_config_variable ( '' ) if not params . region : raise RuntimeError ( '' ) def validate_instance_name ( params ) : if params . instance_name : if not re . match ( INSTANCE_NAME_PATTERN , params . instance_name ) : raise ValueError ( '' ) if params . instance_name . startswith ( '' ) : raise ValueError ( '' ) if len ( params . instance_name ) > MAX_INSTANCE_NAME_LENGTH : raise ValueError ( '' . format ( MAX_INSTANCE_NAME_LENGTH ) ) def validate_tags ( params ) : if params . tags : if len ( params . tags ) > MAX_TAGS_PER_INSTANCE : raise ValueError ( '' . format ( MAX_TAGS_PER_INSTANCE ) ) for tag in params . tags : if len ( tag [ '' ] ) > MAX_TAG_KEY_LENGTH : raise ValueError ( '' . format ( MAX_TAG_KEY_LENGTH ) ) if len ( tag [ '' ] ) > MAX_TAG_KEY_LENGTH : raise ValueError ( '' . format ( MAX_TAG_VALUE_LENGTH ) ) def validate_iam_user_arn ( params ) : if params . iam_user_arn and not re . match ( IAM_USER_ARN_PATTERN , params . iam_user_arn ) : raise ValueError ( '' ) def validate_instance ( params ) : if platform . system ( ) == '' : if '' in platform . linux_distribution ( ) [ ] : params . system = Ubuntu ( params ) if '' in platform . linux_distribution ( ) [ ] : params . system = RHEL ( params ) elif platform . system ( ) == '' : params . system = Windows ( params ) if '' not in params : raise RuntimeError ( System . UNSUPPORTED_SYSTEM_MSG ) try : urlopen ( '' , timeout = ) raise RuntimeError ( '' ) except ( URLError , timeout ) : pass def validate_s3_location ( params , arg_name ) : arg_name = arg_name . replace ( '' , '' ) if arg_name in params : s3_location = getattr ( params , arg_name ) if s3_location : matcher = re . match ( '' , str ( s3_location ) ) if matcher : params . bucket = matcher . group ( ) params . key = matcher . group ( ) else : raise ValueError ( '' ", "answer": "'' . format ("}, {"prompt": " from openstack . identity import identity_service from openstack import resource class Region ( resource . Resource ) : resource_key = '' resources_key = '' base_path = '' service = identity_service . IdentityService ( ) allow_create = True allow_retrieve = True ", "answer": "allow_update = True"}, {"prompt": " \"\"\"\"\"\" import time import codecs from cvs2svn_lib . log import logger DB_OPEN_READ = '' DB_OPEN_WRITE = '' DB_OPEN_NEW = '' SVN_INVALID_REVNUM = - warning_prefix = \"\" error_prefix = \"\" class FatalException ( Exception ) : \"\"\"\"\"\" pass class InternalError ( Exception ) : \"\"\"\"\"\" pass class FatalError ( FatalException ) : \"\"\"\"\"\" def __init__ ( self , msg ) : \"\"\"\"\"\" FatalException . __init__ ( self , '' % ( error_prefix , msg , ) ) class CommandError ( FatalError ) : \"\"\"\"\"\" def __init__ ( self , command , exit_status , error_output = '' ) : self . command = command self . exit_status = exit_status self . error_output = error_output if error_output . rstrip ( ) : FatalError . __init__ ( self , '' '' '' % ( self . command , self . exit_status , self . error_output . rstrip ( ) ) ) else : FatalError . __init__ ( self , '' % ( self . command , self . exit_status ) ) def canonicalize_eol ( text , eol ) : \"\"\"\"\"\" text = text . replace ( '' , '' ) text = text . replace ( '' , '' ) if eol != '' : text = text . replace ( '' , eol ) return text def path_join ( * components ) : \"\"\"\"\"\" return '' . join ( filter ( None , components ) ) def path_split ( path ) : \"\"\"\"\"\" pos = path . rfind ( '' ) if pos == - : return ( '' , path , ) else : return ( path [ : pos ] , path [ pos + : ] , ) class IllegalSVNPathError ( FatalException ) : pass def normalize_svn_path ( path , allow_empty = False ) : \"\"\"\"\"\" norm_path = path_join ( * path . split ( '' ) ) if not allow_empty and not norm_path : raise IllegalSVNPathError ( \"\" ) return norm_path class PathRepeatedException ( Exception ) : def __init__ ( self , path , count ) : self . path = path self . count = count Exception . __init__ ( self , '' % ( self . path , self . count , ) ) class PathsNestedException ( Exception ) : def __init__ ( self , nest , nestlings ) : self . nest = nest self . nestlings = nestlings Exception . __init__ ( self , '' % ( self . nest , '' . join ( self . nestlings ) , ) ) class PathsNotDisjointException ( FatalException ) : \"\"\"\"\"\" def __init__ ( self , problems ) : self . problems = problems Exception . __init__ ( self , '' '' % ( '' . join ( [ str ( problem ) for problem in self . problems ] ) , ) ) def verify_paths_disjoint ( * paths ) : \"\"\"\"\"\" def split ( path ) : if not path : return [ ] else : return path . split ( '' ) def contains ( split_path1 , split_path2 ) : \"\"\"\"\"\" return ( len ( split_path1 ) < len ( split_path2 ) and split_path2 [ : len ( split_path1 ) ] == split_path1 ) paths = [ ( split ( path ) , path ) for path in paths ] paths . sort ( ) problems = [ ] i = while i < len ( paths ) : split_path , path = paths [ i ] ", "answer": "j = i + "}, {"prompt": " \"\"\"\"\"\" from bayeslite . bayesdb import BayesDB from bayeslite . bayesdb import bayesdb_open from bayeslite . bayesdb import IBayesDBTracer from bayeslite . codebook import bayesdb_load_codebook_csv_file from bayeslite . exception import BayesDBException from bayeslite . exception import BQLError from bayeslite . legacy_models import bayesdb_load_legacy_models from bayeslite . metamodel import IBayesDBMetamodel from bayeslite . metamodel import bayesdb_builtin_metamodel from bayeslite . metamodel import bayesdb_deregister_metamodel from bayeslite . metamodel import bayesdb_register_metamodel from bayeslite . parse import BQLParseError from bayeslite . read_csv import bayesdb_read_csv from bayeslite . read_csv import bayesdb_read_csv_file from bayeslite . schema import bayesdb_upgrade_schema from bayeslite . sqlite3_util import sqlite3_quote_name from bayeslite . txn import BayesDBTxnError from bayeslite . version import __version__ def bql_quote_name ( name ) : \"\"\"\"\"\" return sqlite3_quote_name ( name ) __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " from networking_onos . common import utils as onos_utils ADD_INTF_BY_PORT = ADD_INTF_BY_SUBNET = class ONOSRouter ( object ) : \"\"\"\"\"\" def send_router_msg ( self , msg_type , entity_path , entity ) : onos_utils . send_msg ( self . onos_path , self . onos_auth , msg_type , entity_path , entity ) def handle_create_router ( self , router_dict ) : self . send_router_msg ( '' , '' , { '' : router_dict } ) def handle_update_router ( self , router_dict , id ) : url_path = '' + '' + id resource = router_dict . copy ( ) onos_utils . safe_delete_from_dict ( resource , [ '' , '' , '' ] ) ", "answer": "self . send_router_msg ( '' , url_path , { '' : resource } )"}, {"prompt": " from __future__ import division \"\"\"\"\"\" __license__ = \"\"\"\"\"\" __all__ = [ \"\" ] import itertools import logging import socket import sys import time import traceback from uuid import uuid4 import weakref from kazoo . client import KazooClient from kazoo . handlers . gevent import SequentialGeventHandler from kazoo . exceptions import NoNodeException , NodeExistsError from kazoo . recipe . watchers import ChildrenWatch from . common import OffsetType from . exceptions import KafkaException , PartitionOwnedError , ConsumerStoppedException from . handlers import GEventHandler from . simpleconsumer import SimpleConsumer from . utils . compat import range , get_bytes , itervalues , iteritems , get_string try : from . import rdkafka except ImportError : rdkafka = False log = logging . getLogger ( __name__ ) def _catch_thread_exception ( fn ) : \"\"\"\"\"\" def wrapped ( self , * args , ** kwargs ) : try : ret = fn ( self , * args , ** kwargs ) except Exception : self . _worker_exception = sys . exc_info ( ) else : return ret return wrapped class BalancedConsumer ( object ) : \"\"\"\"\"\" def __init__ ( self , topic , cluster , consumer_group , fetch_message_max_bytes = * , num_consumer_fetchers = , auto_commit_enable = False , auto_commit_interval_ms = * , queued_max_messages = , fetch_min_bytes = , fetch_wait_max_ms = , offsets_channel_backoff_ms = , offsets_commit_max_retries = , auto_offset_reset = OffsetType . EARLIEST , consumer_timeout_ms = - , rebalance_max_retries = , rebalance_backoff_ms = * , zookeeper_connection_timeout_ms = * , zookeeper_connect = '' , zookeeper = None , auto_start = True , reset_offset_on_start = False , post_rebalance_callback = None , use_rdkafka = False , compacted_topic = False ) : \"\"\"\"\"\" self . _cluster = cluster if not isinstance ( consumer_group , bytes ) : raise TypeError ( \"\" ) self . _consumer_group = consumer_group self . _topic = topic self . _auto_commit_enable = auto_commit_enable self . _auto_commit_interval_ms = auto_commit_interval_ms self . _fetch_message_max_bytes = fetch_message_max_bytes self . _fetch_min_bytes = fetch_min_bytes self . _rebalance_max_retries = rebalance_max_retries self . _num_consumer_fetchers = num_consumer_fetchers self . _queued_max_messages = queued_max_messages self . _fetch_wait_max_ms = fetch_wait_max_ms self . _rebalance_backoff_ms = rebalance_backoff_ms self . _consumer_timeout_ms = consumer_timeout_ms self . _offsets_channel_backoff_ms = offsets_channel_backoff_ms self . _offsets_commit_max_retries = offsets_commit_max_retries self . _auto_offset_reset = auto_offset_reset self . _zookeeper_connect = zookeeper_connect self . _zookeeper_connection_timeout_ms = zookeeper_connection_timeout_ms self . _reset_offset_on_start = reset_offset_on_start self . _post_rebalance_callback = post_rebalance_callback self . _generation_id = - self . _running = False self . _worker_exception = None self . _worker_trace_logged = False self . _is_compacted_topic = compacted_topic if not rdkafka and use_rdkafka : raise ImportError ( \"\" ) if isinstance ( self . _cluster . handler , GEventHandler ) and use_rdkafka : raise ImportError ( \"\" ) self . _use_rdkafka = rdkafka and use_rdkafka self . _rebalancing_lock = cluster . handler . Lock ( ) self . _consumer = None self . _consumer_id = get_bytes ( \"\" . format ( hostname = socket . gethostname ( ) , uuid = uuid4 ( ) ) ) self . _setting_watches = True self . _topic_path = '' . format ( group = self . _consumer_group , topic = self . _topic . name ) self . _consumer_id_path = '' . format ( group = self . _consumer_group ) self . _zookeeper = None self . _owns_zookeeper = zookeeper is None if zookeeper is not None : self . _zookeeper = zookeeper if auto_start is True : self . start ( ) def __del__ ( self ) : log . debug ( \"\" . format ( self ) ) if self . _running : self . stop ( ) def __repr__ ( self ) : return \"\" . format ( module = self . __class__ . __module__ , name = self . __class__ . __name__ , id_ = hex ( id ( self ) ) , group = self . _consumer_group ) def _raise_worker_exceptions ( self ) : \"\"\"\"\"\" if self . _worker_exception is not None : _ , ex , tb = self . _worker_exception if not self . _worker_trace_logged : self . _worker_trace_logged = True log . error ( \"\" , \"\" . join ( traceback . format_tb ( tb ) ) ) raise ex @ property def topic ( self ) : \"\"\"\"\"\" return self . _topic @ property def partitions ( self ) : \"\"\"\"\"\" return self . _consumer . partitions if self . _consumer else dict ( ) @ property def _partitions ( self ) : \"\"\"\"\"\" return set ( [ ] if self . partitions is None else itervalues ( self . partitions ) ) @ property def held_offsets ( self ) : \"\"\"\"\"\" if not self . _consumer : return None return self . _consumer . held_offsets def start ( self ) : \"\"\"\"\"\" try : if self . _zookeeper is None : self . _setup_zookeeper ( self . _zookeeper_connect , self . _zookeeper_connection_timeout_ms ) self . _zookeeper . ensure_path ( self . _topic_path ) self . _add_self ( ) self . _running = True self . _set_watches ( ) self . _rebalance ( ) except Exception : log . exception ( \"\" ) self . stop ( ) def stop ( self ) : \"\"\"\"\"\" log . debug ( \"\" . format ( self ) ) with self . _rebalancing_lock : self . _running = False if self . _consumer is not None : self . _consumer . stop ( ) if self . _owns_zookeeper : self . _zookeeper . stop ( ) else : self . _remove_partitions ( self . _get_held_partitions ( ) ) try : self . _zookeeper . delete ( self . _path_self ) except NoNodeException : pass def _setup_zookeeper ( self , zookeeper_connect , timeout ) : \"\"\"\"\"\" kazoo_kwargs = { '' : timeout / } if isinstance ( self . _cluster . handler , GEventHandler ) : kazoo_kwargs [ '' ] = SequentialGeventHandler ( ) self . _zookeeper = KazooClient ( zookeeper_connect , ** kazoo_kwargs ) self . _zookeeper . start ( ) def _setup_internal_consumer ( self , partitions = None , start = True ) : \"\"\"\"\"\" if partitions is None : partitions = [ ] if partitions != self . _partitions : cns = self . _get_internal_consumer ( partitions = list ( partitions ) , start = start ) if self . _post_rebalance_callback is not None : old_offsets = ( self . _consumer . held_offsets if self . _consumer else dict ( ) ) new_offsets = cns . held_offsets try : reset_offsets = self . _post_rebalance_callback ( self , old_offsets , new_offsets ) except Exception : log . exception ( \"\" ) self . _worker_exception = sys . exc_info ( ) return False if reset_offsets : cns . reset_offsets ( partition_offsets = [ ( cns . partitions [ id_ ] , offset ) for ( id_ , offset ) in iteritems ( reset_offsets ) ] ) self . _consumer = cns return True def _get_internal_consumer ( self , partitions = None , start = True ) : \"\"\"\"\"\" if partitions is None : partitions = [ ] reset_offset_on_start = self . _reset_offset_on_start if self . _consumer is not None : self . _consumer . stop ( ) reset_offset_on_start = False Cls = ( rdkafka . RdKafkaSimpleConsumer if self . _use_rdkafka else SimpleConsumer ) return Cls ( self . _topic , self . _cluster , consumer_group = self . _consumer_group , partitions = partitions , auto_commit_enable = self . _auto_commit_enable , auto_commit_interval_ms = self . _auto_commit_interval_ms , fetch_message_max_bytes = self . _fetch_message_max_bytes , fetch_min_bytes = self . _fetch_min_bytes , num_consumer_fetchers = self . _num_consumer_fetchers , queued_max_messages = self . _queued_max_messages , fetch_wait_max_ms = self . _fetch_wait_max_ms , consumer_timeout_ms = self . _consumer_timeout_ms , offsets_channel_backoff_ms = self . _offsets_channel_backoff_ms , offsets_commit_max_retries = self . _offsets_commit_max_retries , auto_offset_reset = self . _auto_offset_reset , reset_offset_on_start = reset_offset_on_start , auto_start = start , compacted_topic = self . _is_compacted_topic , generation_id = self . _generation_id , consumer_id = self . _consumer_id ) def _decide_partitions ( self , participants , consumer_id = None ) : \"\"\"\"\"\" p_to_str = lambda p : '' . join ( [ str ( p . topic . name ) , str ( p . leader . id ) , str ( p . id ) ] ) all_parts = self . _topic . partitions . values ( ) all_parts = sorted ( all_parts , key = p_to_str ) participants = sorted ( participants ) idx = participants . index ( consumer_id or self . _consumer_id ) parts_per_consumer = len ( all_parts ) // len ( participants ) ", "answer": "remainder_ppc = len ( all_parts ) % len ( participants )"}, {"prompt": " import os . path import platform from nose2 . compat import unittest from nose2 . tests . _common import FunctionalTestCase class TestCoverage ( FunctionalTestCase ) : @ unittest . skipIf ( platform . python_version_tuple ( ) [ : ] == ( '' , '' ) , '' ) def test_run ( self ) : proc = self . runIn ( '' , '' , '' , '' ", "answer": ")"}, {"prompt": " \"\"\"\"\"\" __all__ = [ \"\" ] from traits . api import Instance from openmdao . main . variable import Variable , gui_excludes class VarTree ( Variable ) : \"\"\"\"\"\" def __init__ ( self , default_value , allow_none = True , ** metadata ) : from openmdao . main . vartree import VariableTree if isinstance ( default_value , VariableTree ) : klass = default_value . __class__ if '' in metadata : default_value . _iotype = metadata [ '' ] else : metadata [ '' ] = default_value . iotype else : raise TypeError ( '' '' ) metadata . setdefault ( '' , '' ) self . _allow_none = allow_none self . klass = klass self . _instance = Instance ( klass = klass , allow_none = False , factory = None , args = None , kw = None , ** metadata ) self . _instance . default_value = default_value super ( VarTree , self ) . __init__ ( default_value , ** metadata ) def validate ( self , obj , name , value ) : \"\"\"\"\"\" if value is None : if self . _allow_none : return value self . validate_failed ( obj , name , value ) try : value = self . _instance . validate ( obj , name , value ) except Exception : obj . raise_exception ( '' % ( name , self . _instance . klass . __module__ , self . _instance . klass . __name__ , type ( value ) ) , TypeError ) return value def post_setattr ( self , obj , name , value ) : \"\"\"\"\"\" if value . parent is not obj : value . parent = obj value . name = name value . _iotype = self . iotype def get_attribute ( self , name , value , trait , meta ) : \"\"\"\"\"\" io_attr = { } io_attr [ '' ] = name io_attr [ '' ] = trait . trait_type . klass . __name__ ", "answer": "io_attr [ '' ] = ''"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import json import uuid from django . core . urlresolvers import reverse from models import CrowdModelSpecification class CrowdInterface ( object ) : def __init__ ( self , crowd_name ) : self . crowd_name = crowd_name @ staticmethod def validate_configuration ( configuration ) : \"\"\"\"\"\" return True @ staticmethod def create_task ( configuration , content ) : \"\"\"\"\"\" return uuid . uuid4 ( ) @ staticmethod def task_pre_save ( task_object ) : \"\"\"\"\"\" pass @ staticmethod def group_pre_save ( group_object ) : \"\"\"\"\"\" pass @ staticmethod def delete_tasks ( task_objects ) : \"\"\"\"\"\" pass @ staticmethod def get_assignment_context ( request ) : \"\"\"\"\"\" return { '' : request . GET . get ( '' , None ) , '' : request . GET . get ( '' , None ) , '' : request . GET . get ( '' , True ) } @ staticmethod def get_response_context ( request ) : \"\"\"\"\"\" return { '' : request . POST . get ( '' , None ) , '' : request . POST . get ( '' , None ) , '' : request . POST . get ( '' , None ) , '' : request . POST . get ( '' , None ) } @ staticmethod def worker_pre_save ( worker_object ) : \"\"\"\"\"\" pass ", "answer": "@ staticmethod"}, {"prompt": " import sys , types from pprint import pformat from twisted . trial import unittest from twisted . news import database from twisted . internet import reactor MESSAGE_ID = \"\" POST_STRING = \"\"\"\"\"\" % ( MESSAGE_ID ) class NewsTestCase ( unittest . TestCase ) : def setUp ( self ) : self . backend = database . NewsShelf ( None , '' ) self . backend . addGroup ( '' , '' ) self . backend . postRequest ( POST_STRING . replace ( '' , '' ) ) def testArticleExists ( self ) : d = self . backend . articleExistsRequest ( MESSAGE_ID ) d . addCallback ( self . failUnless ) return d def testArticleRequest ( self ) : d = self . backend . articleRequest ( None , None , MESSAGE_ID ) def cbArticle ( result ) : self . failUnless ( isinstance ( result , tuple ) , '' + str ( result ) ) self . assertEquals ( len ( result ) , , '' + str ( result ) ) self . assertEquals ( result [ ] , MESSAGE_ID , \"\" % ( MESSAGE_ID , result [ ] ) ) body = result [ ] . read ( ) self . failIfEqual ( body . find ( '' ) , - , \"\" ) return result ", "answer": "d . addCallback ( cbArticle )"}, {"prompt": " from future . builtins import str from future . utils import python_2_unicode_compatible from django . db import models from django . utils . translation import ugettext_lazy as _ from fluent_contents . extensions import PluginImageField , PluginUrlField from fluent_contents . models . db import ContentItem from . import appsettings @ python_2_unicode_compatible class PictureItem ( ContentItem ) : \"\"\"\"\"\" ALIGN_LEFT = '' ALIGN_CENTER = '' ALIGN_RIGHT = '' ALIGN_CHOICES = ( ( ALIGN_LEFT , _ ( \"\" ) ) , ( ALIGN_CENTER , _ ( \"\" ) ) , ( ALIGN_RIGHT , _ ( \"\" ) ) , ) image = PluginImageField ( _ ( \"\" ) , upload_to = appsettings . FLUENT_PICTURE_UPLOAD_TO ) caption = models . TextField ( _ ( \"\" ) , blank = True ) align = models . CharField ( _ ( \"\" ) , max_length = , choices = ALIGN_CHOICES , blank = True ) url = PluginUrlField ( _ ( \"\" ) , blank = True ) ", "answer": "in_new_window = models . BooleanField ( _ ( \"\" ) , default = False , blank = True )"}, {"prompt": " import numpy import collada from meshtool . filters . panda_filters import pdae_utils from meshtool . args import FileArgument , FilterArgument from meshtool . filters . base_filters import SimplifyFilter , FilterException def add_back_pm ( mesh , pm_file , percent ) : refinements = pdae_utils . readPDAE ( pm_file ) num_to_load = len ( refinements ) * ( percent / ) num_to_load = min ( num_to_load , len ( refinements ) ) num_to_load = int ( round ( num_to_load ) ) if num_to_load <= : return mesh assert ( len ( mesh . geometries ) == ) geom = mesh . geometries [ ] assert ( len ( geom . primitives ) == ) triset = geom . primitives [ ] assert ( isinstance ( triset , collada . triangleset . TriangleSet ) ) indices2stack = [ triset . vertex_index . reshape ( - , ) , triset . normal_index . reshape ( - , ) , triset . texcoord_indexset [ ] . reshape ( - , ) ] stacked_indices = numpy . hstack ( indices2stack ) . flatten ( ) . reshape ( ( - , ) ) unique_stacked_indices , index_map , inverse_map = numpy . unique ( stacked_indices . view ( [ ( '' , stacked_indices . dtype ) ] * stacked_indices . shape [ ] ) , return_index = True , return_inverse = True ) ", "answer": "unique_stacked_indices = unique_stacked_indices . view ( stacked_indices . dtype ) . reshape ( - , stacked_indices . shape [ ] )"}, {"prompt": " from sellmo . core . apps import SellmoAppConfig ", "answer": "class DefaultConfig ( SellmoAppConfig ) :"}, {"prompt": " import sys import traceback from types import ModuleType from importlib import import_module from django . apps import apps from django . conf import settings from django . utils import six from django . utils . functional import cached_property from . exceptions import RegistryError allowed = None def should_fix_type ( typ ) : global allowed if allowed is None : allowed = [ '' ] for app in apps . get_app_configs ( ) : allowed . append ( app . name ) return any ( typ . __module__ . startswith ( name ) for name in allowed ) class ModuleAttribute ( object ) : def __init__ ( self , module_name , name ) : self . module_name = module_name self . name = name self . _accessed = False self . _access_traceback = None self . _injection_handlers = [ ] def inject ( self , handler ) : self . _injection_handlers . insert ( , handler ) @ property def is_accesed ( self ) : return self . _accessed @ property def is_assigned ( self ) : return hasattr ( self , '' ) def access ( self ) : if not self . _accessed : if getattr ( settings , '' , False ) : self . _access_traceback = traceback . extract_stack ( ) value = self . _value for handler in self . _injection_handlers : try : value = handler ( value ) except Exception as ex : raise RegistryError , ex , sys . exc_info ( ) [ ] if isinstance ( value , type ) and should_fix_type ( value ) : value . __module__ = self . module_name self . _accessed = True self . _value = value return self . _value def assign ( self , value ) : if self . is_accesed : filename , line , name , text = '' , '' , '' , '' if self . _access_traceback is not None : filename , line , name , text = self . _access_traceback [ - ] raise RegistryError ( \"\" \"\" \"\" % ( self . name , filename , line , name , text ) ) self . _value = value class BaseModule ( ModuleType ) : _imports = None _imported_attrs = None _modules = { } def __new__ ( cls , fullname ) : if fullname in cls . _modules : raise Exception ( ) module = super ( BaseModule , cls ) . __new__ ( cls , fullname ) cls . _modules [ fullname ] = module return module def __init__ ( self , fullname ) : super ( BaseModule , self ) . __init__ ( fullname ) self . _attrs = { } def _import ( self ) : if self . _imported_attrs is None : self . _imported_attrs = { } if self . _imports : module = import_module ( self . _imports ) self . _imported_attrs . update ( ** { name : value for name , value in six . iteritems ( vars ( module ) ) if not name . startswith ( '' ) } ", "answer": ")"}, {"prompt": " from . import alexa_io '''''' ResponseBuilder = alexa_io . ResponseBuilder alexa = alexa_io . VoiceHandler ( ) ", "answer": "Request = alexa_io . Request "}, {"prompt": " \"\"\"\"\"\" from . common import Remote from . . compat import IS_PYTHON3 __all__ = ( '' ) if IS_PYTHON3 : basestring = str class Buffer ( Remote ) : \"\"\"\"\"\" _api_prefix = \"\" def __len__ ( self ) : \"\"\"\"\"\" return self . request ( '' ) def __getitem__ ( self , idx ) : \"\"\"\"\"\" if not isinstance ( idx , slice ) : return self . _session . request ( '' , self , idx ) include_end = False start = idx . start end = idx . stop if start is None : start = if end is None : end = - include_end = True return self . _session . request ( '' , self , start , end , True , include_end ) def __setitem__ ( self , idx , lines ) : \"\"\"\"\"\" if not isinstance ( idx , slice ) : if lines is None : return self . _session . request ( '' , self , idx ) else : return self . _session . request ( '' , self , idx , lines ) if lines is None : lines = [ ] include_end = False start = idx . start end = idx . stop if start is None : start = if end is None : end = - include_end = True return self . _session . request ( '' , self , start , end , True , include_end , lines ) def __iter__ ( self ) : \"\"\"\"\"\" lines = self [ : ] for line in lines : yield line def __delitem__ ( self , idx ) : \"\"\"\"\"\" if not isinstance ( idx , slice ) : self . __setitem__ ( idx , None ) else : self . __setitem__ ( idx , [ ] ) def get_line_slice ( self , start , stop , start_incl , end_incl ) : \"\"\"\"\"\" return self . _session . request ( '' , self , start , stop , start_incl , end_incl ) def set_line_slice ( self , start , stop , start_incl , end_incl , lines ) : \"\"\"\"\"\" return self . _session . request ( '' , self , start , stop , start_incl , end_incl , lines ) def append ( self , lines , index = - ) : \"\"\"\"\"\" if isinstance ( lines , basestring ) : lines = [ lines ] return self . _session . request ( '' , self , index , lines ) def mark ( self , name ) : \"\"\"\"\"\" return self . request ( '' , name ) def range ( self , start , end ) : \"\"\"\"\"\" return Range ( self , start , end ) def add_highlight ( self , hl_group , line , col_start = , col_end = - , src_id = - , async = None ) : \"\"\"\"\"\" if async is None : async = ( src_id != ) return self . request ( '' , src_id , hl_group , line , col_start , col_end , async = async ) def clear_highlight ( self , src_id , line_start = , line_end = - , async = True ) : \"\"\"\"\"\" self . request ( '' , src_id , line_start , line_end , async = async ) @ property def name ( self ) : \"\"\"\"\"\" return self . request ( '' ) @ name . setter def name ( self , value ) : \"\"\"\"\"\" ", "answer": "return self . request ( '' , value )"}, {"prompt": " from __future__ import unicode_literals from collections import OrderedDict import sys from django . apps import apps as django_apps from django . conf import settings from django . core . exceptions import ImproperlyConfigured PY3 = sys . version > \"\" subscriber_request_callback = getattr ( settings , \"\" , ( lambda request : request . user ) ) INVOICE_FROM_EMAIL = getattr ( settings , \"\" , \"\" ) PAYMENTS_PLANS = getattr ( settings , \"\" , { } ) PLAN_HIERARCHY = getattr ( settings , \"\" , { } ) ", "answer": "PAYMENT_PLANS = OrderedDict ( sorted ( PAYMENTS_PLANS . items ( ) , key = lambda t : t [ ] [ '' ] ) )"}, {"prompt": " \"\"\"\"\"\" import base64 import random from twisted . python import log from twisted . web . error import Error as WebError from opennsa import constants as cnt , config from opennsa . backends . common import genericbackend from opennsa . protocols . shared import httpclient NCS_TIMEOUT = NO_OUT_OF_SYNC_CHECK = '' ETHERNET_VPN_PAYLOAD_BASE = \"\"\"\"\"\" ETHERNET_VLAN_VPN_PAYLOAD_BASE = \"\"\"\"\"\" ETHERNET_VLAN_REWRITE_VPN_PAYLOAD_BASE = \"\"\"\"\"\" LOG_SYSTEM = '' class NCSVPNTarget ( object ) : def __init__ ( self , router , interface , vlan = None ) : self . router = router self . interface = interface self . vlan = vlan def __str__ ( self ) : if self . vlan : return '' % ( self . router , self . interface , self . vlan ) else : return '' % ( self . router , self . interface ) def createVPNPayload ( service_name , source_target , dest_target ) : intps = { '' : service_name , '' : service_name , '' : source_target . router , '' : source_target . interface , '' : dest_target . router , '' : dest_target . interface } if source_target . vlan and dest_target . vlan : if source_target . vlan == dest_target . vlan : intps [ '' ] = source_target . vlan payload = ETHERNET_VLAN_VPN_PAYLOAD_BASE % intps else : intps [ '' ] = source_target . vlan intps [ '' ] = dest_target . vlan payload = ETHERNET_VLAN_REWRITE_VPN_PAYLOAD_BASE % intps else : payload = ETHERNET_VPN_PAYLOAD_BASE % intps return payload def _extractErrorMessage ( failure ) : if isinstance ( failure . value , WebError ) : return failure . value . response else : return failure . getErrorMessage ( ) class NCSVPNConnectionManager : def __init__ ( self , ncs_services_url , user , password , port_map , log_system ) : self . ncs_services_url = ncs_services_url self . user = user self . password = password self . port_map = port_map self . log_system = log_system def getResource ( self , port , label_type , label_value ) : ", "answer": "assert label_type in ( None , cnt . ETHERNET_VLAN ) , ''"}, {"prompt": " from guppy . heapy . Remote import on ", "answer": "on ( ) "}, {"prompt": " \"\"\"\"\"\" import unittest , sys , os . path this_dir = os . path . dirname ( __file__ ) ", "answer": "if this_dir not in sys . path :"}, {"prompt": " from operator import getitem from pyasn1 import error tagClassUniversal = tagClassApplication = tagClassContext = tagClassPrivate = tagFormatSimple = tagFormatConstructed = tagCategoryImplicit = tagCategoryExplicit = tagCategoryUntagged = class Tag : def __init__ ( self , tagClass , tagFormat , tagId ) : if tagId < : raise error . PyAsn1Error ( '' % ( tagId , ) ) self . __tag = ( tagClass , tagFormat , tagId ) self . uniq = ( tagClass , tagId ) self . __hashedUniqTag = hash ( self . uniq ) def __str__ ( self ) : return '' % self . __tag def __repr__ ( self ) : return '' % ( ( self . __class__ . __name__ , ) + self . __tag ) def __eq__ ( self , other ) : return self . uniq == other . uniq def __ne__ ( self , other ) : return self . uniq != other . uniq def __lt__ ( self , other ) : return self . uniq < other . uniq def __le__ ( self , other ) : return self . uniq <= other . uniq def __gt__ ( self , other ) : return self . uniq > other . uniq def __ge__ ( self , other ) : return self . uniq >= other . uniq def __hash__ ( self ) : return self . __hashedUniqTag def __getitem__ ( self , idx ) : return self . __tag [ idx ] def __and__ ( self , otherTag ) : ( tagClass , tagFormat , tagId ) = otherTag return self . __class__ ( self . __tag & tagClass , self . __tag & tagFormat , self . __tag & tagId ) def __or__ ( self , otherTag ) : ( tagClass , tagFormat , tagId ) = otherTag return self . __class__ ( self . __tag [ ] | tagClass , self . __tag [ ] | tagFormat , self . __tag [ ] | tagId ) def asTuple ( self ) : return self . __tag class TagSet : def __init__ ( self , baseTag = ( ) , * superTags ) : self . __baseTag = baseTag self . __superTags = superTags self . __hashedSuperTags = hash ( superTags ) _uniq = ( ) for t in superTags : _uniq = _uniq + t . uniq self . uniq = _uniq self . __lenOfSuperTags = len ( superTags ) def __str__ ( self ) : return self . __superTags and '' . join ( [ str ( x ) for x in self . __superTags ] ) or '' def __repr__ ( self ) : return '' % ( self . __class__ . __name__ , '' + '' . join ( [ repr ( x ) for x in self . __superTags ] ) ) def __add__ ( self , superTag ) : return self . __class__ ( self . __baseTag , * self . __superTags + ( superTag , ) ) def __radd__ ( self , superTag ) : return self . __class__ ( self . __baseTag , * ( superTag , ) + self . __superTags ) def tagExplicitly ( self , superTag ) : tagClass , tagFormat , tagId = superTag if tagClass == tagClassUniversal : raise error . PyAsn1Error ( '' ) if tagFormat != tagFormatConstructed : superTag = Tag ( tagClass , tagFormatConstructed , tagId ) return self + superTag def tagImplicitly ( self , superTag ) : tagClass , tagFormat , tagId = superTag if self . __superTags : superTag = Tag ( tagClass , self . __superTags [ - ] [ ] , tagId ) return self [ : - ] + superTag def getBaseTag ( self ) : return self . __baseTag def __getitem__ ( self , idx ) : if isinstance ( idx , slice ) : return self . __class__ ( self . __baseTag , * getitem ( self . __superTags , idx ) ) return self . __superTags [ idx ] def __eq__ ( self , other ) : return self . uniq == other . uniq def __ne__ ( self , other ) : return self . uniq != other . uniq def __lt__ ( self , other ) : return self . uniq < other . uniq def __le__ ( self , other ) : return self . uniq <= other . uniq def __gt__ ( self , other ) : return self . uniq > other . uniq def __ge__ ( self , other ) : return self . uniq >= other . uniq def __hash__ ( self ) : return self . __hashedSuperTags def __len__ ( self ) : return self . __lenOfSuperTags def isSuperTagSetOf ( self , tagSet ) : if len ( tagSet ) < self . __lenOfSuperTags : return idx = self . __lenOfSuperTags - while idx >= : if self . __superTags [ idx ] != tagSet [ idx ] : ", "answer": "return"}, {"prompt": " \"\"\"\"\"\" __all__ = [ \"\" , \"\" , \"\" , \"\" ] from pikos . _internal import _lsprof_rt as _lsprof def run ( statement , filename = None , sort = - ) : \"\"\"\"\"\" prof = Profile ( ) result = None try : try : prof = prof . run ( statement ) except SystemExit : pass finally : if filename is not None : prof . dump_stats ( filename ) else : result = prof . print_stats ( sort ) return result def runctx ( statement , globals , locals , filename = None , sort = - ) : \"\"\"\"\"\" prof = Profile ( ) result = None try : try : prof = prof . runctx ( statement , globals , locals ) except SystemExit : pass finally : if filename is not None : prof . dump_stats ( filename ) else : result = prof . print_stats ( sort ) return result def help ( ) : print \"\" print \"\" class Profile ( _lsprof . Profiler ) : \"\"\"\"\"\" def print_stats ( self , sort = - ) : import pstats pstats . Stats ( self ) . strip_dirs ( ) . sort_stats ( sort ) . print_stats ( ) def dump_stats ( self , file ) : import marshal f = open ( file , '' ) self . create_stats ( ) marshal . dump ( self . stats , f ) f . close ( ) def create_stats ( self ) : self . disable ( ) self . snapshot_stats ( ) def snapshot_stats ( self ) : entries = self . getstats ( ) self . stats = { } callersdicts = { } ", "answer": "for entry in entries :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Ship ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from django . contrib . admin . decorators import register from django . contrib . admin . filters import ( AllValuesFieldListFilter , BooleanFieldListFilter , ChoicesFieldListFilter , DateFieldListFilter , FieldListFilter , ListFilter , RelatedFieldListFilter , ", "answer": "RelatedOnlyFieldListFilter , SimpleListFilter ,"}, {"prompt": " from __future__ import unicode_literals from django . test import SimpleTestCase from localflavor . jp . forms import JPPostalCodeField , JPPrefectureCodeSelect , JPPrefectureSelect class JPLocalFlavorTests ( SimpleTestCase ) : def test_JPPrefectureSelect ( self ) : f = JPPrefectureSelect ( ) out = '''''' self . assertHTMLEqual ( f . render ( '' , '' ) , out ) def test_JPPrefectureCodeSelect ( self ) : f = JPPrefectureCodeSelect ( ) out = '''''' ", "answer": "self . assertHTMLEqual ( f . render ( '' , '' ) , out )"}, {"prompt": " from __future__ import absolute_import ", "answer": "from . hedwig import start_consumer "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) ", "answer": "result . template = \"\""}, {"prompt": " \"\"\"\"\"\" import posixpath import re from mrjob . util import file_ext from . ids import _add_implied_task_id from . ids import _to_job_id from . log4j import _parse_hadoop_log4j_records from . wrap import _cat_log from . wrap import _ls_logs _JAVA_TRACEBACK_RE = re . compile ( r'' , re . MULTILINE ) _OPENING_FOR_READING_RE = re . compile ( r\"\" ) _PRE_YARN_TASK_SYSLOG_PATH_RE = re . compile ( r'' r'' r'' r'' r'' ) _TASK_STDERR_IGNORE_RE = re . compile ( r'' ) _YARN_INPUT_SPLIT_RE = re . compile ( r'' r'' ) _YARN_TASK_SYSLOG_PATH_RE = re . compile ( r'' r'' r'' r'' ) def _ls_task_syslogs ( fs , log_dir_stream , application_id = None , job_id = None ) : \"\"\"\"\"\" return _ls_logs ( fs , log_dir_stream , _match_task_syslog_path , application_id = application_id , job_id = job_id ) def _match_task_syslog_path ( path , application_id = None , job_id = None ) : \"\"\"\"\"\" m = _PRE_YARN_TASK_SYSLOG_PATH_RE . match ( path ) if m : if job_id and job_id != _to_job_id ( m . group ( '' ) ) : return None return dict ( attempt_id = m . group ( '' ) ) m = _YARN_TASK_SYSLOG_PATH_RE . match ( path ) if m : if application_id and application_id != m . group ( '' ) : return None return dict ( application_id = m . group ( '' ) , container_id = m . group ( '' ) ) return None def _interpret_task_logs ( fs , matches , partial = True , stderr_callback = None ) : \"\"\"\"\"\" result = { } for match in matches : syslog_path = match [ '' ] error = _parse_task_syslog ( _cat_log ( fs , syslog_path ) ) if not error . get ( '' ) : continue error [ '' ] [ '' ] = syslog_path for id_key in '' , '' , '' : if id_key in match : error [ id_key ] = match [ id_key ] _add_implied_task_id ( error ) stderr_path = _syslog_to_stderr_path ( syslog_path ) if fs . exists ( stderr_path ) : if stderr_callback : stderr_callback ( stderr_path ) task_error = _parse_task_stderr ( _cat_log ( fs , stderr_path ) ) if task_error : task_error [ '' ] = stderr_path error [ '' ] = task_error result . setdefault ( '' , [ ] ) result [ '' ] . append ( error ) if partial : result [ '' ] = True break return result def _syslog_to_stderr_path ( path ) : \"\"\"\"\"\" stem , filename = posixpath . split ( path ) return posixpath . join ( stem , '' + file_ext ( filename ) ) def _parse_task_syslog ( lines ) : \"\"\"\"\"\" result = { } for record in _parse_hadoop_log4j_records ( lines ) : message = record [ '' ] m = _OPENING_FOR_READING_RE . match ( message ) if m : result [ '' ] = dict ( path = m . group ( '' ) ) continue m = _YARN_INPUT_SPLIT_RE . match ( message ) if m : result [ '' ] = dict ( path = m . group ( '' ) , start_line = int ( m . group ( '' ) ) , ", "answer": "num_lines = int ( m . group ( '' ) ) )"}, {"prompt": " import sys import optparse from acmd import tool from acmd import OK from acmd import deploy_bash_completion parser = optparse . OptionParser ( \"\" ) @ tool ( '' ) class InstallBashCompletionTool ( object ) : \"\"\"\"\"\" def execute ( self , server , argv ) : ", "answer": "install_path = deploy_bash_completion ( )"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from globals import * import life as lfe import language import graphics import numbers import timers import items import alife import logging import random def get_puncture_value ( item , target_structure , target_structure_name = '' , debug = True ) : _damage = ( ( ( item [ '' ] / float ( item [ '' ] ) ) * item [ '' ] [ '' ] ) * ( target_structure [ '' ] / float ( target_structure [ '' ] ) ) ) * ( item [ '' ] / float ( numbers . get_surface_area ( target_structure ) ) ) if debug : logging . debug ( '' % ( item [ '' ] , target_structure_name ) ) logging . debug ( '' % ( item [ '' ] , item [ '' ] , item [ '' ] ) ) logging . debug ( '' % ( target_structure_name , target_structure [ '' ] , target_structure [ '' ] ) ) logging . debug ( '' % ( item [ '' ] , item [ '' ] [ '' ] ) ) logging . debug ( '' % ( item [ '' ] , item [ '' ] , target_structure_name , target_structure [ '' ] ) ) logging . debug ( '' % ( item [ '' ] , _damage , target_structure_name ) ) return _damage def own_language ( life , message ) : ", "answer": "_mentioned_name = False"}, {"prompt": " import re from routersploit import ( exploits , sanitize_url , ", "answer": "print_error ,"}, {"prompt": " from . import contexts from . import util from . models import Venue from . views import geo_name from bs4 import BeautifulSoup from flask import request , jsonify , redirect , url_for , Blueprint , current_app , render_template import datetime import mf2py import mf2util import requests import sys import urllib services = Blueprint ( '' , __name__ ) USER_AGENT = '' @ services . route ( '' ) def fetch_profile ( ) : url = request . args . get ( '' ) if not url : return \"\"\"\"\"\" try : name = None image = None d = mf2py . Parser ( url = url ) . to_dict ( ) relmes = d [ '' ] . get ( '' , [ ] ) hfeed = next ( ( item for item in d [ '' ] if '' in item [ '' ] ) , None ) if hfeed : authors = hfeed . get ( '' , { } ) . get ( '' ) images = hfeed . get ( '' , { } ) . get ( '' ) if authors : if isinstance ( authors [ ] , dict ) : name = authors [ ] . get ( '' , { } ) . get ( '' ) image = authors [ ] . get ( '' , { } ) . get ( '' ) else : name = authors [ ] if images and not image : image = images [ ] for item in d [ '' ] : if '' in item . get ( '' , [ ] ) : if not name : name = item . get ( '' , { } ) . get ( '' ) if not image : image = item . get ( '' , { } ) . get ( '' ) return jsonify ( { '' : name , ", "answer": "'' : image ,"}, {"prompt": " from __future__ import unicode_literals from django . test import TestCase from django . core . exceptions import ImproperlyConfigured from django . core . exceptions import ValidationError from djangobmf . workflow import State from djangobmf . workflow import Transition from djangobmf . workflow import Workflow from django . contrib . auth . models import User class ClassTests ( TestCase ) : def test_state ( self ) : obj = State ( b'' ) self . assertEqual ( obj . name , b\"\" ) self . assertEqual ( str ( obj ) , \"\" ) self . assertEqual ( repr ( obj ) , \"\" ) def test_transition ( self ) : obj = Transition ( b'' , '' , '' ) self . assertEqual ( obj . name , b\"\" ) self . assertEqual ( str ( obj ) , \"\" ) self . assertEqual ( repr ( obj ) , \"\" ) self . assertEqual ( obj . sources , [ \"\" , ] ) obj = Transition ( '' , object , '' ) self . assertEqual ( obj . sources , [ object , ] ) obj = Transition ( '' , [ '' , '' ] , '' ) self . assertEqual ( obj . sources , [ \"\" , \"\" , ] ) self . assertEqual ( obj . affected_states ( ) , [ \"\" , \"\" , \"\" ] ) def test_validation ( self ) : msg = \"\" with self . assertRaises ( ImproperlyConfigured , msg = msg ) : class TestWF ( Workflow ) : class Transitions : pass msg = \"\" with self . assertRaises ( ImproperlyConfigured , msg = msg ) : class TestWF ( Workflow ) : class States : pass msg = \"\" with self . assertRaises ( ImproperlyConfigured , msg = msg ) : class TestWF ( Workflow ) : class States : pass class Transitions : pass msg = \"\" with self . assertRaises ( ImproperlyConfigured , msg = msg ) : class TestWF ( Workflow ) : class States : test = State ( '' , default = False ) class Transitions : pass msg = \"\" with self . assertRaises ( ImproperlyConfigured , msg = msg ) : class TestWF ( Workflow ) : class States : test1 = State ( '' , default = True ) test2 = State ( '' , default = True ) class Transitions : pass msg = \"\" with self . assertRaises ( ImproperlyConfigured , msg = msg ) : class TestWF ( Workflow ) : class States : test1 = State ( '' , default = True ) test2 = State ( '' ) class Transitions : trans1 = Transition ( '' , '' , '' ) msg = \"\" with self . assertRaises ( ImproperlyConfigured , msg = msg ) : class TestWF ( Workflow ) : class States : test1 = State ( '' , default = True ) test2 = State ( '' ) class Transitions : instance = Transition ( '' , '' , '' ) msg = \"\" with self . assertRaises ( ImproperlyConfigured , msg = msg ) : class TestWF ( Workflow ) : class States : test1 = State ( '' , default = True ) test2 = State ( '' ) class Transitions : _test = Transition ( '' , '' , '' ) msg = \"\" with self . assertRaises ( ImproperlyConfigured , msg = msg ) : class TestWF ( Workflow ) : class States : test1 = State ( '' , default = True ) test2 = State ( '' ) class Transitions : user = Transition ( '' , '' , '' ) def test_api ( self ) : user = User ( ) user . save ( ) ", "answer": "class TestWF ( Workflow ) :"}, {"prompt": " from gevent import monkey ; monkey . patch_all ( ) import gevent from ws4py . client . geventclient import WebSocketClient if __name__ == '' : ws = WebSocketClient ( '' , protocols = [ '' , '' ] ) ws . connect ( ) ws . send ( \"\" ) print ( ( ws . receive ( ) , ) ) ws . send ( \"\" ) print ( ( ws . receive ( ) , ) ) def incoming ( ) : while True : m = ws . receive ( ) if m is not None : m = str ( m ) print ( ( m , len ( m ) ) ) if len ( m ) == : ws . close ( ) break else : break print ( ( \"\" , ) ) def outgoing ( ) : for i in range ( , , ) : ws . send ( \"\" * i ) ", "answer": "ws . send ( \"\" )"}, {"prompt": " \"\"\"\"\"\" import sys import certbot ", "answer": "sys . modules [ '' ] = certbot "}, {"prompt": " \"\"\"\"\"\" from decimal import Decimal import moneyed import pytest from moneyed import Money from . testapp . forms import ( MoneyForm , MoneyFormMultipleCurrencies , MoneyModelForm , OptionalMoneyForm , ) from . testapp . models import ModelWithVanillaMoneyField pytestmark = pytest . mark . django_db def test_save ( ) : money = Money ( Decimal ( '' ) , moneyed . SEK ) form = MoneyModelForm ( { '' : money . amount , '' : money . currency } ) assert form . is_valid ( ) instance = form . save ( ) retrieved = ModelWithVanillaMoneyField . objects . get ( pk = instance . pk ) assert money == retrieved . money def test_validate ( ) : money = Money ( Decimal ( '' ) , moneyed . SEK ) form = MoneyForm ( { '' : money . amount , '' : money . currency } ) assert form . is_valid ( ) result = form . cleaned_data [ '' ] assert result == money @ pytest . mark . parametrize ( '' , ( { '' : '' , '' : moneyed . SEK } , { '' : , '' : moneyed . SEK } , { '' : , '' : moneyed . SEK } , { '' : , '' : moneyed . EUR } ) ) def test_form_is_invalid ( data ) : assert not MoneyForm ( data ) . is_valid ( ) @ pytest . mark . parametrize ( ", "answer": "'' ,"}, {"prompt": " try : import numpy as np except ImportError : np = None if np : try : import pandas as pd except ImportError : pd = None from . import Converter , Options class NumpyArrayConverter ( Converter ) : ", "answer": "writes_types = np . ndarray"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( null = True , max_length = , db_index = True ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( '' , '' ) models = { '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } } ", "answer": "complete_apps = [ '' ] "}, {"prompt": " gettext_noop = lambda s : s DEBUG = False TEMPLATE_DEBUG = False DEBUG_PROPAGATE_EXCEPTIONS = False ", "answer": "USE_ETAGS = False"}, {"prompt": " from flask import Flask , url_for , request , session , redirect from moves import MovesClient from datetime import datetime , timedelta import _keys app = Flask ( __name__ ) Moves = MovesClient ( _keys . client_id , _keys . client_secret ) @ app . route ( \"\" ) def index ( ) : if '' not in session : oauth_return_url = url_for ( '' , _external = True ) auth_url = Moves . build_oauth_url ( oauth_return_url ) return '' % ( auth_url , auth_url ) return redirect ( url_for ( '' ) ) @ app . route ( \"\" ) def oauth_return ( ) : error = request . values . get ( '' , None ) if error is not None : return error oauth_return_url = url_for ( '' , _external = True ) code = request . args . get ( \"\" ) token = Moves . get_oauth_token ( code , redirect_uri = oauth_return_url ) session [ '' ] = token return redirect ( url_for ( '' ) ) @ app . route ( '' ) def logout ( ) : if '' in session : del ( session [ '' ] ) return redirect ( url_for ( '' ) ) @ app . route ( \"\" ) def show_info ( ) : profile = Moves . user_profile ( access_token = session [ '' ] ) response = '' % ( profile [ '' ] , profile [ '' ] [ '' ] ) return response + \"\" % url_for ( '' ) + \"\" % url_for ( '' ) @ app . route ( \"\" ) def today ( ) : today = datetime . now ( ) . strftime ( '' ) info = Moves . user_summary_daily ( today , access_token = session [ '' ] ) res = '' for activity in info [ ] [ '' ] : if activity [ '' ] == '' : res += '' % activity [ '' ] elif activity [ '' ] == '' : res += '' % activity [ '' ] elif activity [ '' ] == '' : res += '' % activity [ '' ] return res @ app . route ( \"\" ) def expanded_summary ( ) : today = datetime . now ( ) . strftime ( '' ) info = Moves . user_summary_daily ( today , access_token = session [ '' ] ) res = '' for activity in info [ ] [ '' ] : res = activities_block ( activity , res ) if activity [ '' ] == '' : res += '' % activity [ '' ] res += '' % activity [ '' ] res += '' % activity [ '' ] res += '' % activity [ '' ] elif activity [ '' ] == '' : res += '' % activity [ '' ] res += '' % activity [ '' ] res += '' % activity [ '' ] res += '' % activity [ '' ] elif activity [ '' ] == '' : res += '' % activity [ '' ] res += '' % activity [ '' ] res += '' % activity [ '' ] res += '' % activity [ '' ] return res @ app . route ( \"\" ) def activities ( ) : today = datetime . now ( ) . strftime ( '' ) info = Moves . user_activities_daily ( today , access_token = session [ '' ] ) res = '' for segment in info [ ] [ '' ] : if segment [ '' ] == '' : res += '' res = segment_start_end ( segment , res ) for activity in segment [ '' ] : res += '' % activity [ '' ] res = activity_start_end ( activity , res ) res += '' % activity [ '' ] res += '' % activity [ '' ] res += '' elif segment [ '' ] == '' : res += '' res = segment_start_end ( segment , res ) for activity in segment [ '' ] : res += '' % activity [ '' ] res = activity_start_end ( activity , res ) res += '' % activity [ '' ] res += '' % activity [ '' ] res += '' return res @ app . route ( \"\" ) def places ( ) : today = datetime . now ( ) . strftime ( '' ) info = Moves . user_places_daily ( today , access_token = session [ '' ] ) res = '' for segment in info [ ] [ '' ] : res = place ( segment , res ) return res @ app . route ( \"\" ) def storyline ( ) : today = datetime . now ( ) . strftime ( '' ) info = Moves . user_storyline_daily ( today , trackPoints = { '' } , access_token = session [ '' ] ) res = '' for segment in info [ ] [ '' ] : if segment [ '' ] == '' : res = place ( segment , res ) elif segment [ '' ] == '' : res = move ( segment , res ) res += '' return res def segment_start_end ( segment , res ) : res += '' % segment [ '' ] res += '' % segment [ '' ] return res def activity_start_end ( activity , res ) : res += '' % activity [ '' ] res += '' % activity [ '' ] return res def place_block ( segment , res ) : res += '' % segment [ '' ] [ '' ] res += '' % segment [ '' ] [ '' ] res += '' % segment [ '' ] [ '' ] if segment [ '' ] [ '' ] == '' : res += '' % segment [ '' ] [ '' ] res += '' res += '' % segment [ '' ] [ '' ] [ '' ] res += '' % segment [ '' ] [ '' ] [ '' ] ", "answer": "return res"}, {"prompt": " HEADER = '' OKBLUE = '' OKGREEN = '' WARNING = '' FAIL = '' ENDC = '' def print_warning ( text ) : print WARNING + text + ENDC def print_header ( text ) : print HEADER + text + ENDC def print_error ( text ) : print FAIL + text + ENDC def print_green ( text ) : ", "answer": "print OKGREEN + text + ENDC "}, {"prompt": " from . import multiarray ", "answer": "__all__ = [ ] "}, {"prompt": " from rackclient . tests import utils from rackclient . tests . v1 import fakes from rackclient . v1 import groups class GroupsTest ( utils . TestCase ) : def setUp ( self ) : super ( GroupsTest , self ) . setUp ( ) self . cs = fakes . FakeClient ( ) self . group_type = groups . Group def test_list ( self ) : groups = self . cs . groups . list ( ) self . cs . assert_called ( '' , '' ) for group in groups : self . assertIsInstance ( group , self . group_type ) def test_get ( self ) : group = self . cs . groups . get ( '' ) self . cs . assert_called ( '' , '' ) self . assertEqual ( '' , group . gid ) self . assertEqual ( '' , group . user_id ) self . assertEqual ( '' , group . project_id ) self . assertEqual ( '' , group . name ) self . assertEqual ( '' , group . description ) self . assertEqual ( '' , group . status ) def _create_body ( self , name , description ) : return { '' : { '' : name , '' : description } } def test_create ( self ) : name = '' description = '' group = self . cs . groups . create ( name , description ) body = self . _create_body ( name , description ) self . cs . assert_called ( '' , '' , body ) self . assertIsInstance ( group , self . group_type ) ", "answer": "def test_update ( self ) :"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " import six from django . conf import settings from django . db import models from django . utils . text import capfirst from django_filters import Filter , MultipleChoiceFilter from django_filters . filterset import FilterSet , FilterSetMetaclass from graphql_relay . node . node import from_global_id from graphene . contrib . django . forms import ( GlobalIDFormField , GlobalIDMultipleChoiceField ) class GlobalIDFilter ( Filter ) : field_class = GlobalIDFormField def filter ( self , qs , value ) : gid = from_global_id ( value ) return super ( GlobalIDFilter , self ) . filter ( qs , gid . id ) class GlobalIDMultipleChoiceFilter ( MultipleChoiceFilter ) : field_class = GlobalIDMultipleChoiceField def filter ( self , qs , value ) : gids = [ from_global_id ( v ) . id for v in value ] return super ( GlobalIDMultipleChoiceFilter , self ) . filter ( qs , gids ) ORDER_BY_FIELD = getattr ( settings , '' , '' ) GRAPHENE_FILTER_SET_OVERRIDES = { models . AutoField : { '' : GlobalIDFilter , } , models . OneToOneField : { '' : GlobalIDFilter , } , models . ForeignKey : { '' : GlobalIDFilter , } , models . ManyToManyField : { '' : GlobalIDMultipleChoiceFilter , } } class GrapheneFilterSetMetaclass ( FilterSetMetaclass ) : def __new__ ( cls , name , bases , attrs ) : new_class = super ( GrapheneFilterSetMetaclass , cls ) . __new__ ( cls , name , bases , attrs ) for k , v in GRAPHENE_FILTER_SET_OVERRIDES . items ( ) : new_class . filter_overrides . setdefault ( k , v ) return new_class class GrapheneFilterSetMixin ( object ) : order_by_field = ORDER_BY_FIELD @ classmethod def filter_for_reverse_field ( cls , f , name ) : \"\"\"\"\"\" rel = f . field . rel default = { '' : name , '' : capfirst ( rel . related_name ) } if rel . multiple : return GlobalIDMultipleChoiceFilter ( ** default ) else : return GlobalIDFilter ( ** default ) class GrapheneFilterSet ( six . with_metaclass ( GrapheneFilterSetMetaclass , GrapheneFilterSetMixin , FilterSet ) ) : \"\"\"\"\"\" def setup_filterset ( filterset_class ) : \"\"\"\"\"\" return type ( '' . format ( filterset_class . __name__ ) , ( six . with_metaclass ( GrapheneFilterSetMetaclass , GrapheneFilterSetMixin , filterset_class ) , ) , { } , ) def custom_filterset_factory ( model , filterset_base_class = GrapheneFilterSet , ** meta ) : \"\"\"\"\"\" ", "answer": "meta . update ( {"}, {"prompt": " \"\"\"\"\"\" import sys from collections import defaultdict from bacpypes . debugging import Logging , function_debugging , ModuleLogger from bacpypes . consolelogging import ConsoleLogHandler from bacpypes . pdu import Address from bacpypes . analysis import trace , strftimestamp , Tracer from bacpypes . npdu import WhoIsRouterToNetwork _debug = _log = ModuleLogger ( globals ( ) ) filterSource = None filterDestination = None filterHost = None requests = defaultdict ( int ) networks = defaultdict ( list ) @ function_debugging def Match ( addr1 , addr2 ) : \"\"\"\"\"\" if _debug : Match . _debug ( \"\" , addr1 , addr2 ) if ( addr2 . addrType == Address . localBroadcastAddr ) : return ( addr1 . addrType == Address . localStationAddr ) or ( addr1 . addrType == Address . localBroadcastAddr ) elif ( addr2 . addrType == Address . localStationAddr ) : return ( addr1 . addrType == Address . localStationAddr ) and ( addr1 . addrAddr == addr2 . addrAddr ) elif ( addr2 . addrType == Address . remoteBroadcastAddr ) : return ( ( addr1 . addrType == Address . remoteStationAddr ) or ( addr1 . addrType == Address . remoteBroadcastAddr ) ) and ( addr1 . addrNet == addr2 . addrNet ) elif ( addr2 . addrType == Address . remoteStationAddr ) : return ( addr1 . addrType == Address . remoteStationAddr ) and ( addr1 . addrNet == addr2 . addrNet ) and ( addr1 . addrAddr == addr2 . addrAddr ) elif ( addr2 . addrType == Address . globalBroadcastAddr ) : return ( addr1 . addrType == Address . globalBroadcastAddr ) else : raise RuntimeError , \"\" class WhoIsRouterToNetworkSummary ( Tracer , Logging ) : def __init__ ( self ) : if _debug : IAmRouterToNetworkSummary . _debug ( \"\" ) Tracer . __init__ ( self , self . Filter ) def Filter ( self , pkt ) : if _debug : WhoIsRouterToNetworkSummary . _debug ( \"\" , pkt ) global requests , networks if not isinstance ( pkt , WhoIsRouterToNetwork ) : return if filterSource : if not Match ( pkt . pduSource , filterSource ) : if _debug : WhoIsRouterToNetworkSummary . _debug ( \"\" ) return if filterDestination : if not Match ( pkt . pduDestination , filterDestination ) : if _debug : WhoIsRouterToNetworkSummary . _debug ( \"\" ) return ", "answer": "if filterHost :"}, {"prompt": " '''''' '''''' from flask import g from . . database import db_session , NoResultFound from . . models import Certificate as DBCertificate , PrivateKey as DBPrivateKey , certificate_private_key_assoc from m2certs import RSAPrivateKey , Certificate , CertificateRequest , Identity , NID_userId MDM_CA_CN = '' MDM_DEVICE_CN = '' def get_ca ( ) : ca = getattr ( g , '' , None ) if ca is None : ca = g . _mdm_ca = CA ( ) return ca class CA ( object ) : def __init__ ( self ) : try : q = db_session . query ( DBCertificate , DBPrivateKey ) . join ( DBCertificate , DBPrivateKey . certificates ) . filter ( DBCertificate . cert_type == '' ) cert , pk = q . one ( ) self . ca_privkey = RSAPrivateKey . load ( str ( pk . pem_key ) ) self . ca_cert = Certificate . load ( str ( cert . pem_certificate ) ) except NoResultFound : ", "answer": "self . ca_privkey = RSAPrivateKey ( )"}, {"prompt": " \"\"\"\"\"\" import datetime import copy import pprint import socket import sys import weakref copy . _copy_dispatch [ weakref . ref ] = copy . _copy_immutable copy . _deepcopy_dispatch [ weakref . ref ] = copy . _deepcopy_atomic copy . _deepcopy_dispatch [ weakref . KeyedRef ] = copy . _deepcopy_atomic from zope . interface import Interface , implements from numpy import ndarray from traits . api import HasTraits , Missing , Python , push_exception_handler , TraitType , CTrait from traits . has_traits import FunctionType , _clone_trait , MetaHasTraits from traits . trait_base import not_none from multiprocessing import connection from openmdao . main . datatypes . file import FileRef from openmdao . main . datatypes . list import List from openmdao . main . datatypes . slot import Slot from openmdao . main . datatypes . vtree import VarTree from openmdao . main . interfaces import ICaseIterator , IResourceAllocator , IContainer , IVariableTree , IContainerProxy , IOverrideSet from openmdao . main . mp_support import ObjectManager , is_instance , CLASSES_TO_PROXY , has_interface from openmdao . main . rbac import rbac from openmdao . main . variable import Variable , is_legal_name , _missing from openmdao . main . array_helpers import flattened_value , get_index from openmdao . util . log import Logger , logger from openmdao . util import eggloader , eggsaver , eggobserver from openmdao . util . eggsaver import SAVE_CPICKLE from openmdao . util . typegroups import int_types , complex_or_real_types _copydict = { '' : copy . deepcopy , '' : copy . copy } _iodict = { '' : '' , '' : '' } __missing__ = object ( ) def get_closest_proxy ( obj , pathname ) : \"\"\"\"\"\" names = pathname . split ( '' ) i = for name in names : if IContainerProxy . providedBy ( obj ) : return ( obj , '' . join ( names [ i : ] ) ) try : obj = getattr ( obj , name ) except AttributeError : break i += return ( obj , '' . join ( names [ i : ] ) ) def proxy_parent ( obj , pathname ) : \"\"\"\"\"\" names = pathname . split ( '' ) i = for name in names [ : - ] : if IContainerProxy . providedBy ( obj ) : return ( obj , '' . join ( names [ i : ] ) ) try : obj = getattr ( obj , name ) except AttributeError : break i += return ( obj , '' . join ( names [ i : ] ) ) push_exception_handler ( handler = lambda o , t , ov , nv : None , reraise_exceptions = True , main = True , locked = True ) class _MetaSafe ( MetaHasTraits ) : \"\"\"\"\"\" def __new__ ( mcs , class_name , bases , class_dict ) : for name , obj in class_dict . items ( ) : if isinstance ( obj , Variable ) : for base in bases : if name in base . __dict__ : raise NameError ( '' % ( class_name , name , base . __name__ ) ) return super ( _MetaSafe , mcs ) . __new__ ( mcs , class_name , bases , class_dict ) class SafeHasTraits ( HasTraits ) : \"\"\"\"\"\" __metaclass__ = _MetaSafe def _check_bad_default ( name , trait , obj = None ) : if trait . vartypename not in [ '' , '' ] and trait . required is True and not trait . assumed_default and trait . _illegal_default_ is True : msg = \"\" % name if obj is None : raise RuntimeError ( msg ) else : obj . raise_exception ( msg , RuntimeError ) class Container ( SafeHasTraits ) : \"\"\"\"\"\" implements ( IContainer ) def __init__ ( self ) : self . _parent = None self . _name = None super ( Container , self ) . __init__ ( ) self . _call_cpath_updated = True self . _call_configure = True self . _managers = { } self . _added_traits = { } self . _getcache = { } self . _setcache = { } self . _copycache = { } self . _cached_traits_ = None self . _repair_trait_info = None self . _trait_metadata = { } self . _logger = Logger ( '' ) for name , obj in self . items ( ) : if isinstance ( obj , FileRef ) : setattr ( self , name , obj . copy ( owner = self ) ) for name , obj in self . __class__ . __dict__ [ '' ] . items ( ) : ttype = obj . trait_type if isinstance ( ttype , VarTree ) : variable_tree = getattr ( self , name ) if not obj . required : new_tree = variable_tree . copy ( ) setattr ( self , name , new_tree ) if obj . required : _check_bad_default ( name , obj , self ) @ property def parent ( self ) : \"\"\"\"\"\" return self . _parent @ parent . setter def parent ( self , value ) : \"\"\"\"\"\" if self . _parent is not value : self . _parent = value self . _fix_loggers ( self , recurse = True ) self . _branch_moved ( ) def _branch_moved ( self ) : self . _call_cpath_updated = True for n , cont in self . items ( ) : if is_instance ( cont , Container ) and cont is not self . _parent : cont . _branch_moved ( ) @ property def name ( self ) : \"\"\"\"\"\" if self . _name is None : if self . parent : self . _name = find_name ( self . parent , self ) self . _fix_loggers ( self , recurse = True ) elif self . _call_cpath_updated is False : self . _name = '' else : return '' return self . _name @ name . setter def name ( self , name ) : \"\"\"\"\"\" if not is_legal_name ( name ) : raise NameError ( \"\" % name ) if self . _name != name : self . _name = name self . _fix_loggers ( self , recurse = True ) def _fix_loggers ( self , container , recurse ) : \"\"\"\"\"\" container . _logger . rename ( container . get_pathname ( ) . replace ( '' , '' ) ) if recurse : for name in container . list_containers ( ) : obj = getattr ( container , name ) self . _fix_loggers ( obj , recurse ) @ rbac ( ( '' , '' ) ) def get_pathname ( self , rel_to_scope = None ) : \"\"\"\"\"\" path = [ ] obj = self name = obj . name while obj is not rel_to_scope and name : path . append ( name ) obj = obj . parent if obj is None : break name = obj . name return '' . join ( path [ : : - ] ) def get_trait ( self , name , copy = False ) : \"\"\"\"\"\" if self . _cached_traits_ is None : self . _cached_traits_ = self . traits ( ) self . _cached_traits_ . update ( self . _instance_traits ( ) ) if copy : if self . _cached_traits_ . get ( name ) : return self . trait ( name , copy = copy ) else : return None else : return self . _cached_traits_ . get ( name ) def __deepcopy__ ( self , memo ) : \"\"\"\"\"\" id_self = id ( self ) if id_self in memo : return memo [ id_self ] memo [ '' ] = \"\" saved_p = self . _parent saved_c = self . _cached_traits_ saved_s = self . _setcache saved_g = self . _getcache self . _parent = None self . _cached_traits_ = None self . _getcache = { } self . _setcache = { } try : result = super ( Container , self ) . __deepcopy__ ( memo ) finally : self . _parent = saved_p self . _cached_traits_ = saved_c self . _getcache = saved_g self . _setcache = saved_s olditraits = self . _instance_traits ( ) for name , trait in olditraits . items ( ) : if trait . type is not '' and name in self . _added_traits : if isinstance ( trait . trait_type , VarTree ) : if name not in result . _added_traits : result . add_trait ( name , _clone_trait ( trait ) ) else : result . add_trait ( name , _clone_trait ( trait ) ) if name in self . __dict__ : result . __dict__ [ name ] = copy . deepcopy ( self . __dict__ [ name ] ) return result def __getstate__ ( self ) : \"\"\"\"\"\" state = super ( Container , self ) . __getstate__ ( ) dct = { } for name , trait in state [ '' ] . items ( ) : if trait . transient is not True : dct [ name ] = trait state [ '' ] = dct state [ '' ] = None state [ '' ] = { } state [ '' ] = { } return state def __setstate__ ( self , state ) : \"\"\"\"\"\" super ( Container , self ) . __setstate__ ( { } ) self . __dict__ . update ( state ) self . _repair_trait_info = { } self . _cached_traits_ = None traits = self . _alltraits ( ) for name , trait in self . _added_traits . items ( ) : if name not in traits : self . add_trait ( name , trait , refresh = False ) fixups = [ ] for name , trait in traits . items ( ) : try : get = trait . trait_type . get except AttributeError : continue if get is not None : if name not in self . _added_traits : try : val = getattr ( self , name ) self . remove_trait ( name ) self . add_trait ( name , trait ) setattr ( self , name , val ) except Exception as exc : self . _logger . warning ( '' , name , val , exc ) fixups . append ( ( name , trait ) ) self . _repair_trait_info [ '' ] = fixups fixups = [ ] for name , val in self . __dict__ . items ( ) : if not name . startswith ( '' ) and not self . get_trait ( name ) : try : setattr ( self , name , val ) except Exception as exc : self . _logger . warning ( '' , name , val , exc ) fixups . append ( ( name , val ) ) self . _repair_trait_info [ '' ] = fixups fixups = [ ] for name , trait in self . _alltraits ( ) . items ( ) : if isinstance ( trait . trait_type , List ) : try : setattr ( self , name , getattr ( self , name ) ) except Exception as exc : self . _logger . warning ( '' , name , val , exc ) fixups . append ( name ) self . _repair_trait_info [ '' ] = fixups self . _cached_traits_ = None def _repair_traits ( self ) : \"\"\"\"\"\" if self . _repair_trait_info is None : return for name , trait in self . _repair_trait_info [ '' ] : val = getattr ( self , name ) self . remove_trait ( name ) self . add_trait ( name , trait ) setattr ( self , name , val ) for name , val in self . _repair_trait_info [ '' ] : setattr ( self , name , val ) for name in self . _repair_trait_info [ '' ] : setattr ( self , name , getattr ( self , name ) ) self . _repair_trait_info = None @ classmethod def add_class_trait ( cls , name , * trait ) : \"\"\"\"\"\" bases = [ cls ] bases . extend ( cls . __bases__ ) for base in bases : if name in base . __dict__ : raise NameError ( '' % ( name , base . __name__ ) ) for t in trait : _check_bad_default ( name , t ) break if name in cls . _trait_metadata : del cls . _trait_metadata [ name ] return super ( Container , cls ) . add_class_trait ( name , * trait ) def add_trait ( self , name , trait , refresh = True ) : \"\"\"\"\"\" if name . endswith ( '' ) and trait . type == '' : super ( Container , self ) . add_trait ( name , trait ) return bases = [ self . __class__ ] bases . extend ( self . __class__ . __bases__ ) for base in bases : if name in base . __dict__ : raise NameError ( '' % ( name , base . __name__ ) ) _check_bad_default ( name , trait , self ) if name not in self . _added_traits : self . _added_traits [ name ] = trait super ( Container , self ) . add_trait ( name , trait ) if self . _cached_traits_ is not None : self . _cached_traits_ [ name ] = self . trait ( name ) if name in self . _trait_metadata : del self . _trait_metadata [ name ] if refresh : getattr ( self , name ) def remove_trait ( self , name ) : \"\"\"\"\"\" try : del self . _added_traits [ name ] except KeyError : pass try : del self . _cached_traits_ [ name ] except ( KeyError , TypeError ) : pass try : del self . _trait_metadata [ name ] except KeyError : pass super ( Container , self ) . remove_trait ( name ) @ rbac ( ( '' , '' ) ) def get_attr_w_copy ( self , path ) : \"\"\"\"\"\" obj = self . get ( path ) copy = self . _copycache . get ( path , _missing ) if copy is _missing : copy = self . get_metadata ( path . split ( '' , ) [ ] , '' ) self . _copycache [ path ] = copy if copy : if isinstance ( obj , Container ) : obj = obj . copy ( ) else : obj = _copydict [ copy ] ( obj ) return obj def _add_after_parent_set ( self , name , obj ) : pass def _prep_for_add ( self , name , obj ) : \"\"\"\"\"\" if '' in name : self . raise_exception ( '' % name , ValueError ) elif not is_legal_name ( name ) : self . raise_exception ( \"\" % name , NameError ) removed = False if has_interface ( obj , IContainer ) : if self . contains ( name ) and getattr ( self , name ) : self . remove ( name ) removed = True if has_interface ( obj , IContainer ) : self . _check_recursion ( obj ) if IContainerProxy . providedBy ( obj ) : obj . parent = self . _get_proxy ( obj ) else : obj . parent = self obj . name = name self . _add_after_parent_set ( name , obj ) if self . _call_cpath_updated is False : obj . cpath_updated ( ) return removed def _post_container_add ( self , name , obj , removed ) : pass def add ( self , name , obj ) : \"\"\"\"\"\" removed = self . _prep_for_add ( name , obj ) if has_interface ( obj , IContainer ) : setattr ( self , name , obj ) if self . _cached_traits_ is None : self . get_trait ( name ) else : self . _cached_traits_ [ name ] = self . trait ( name ) self . _post_container_add ( name , obj , removed ) elif is_instance ( obj , TraitType ) : self . add_trait ( name , obj ) else : setattr ( self , name , obj ) return obj def _check_recursion ( self , obj ) : \"\"\"\"\"\" ancestor = self while is_instance ( ancestor , Container ) : if obj is ancestor : self . raise_exception ( '' , ValueError ) ancestor = ancestor . parent def _get_proxy ( self , proxy ) : \"\"\"\"\"\" addr_type = connection . address_type ( proxy . _token . address ) addr = proxy . _token . address [ ] if addr_type == '' else None key = ( addr_type , addr , proxy . _authkey ) try : manager = self . _managers [ key ] except KeyError : if addr_type == '' : ip_addr = socket . gethostbyname ( socket . gethostname ( ) ) address = ( ip_addr , ) allowed_hosts = [ addr ] if addr == ip_addr : allowed_hosts . append ( '' ) else : address = None allowed_hosts = None name = self . name or '' access = addr if addr_type == '' else addr_type name = '' % ( name , access ) manager = ObjectManager ( self , address , authkey = proxy . _authkey , name = name , allowed_hosts = allowed_hosts ) self . _managers [ key ] = manager return manager . proxy def _check_rename ( self , oldname , newname ) : if '' in oldname or '' in newname : self . raise_exception ( \"\" \"\" % ( oldname , newname ) , RuntimeError ) if not self . contains ( oldname ) : self . raise_exception ( \"\" % ( oldname , newname , oldname ) , RuntimeError ) if self . contains ( newname ) : self . raise_exception ( \"\" % ( oldname , newname , newname ) , RuntimeError ) def rename ( self , oldname , newname ) : \"\"\"\"\"\" self . _check_rename ( oldname , newname ) obj = self . remove ( oldname ) self . add ( newname , obj ) def remove ( self , name ) : \"\"\"\"\"\" if '' in name : self . raise_exception ( '' % name , NameError ) try : obj = getattr ( self , name ) except AttributeError : return None trait = self . get_trait ( name ) if trait is None : delattr ( self , name ) else : if trait . is_trait_type ( Slot ) : try : setattr ( self , name , None ) except TypeError as err : self . raise_exception ( str ( err ) , RuntimeError ) else : self . remove_trait ( name ) return obj @ rbac ( ( '' , '' ) ) def configure ( self ) : pass @ rbac ( ( '' , '' ) ) def copy ( self ) : \"\"\"\"\"\" cp = copy . deepcopy ( self ) cp . _relink ( ) return cp def _relink ( self ) : \"\"\"\"\"\" for name in self . list_containers ( ) : container = getattr ( self , name ) if container is not self . _parent : container . _parent = self container . _relink ( ) @ rbac ( ( '' , '' ) ) def cpath_updated ( self ) : \"\"\"\"\"\" self . _fix_loggers ( self , recurse = False ) self . _call_cpath_updated = False for cont in self . list_containers ( ) : cont = getattr ( self , cont ) if cont is not self . _parent : cont . cpath_updated ( ) def revert_to_defaults ( self , recurse = True ) : \"\"\"\"\"\" self . reset_traits ( iotype = '' ) if recurse : for cname in self . list_containers ( ) : getattr ( self , cname ) . revert_to_defaults ( recurse ) def _items ( self , visited , recurse = False , ** metadata ) : \"\"\"\"\"\" if id ( self ) not in visited : visited . add ( id ( self ) ) match_dict = self . _alltraits ( ** metadata ) if recurse : for name in self . list_containers ( ) : obj = getattr ( self , name ) if name in match_dict and id ( obj ) not in visited : yield ( name , obj ) if obj : for chname , child in obj . _items ( visited , recurse , ** metadata ) : yield ( '' . join ( ( name , chname ) ) , child ) for name , trait in match_dict . items ( ) : obj = getattr ( self , name , Missing ) if obj is not Missing : if is_instance ( obj , ( Container , VarTree ) ) and id ( obj ) not in visited : if not recurse : yield ( name , obj ) elif trait . iotype is not None : yield ( name , obj ) def items ( self , recurse = False , ** metadata ) : \"\"\"\"\"\" return self . _items ( set ( [ id ( self . parent ) ] ) , recurse , ** metadata ) def list_containers ( self ) : \"\"\"\"\"\" return [ n for n , v in self . items ( ) if is_instance ( v , Container ) ] def list_vars ( self ) : \"\"\"\"\"\" return [ k for k , v in self . items ( iotype = not_none ) ] @ rbac ( ( '' , '' ) ) def _alltraits ( self , traits = None , events = False , ** metadata ) : \"\"\"\"\"\" if traits is None : if self . _cached_traits_ : traits = self . _cached_traits_ else : traits = self . traits ( ) traits . update ( self . _instance_traits ( ) ) self . _cached_traits_ = traits result = { } for name , trait in traits . items ( ) : if not events and trait . type is '' : continue for meta_name , meta_eval in metadata . items ( ) : if type ( meta_eval ) is FunctionType : if not meta_eval ( getattr ( trait , meta_name ) ) : break elif meta_eval != getattr ( trait , meta_name ) : break else : result [ name ] = trait return result @ rbac ( ( '' , '' ) ) def contains ( self , path ) : \"\"\"\"\"\" childname , _ , restofpath = path . partition ( '' ) if restofpath : obj = getattr ( self , childname , Missing ) if obj is Missing : return False elif is_instance ( obj , Container ) : return obj . contains ( restofpath ) else : return hasattr ( obj , restofpath ) return hasattr ( self , path ) def _get_metadata_failed ( self , traitpath , metaname ) : self . raise_exception ( \"\" % traitpath , AttributeError ) @ rbac ( ( '' , '' ) ) def get_metadata ( self , traitpath , metaname = None ) : \"\"\"\"\"\" childname , _ , restofpath = traitpath . partition ( '' ) if restofpath : obj = getattr ( self , childname , Missing ) if obj is Missing : return self . _get_metadata_failed ( traitpath , metaname ) elif hasattr ( obj , '' ) : return obj . get_metadata ( restofpath , metaname ) else : t = self . get_trait ( childname ) if t is not None and t . iotype and metaname == '' : return t . iotype else : self . _get_metadata_failed ( traitpath , metaname ) varname , _ , _ = traitpath . partition ( '' ) try : mdict = self . _trait_metadata [ varname ] except KeyError : t = self . get_trait ( varname ) if t : t = t . trait_type mdict = t . _metadata . copy ( ) mdict . setdefault ( '' , t . __class__ . __name__ ) else : mdict = self . _get_metadata_failed ( traitpath , None ) self . _trait_metadata [ varname ] = mdict if metaname is None : return mdict else : return mdict . get ( metaname , None ) @ rbac ( ( '' , '' ) ) def set_metadata ( self , traitpath , metaname , value ) : \"\"\"\"\"\" if metaname in ( '' , ) : self . raise_exception ( \"\" % ( metaname , traitpath ) , TypeError ) self . get_metadata ( traitpath ) [ metaname ] = value @ rbac ( ( '' , '' ) , proxy_types = [ FileRef ] ) def get ( self , path ) : \"\"\"\"\"\" expr = self . _getcache . get ( path ) if expr is not None : return eval ( expr , self . __dict__ ) obj , restofpath = get_closest_proxy ( self , path ) if restofpath and IContainerProxy . providedBy ( obj ) : return obj . get ( restofpath ) expr = compile ( path , path , mode = '' ) try : val = eval ( expr , self . __dict__ ) except ( AttributeError , NameError ) as err : if not restofpath : return obj self . raise_exception ( str ( err ) , AttributeError ) else : self . _getcache [ path ] = expr return val @ rbac ( ( '' , '' ) , proxy_types = [ FileRef ] ) def get_flattened_value ( self , path ) : \"\"\"\"\"\" return flattened_value ( path , self . get ( path ) ) @ rbac ( ( '' , '' ) ) def set_flattened_value ( self , path , value ) : obj , restofpath = proxy_parent ( self , path ) if restofpath and IContainerProxy . providedBy ( obj ) : obj . set_flattened_value ( restofpath , value ) return val = self . get ( path ) if not isinstance ( val , int_types ) and isinstance ( val , complex_or_real_types ) : self . set ( path , value [ ] ) return elif hasattr ( val , '' ) : val . set_flattened_value ( value ) return elif isinstance ( val , ndarray ) : try : newshape = value . shape self . set ( path , value . reshape ( val . shape ) ) except Exception as err : self . reraise_exception ( \"\" % ( self . get_pathname ( ) , path , val . shape , newshape ) , sys . exc_info ( ) ) return val = self . get ( path . split ( '' , ) [ ] ) idx = get_index ( path ) if isinstance ( val , int_types ) : pass elif hasattr ( val , '' ) and idx is not None : if isinstance ( val [ idx ] , complex_or_real_types ) : val [ idx ] = value [ ] else : val [ idx ] = value return elif IVariableTree . providedBy ( val ) : raise NotImplementedError ( \"\" ) elif hasattr ( val , '' ) : val . set_flattened_value ( value ) return self . raise_exception ( \"\" % path , TypeError ) def get_iotype ( self , name ) : return self . get_trait ( name ) . iotype @ rbac ( ( '' , '' ) ) def set ( self , path , value ) : \"\"\"\"\"\" _local_setter_ = value expr = self . _setcache . get ( path ) if expr is not None : exec ( expr ) return obj , restofpath = proxy_parent ( self , path ) if IOverrideSet . providedBy ( obj ) or ( restofpath and IContainerProxy . providedBy ( obj ) ) : obj . set ( restofpath , value ) return assign = \"\" % path expr = compile ( assign , assign , mode = '' ) try : exec ( expr ) except Exception as err : self . raise_exception ( str ( err ) , err . __class__ ) else : self . _setcache [ path ] = expr def save_to_egg ( self , name , version , py_dir = None , src_dir = None , src_files = None , child_objs = None , dst_dir = None , observer = None , need_requirements = True ) : \"\"\"\"\"\" assert name and isinstance ( name , basestring ) assert version and isinstance ( version , basestring ) if not version . endswith ( '' ) : version += '' now = datetime . datetime . now ( ) tstamp = '' % ( now . year , now . month , now . day , now . hour , now . minute ) version += tstamp observer = eggobserver . EggObserver ( observer , self . _logger ) entry_pts = [ ( self , name , _get_entry_group ( self ) ) ] if child_objs is not None : root_pathname = self . get_pathname ( ) root_start = root_pathname . rfind ( '' ) root_start = root_start + if root_start >= else root_pathname += '' for child in child_objs : pathname = child . get_pathname ( ) if not pathname . startswith ( root_pathname ) : msg = '' % ( pathname , root_pathname ) observer . exception ( msg ) self . raise_exception ( msg , RuntimeError ) entry_pts . append ( ( child , pathname [ root_start : ] , _get_entry_group ( child ) ) ) parent = self . parent self . parent = None try : return eggsaver . save_to_egg ( entry_pts , version , py_dir , src_dir , src_files , dst_dir , self . _logger , observer . observer , need_requirements ) except Exception : self . reraise_exception ( info = sys . exc_info ( ) ) finally : self . parent = parent def save ( self , outstream , fmt = SAVE_CPICKLE , proto = - ) : \"\"\"\"\"\" parent = self . parent self . parent = None try : eggsaver . save ( self , outstream , fmt , proto , self . _logger ) except Exception : self . reraise_exception ( info = sys . exc_info ( ) ) finally : self . parent = parent @ staticmethod def load_from_eggfile ( filename , observer = None , log = None ) : \"\"\"\"\"\" entry_group = '' entry_name = '' log = log or logger return eggloader . load_from_eggfile ( filename , entry_group , entry_name , log , observer ) @ staticmethod def load_from_eggpkg ( package , entry_name = None , instance_name = None , observer = None ) : \"\"\"\"\"\" entry_group = '' if not entry_name : entry_name = package return eggloader . load_from_eggpkg ( package , entry_group , entry_name , instance_name , logger , observer ) @ staticmethod def load ( instream , fmt = SAVE_CPICKLE , package = None , call_post_load = True , name = None ) : \"\"\"\"\"\" top = eggloader . load ( instream , fmt , package , logger ) top . cpath_updated ( ) if name : top . name = name if call_post_load : top . parent = None top . post_load ( ) return top def post_load ( self ) : \"\"\"\"\"\" self . _repair_traits ( ) for name in self . list_containers ( ) : getattr ( self , name ) . post_load ( ) @ rbac ( '' ) def pre_delete ( self ) : \"\"\"\"\"\" for name in self . list_containers ( ) : getattr ( self , name ) . pre_delete ( ) @ rbac ( ( '' , '' ) , proxy_types = [ CTrait ] ) def get_dyn_trait ( self , pathname , iotype = None , trait = None ) : \"\"\"\"\"\" if pathname . startswith ( '' ) : return None cname , _ , restofpath = pathname . partition ( '' ) if restofpath : child = getattr ( self , cname ) if is_instance ( child , Container ) : return child . get_dyn_trait ( restofpath , iotype , trait ) else : if deep_hasattr ( child , restofpath ) : return None else : trait = self . get_trait ( cname ) if trait is not None : if iotype is not None : if isinstance ( trait . trait_type , Python ) : obj = getattr ( self , cname ) t_iotype = getattr ( obj , '' , None ) else : t_iotype = self . get_iotype ( cname ) if ( iotype == '' and t_iotype not in ( '' , '' ) ) or ( iotype == '' and t_iotype not in ( '' , '' , '' , '' ) ) : self . raise_exception ( \"\" % ( pathname , _iodict [ iotype ] ) , RuntimeError ) return trait elif trait is None and self . contains ( cname ) : return None self . raise_exception ( \"\" % pathname , AttributeError ) @ rbac ( ( '' , '' ) ) def get_trait_typenames ( self , pathname , iotype = None ) : \"\"\"\"\"\" if not pathname : obj = self else : trait = self . get_dyn_trait ( pathname , iotype = iotype ) if trait is None : return [ ] trait = trait . trait_type or trait . trait or trait if trait . target : trait = self . get_dyn_trait ( trait . target ) try : ", "answer": "ttype = trait . trait_type"}, {"prompt": " '''''' import os import hashlib import pprint import collections from rekall_adapter . rekall_adapter import RekallAdapter class MemoryImageConnScan ( object ) : '''''' dependencies = [ '' ] def __init__ ( self ) : '''''' self . plugin_name = '' self . current_table_name = '' self . output = { '' : collections . defaultdict ( list ) } self . column_map = { } def execute ( self , input_data ) : '''''' adapter = RekallAdapter ( ) adapter . set_plugin_name ( self . plugin_name ) rekall_output = adapter . execute ( input_data ) for line in rekall_output : if line [ '' ] == '' : self . output [ '' ] = line [ '' ] elif line [ '' ] == '' : self . current_table_name = line [ '' ] [ '' ] [ ] elif line [ '' ] == '' : self . column_map = { item [ '' ] : item [ '' ] if '' in item else item [ '' ] for item in line [ '' ] } elif line [ '' ] == '' : row = RekallAdapter . process_row ( line [ '' ] , self . column_map ) self . output [ '' ] [ self . current_table_name ] . append ( row ) else : print '' % ( line [ '' ] , line [ '' ] ) return self . output import pytest @ pytest . mark . xfail def test ( ) : '''''' ", "answer": "import zerorpc"}, {"prompt": " import numpy as _np def normal ( std ) : def init ( shape , fan ) : ", "answer": "return std * _np . random . randn ( * shape )"}, {"prompt": " from __future__ import absolute_import from django . conf . urls import patterns ", "answer": "from . views import empty_view"}, {"prompt": " import requests import data def choose_mirror ( url_list ) : \"\"\"\"\"\" for url in url_list : print '' . format ( url ) status_code = check_connection ( url ) if status_code != and status_code != : print '' . format ( url ) return url else : '' . format ( str ( status_code ) ) return None def check_connection ( url ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import division from numpy import ( zeros , argmin , argwhere , take , sum as np_sum , any as np_any , abs as np_abs ) from numpy . linalg import norm from neupy . utils import format_data from neupy . core . properties import IntProperty from neupy . algorithms . gd import NoStepSelection from neupy . network . base import BaseNetwork from neupy . network . learning import UnsupervisedLearning __all__ = ( '' , ) class RBFKMeans ( NoStepSelection , UnsupervisedLearning , BaseNetwork ) : \"\"\"\"\"\" n_clusters = IntProperty ( minval = ) def __init__ ( self , ** options ) : self . centers = None super ( RBFKMeans , self ) . __init__ ( ** options ) def predict ( self , input_data ) : input_data = format_data ( input_data ) centers = self . centers classes = zeros ( ( input_data . shape [ ] , ) ) for i , value in enumerate ( input_data ) : classes [ i ] = argmin ( norm ( centers - value , axis = ) ) return classes def train_epoch ( self , input_train , target_train ) : centers = self . centers old_centers = centers . copy ( ) output_train = self . predict ( input_train ) for i , center in enumerate ( centers ) : positions = argwhere ( output_train [ : , ] == i ) if not np_any ( positions ) : continue class_data = take ( input_train , positions , axis = ) centers [ i , : ] = ( / len ( class_data ) ) * np_sum ( class_data , axis = ) ", "answer": "return np_abs ( old_centers - centers )"}, {"prompt": " import unittest from marmot . features . phrase . ne_feature_extractor import NEFeatureExtractor class AlphaNumericFeatureExtractorTests ( unittest . TestCase ) : def setUp ( self ) : self . extractor = NEFeatureExtractor ( ) def test_get_features ( self ) : obj = { '' : [ '' , '' , '' , '' , '' , '' , '' , '' ] , '' : [ '' , '' , '' , '' , '' , '' , '' , '' ] , '' : [ '' , '' , '' , '' , '' ] , '' : ( , ) , '' : [ '' , '' , '' , '' , '' ] , '' : ( , ) } ( src_ne , tg_ne ) = self . extractor . get_features ( obj ) self . assertEqual ( src_ne , ) self . assertEqual ( tg_ne , ) def test_get_features_no_src ( self ) : obj_no_src = { '' : [ '' , '' , '' , '' , '' , '' , '' , '' ] , '' : [ '' , '' , '' , '' , '' , '' , '' , '' ] , '' : [ '' , '' , '' , '' , '' ] , '' : ( , ) , '' : [ ] , '' : [ ] } ( src_ne , tg_ne ) = self . extractor . get_features ( obj_no_src ) self . assertEqual ( src_ne , ) self . assertEqual ( tg_ne , ) def test_get_features_no_NE ( self ) : obj_no_src = { '' : [ '' , '' , '' , '' , '' , '' , '' , '' ] , '' : [ '' , '' , '' , '' , '' , '' , '' , '' ] , '' : [ '' , '' , '' , '' , '' ] , '' : ( , ) , '' : [ ] , '' : [ ] } ( src_ne , tg_ne ) = self . extractor . get_features ( obj_no_src ) ", "answer": "self . assertEqual ( src_ne , )"}, {"prompt": " import unittest , os , sys ", "answer": "from custom_test_case import CustomTestCase"}, {"prompt": " \"\"\"\"\"\" from django . db import models from sortedm2m . fields import SortedManyToManyField class Target ( models . Model ) : pass class M2MToSortedM2M ( models . Model ) : \"\"\"\"\"\" m2m = SortedManyToManyField ( '' ) class SortedM2MToM2M ( models . Model ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " EOF = b'' def ttyflags ( fd ) : \"\"\"\"\"\" import termios as T attrs = T . tcgetattr ( fd ) attrs [ ] &= ~ T . OPOST attrs [ ] &= ~ T . ECHO T . tcsetattr ( fd , T . TCSANOW , attrs ) def readall ( fd ) : \"\"\"\"\"\" from os import read result = b'' while True : try : chunk = read ( fd , << ) except OSError as error : if error . errno == : return result else : raise if chunk == '' : return result else : result += chunk def _test ( fd ) : \"\"\"\"\"\" ttyflags ( fd ) from os import write assert write ( fd , b'' ) == ", "answer": "assert write ( fd , EOF * ) == "}, {"prompt": " \"\"\"\"\"\" import tempfile from googleads import dfp from googleads import errors ORDER_ID = '' def main ( client , order_id ) : line_item_service = client . GetService ( '' , version = '' ) report_downloader = client . GetDataDownloader ( version = '' ) values = [ { '' : '' , '' : { '' : '' , '' : order_id } } ] query = '' statement = dfp . FilterStatement ( query , values ) custom_field_ids = set ( ) while True : response = line_item_service . getLineItemsByStatement ( statement . ToStatement ( ) ) if '' in response : for line_item in response [ '' ] : if '' in line_item : for custom_field_value in line_item [ '' ] : custom_field_ids . add ( custom_field_value [ '' ] ) statement . offset += dfp . SUGGESTED_PAGE_LIMIT else : break ", "answer": "filter_statement = { '' : query , '' : values }"}, {"prompt": " from flask_appbuilder . security . views import UserDBModelView from flask_babelpkg import lazy_gettext class MyUserDBModelView ( UserDBModelView ) : \"\"\"\"\"\" show_fieldsets = [ ( lazy_gettext ( '' ) , { '' : [ '' , '' , '' , '' , '' , '' ] } ) , ( lazy_gettext ( '' ) , { '' : [ '' , '' , '' ] , '' : True } ) , ( lazy_gettext ( '' ) , { '' : [ '' , '' , '' , '' , '' , '' ] , '' : False } ) , ] user_show_fieldsets = [ ( lazy_gettext ( '' ) , { '' : [ '' , '' , '' , '' , '' , '' ] } ) , ( lazy_gettext ( '' ) , { '' : [ '' , '' , '' ] , '' : True } ) , ] add_columns = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ", "answer": "list_columns = [ '' , '' , '' , '' , '' , '' , '' , '' ]"}, {"prompt": " from libcloud . compute . types import Provider from libcloud . compute . providers import get_driver cls = get_driver ( Provider . CLOUDSIGMA ) ", "answer": "driver = cls ( '' , '' , region = '' , api_version = '' )"}, {"prompt": " \"\"\"\"\"\" from pyqode . qt import QtGui from pyqode . core . api import Mode , DelayJobRunner , TextHelper , TextDecoration from pyqode . core . backend import NotRunning from pyqode . core . backend . workers import findall class OccurrencesHighlighterMode ( Mode ) : \"\"\"\"\"\" @ property def delay ( self ) : \"\"\"\"\"\" return self . timer . delay @ delay . setter def delay ( self , value ) : self . timer . delay = value if self . editor : for clone in self . editor . clones : try : clone . modes . get ( self . __class__ ) . delay = value except KeyError : pass @ property def background ( self ) : \"\"\"\"\"\" return self . _background @ background . setter def background ( self , value ) : self . _background = value if self . editor : for clone in self . editor . clones : try : clone . modes . get ( self . __class__ ) . background = value except KeyError : pass @ property def foreground ( self ) : \"\"\"\"\"\" return self . _foreground @ foreground . setter def foreground ( self , value ) : self . _foreground = value if self . editor : for clone in self . editor . clones : try : clone . modes . get ( self . __class__ ) . foreground = value except KeyError : pass @ property def underlined ( self ) : \"\"\"\"\"\" return self . _underlined @ underlined . setter def underlined ( self , value ) : self . _underlined = value if self . editor : for clone in self . editor . clones : try : clone . modes . get ( self . __class__ ) . underlined = value except KeyError : pass def __init__ ( self ) : super ( OccurrencesHighlighterMode , self ) . __init__ ( ) self . _decorations = [ ] self . timer = DelayJobRunner ( delay = ) self . _sub = None self . _background = QtGui . QColor ( '' ) self . _foreground = None self . _underlined = False def on_state_changed ( self , state ) : if state : self . editor . cursorPositionChanged . connect ( self . _request_highlight ) else : self . editor . cursorPositionChanged . disconnect ( self . _request_highlight ) self . timer . cancel_requests ( ) def _clear_decos ( self ) : for d in self . _decorations : self . editor . decorations . remove ( d ) self . _decorations [ : ] = [ ] def _request_highlight ( self ) : if self . editor is not None : sub = TextHelper ( self . editor ) . word_under_cursor ( select_whole_word = True ) . selectedText ( ) if sub != self . _sub : self . _clear_decos ( ) if len ( sub ) > : self . timer . request_job ( self . _send_request ) def _send_request ( self ) : if self . editor is None : return cursor = self . editor . textCursor ( ) self . _sub = TextHelper ( self . editor ) . word_under_cursor ( select_whole_word = True ) . selectedText ( ) if not cursor . hasSelection ( ) or cursor . selectedText ( ) == self . _sub : request_data = { ", "answer": "'' : self . editor . toPlainText ( ) ,"}, {"prompt": " \"\"\"\"\"\" from django . db import models from django . contrib . auth . models import User class Minisite ( models . Model ) : key = models . AutoField ( primary_key = True ) name = models . CharField ( max_length = , verbose_name = '' ) slug = models . CharField ( unique = True , max_length = , verbose_name = '' ) meta = models . TextField ( blank = True , verbose_name = '' ) description = models . TextField ( blank = True , verbose_name = '' ) ", "answer": "author = models . ForeignKey ( User , verbose_name = '' )"}, {"prompt": " import cStringIO import csv import codecs import decimal import datetime import json import random import re import hashlib import pytz import pystache from funcy import distinct from . human_time import parse_human_time from redash import settings COMMENTS_REGEX = re . compile ( \"\" ) def utcnow ( ) : \"\"\"\"\"\" return datetime . datetime . now ( pytz . utc ) def slugify ( s ) : return re . sub ( '' , '' , s . lower ( ) ) def gen_query_hash ( sql ) : \"\"\"\"\"\" sql = COMMENTS_REGEX . sub ( \"\" , sql ) sql = \"\" . join ( sql . split ( ) ) . lower ( ) return hashlib . md5 ( sql . encode ( '' ) ) . hexdigest ( ) def generate_token ( length ) : chars = ( '' '' '' ) rand = random . SystemRandom ( ) return '' . join ( rand . choice ( chars ) for x in range ( length ) ) class JSONEncoder ( json . JSONEncoder ) : \"\"\"\"\"\" def default ( self , o ) : if isinstance ( o , decimal . Decimal ) : return float ( o ) if isinstance ( o , ( datetime . date , datetime . time ) ) : return o . isoformat ( ) if isinstance ( o , datetime . timedelta ) : return str ( o ) super ( JSONEncoder , self ) . default ( o ) def json_dumps ( data ) : return json . dumps ( data , cls = JSONEncoder ) def build_url ( request , host , path ) : parts = request . host . split ( '' ) if len ( parts ) > : port = parts [ ] if ( port , request . scheme ) not in ( ( '' , '' ) , ( '' , '' ) ) : host = '' . format ( host , port ) return \"\" . format ( request . scheme , host , path ) class UnicodeWriter : \"\"\"\"\"\" def __init__ ( self , f , dialect = csv . excel , encoding = \"\" , ** kwds ) : self . queue = cStringIO . StringIO ( ) self . writer = csv . writer ( self . queue , dialect = dialect , ** kwds ) self . stream = f self . encoder = codecs . getincrementalencoder ( encoding ) ( ) def _encode_utf8 ( self , val ) : if isinstance ( val , ( unicode , str ) ) : return val . encode ( '' ) return val def writerow ( self , row ) : self . writer . writerow ( [ self . _encode_utf8 ( s ) for s in row ] ) data = self . queue . getvalue ( ) data = data . decode ( \"\" ) data = self . encoder . encode ( data ) self . stream . write ( data ) self . queue . truncate ( ) def writerows ( self , rows ) : for row in rows : ", "answer": "self . writerow ( row )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function from OpenSSL import crypto from certgen import ( createKeyPair , createCertRequest , createCertificate , ) cakey = createKeyPair ( crypto . TYPE_RSA , ) careq = createCertRequest ( cakey , CN = '' ) cacert = createCertificate ( careq , ( careq , cakey ) , , ( , * * * * ) ) print ( '' ) with open ( '' , '' ) as capkey : capkey . write ( crypto . dump_privatekey ( crypto . FILETYPE_PEM , cakey ) . decode ( '' ) ) print ( '' ) with open ( '' , '' ) as ca : ca . write ( crypto . dump_certificate ( crypto . FILETYPE_PEM , cacert ) . decode ( '' ) ) for ( fname , cname ) in [ ( '' , '' ) , ( '' , '' ) ] : pkey = createKeyPair ( crypto . TYPE_RSA , ) req = createCertRequest ( pkey , CN = cname ) cert = createCertificate ( req , ( cacert , cakey ) , , ( , * * * * ) ) print ( '' % ( fname , fname ) ) with open ( '' % ( fname , ) , '' ) as leafpkey : leafpkey . write ( crypto . dump_privatekey ( crypto . FILETYPE_PEM , pkey ) . decode ( '' ) ", "answer": ")"}, {"prompt": " import decimal import os from contextlib import contextmanager from django . test import TestCase from django . core . exceptions import ImproperlyConfigured from mock import patch from configurations . values import ( Value , BooleanValue , IntegerValue , FloatValue , DecimalValue , ListValue , TupleValue , SingleNestedTupleValue , SingleNestedListValue , SetValue , DictValue , URLValue , EmailValue , IPValue , RegexValue , PathValue , SecretValue , DatabaseURLValue , EmailURLValue , CacheURLValue , BackendsValue , CastingMixin , SearchURLValue , setup_value ) @ contextmanager def env ( ** kwargs ) : with patch . dict ( os . environ , clear = True , ** kwargs ) : yield class FailingCasterValue ( CastingMixin , Value ) : caster = '' class ValueTests ( TestCase ) : def test_value_with_default ( self ) : value = Value ( '' , environ = False ) self . assertEqual ( type ( value ) , type ( '' ) ) self . assertEqual ( value , '' ) self . assertEqual ( str ( value ) , '' ) def test_value_with_default_and_late_binding ( self ) : value = Value ( '' , environ = False , late_binding = True ) self . assertEqual ( type ( value ) , Value ) with env ( DJANGO_TEST = '' ) : self . assertEqual ( value . setup ( '' ) , '' ) value = Value ( environ_name = '' ) self . assertEqual ( type ( value ) , type ( '' ) ) self . assertEqual ( value , '' ) self . assertEqual ( str ( value ) , '' ) self . assertEqual ( '' . format ( value ) , '' ) self . assertEqual ( '' % value , '' ) value = Value ( environ_name = '' , late_binding = True ) self . assertEqual ( type ( value ) , Value ) self . assertEqual ( value . value , '' ) self . assertEqual ( str ( value ) , '' ) self . assertEqual ( '' . format ( value ) , '' ) self . assertEqual ( '' % value , '' ) self . assertEqual ( repr ( value ) , repr ( '' ) ) @ patch . dict ( os . environ , clear = True , DJANGO_TEST = '' ) def test_env_var ( self ) : value = Value ( '' ) self . assertEqual ( value . setup ( '' ) , '' ) self . assertEqual ( str ( value ) , '' ) self . assertNotEqual ( value . setup ( '' ) , value . default ) self . assertEqual ( value . to_python ( os . environ [ '' ] ) , value . setup ( '' ) ) def test_value_reuse ( self ) : value1 = Value ( '' ) value2 = Value ( value1 ) self . assertEqual ( value1 . setup ( '' ) , '' ) self . assertEqual ( value2 . setup ( '' ) , '' ) with env ( DJANGO_TEST1 = '' , DJANGO_TEST2 = '' ) : self . assertEqual ( value1 . setup ( '' ) , '' ) self . assertEqual ( value2 . setup ( '' ) , '' ) def test_value_var_equal ( self ) : value1 = Value ( '' ) value2 = Value ( '' ) self . assertEqual ( value1 , value2 ) self . assertTrue ( value1 in [ '' ] ) def test_env_var_prefix ( self ) : with patch . dict ( os . environ , clear = True , ACME_TEST = '' ) : value = Value ( '' , environ_prefix = '' ) self . assertEqual ( value . setup ( '' ) , '' ) with patch . dict ( os . environ , clear = True , TEST = '' ) : value = Value ( '' , environ_prefix = '' ) self . assertEqual ( value . setup ( '' ) , '' ) with patch . dict ( os . environ , clear = True , ACME_TEST = '' ) : value = Value ( '' , environ_prefix = '' ) self . assertEqual ( value . setup ( '' ) , '' ) def test_boolean_values_true ( self ) : value = BooleanValue ( False ) for truthy in value . true_values : with env ( DJANGO_TEST = truthy ) : self . assertTrue ( value . setup ( '' ) ) def test_boolean_values_faulty ( self ) : self . assertRaises ( ValueError , BooleanValue , '' ) def test_boolean_values_false ( self ) : value = BooleanValue ( True ) for falsy in value . false_values : with env ( DJANGO_TEST = falsy ) : self . assertFalse ( value . setup ( '' ) ) def test_boolean_values_nonboolean ( self ) : value = BooleanValue ( True ) with env ( DJANGO_TEST = '' ) : self . assertRaises ( ValueError , value . setup , '' ) def test_boolean_values_assign_false_to_another_booleanvalue ( self ) : value1 = BooleanValue ( False ) value2 = BooleanValue ( value1 ) self . assertFalse ( value1 . setup ( '' ) ) self . assertFalse ( value2 . setup ( '' ) ) def test_integer_values ( self ) : value = IntegerValue ( ) with env ( DJANGO_TEST = '' ) : self . assertEqual ( value . setup ( '' ) , ) with env ( DJANGO_TEST = '' ) : ", "answer": "self . assertRaises ( ValueError , value . setup , '' )"}, {"prompt": " import RPi . GPIO as io class GPIOPin ( object ) : def __init__ ( self , pin_number , mode = io . BCM , in_out = io . OUT ) : \"\"\"\"\"\" self . pin_number = pin_number self . range = ( , ) io . setmode ( mode ) io . setup ( pin_number , in_out ) io . output ( self . pin_number , io . LOW ) def set ( self , value ) : \"\"\"\"\"\" io . output ( self . pin_number , value ) def set_normalized ( self , value ) : if value >= : ", "answer": "self . set ( )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) ", "answer": "result . template = \"\""}, {"prompt": " import setuptools ", "answer": "setuptools . setup ("}, {"prompt": " from django . core . management . base import NoArgsCommand ", "answer": "from ella . core . management import generate_publish_signals"}, {"prompt": " import copy import mock import random import uuid from openstackclient . common import utils as common_utils from openstackclient . tests import fakes from openstackclient . tests import utils from openstackclient . tests . identity . v3 import fakes as identity_fakes image_id = '' image_name = '' image_owner = '' image_protected = False image_visibility = '' image_tags = [ ] IMAGE = { '' : image_id , '' : image_name , '' : image_owner , '' : image_protected , '' : image_visibility , '' : image_tags } IMAGE_columns = tuple ( sorted ( IMAGE ) ) IMAGE_data = tuple ( ( IMAGE [ x ] for x in sorted ( IMAGE ) ) ) IMAGE_SHOW = copy . copy ( IMAGE ) IMAGE_SHOW [ '' ] = '' IMAGE_SHOW_data = tuple ( ( IMAGE_SHOW [ x ] for x in sorted ( IMAGE_SHOW ) ) ) member_status = '' MEMBER = { '' : identity_fakes . project_id , '' : image_id , '' : member_status , } IMAGE_schema = { \"\" : { \"\" : \"\" } , \"\" : \"\" , \"\" : [ { \"\" : \"\" , \"\" : \"\" } , { \"\" : \"\" , \"\" : \"\" } , { \"\" : \"\" , \"\" : \"\" } ] , \"\" : { \"\" : { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } , \"\" : { \"\" : [ ", "answer": "\"\" ,"}, {"prompt": " import IECore import Gaffer import GafferUI class NameLabel ( GafferUI . Label ) : def __init__ ( self , graphComponent , horizontalAlignment = GafferUI . Label . HorizontalAlignment . Left , verticalAlignment = GafferUI . Label . VerticalAlignment . Center , numComponents = , formatter = None , parenting = None ) : GafferUI . Label . __init__ ( self , \"\" , horizontalAlignment , verticalAlignment , parenting = parenting ) self . __formatter = formatter if formatter is not None else self . defaultFormatter self . __numComponents = numComponents self . __connections = [ ] self . __graphComponent = False self . setGraphComponent ( graphComponent ) self . __buttonPressConnection = self . buttonPressSignal ( ) . connect ( Gaffer . WeakMethod ( self . __buttonPress ) ) self . __dragBeginConnection = self . dragBeginSignal ( ) . connect ( Gaffer . WeakMethod ( self . __dragBegin ) ) self . __dragEndConnection = self . dragEndSignal ( ) . connect ( Gaffer . WeakMethod ( self . __dragEnd ) ) def setText ( self , text ) : GafferUI . Label . setText ( self , text ) self . __connections = [ ] def setGraphComponent ( self , graphComponent ) : if graphComponent is not None and self . __graphComponent is not False : if graphComponent . isSame ( self . __graphComponent ) : return elif self . __graphComponent is None : return self . __graphComponent = graphComponent self . __setupConnections ( ) self . __setText ( ) def getGraphComponent ( self ) : return self . __graphComponent def setNumComponents ( self , numComponents ) : assert ( numComponents > ) if numComponents == self . __numComponents : return self . __numComponents = numComponents self . __setupConnections ( ) self . __setText ( ) def getNumComponents ( self ) : return self . __numComponents def setFormatter ( self , formatter ) : self . __formatter = formatter self . __setText ( ) def getFormatter ( self ) : return self . __formatter @ staticmethod ", "answer": "def defaultFormatter ( graphComponents ) :"}, {"prompt": " '''''' import logging import os from mc_states import saltapi from mc_states . grains . makina_grains import _is_docker _errmsg = saltapi . _errmsg __name = '' log = logging . getLogger ( __name__ ) VT = '' PREFIX = '' . format ( VT ) def vt ( ) : return __salt__ [ '' ] ( VT ) def is_docker ( ) : \"\"\"\"\"\" return _is_docker ( ) def vt_default_settings ( cloudSettings , imgSettings ) : '''''' _s = __salt__ vmSettings = _s [ '' ] ( _s [ '' ] ( cloudSettings , imgSettings ) , { '' : VT , '' : \"\" , '' : { '' : { \"\" : \"\" } , '' : { \"\" : \"\" } , '' : { \"\" : \"\" } , '' : { } , '' : { } , '' : { ", "answer": "'' :"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division , print_function , with_statement , unicode_literals import oz oz . options ( debug = dict ( type = bool , default = False , help = \"\" ) , ", "answer": "port = dict ( type = int , default = , help = \"\" ) ,"}, {"prompt": " \"\"\"\"\"\" class Connection ( object ) : def send ( self , data ) : return def recv ( self , size = ** ) : return def settimeout ( self , timeout ) : return def isalive ( self ) : return def shutdown ( self ) : return def close ( self ) : return class Client ( Connection ) : def __init__ ( self , address = None , timeout = None ) : self . address = address def open ( self ) : return class Server ( object ) : def __init__ ( self , address = None , timeout = None ) : self . address = address def open ( self ) : return def accept ( self ) : return def settimeout ( self ) : return def isalive ( self ) : return def shutdown ( self ) : return def close ( self ) : return class Socket ( object ) : name = None ", "answer": "available = False"}, {"prompt": " from __future__ import absolute_import import logging from django . conf import settings from django . utils . functional import cached_property from django . utils . translation import ugettext_lazy as _ import six from novaclient import client as nova_client from novaclient import exceptions as nova_exceptions from novaclient . v2 . contrib import instance_action as nova_instance_action from novaclient . v2 . contrib import list_extensions as nova_list_extensions from novaclient . v2 import security_group_rules as nova_rules from novaclient . v2 import security_groups as nova_security_groups from novaclient . v2 import servers as nova_servers from horizon import conf from horizon import exceptions as horizon_exceptions from horizon . utils import functions as utils from horizon . utils . memoized import memoized from openstack_dashboard . api import base from openstack_dashboard . api import network_base LOG = logging . getLogger ( __name__ ) VERSIONS = base . APIVersionManager ( \"\" , preferred_version = ) VERSIONS . load_supported_version ( , { \"\" : nova_client , \"\" : } ) VERSIONS . load_supported_version ( , { \"\" : nova_client , \"\" : } ) INSTANCE_ACTIVE_STATE = '' VOLUME_STATE_AVAILABLE = \"\" DEFAULT_QUOTA_NAME = '' class VNCConsole ( base . APIDictWrapper ) : \"\"\"\"\"\" _attrs = [ '' , '' ] class SPICEConsole ( base . APIDictWrapper ) : \"\"\"\"\"\" _attrs = [ '' , '' ] class RDPConsole ( base . APIDictWrapper ) : \"\"\"\"\"\" _attrs = [ '' , '' ] class SerialConsole ( base . APIDictWrapper ) : \"\"\"\"\"\" _attrs = [ '' , '' ] class Server ( base . APIResourceWrapper ) : \"\"\"\"\"\" _attrs = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] def __init__ ( self , apiresource , request ) : super ( Server , self ) . __init__ ( apiresource ) self . request = request @ property def image_name ( self ) : import glanceclient . exc as glance_exceptions from openstack_dashboard . api import glance if not self . image : return _ ( \"\" ) if hasattr ( self . image , '' ) : return self . image . name if '' in self . image : return self . image [ '' ] else : try : image = glance . image_get ( self . request , self . image [ '' ] ) return image . name except ( glance_exceptions . ClientException , horizon_exceptions . ServiceCatalogException ) : return _ ( \"\" ) @ property def internal_name ( self ) : return getattr ( self , '' , \"\" ) @ property def availability_zone ( self ) : return getattr ( self , '' , \"\" ) @ property def host_server ( self ) : return getattr ( self , '' , '' ) class Hypervisor ( base . APIDictWrapper ) : \"\"\"\"\"\" _attrs = [ '' , '' , '' , '' , '' , '' ] @ property def servers ( self ) : servers = [ ] try : servers = self . _apidict . servers except Exception : pass return servers class NovaUsage ( base . APIResourceWrapper ) : \"\"\"\"\"\" _attrs = [ '' , '' , '' , '' , '' , '' , '' , '' ] def get_summary ( self ) : ", "answer": "return { '' : self . total_active_instances ,"}, {"prompt": " from gwt . Canvas . ImageLoader import ( DOM , Event , Image , ", "answer": "ImageLoader ,"}, {"prompt": " class Solution : ", "answer": "def containsDuplicate ( self , nums ) :"}, {"prompt": " \"\"\"\"\"\" import re from abusehelper . core import bot from . import host_or_ip , resolve_level , split_description , AbuseCHFeedBot ", "answer": "class ZeusCcBot ( AbuseCHFeedBot ) :"}, {"prompt": " from south . db import db from south . v2 import SchemaMigration class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( default = ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( '' , '' ) models = { '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) ", "answer": "} ,"}, {"prompt": " import sys ", "answer": "from . runner import main"}, {"prompt": " import sys , os , re , tarfile , json FILES = { '' , '' , '' , '' , '' , '' , '' , } WS_SPLIT = re . compile ( \"\" ) def lines ( fn ) : with tarfile . open ( fn , '' ) as tar : for info in tar : if not info . isfile ( ) or info . name not in FILES : continue f = tar . extractfile ( info ) for ln in f : ln = ln . rstrip ( ) ln = ln . split ( '' , ) [ ] ln = ln . rstrip ( '' ) if ln : yield ln . decode ( '' ) f . close ( ) def offset ( s ) : if s in { '' , '' } : return dir , s = ( - , s [ : ] ) if s [ ] == '' else ( , s ) words = [ int ( n ) for n in s . split ( '' ) ] assert <= len ( words ) < , words words = words + [ ] * ( - len ( words ) ) assert <= words [ ] < , words assert <= words [ ] < , words assert <= words [ ] < , words return dir * sum ( ( i * num ) for ( i , num ) in zip ( words , ( , , ) ) ) def zoneline ( ls ) : ls [ ] = None if ls [ ] == '' else ls [ ] tmp = offset ( ls [ ] ) , ls [ ] , ls [ ] , ls [ : ] return { k : v for ( k , v ) in zip ( '' , tmp ) } def parse ( fn ) : zones , rules , zone = { } , { } , None for ln in lines ( fn ) : words = WS_SPLIT . split ( ln ) if words [ ] == '' : assert words [ ] not in zones , words [ ] zone = [ ] zone . append ( zoneline ( words [ : ] ) ) if '' in words [ ] : zones [ words [ ] ] = zone elif words [ ] == '' : ", "answer": "assert zone is not None"}, {"prompt": " \"\"\"\"\"\" from grr . lib import config_lib config_lib . DEFINE_constant_string ( \"\" , \"\" , \"\" ) config_lib . DEFINE_constant_string ( \"\" , default = \"\" , help = \"\" ) config_lib . DEFINE_constant_string ( \"\" , default = \"\" , help = \"\" ) config_lib . DEFINE_string ( \"\" , \"\" , help = \"\" ) config_lib . DEFINE_string ( \"\" , \"\" , \"\" ) config_lib . DEFINE_integer ( \"\" , , \"\" ) config_lib . DEFINE_list ( \"\" , [ ] , \"\" \"\" \"\" ) ", "answer": "config_lib . DEFINE_list ( \"\" , [ ] ,"}, {"prompt": " import os import time from datetime import datetime from celery import Celery celery = Celery ( \"\" , broker = \"\" ) celery . conf . CELERY_RESULT_BACKEND = os . environ . get ( '' , '' ) @ celery . task def add ( x , y ) : return int ( x ) + int ( y ) @ celery . task def sleep ( seconds ) : time . sleep ( float ( seconds ) ) return seconds @ celery . task def echo ( msg , timestamp = False ) : return \"\" % ( datetime . now ( ) , msg ) if timestamp else msg @ celery . task def error ( msg ) : ", "answer": "raise Exception ( msg )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " \"\" from . import pytree from . pgen2 import grammar , token from . pygram import pattern_symbols , python_symbols syms = pattern_symbols pysyms = python_symbols tokens = grammar . opmap token_labels = token TYPE_ANY = - TYPE_ALTERNATIVES = - TYPE_GROUP = - class MinNode ( object ) : \"\"\"\"\"\" def __init__ ( self , type = None , name = None ) : self . type = type self . name = name self . children = [ ] self . leaf = False self . parent = None self . alternatives = [ ] self . group = [ ] def __repr__ ( self ) : return str ( self . type ) + '' + str ( self . name ) def leaf_to_root ( self ) : \"\"\"\"\"\" node = self subp = [ ] while node : if node . type == TYPE_ALTERNATIVES : node . alternatives . append ( subp ) if len ( node . alternatives ) == len ( node . children ) : subp = [ tuple ( node . alternatives ) ] node . alternatives = [ ] node = node . parent continue else : node = node . parent subp = None break if node . type == TYPE_GROUP : node . group . append ( subp ) if len ( node . group ) == len ( node . children ) : subp = get_characteristic_subpattern ( node . group ) node . group = [ ] node = node . parent continue else : node = node . parent subp = None break if node . type == token_labels . NAME and node . name : subp . append ( node . name ) else : subp . append ( node . type ) node = node . parent return subp def get_linear_subpattern ( self ) : \"\"\"\"\"\" for l in self . leaves ( ) : subp = l . leaf_to_root ( ) if subp : return subp def leaves ( self ) : \"\" for child in self . children : for x in child . leaves ( ) : yield x if not self . children : yield self def reduce_tree ( node , parent = None ) : \"\"\"\"\"\" new_node = None if node . type == syms . Matcher : node = node . children [ ] if node . type == syms . Alternatives : if len ( node . children ) <= : new_node = reduce_tree ( node . children [ ] , parent ) else : new_node = MinNode ( type = TYPE_ALTERNATIVES ) for child in node . children : if node . children . index ( child ) % : continue reduced = reduce_tree ( child , new_node ) if reduced is not None : new_node . children . append ( reduced ) elif node . type == syms . Alternative : if len ( node . children ) > : new_node = MinNode ( type = TYPE_GROUP ) for child in node . children : reduced = reduce_tree ( child , new_node ) ", "answer": "if reduced :"}, {"prompt": " \"\"\"\"\"\" import logging import re , os , urllib logger = logging . getLogger ( __name__ ) class dataset_resolver : class package_info : \"\"\"\"\"\" def __init__ ( self , cf , name , ts , rs , src , whr ) : self . configuration_file = cf self . name = name self . timestamp = int ( ts ) self . readable_size = rs self . source = src self . where = whr installed_packages_list = { } def read_installed_packages_list ( self , from_location ) : \"\"\"\"\"\" try : installed_list_file = open ( from_location + \"\" ) except IOError : pass else : for line in installed_list_file : l = line . rstrip ( ) . split ( '' ) if l : self . installed_packages_list [ l [ ] ] = this_package = self . package_info ( from_location , l [ ] , l [ ] , l [ ] , urllib . unquote ( l [ ] ) , urllib . unquote ( l [ ] ) ) else : pass def resolve_dataset ( self , dataset_name ) : \"\"\"\"\"\" if dataset_name in self . installed_packages_list : ", "answer": "return os . path . join ( self . installed_packages_list [ dataset_name ] . where ,"}, {"prompt": " import sublime from . base import DeleteBaseCommand class IndicesDeleteAliasCommand ( DeleteBaseCommand ) : command_name = \"\" def is_enabled ( self ) : return True def run_request ( self , index = None , name = None ) : if not index or not name : self . show_alias_list_panel ( self . run ) return options = dict ( index = index , name = name ) if sublime . ok_cancel_dialog ( \"\" , ok_title = '' ) : ", "answer": "return self . client . indices . delete_alias ( ** options ) "}, {"prompt": " __author__ = '' import datetime import imutils import time import cv2 import numpy import os import multiprocessing from cerebrum . vision . utilities import VisionMemoryUtil import random import Tkinter STABILIZATION_DETECTION = NON_STATIONARY_PERCENTAGE = NON_ZERO_PERCENTAGE = TARGET_HEIGHT = MIN_AREA = root = Tkinter . Tk ( ) SCREEN_WIDTH = root . winfo_screenwidth ( ) SCREEN_HEIGHT = root . winfo_screenheight ( ) class VisionPerception ( ) : @ staticmethod def start ( video_input , vision_perception_stimulated ) : if video_input == \"\" : camera = cv2 . VideoCapture ( ) time . sleep ( ) else : time . sleep ( ) camera = cv2 . VideoCapture ( video_input ) referenceFrame = None starting_time = None memory_data_thresh = [ ] memory_data_frameDeltaColored = [ ] ( grabbed , first_frame ) = camera . read ( ) height , width = first_frame . shape [ : ] if float ( width ) / float ( height ) != float ( ) / float ( ) : if video_input == \"\" : pass else : raise ValueError ( '' ) frame_counter = motion_detected = delta_value_stack = [ ] non_stationary_camera = motion_counter = nonzero_toolow = beginning_of_stream = datetime . datetime . now ( ) while True : ( grabbed , frame ) = camera . read ( ) if not grabbed : break frame_counter += if video_input == \"\" : pass else : time_delta = datetime . datetime . now ( ) - beginning_of_stream current_time_of_realworld = time_delta . seconds + time_delta . microseconds / float ( ) current_time_of_stream = frame_counter / camera . get ( cv2 . cv . CV_CAP_PROP_FPS ) diff_of_time = current_time_of_stream - current_time_of_realworld if abs ( diff_of_time ) > ( / camera . get ( cv2 . cv . CV_CAP_PROP_FPS ) ) : if diff_of_time > : time . sleep ( / camera . get ( cv2 . cv . CV_CAP_PROP_FPS ) ) else : ( grabbed , frame ) = camera . read ( ) if not grabbed : break frame_counter += continue delta_value = frame = imutils . resize ( frame , height = TARGET_HEIGHT ) height , width = frame . shape [ : ] gray = cv2 . cvtColor ( frame , cv2 . COLOR_BGR2GRAY ) gray = cv2 . bilateralFilter ( gray , , , ) if referenceFrame is None : referenceFrame = gray continue frameDelta = cv2 . absdiff ( referenceFrame , gray ) thresh = cv2 . threshold ( frameDelta , , , cv2 . THRESH_BINARY ) [ ] thresh = cv2 . dilate ( thresh , None , iterations = ) frameDeltaColored = cv2 . bitwise_and ( frame , frame , mask = thresh ) ( cnts , _ ) = cv2 . findContours ( thresh . copy ( ) , cv2 . RETR_EXTERNAL , cv2 . CHAIN_APPROX_SIMPLE ) contour_area_stack = [ ] if cnts : for c in cnts : contour_area_stack . append ( cv2 . contourArea ( c ) ) if cv2 . contourArea ( c ) > MIN_AREA : ( x , y , w , h ) = cv2 . boundingRect ( c ) cv2 . rectangle ( frame , ( x , y ) , ( x + w , y + h ) , ( , , ) , ) delta_value = max ( contour_area_stack ) if delta_value > MIN_AREA : motion_detected = if delta_value > ( height * width * float ( NON_STATIONARY_PERCENTAGE ) / float ( ) ) : ", "answer": "non_stationary_camera = "}, {"prompt": " import pytest from pushkin import pushkin_cli import tornado . web from pushkin import context from pushkin . database import database from pushkin . request . request_processor import RequestProcessor from pushkin . requesthandlers . events import JsonEventHandler from pushkin . requesthandlers . notifications import JsonNotificationHandler from pushkin import test_config_ini_path from pushkin import config @ pytest . fixture def setup_database ( ) : database . create_database ( ) @ pytest . fixture def mock_processor ( mocker ) : '''''' mocker . patch ( '' ) mocker . patch ( '' ) @ pytest . fixture def app ( ) : pushkin_cli . CONFIGURATION_FILENAME = test_config_ini_path pushkin_cli . init ( ) return pushkin_cli . create_app ( ) @ pytest . fixture def notification_batch_json ( ) : '''''' return '''''' @ pytest . fixture def post_notification_url ( base_url ) : return base_url + config . json_notification_handler_url @ pytest . fixture def event_batch_json ( ) : '''''' return '''''' @ pytest . fixture def post_event_url ( base_url ) : return base_url + config . json_event_handler_url @ pytest . mark . gen_test @ pytest . mark . parametrize ( \"\" , [ ( '' ) , ( '' ) , ] ) def test_post_notification_empty_request ( setup_database , mock_processor , http_client , post_notification_url , input ) : '''''' request = tornado . httpclient . HTTPRequest ( post_notification_url , method = '' , body = input ) with pytest . raises ( tornado . httpclient . HTTPError ) : yield http_client . fetch ( request ) assert not context . request_processor . submit . called @ pytest . mark . gen_test def test_post_notification ( setup_database , mock_processor , http_client , post_notification_url , notification_batch_json ) : '''''' request = tornado . httpclient . HTTPRequest ( post_notification_url , method = '' , body = notification_batch_json ) response = yield http_client . fetch ( request ) assert response . code == assert context . request_processor . submit . called @ pytest . mark . gen_test @ pytest . mark . parametrize ( \"\" , [ ( '' ) , ( '' ) , ", "answer": "] )"}, {"prompt": " \"\"\"\"\"\" import importlib import os import pdb import time from django import http from django import shortcuts from django import template from django . views . decorators import csrf import psutil import logging from grr . gui import http_api from grr . gui import renderers from grr . gui import urls from grr . gui import webauth from grr . lib import access_control from grr . lib import aff4 from grr . lib import config_lib from grr . lib import flags from grr . lib import rdfvalue from grr . lib import registry from grr . lib import stats class ViewsInit ( registry . InitHook ) : def RunOnce ( self ) : \"\"\"\"\"\" stats . STATS . RegisterEventMetric ( \"\" , fields = [ ( \"\" , str ) ] ) stats . STATS . RegisterEventMetric ( \"\" , fields = [ ( \"\" , str ) ] , units = stats . MetricUnits . BYTES ) stats . STATS . RegisterCounterMetric ( \"\" , fields = [ ( \"\" , str ) ] ) stats . STATS . RegisterCounterMetric ( \"\" ) stats . STATS . RegisterCounterMetric ( \"\" ) stats . STATS . RegisterCounterMetric ( \"\" ) @ webauth . SecurityCheck @ csrf . ensure_csrf_cookie def Homepage ( request ) : \"\"\"\"\"\" renderers_js_files = set ( [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] ) create_time = psutil . Process ( os . getpid ( ) ) . create_time ( ) context = { \"\" : config_lib . CONFIG [ \"\" ] , \"\" : config_lib . CONFIG [ \"\" ] , \"\" : config_lib . CONFIG [ \"\" ] , \"\" : config_lib . CONFIG [ \"\" ] , \"\" : config_lib . CONFIG [ \"\" ] , \"\" : renderers_js_files , \"\" : create_time } return shortcuts . render_to_response ( \"\" , context , context_instance = template . RequestContext ( request ) ) @ webauth . SecurityCheck def RenderBinaryDownload ( request ) : \"\"\"\"\"\" path , filename = request . path . split ( \"\" , ) [ - ] . rsplit ( \"\" , ) if not path or not filename : return AccessDenied ( \"\" ) request . REQ = request . REQUEST def Generator ( ) : with aff4 . FACTORY . Open ( aff4_path , aff4_type = \"\" , token = BuildToken ( request , ) ) as fd : while True : data = fd . Read ( ) if not data : break yield data base_path = rdfvalue . RDFURN ( \"\" ) aff4_path = base_path . Add ( path ) . Add ( filename ) if not aff4_path . RelativeName ( base_path ) : return AccessDenied ( \"\" ) filename = aff4_path . Basename ( ) response = http . StreamingHttpResponse ( streaming_content = Generator ( ) , content_type = \"\" ) response [ \"\" ] = ( \"\" % filename ) return response @ webauth . SecurityCheck @ renderers . ErrorHandler ( ) def RenderApi ( request ) : \"\"\"\"\"\" return http_api . RenderHttpResponse ( request ) @ webauth . SecurityCheck @ renderers . ErrorHandler ( ) def RenderGenericRenderer ( request ) : \"\"\"\"\"\" try : action , renderer_name = request . path . split ( \"\" ) [ - : ] renderer_cls = renderers . Renderer . GetPlugin ( name = renderer_name ) except KeyError : stats . STATS . IncrementCounter ( \"\" ) return AccessDenied ( \"\" % renderer_name ) [ \"\" , \"\" , \"\" , \"\" ] . index ( action ) renderer = renderer_cls ( ) result = http . HttpResponse ( content_type = \"\" ) if flags . FLAGS . debug : request . REQ = request . POST . dict ( ) request . REQ . update ( request . GET . dict ( ) ) else : request . REQ = request . POST . dict ( ) request . token = BuildToken ( request , renderer . max_execution_time ) request . canary_mode = \"\" in request . COOKIES renderer . CheckAccess ( request ) try : method = getattr ( renderer , action ) start_time = time . time ( ) try : result = method ( request , result ) or result finally : total_time = time . time ( ) - start_time stats . STATS . RecordEvent ( \"\" , total_time , fields = [ renderer_name ] ) except access_control . UnauthorizedAccess , e : result = http . HttpResponse ( content_type = \"\" ) result = renderers . Renderer . GetPlugin ( \"\" ) ( ) . Layout ( request , result , exception = e ) except Exception : stats . STATS . IncrementCounter ( \"\" , fields = [ renderer_name ] ) if flags . FLAGS . debug : pdb . post_mortem ( ) raise if not isinstance ( result , ( http . HttpResponse , http . StreamingHttpResponse ) ) : raise RuntimeError ( \"\" % result ) return result def RedirectToRemoteHelp ( path ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" revision = '' down_revision = '' from alembic import op from oslo_serialization import jsonutils import sqlalchemy as sa from sqlalchemy . dialects import postgresql from nailgun import consts from nailgun . db . sqlalchemy . models import fields from nailgun . utils . migration import drop_enum from nailgun . utils . migration import upgrade_enum release_states_old = ( '' , '' , ) release_states_new = ( '' , '' , '' , ) task_statuses_old = ( '' , '' , '' ) task_statuses_new = task_statuses_old + ( '' , ) task_names_old = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ) task_names_new = task_names_old + ( '' , ) node_errors_old = ( '' , '' , '' , ) node_errors_new = ( '' , '' , '' , '' , ) openstack_config_types = ( '' , '' , '' , ) def upgrade ( ) : upgrade_nodegroups_name_cluster_constraint ( ) upgrade_release_state ( ) task_statuses_upgrade ( ) task_names_upgrade ( ) add_node_discover_error_upgrade ( ) upgrade_neutron_parameters ( ) upgrade_cluster_plugins ( ) upgrade_add_baremetal_net ( ) upgrade_with_components ( ) plugin_links_upgrade ( ) cluster_plugin_links_upgrade ( ) upgrade_master_node_bootstrap_settings ( ) upgrade_all_network_data_from_string_to_appropriate_data_type ( ) create_openstack_configs_table ( ) upgrade_master_node_ui_settings ( ) upgrade_plugins_parameters ( ) upgrade_oswl_stats_version_info ( ) upgrade_nodegroups_parameters ( ) def downgrade ( ) : downgrade_nodegroups_parameters ( ) downgrade_oswl_stats_version_info ( ) downgrade_plugins_parameters ( ) downgrade_master_node_ui_settings ( ) downgrade_openstack_configs ( ) downgrade_all_network_data_to_string ( ) downgrade_master_node_bootstrap_settings ( ) cluster_plugin_links_downgrade ( ) plugin_links_downgrade ( ) downgrade_with_components ( ) downgrade_add_baremetal_net ( ) downgrade_cluster_plugins ( ) downgrade_neutron_parameters ( ) add_node_discover_error_downgrade ( ) task_names_downgrade ( ) task_statuses_downgrade ( ) downgrade_release_state ( ) downgrade_nodegroups_name_cluster_constraint ( ) def upgrade_release_state ( ) : connection = op . get_bind ( ) op . drop_column ( '' , '' ) upgrade_enum ( '' , '' , '' , release_states_old , release_states_new , ) connection . execute ( sa . sql . text ( \"\" ) ) def upgrade_nodegroups_name_cluster_constraint ( ) : connection = op . get_bind ( ) select_query = sa . sql . text ( \"\" ) update_query = sa . sql . text ( \"\" ) ng_query = sa . sql . text ( \"\" ) for name in connection . execute ( select_query ) : for i , data in enumerate ( connection . execute ( ng_query , name = name [ ] ) ) : connection . execute ( update_query , ng_id = data [ ] , name = \"\" . format ( data [ ] , i ) ) op . create_unique_constraint ( '' , '' , [ '' , '' ] ) def downgrade_nodegroups_name_cluster_constraint ( ) : op . drop_constraint ( '' , '' , ) def upgrade_with_components ( ) : op . add_column ( '' , sa . Column ( '' , fields . JSON ( ) , server_default = '' ) ) op . add_column ( '' , sa . Column ( '' , fields . JSON ( ) , server_default = '' ) ) op . add_column ( '' , sa . Column ( '' , fields . JSON ( ) , nullable = False , server_default = '' ) ) def create_openstack_configs_table ( ) : op . create_table ( '' , sa . Column ( '' , sa . Integer , nullable = False ) , sa . Column ( '' , sa . Boolean , nullable = False ) , sa . Column ( '' , sa . Enum ( * openstack_config_types , name = '' ) , nullable = False ) , sa . Column ( '' , sa . Integer , nullable = False ) , sa . Column ( '' , sa . Integer , nullable = True ) , sa . Column ( '' , sa . String ( length = ) , nullable = True ) , sa . Column ( '' , sa . DateTime , nullable = False ) , sa . Column ( '' , fields . JSON , nullable = False , server_default = '' ) , sa . ForeignKeyConstraint ( [ '' ] , [ '' ] ) , sa . ForeignKeyConstraint ( [ '' ] , [ '' ] ) , sa . PrimaryKeyConstraint ( '' ) ) def downgrade_openstack_configs ( ) : op . drop_table ( '' ) drop_enum ( '' ) def downgrade_release_state ( ) : connection = op . get_bind ( ) connection . execute ( sa . sql . text ( \"\" ) ) op . add_column ( '' , sa . Column ( '' , sa . Boolean ( ) , nullable = False , server_default = '' , ) ) upgrade_enum ( '' , '' , '' , release_states_new , release_states_old , ) def task_statuses_upgrade ( ) : upgrade_enum ( '' , '' , '' , task_statuses_old , task_statuses_new ) def task_statuses_downgrade ( ) : upgrade_enum ( '' , '' , '' , task_statuses_new , task_statuses_old ) def task_names_upgrade ( ) : upgrade_enum ( \"\" , \"\" , \"\" , task_names_old , task_names_new ) def task_names_downgrade ( ) : upgrade_enum ( \"\" , \"\" , \"\" , task_names_new , task_names_old ) def add_node_discover_error_upgrade ( ) : upgrade_enum ( \"\" , \"\" , \"\" , node_errors_old , node_errors_new ) def add_node_discover_error_downgrade ( ) : upgrade_enum ( \"\" , \"\" , \"\" , node_errors_new , node_errors_old ) def upgrade_neutron_parameters ( ) : connection = op . get_bind ( ) op . add_column ( '' , sa . Column ( '' , sa . String ( length = ) , nullable = True ) ) op . add_column ( '' , sa . Column ( '' , sa . String ( length = ) , nullable = True ) ) connection . execute ( sa . sql . text ( \"\"\"\"\"\" ) ) op . alter_column ( '' , '' , nullable = False ) op . alter_column ( '' , '' , nullable = False ) select_query = sa . sql . text ( \"\" ) for id_ , networks_metadata in connection . execute ( select_query ) : networks_metadata = jsonutils . loads ( networks_metadata ) if networks_metadata . get ( '' , { } ) . get ( '' ) is not None : networks_metadata [ '' ] [ '' ] . update ( { '' : '' , '' : '' , } ) connection . execute ( sa . sql . text ( \"\"\"\"\"\" ) , id = id_ , networks_metadata = jsonutils . dumps ( networks_metadata ) ) def downgrade_neutron_parameters ( ) : op . drop_column ( '' , '' ) op . drop_column ( '' , '' ) def upgrade_cluster_plugins ( ) : op . alter_column ( '' , '' , nullable = False ) op . drop_constraint ( '' , '' , type_ = '' ) op . create_foreign_key ( '' , '' , '' , [ '' ] , [ '' ] , ondelete = '' ) op . add_column ( '' , sa . Column ( '' , sa . Boolean , nullable = False , server_default = '' ) ) op . add_column ( '' , sa . Column ( '' , fields . JSON ( ) , nullable = False , server_default = '' ) ) connection = op . get_bind ( ) q_get_plugins = sa . text ( '''''' ) q_get_cluster_attributes = sa . text ( '''''' ) q_update_cluster_attributes = sa . text ( '''''' ) q_get_cluster_plugins = sa . text ( '''''' ) q_update_cluster_plugins = sa . text ( '''''' ) q_insert_cluster_plugins = sa . text ( '''''' ) plugins = list ( connection . execute ( q_get_plugins ) ) for cluster_id , editable in connection . execute ( q_get_cluster_attributes ) : editable = jsonutils . loads ( editable ) for plugin_id , plugin_name in plugins : if plugin_name in editable : attributes = editable . pop ( plugin_name ) metadata = attributes . pop ( '' ) if connection . execute ( q_get_cluster_plugins , cluster_id = cluster_id , plugin_id = plugin_id ) . first ( ) : action = q_update_cluster_plugins else : action = q_insert_cluster_plugins connection . execute ( action , cluster_id = cluster_id , ", "answer": "plugin_id = plugin_id ,"}, {"prompt": " import sys import xml . sax . saxutils from pyglet . gl import * from pyglet . window import mouse , key from wydget import event , layouts , loadxml from wydget . widgets . frame import Frame from wydget . widgets . label import Label class MenuItem ( Label ) : name = '' @ event . default ( '' ) def on_element_enter ( item , x , y ) : item . _save_bgcolor = item . bgcolor item . bgcolor = ( , , , ) return event . EVENT_HANDLED @ event . default ( '' ) def on_element_leave ( item , x , y ) : item . bgcolor = item . _save_bgcolor return event . EVENT_HANDLED @ event . default ( '' ) def on_click ( widget , * args ) : menu = widget . parent menu . hide ( ) return event . EVENT_HANDLED class PopupMenu ( Frame ) : '''''' name = '' is_focusable = True def __init__ ( self , parent , items , ** kw ) : super ( PopupMenu , self ) . __init__ ( parent , border = \"\" , is_visible = False , ** kw ) for n , ( label , id ) in enumerate ( items ) : MenuItem ( self , text = label , id = id , width = '' , ", "answer": "bgcolor = ( ( , , , ) , ( , , , ) ) [ n % ] )"}, {"prompt": " \"\"\"\"\"\" from __future__ import division from __future__ import print_function from __future__ import unicode_literals import utils @ utils . Timed ( ) def main ( ) : tool = utils . AlignmentFileTool ( utils . AlignmentFileConstants . BAM , ", "answer": "utils . AlignmentFileConstants . SAM )"}, {"prompt": " import pickle from pylab import * loaded = pickle . load ( open ( \"\" ) ) ", "answer": "set_cmap ( \"\" )"}, {"prompt": " import numpy as np import sys import logging from gensim . models import Word2Vec from marmot . features . feature_extractor import FeatureExtractor logging . basicConfig ( format = '' , level = logging . INFO ) logger = logging . getLogger ( '' ) def left_context ( token_list , token , context_size , idx ) : left_window = [ ] if idx <= : return [ '' for i in range ( context_size ) ] assert ( token_list [ idx ] == token ) for i in range ( idx - context_size , idx ) : if i < : left_window . append ( '' ) else : left_window . append ( token_list [ i ] ) return left_window def right_context ( token_list , token , context_size , idx ) : right_window = [ ] if idx >= len ( token_list ) : return [ '' for i in range ( context_size ) ] assert ( token_list [ idx ] == token ) , \"\" . format ( token_list [ idx ] , idx , token ) for i in range ( idx + , idx + context_size + ) : if i > len ( token_list ) - : right_window . append ( '' ) else : right_window . append ( token_list [ i ] ) return right_window class Word2VecFeatureExtractor ( FeatureExtractor ) : '''''' def __init__ ( self , w2v_file , combination = '' , context_size = ) : self . model = Word2Vec . load ( w2v_file ) self . default_vector = np . average ( np . array ( [ self . model [ x ] for x in self . model . vocab ] ) , axis = ) . reshape ( ( - , ) ) self . zero_vector = np . zeros ( self . default_vector . shape [ ] ) self . context_size = context_size if combination == '' : self . combine = np . sum elif combination == '' : self . combine = np . average else : print ( \"\" . format ( combination ) ) def extract_word2vec_vector ( self , token ) : ", "answer": "if token in self . model . vocab :"}, {"prompt": " class HorizontalAlgorithm ( object ) : ", "answer": "def process ( self , sprite ) :"}, {"prompt": " if __name__ == \"\" : import sys sys . path . append ( '' ) import unittest2 as unittest from vdebug . opts import Options , OptionsError class OptionsTest ( unittest . TestCase ) : def tearDown ( self ) : Options . instance = None def test_has_instance ( self ) : Options . set ( { : \"\" , : \"\" } ) self . assertIsInstance ( Options . inst ( ) , Options ) def test_get_option ( self ) : Options . set ( { '' : \"\" , '' : \"\" } ) self . assertEqual ( \"\" , Options . get ( '' ) ) def test_get_option_as_type ( self ) : Options . set ( { '' : \"\" , '' : \"\" } ) opt = Options . get ( '' , int ) self . assertIsInstance ( opt , int ) ", "answer": "self . assertEqual ( , opt )"}, {"prompt": " try : from functools import lru_cache except ImportError : from collections import namedtuple from functools import update_wrapper from threading import RLock _CacheInfo = namedtuple ( \"\" , [ \"\" , \"\" , \"\" , \"\" ] ) class _HashedSeq ( list ) : __slots__ = '' def __init__ ( self , tup , hash = hash ) : self [ : ] = tup self . hashvalue = hash ( tup ) def __hash__ ( self ) : return self . hashvalue def _make_key ( args , kwds , typed , kwd_mark = ( object ( ) , ) , fasttypes = { int , str , frozenset , type ( None ) } , sorted = sorted , tuple = tuple , type = type , len = len ) : '' key = args if kwds : sorted_items = sorted ( kwds . items ( ) ) key += kwd_mark for item in sorted_items : key += item if typed : key += tuple ( type ( v ) for v in args ) if kwds : key += tuple ( type ( v ) for k , v in sorted_items ) elif len ( key ) == and type ( key [ ] ) in fasttypes : return key [ ] return _HashedSeq ( key ) def lru_cache ( maxsize = , typed = False ) : \"\"\"\"\"\" def decorating_function ( user_function ) : cache = dict ( ) stats = [ , ] HITS , MISSES = , make_key = _make_key cache_get = cache . get _len = len lock = RLock ( ) root = [ ] root [ : ] = [ root , root , None , None ] nonlocal_root = [ root ] PREV , NEXT , KEY , RESULT = , , , if maxsize == : def wrapper ( * args , ** kwds ) : result = user_function ( * args , ** kwds ) stats [ MISSES ] += return result elif maxsize is None : def wrapper ( * args , ** kwds ) : key = make_key ( args , kwds , typed ) result = cache_get ( key , root ) if result is not root : stats [ HITS ] += return result result = user_function ( * args , ** kwds ) cache [ key ] = result stats [ MISSES ] += return result else : def wrapper ( * args , ** kwds ) : key = make_key ( args , kwds , typed ) if kwds or typed else args with lock : link = cache_get ( key ) if link is not None : root , = nonlocal_root link_prev , link_next , key , result = link link_prev [ NEXT ] = link_next link_next [ PREV ] = link_prev last = root [ PREV ] last [ NEXT ] = root [ PREV ] = link link [ PREV ] = last link [ NEXT ] = root stats [ HITS ] += return result result = user_function ( * args , ** kwds ) with lock : root , = nonlocal_root if key in cache : pass elif _len ( cache ) >= maxsize : oldroot = root oldroot [ KEY ] = key oldroot [ RESULT ] = result root = nonlocal_root [ ] = oldroot [ NEXT ] oldkey = root [ KEY ] oldvalue = root [ RESULT ] root [ KEY ] = root [ RESULT ] = None del cache [ oldkey ] cache [ key ] = oldroot else : last = root [ PREV ] link = [ last , root , key , result ] last [ NEXT ] = root [ PREV ] = cache [ key ] = link stats [ MISSES ] += return result ", "answer": "def cache_info ( ) :"}, {"prompt": " \"\"\"\"\"\" ", "answer": "DEBUG = False"}, {"prompt": " \"\"\"\"\"\" import os import sys from functools import partial from . exceptions import SourceMapDecodeError from . objects import Token , SourceMapIndex try : import simplejson as json except ImportError : import json __all__ = ( '' , ) PY3 = sys . version_info [ ] == text_type = str if PY3 else unicode class SourceMapDecoder ( object ) : def parse_vlq ( self , segment ) : \"\"\"\"\"\" values = [ ] cur , shift = , for c in segment : val = B64 [ ord ( c ) ] val , cont = val & , val >> cur += val << shift shift += if not cont : cur , sign = cur >> , cur & if sign : cur = - cur values . append ( cur ) cur , shift = , if cur or shift : ", "answer": "raise SourceMapDecodeError ( '' )"}, {"prompt": " \"\"\"\"\"\" identifier = '' name = '' version = '' def package_dependencies ( ) : import core . packagemanager manager = core . packagemanager . get_package_manager ( ) ret = [ ] ret . append ( '' ) ret . append ( '' ) return ret def package_requirements ( ) : import core . requirements if not core . requirements . python_module_exists ( '' ) : raise core . requirements . MissingRequirement ( '' ) if not core . requirements . python_module_exists ( '' ) : print '' , print '' ", "answer": "import titan "}, {"prompt": " from unittest2 import TestCase from st2actions . runners . utils import get_action_class_instance from st2tests . mocks . action import MockActionWrapper from st2tests . mocks . action import MockActionService __all__ = [ '' ", "answer": "]"}, {"prompt": " \"\"\"\"\"\" import dpkt , ip6 ICMP6_DST_UNREACH = ICMP6_PACKET_TOO_BIG = ICMP6_TIME_EXCEEDED = ICMP6_PARAM_PROB = ICMP6_ECHO_REQUEST = ICMP6_ECHO_REPLY = MLD_LISTENER_QUERY = MLD_LISTENER_REPORT = MLD_LISTENER_DONE = ICMP6_MEMBERSHIP_QUERY = ICMP6_MEMBERSHIP_REPORT = ICMP6_MEMBERSHIP_REDUCTION = ND_ROUTER_SOLICIT = ND_ROUTER_ADVERT = ND_NEIGHBOR_SOLICIT = ND_NEIGHBOR_ADVERT = ND_REDIRECT = ICMP6_ROUTER_RENUMBERING = ICMP6_WRUREQUEST = ICMP6_WRUREPLY = ICMP6_FQDN_QUERY = ICMP6_FQDN_REPLY = ICMP6_NI_QUERY = ICMP6_NI_REPLY = ", "answer": "ICMP6_MAXTYPE = "}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import ", "answer": "import debug_toolbar"}, {"prompt": " \"\"\"\"\"\" import collections import copy LINK_GENERATORS_KEY = '' class AnnotationBasePresenter ( object ) : def __init__ ( self , request , annotation ) : self . annotation = annotation self . request = request @ property def created ( self ) : if self . annotation . created : return utc_iso8601 ( self . annotation . created ) @ property def updated ( self ) : if self . annotation . updated : return utc_iso8601 ( self . annotation . updated ) @ property def links ( self ) : \"\"\"\"\"\" link_generators = self . request . registry . get ( LINK_GENERATORS_KEY , { } ) out = { } for name , generator in link_generators . items ( ) : link = generator ( self . request , self . annotation ) if link is not None : out [ name ] = link return out @ property def text ( self ) : if self . annotation . text : return self . annotation . text else : return '' @ property def tags ( self ) : if self . annotation . tags : return self . annotation . tags else : return [ ] @ property def target ( self ) : target = { '' : self . annotation . target_uri } if self . annotation . target_selectors : target [ '' ] = self . annotation . target_selectors return [ target ] class AnnotationJSONPresenter ( AnnotationBasePresenter ) : def asdict ( self ) : docpresenter = DocumentJSONPresenter ( self . annotation . document ) base = { '' : self . annotation . id , '' : self . created , '' : self . updated , '' : self . annotation . userid , '' : self . annotation . target_uri , '' : self . text , '' : self . tags , '' : self . annotation . groupid , '' : self . permissions , '' : self . target , '' : docpresenter . asdict ( ) , '' : self . links , } if self . annotation . references : base [ '' ] = self . annotation . references annotation = copy . copy ( self . annotation . extra ) or { } annotation . update ( base ) return annotation @ property def permissions ( self ) : read = self . annotation . userid if self . annotation . shared : read = '' . format ( self . annotation . groupid ) return { '' : [ read ] , '' : [ self . annotation . userid ] , '' : [ self . annotation . userid ] , '' : [ self . annotation . userid ] } class AnnotationJSONLDPresenter ( AnnotationBasePresenter ) : \"\"\"\"\"\" CONTEXT_URL = '' def asdict ( self ) : return { '' : self . CONTEXT_URL , '' : '' , '' : self . id , '' : self . created , '' : self . updated , '' : self . annotation . userid , '' : self . bodies , '' : self . target , } @ property def id ( self ) : return self . request . route_url ( '' , id = self . annotation . id ) @ property def bodies ( self ) : bodies = [ { '' : '' , '' : self . text , '' : '' , } ] for t in self . tags : bodies . append ( { '' : '' , '' : t , '' : '' , } ) return bodies class DocumentJSONPresenter ( object ) : def __init__ ( self , document ) : self . document = document def asdict ( self ) : if not self . document : return { } d = { } for docmeta in self . document . meta : meta_presenter = DocumentMetaJSONPresenter ( docmeta ) deep_merge_dict ( d , meta_presenter . asdict ( ) ) d [ '' ] = [ ] for docuri in self . document . document_uris : uri_presenter = DocumentURIJSONPresenter ( docuri ) d [ '' ] . append ( uri_presenter . asdict ( ) ) return d class DocumentMetaJSONPresenter ( object ) : def __init__ ( self , document_meta ) : self . document_meta = document_meta def asdict ( self ) : reversed_path = self . document_meta . type . split ( '' ) [ : : - ] d = self . document_meta . value for nested in reversed_path : d = { nested : d } return d class DocumentURIJSONPresenter ( object ) : def __init__ ( self , document_uri ) : self . document_uri = document_uri def asdict ( self ) : data = { '' : self . document_uri . uri } rel = self . rel if rel : data [ '' ] = rel type = self . document_uri . content_type if type : data [ '' ] = type return data @ property def rel ( self ) : type = self . document_uri . type if type and type . startswith ( '' ) : return self . document_uri . type [ : ] def add_annotation_link_generator ( registry , name , generator ) : \"\"\"\"\"\" if LINK_GENERATORS_KEY not in registry : registry [ LINK_GENERATORS_KEY ] = { } registry [ LINK_GENERATORS_KEY ] [ name ] = generator def utc_iso8601 ( datetime ) : return datetime . strftime ( '' ) def deep_merge_dict ( a , b ) : \"\"\"\"\"\" for k , v in b . items ( ) : if isinstance ( v , collections . Mapping ) : ", "answer": "if k not in a or not isinstance ( a [ k ] , dict ) :"}, {"prompt": " try : import re import shlex import datetime import subprocess from lib . core . core import Core ", "answer": "from lib . screen . webscan import WebScan"}, {"prompt": " \"\"\"\"\"\" import os import sys from textwrap import dedent from optparse import OptionParser PROJECT = VENDOR = ", "answer": "ENV_BRANCH = {"}, {"prompt": " from __future__ import absolute_import , division , print_function , unicode_literals import demo import pi3d from pi3d . util . Scenery import Scene , SceneryItem MSIZE = NX = NZ = SMOOTH_1 = SMOOTH_2 = - ROUGH_1 = ", "answer": "ROUGH_2 = "}, {"prompt": " from __future__ import absolute_import from __future__ import division , print_function , unicode_literals from operator import attrgetter from itertools import chain from . . _compat import ffilter from . _summarizer import AbstractSummarizer class EdmundsonTitleMethod ( AbstractSummarizer ) : def __init__ ( self , stemmer , null_words ) : super ( EdmundsonTitleMethod , self ) . __init__ ( stemmer ) self . _null_words = null_words def __call__ ( self , document , sentences_count ) : sentences = document . sentences significant_words = self . _compute_significant_words ( document ) return self . _get_best_sentences ( sentences , sentences_count , self . _rate_sentence , significant_words ) ", "answer": "def _compute_significant_words ( self , document ) :"}, {"prompt": " import datetime from south . db import db from south . v2 import DataMigration from django . db import models class Migration ( DataMigration ) : def forwards ( self , orm ) : db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , unique = True ) ) , ( '' , self . gf ( '' ) ( default = ) ) , ", "answer": "( '' , self . gf ( '' ) ( max_length = , blank = True ) ) ,"}, {"prompt": " import pulsar . scripts . chown_working_directory import pulsar . scripts . drmaa_kill import pulsar . scripts . drmaa_launch import pulsar . scripts . mesos_executor import pulsar . scripts . mesos_framework import pulsar . scripts . submit import pulsar . client . test . check MODULES = [ pulsar . scripts . drmaa_kill , ", "answer": "pulsar . scripts . drmaa_launch ,"}, {"prompt": " from django . core . urlresolvers import reverse from sentry . utils . http import absolute_uri from . base import Problem , StatusCheck class WarningStatusCheck ( StatusCheck ) : def __init__ ( self , warning_set ) : self . __warning_set = warning_set def check ( self ) : if self . __warning_set : return [ Problem ( '' . format ( '' if len ( self . __warning_set ) > else '' , len ( self . __warning_set ) , '' if len ( self . __warning_set ) > else '' , ) , severity = Problem . SEVERITY_WARNING , url = absolute_uri ( reverse ( '' ) ) , ", "answer": ") ,"}, {"prompt": " import os . path from django . contrib . auth . models import User from django . core . files . uploadedfile import SimpleUploadedFile from django . test import TestCase , Client from neurovault . apps . statmaps . forms import NIDMResultsForm from neurovault . apps . statmaps . models import Collection , StatisticMap , Comparison from neurovault . apps . statmaps . utils import count_processing_comparisons , count_existing_comparisons from . utils import clearDB class Test_Counter ( TestCase ) : def setUp ( self ) : print \"\" self . test_path = os . path . abspath ( os . path . dirname ( __file__ ) ) self . user = User . objects . create ( username = '' ) self . client = Client ( ) self . client . login ( username = self . user ) self . Collection1 = Collection ( name = '' , owner = self . user , DOI = '' ) self . Collection1 . save ( ) self . Collection2 = Collection ( name = '' , owner = self . user , DOI = '' ) self . Collection2 . save ( ) self . Collection3 = Collection ( name = '' , owner = self . user , DOI = '' ) self . Collection3 . save ( ) def tearDown ( self ) : clearDB ( ) def test_statmaps_processing ( self ) : ", "answer": "print \"\""}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Intangible ( )"}, {"prompt": " import numpy as np from unittest import TestCase from quagga . context import Context from quagga . matrix import GpuMatrix from quagga . connector import Connector from quagga . blocks import MeanPoolingBlock class TestMeanPoolingBlock ( TestCase ) : @ classmethod def setUpClass ( cls ) : cls . rng = np . random . RandomState ( seed = ) cls . N = @ classmethod def get_random_array ( cls , shape = None ) : if shape : a = * cls . rng . rand ( * shape ) - else : nrows , ncols = cls . rng . randint ( low = , high = , size = ) a = * cls . rng . rand ( nrows , ncols ) - return a . astype ( dtype = np . float32 ) def test_fprop ( self ) : r = [ ] for i in xrange ( self . N ) : a = self . get_random_array ( ) a_gpu = Connector ( GpuMatrix . from_npa ( a , '' ) ) vpooling_block = MeanPoolingBlock ( a_gpu , axis = ) hpooling_block = MeanPoolingBlock ( a_gpu , axis = ) vpooling_block . fprop ( ) r . append ( np . allclose ( vpooling_block . output . to_host ( ) , np . mean ( a , axis = , keepdims = True ) , atol = ) ) hpooling_block . fprop ( ) r . append ( np . allclose ( hpooling_block . output . to_host ( ) , np . mean ( a , axis = , keepdims = True ) , atol = ) ) self . assertEqual ( sum ( r ) , * self . N ) def test_bprop ( self ) : r = [ ] context = Context ( ) for i in xrange ( self . N ) : a = self . get_random_array ( ) a_gpu = Connector ( GpuMatrix . from_npa ( a , '' ) , bu_device_id = context ) vpooling_block = MeanPoolingBlock ( a_gpu , axis = ) voutput , dL_dvoutput = vpooling_block . output . register_usage ( context , context ) _dL_voutput = self . get_random_array ( ( dL_dvoutput . nrows , dL_dvoutput . ncols ) ) GpuMatrix . from_npa ( _dL_voutput , '' ) . copy_to ( context , dL_dvoutput ) hpooling_block = MeanPoolingBlock ( a_gpu , axis = ) houtput , dL_dhoutput = hpooling_block . output . register_usage ( context , context ) _dL_houtput = self . get_random_array ( ( dL_dhoutput . nrows , dL_dhoutput . ncols ) ) GpuMatrix . from_npa ( _dL_houtput , '' ) . copy_to ( context , dL_dhoutput ) vpooling_block . fprop ( ) vpooling_block . bprop ( ) dL_dmatrix = vpooling_block . dL_dmatrix . to_host ( ) r . append ( np . allclose ( dL_dmatrix , np . repeat ( _dL_voutput / a . shape [ ] , a . shape [ ] , ) , atol = ) ) hpooling_block . fprop ( ) hpooling_block . bprop ( ) hpooling_block . dL_dmatrix . to_host ( ) ", "answer": "dL_dmatrix = hpooling_block . dL_dmatrix . to_host ( )"}, {"prompt": " import weakref import functools import types import re import collections import IECore import Gaffer import GafferUI class UIEditor ( GafferUI . NodeSetEditor ) : def __init__ ( self , scriptNode , parenting = None ) : self . __frame = GafferUI . Frame ( borderWidth = , borderStyle = GafferUI . Frame . BorderStyle . None ) GafferUI . NodeSetEditor . __init__ ( self , self . __frame , scriptNode , parenting = parenting ) self . __nodeMetadataWidgets = [ ] self . __plugMetadataWidgets = [ ] with self . __frame : self . __tabbedContainer = GafferUI . TabbedContainer ( ) with self . __tabbedContainer : with GafferUI . ListContainer ( spacing = , borderWidth = , parenting = { \"\" : \"\" } ) as self . __nodeTab : with _Row ( ) : _Label ( \"\" ) self . __nodeNameWidget = GafferUI . NameWidget ( None ) with _Row ( ) : _Label ( \"\" , parenting = { \"\" : GafferUI . ListContainer . VerticalAlignment . Top } ) self . __nodeMetadataWidgets . append ( _MultiLineStringMetadataWidget ( key = \"\" ) ) with _Row ( ) : _Label ( \"\" ) self . __nodeMetadataWidgets . append ( _ColorSwatchMetadataWidget ( key = \"\" ) ) with GafferUI . SplitContainer ( orientation = GafferUI . SplitContainer . Orientation . Horizontal , borderWidth = , parenting = { \"\" : \"\" } ) as self . __plugTab : self . __plugListing = _PlugListing ( ) self . __plugListingSelectionChangedConnection = self . __plugListing . selectionChangedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __plugListingSelectionChanged ) ) with GafferUI . TabbedContainer ( ) as self . __plugAndSectionEditorsContainer : self . __plugEditor = _PlugEditor ( ) self . __sectionEditor = _SectionEditor ( ) self . __sectionEditorNameChangedConnection = self . __sectionEditor . nameChangedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __sectionEditorNameChanged ) ) self . __plugAndSectionEditorsContainer . setTabsVisible ( False ) self . __plugTab . setSizes ( [ , ] ) self . __node = None self . __selectedPlug = None self . __updateFromSetInternal ( lazy = False ) def setSelection ( self , selection ) : self . __plugListing . setSelection ( selection ) def getSelection ( self ) : return self . __plugListing . getSelection ( ) def nodeEditor ( self ) : return self . __nodeTab def plugEditor ( self ) : return self . __plugTab @ classmethod def appendNodeContextMenuDefinitions ( cls , nodeGraph , node , menuDefinition ) : menuDefinition . append ( \"\" , { \"\" : True } ) menuDefinition . append ( \"\" , { \"\" : functools . partial ( cls . __setColor , node = node ) } ) @ classmethod def appendNodeEditorToolMenuDefinitions ( cls , nodeEditor , node , menuDefinition ) : menuDefinition . append ( \"\" , { \"\" : functools . partial ( GafferUI . UIEditor . acquire , node ) , \"\" : isinstance ( node , Gaffer . Box ) or nodeEditor . nodeUI ( ) . plugValueWidget ( node [ \"\" ] ) is not None } ) def _updateFromSet ( self ) : GafferUI . NodeSetEditor . _updateFromSet ( self ) self . __updateFromSetInternal ( ) def __updateFromSetInternal ( self , lazy = True ) : node = self . _lastAddedNode ( ) if lazy and node == self . __node : return self . __node = node self . __nodeNameWidget . setGraphComponent ( self . __node ) self . __nodeTab . setEnabled ( self . __node is not None ) if self . __node is None : self . __plugListing . setPlugParent ( None ) self . __sectionEditor . setPlugParent ( None ) else : plugParent = self . __node [ \"\" ] if isinstance ( self . __node , Gaffer . Box ) : plugParent = self . __node self . __plugListing . setPlugParent ( plugParent ) self . __sectionEditor . setPlugParent ( plugParent ) for widget in self . __nodeMetadataWidgets : widget . setTarget ( self . __node ) self . setSelection ( None ) def __plugListingSelectionChanged ( self , listing ) : selection = listing . getSelection ( ) if selection is None or isinstance ( selection , Gaffer . Plug ) : self . __plugEditor . setPlug ( selection ) self . __plugAndSectionEditorsContainer . setCurrent ( self . __plugEditor ) elif isinstance ( selection , basestring ) : self . __plugEditor . setPlug ( None ) self . __sectionEditor . setSection ( selection ) self . __plugAndSectionEditorsContainer . setCurrent ( self . __sectionEditor ) def __sectionEditorNameChanged ( self , sectionEditor , oldName , newName ) : self . __plugListing . setSelection ( newName ) def __repr__ ( self ) : return \"\" @ classmethod def __setColor ( cls , menu , node ) : color = Gaffer . Metadata . nodeValue ( node , \"\" ) or IECore . Color3f ( ) dialogue = GafferUI . ColorChooserDialogue ( color = color , useDisplayTransform = False ) color = dialogue . waitForColor ( parentWindow = menu . ancestor ( GafferUI . Window ) ) if color is not None : with Gaffer . UndoContext ( node . ancestor ( Gaffer . ScriptNode ) ) : Gaffer . Metadata . registerNodeValue ( node , \"\" , color ) GafferUI . EditorWidget . registerType ( \"\" , UIEditor ) def __editPlugUI ( node , plug ) : editor = GafferUI . UIEditor . acquire ( node ) editor . setSelection ( plug ) editor . plugEditor ( ) . reveal ( ) def __plugPopupMenu ( menuDefinition , plugValueWidget ) : plug = plugValueWidget . getPlug ( ) node = plug . node ( ) if node is None : return if isinstance ( node , Gaffer . Box ) : if not plug . parent ( ) . isSame ( node ) : return else : if not plug . parent ( ) . isSame ( node [ \"\" ] ) : return menuDefinition . append ( \"\" , { \"\" : True } ) menuDefinition . append ( \"\" , { \"\" : IECore . curry ( __editPlugUI , node , plug ) , \"\" : not plugValueWidget . getReadOnly ( ) } ) __plugPopupMenuConnection = GafferUI . PlugValueWidget . popupMenuSignal ( ) . connect ( __plugPopupMenu ) class _Label ( GafferUI . Label ) : def __init__ ( self , * args , ** kw ) : GafferUI . Label . __init__ ( self , horizontalAlignment = GafferUI . Label . HorizontalAlignment . Right , * args , ** kw ) self . _qtWidget ( ) . setFixedWidth ( ) class _Row ( GafferUI . ListContainer ) : def __init__ ( self , * args , ** kw ) : GafferUI . ListContainer . __init__ ( self , GafferUI . ListContainer . Orientation . Horizontal , spacing = , * args , ** kw ) class _MetadataWidget ( GafferUI . Widget ) : def __init__ ( self , topLevelWidget , key , target = None , parenting = None ) : GafferUI . Widget . __init__ ( self , topLevelWidget , parenting = parenting ) self . __key = key self . __target = None self . setTarget ( target ) def setTarget ( self , target ) : assert ( isinstance ( target , ( Gaffer . Node , Gaffer . Plug , type ( None ) ) ) ) self . __target = target self . setEnabled ( self . __target is not None ) if isinstance ( self . __target , Gaffer . Node ) : self . __metadataChangedConnection = Gaffer . Metadata . nodeValueChangedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __nodeMetadataChanged ) ) elif isinstance ( self . __target , Gaffer . Plug ) : self . __metadataChangedConnection = Gaffer . Metadata . plugValueChangedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __plugMetadataChanged ) ) else : self . __metadataChangedConnection = None self . __update ( ) def getTarget ( self ) : return self . __target def setKey ( self , key ) : if key == self . __key : return self . __key = key self . __update ( ) def getKey ( self , key ) : return self . __key def _updateFromValue ( self , value ) : raise NotImplementedError def _updateFromWidget ( self , value ) : if self . __target is None : return with Gaffer . UndoContext ( self . __target . ancestor ( Gaffer . ScriptNode ) ) : _registerMetadata ( self . __target , self . __key , value ) def _deregisterValue ( self ) : if self . __target is None : return with Gaffer . UndoContext ( self . __target . ancestor ( Gaffer . ScriptNode ) ) : _deregisterMetadata ( self . __target , self . __key ) def __update ( self ) : if isinstance ( self . __target , Gaffer . Node ) : self . _updateFromValue ( Gaffer . Metadata . nodeValue ( self . __target , self . __key ) ) elif isinstance ( self . __target , Gaffer . Plug ) : self . _updateFromValue ( Gaffer . Metadata . plugValue ( self . __target , self . __key ) ) else : self . _updateFromValue ( None ) def __nodeMetadataChanged ( self , nodeTypeId , key , node ) : if self . __key != key : return if node is not None and not node . isSame ( self . __target ) : return if not self . __target . isInstanceOf ( nodeTypeId ) : return self . __update ( ) def __plugMetadataChanged ( self , nodeTypeId , plugPath , key , plug ) : if self . __key != key : return if plug is not None and not plug . isSame ( self . __target ) : return if not self . __target . node ( ) . isInstanceOf ( nodeTypeId ) : return if not Gaffer . match ( self . __target . relativeName ( self . __target . node ( ) ) , plugPath ) : return self . __update ( ) class _BoolMetadataWidget ( _MetadataWidget ) : def __init__ ( self , key , target = None , parenting = None ) : self . __boolWidget = GafferUI . BoolWidget ( ) _MetadataWidget . __init__ ( self , self . __boolWidget , key , target , parenting = parenting ) self . __stateChangedConnection = self . __boolWidget . stateChangedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __stateChanged ) ) def _updateFromValue ( self , value ) : self . __boolWidget . setState ( value if value is not None else False ) def __stateChanged ( self , * unused ) : self . _updateFromWidget ( self . __boolWidget . getState ( ) ) class _StringMetadataWidget ( _MetadataWidget ) : def __init__ ( self , key , target = None , acceptEmptyString = True , parenting = None ) : self . __textWidget = GafferUI . TextWidget ( ) _MetadataWidget . __init__ ( self , self . __textWidget , key , target , parenting = None ) self . __acceptEmptyString = acceptEmptyString self . __editingFinishedConnection = self . __textWidget . editingFinishedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __editingFinished ) ) def textWidget ( self ) : return self . __textWidget def _updateFromValue ( self , value ) : self . __textWidget . setText ( value if value is not None else \"\" ) def __editingFinished ( self , * unused ) : text = self . __textWidget . getText ( ) if text or self . __acceptEmptyString : self . _updateFromWidget ( text ) else : self . _deregisterValue ( ) class _MultiLineStringMetadataWidget ( _MetadataWidget ) : def __init__ ( self , key , target = None , parenting = None ) : self . __textWidget = GafferUI . MultiLineTextWidget ( ) _MetadataWidget . __init__ ( self , self . __textWidget , key , target , parenting = None ) self . __editingFinishedConnection = self . __textWidget . editingFinishedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __editingFinished ) ) def textWidget ( self ) : return self . __textWidget def _updateFromValue ( self , value ) : self . __textWidget . setText ( value if value is not None else \"\" ) def __editingFinished ( self , * unused ) : self . _updateFromWidget ( self . __textWidget . getText ( ) ) class _ColorSwatchMetadataWidget ( _MetadataWidget ) : def __init__ ( self , key , target = None , parenting = None ) : self . __swatch = GafferUI . ColorSwatch ( useDisplayTransform = False ) _MetadataWidget . __init__ ( self , self . __swatch , key , target , parenting = parenting ) self . __swatch . _qtWidget ( ) . setFixedHeight ( ) self . __swatch . _qtWidget ( ) . setMaximumWidth ( ) self . __value = None self . __buttonReleaseConnection = self . __swatch . buttonReleaseSignal ( ) . connect ( Gaffer . WeakMethod ( self . __buttonRelease ) ) def _updateFromValue ( self , value ) : if value is not None : self . __swatch . setColor ( value ) else : self . __swatch . setColor ( IECore . Color4f ( , , , ) ) self . __value = value def __buttonRelease ( self , swatch , event ) : if event . button != event . Buttons . Left : return False color = self . __value if self . __value is not None else IECore . Color3f ( ) dialogue = GafferUI . ColorChooserDialogue ( color = color , useDisplayTransform = False ) color = dialogue . waitForColor ( parentWindow = self . ancestor ( GafferUI . Window ) ) if color is not None : self . _updateFromWidget ( color ) class _MenuMetadataWidget ( _MetadataWidget ) : def __init__ ( self , key , labelsAndValues , target = None , parenting = None ) : self . __menuButton = GafferUI . MenuButton ( menu = GafferUI . Menu ( Gaffer . WeakMethod ( self . __menuDefinition ) ) ) self . __labelsAndValues = labelsAndValues self . __currentValue = None _MetadataWidget . __init__ ( self , self . __menuButton , key , target , parenting = parenting ) def _updateFromValue ( self , value ) : self . __currentValue = value buttonText = str ( value ) for label , value in self . __labelsAndValues : if value == self . __currentValue : buttonText = label break self . __menuButton . setText ( buttonText ) def __menuDefinition ( self ) : result = IECore . MenuDefinition ( ) for label , value in self . __labelsAndValues : result . append ( \"\" + label , { \"\" : functools . partial ( Gaffer . WeakMethod ( self . __setValue ) , value = value ) , \"\" : value == self . __currentValue } ) return result def __setValue ( self , unused , value ) : self . _updateFromWidget ( value ) class _LayoutItem ( object ) : def __init__ ( self ) : self . __parent = None self . __children = [ ] def parent ( self ) : if self . __parent is None : return None else : return self . __parent ( ) def child ( self , name ) : for c in self . __children : if c . name ( ) == name : return c return None def isAncestorOf ( self , item ) : while item is not None : parent = item . parent ( ) if parent is self : return True item = parent return False def append ( self , child ) : self . insert ( len ( self ) , child ) def insert ( self , index , child ) : assert ( child . parent ( ) is None ) self . __children . insert ( index , child ) child . __parent = weakref . ref ( self ) def remove ( self , child ) : assert ( child . parent ( ) is self ) self . __children . remove ( child ) child . __parent = None def index ( self , child ) : return self . __children . index ( child ) def name ( self ) : raise NotImplementedError def fullName ( self ) : result = \"\" item = self while item . parent ( ) is not None : if result : result = item . name ( ) + \"\" + result else : result = item . name ( ) item = item . parent ( ) return result def __len__ ( self ) : return len ( self . __children ) def __getitem__ ( self , index ) : return self . __children [ index ] class _SectionLayoutItem ( _LayoutItem ) : def __init__ ( self , sectionName ) : _LayoutItem . __init__ ( self ) self . __sectionName = sectionName def name ( self ) : return self . __sectionName class _PlugLayoutItem ( _LayoutItem ) : def __init__ ( self , plug ) : _LayoutItem . __init__ ( self ) self . plug = plug self . __name = plug . getName ( ) def name ( self ) : return self . __name class _PlugListing ( GafferUI . Widget ) : class __LayoutPath ( Gaffer . Path ) : def __init__ ( self , rootItem , path , root = \"\" , filter = None ) : Gaffer . Path . __init__ ( self , path , root , filter ) self . __rootItem = rootItem def rootItem ( self ) : return self . __rootItem def item ( self ) : result = self . __rootItem for name in self : result = result . child ( name ) if result is None : return None return result def copy ( self ) : return self . __class__ ( self . __rootItem , self [ : ] , self . root ( ) , self . getFilter ( ) ) def isLeaf ( self ) : return not isinstance ( self . item ( ) , _SectionLayoutItem ) def isValid ( self ) : return self . item ( ) is not None def _children ( self ) : item = self . item ( ) if item is None : return [ ] result = [ self . __class__ ( self . __rootItem , self [ : ] + [ c . name ( ) ] , self . root ( ) , self . getFilter ( ) ) for c in item ] if len ( result ) == and isinstance ( item , _SectionLayoutItem ) : result . append ( self . __class__ ( self . __rootItem , self [ : ] + [ \"\" ] , self . root ( ) , self . getFilter ( ) ) ) return result def __init__ ( self , parenting = None ) : column = GafferUI . ListContainer ( spacing = ) GafferUI . Widget . __init__ ( self , column , parenting = parenting ) with column : self . __pathListing = GafferUI . PathListingWidget ( self . __LayoutPath ( _SectionLayoutItem ( \"\" ) , \"\" ) , columns = ( GafferUI . PathListingWidget . defaultNameColumn , ) , displayMode = GafferUI . PathListingWidget . DisplayMode . Tree , ) self . __pathListing . setDragPointer ( \"\" ) self . __pathListing . setSortable ( False ) self . __pathListing . setHeaderVisible ( False ) with GafferUI . ListContainer ( GafferUI . ListContainer . Orientation . Horizontal , spacing = ) : GafferUI . MenuButton ( image = \"\" , hasFrame = False , menu = GafferUI . Menu ( definition = Gaffer . WeakMethod ( self . __addMenuDefinition ) ) ) self . __deleteButton = GafferUI . Button ( image = \"\" , hasFrame = False ) self . __deleteButtonClickedConnection = self . __deleteButton . clickedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __deleteButtonClicked ) ) self . __parent = None self . __dragItem = None self . __selectionChangedSignal = Gaffer . Signal1 ( ) self . __dragEnterConnection = self . __pathListing . dragEnterSignal ( ) . connect ( Gaffer . WeakMethod ( self . __dragEnter ) ) self . __dragMoveConnection = self . __pathListing . dragMoveSignal ( ) . connect ( Gaffer . WeakMethod ( self . __dragMove ) ) self . __dragEndConnection = self . __pathListing . dragEndSignal ( ) . connect ( Gaffer . WeakMethod ( self . __dragEnd ) ) self . __selectionChangedConnection = self . __pathListing . selectionChangedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __selectionChanged ) ) self . __keyPressConnection = self . keyPressSignal ( ) . connect ( Gaffer . WeakMethod ( self . __keyPress ) ) self . __nodeMetadataChangedConnection = Gaffer . Metadata . nodeValueChangedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __nodeMetadataChanged ) ) self . __plugMetadataChangedConnection = Gaffer . Metadata . plugValueChangedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __plugMetadataChanged ) ) def setPlugParent ( self , parent ) : assert ( isinstance ( parent , ( Gaffer . Plug , Gaffer . Node , types . NoneType ) ) ) self . __parent = parent self . __childAddedConnection = None self . __childRemovedConnection = None self . __childNameChangedConnections = { } if self . __parent is not None : self . __childAddedConnection = self . __parent . childAddedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __childAddedOrRemoved ) ) self . __childRemovedConnection = self . __parent . childRemovedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __childAddedOrRemoved ) ) for child in self . __parent . children ( ) : self . __updateChildNameChangedConnection ( child ) self . __updatePath ( ) def getPlugParent ( self ) : return self . __parent def setSelection ( self , selection ) : self . __updatePathLazily . flush ( self ) def findPlugPath ( path , plug ) : item = path . item ( ) if isinstance ( item , _PlugLayoutItem ) and item . plug . isSame ( plug ) : return path else : for child in path . children ( ) : r = findPlugPath ( child , plug ) if r is not None : return r return None if isinstance ( selection , Gaffer . Plug ) : path = findPlugPath ( self . __pathListing . getPath ( ) , selection ) if path is None : self . __pathListing . setSelectedPaths ( [ ] ) else : self . __pathListing . setSelectedPaths ( [ path ] ) elif isinstance ( selection , basestring ) : path = self . __pathListing . getPath ( ) . copy ( ) path [ : ] = selection . split ( \"\" ) self . __pathListing . setSelectedPaths ( [ path ] ) else : assert ( selection is None ) self . __pathListing . setSelectedPaths ( [ ] ) def getSelection ( self ) : item = self . __selectedItem ( ) if item is None : return None elif isinstance ( item , _PlugLayoutItem ) : return item . plug elif isinstance ( item , _SectionLayoutItem ) : return item . fullName ( ) else : return None def selectionChangedSignal ( self ) : return self . __selectionChangedSignal def __updatePath ( self ) : if self . __parent is None : self . __pathListing . setPath ( self . __LayoutPath ( _SectionLayoutItem ( \"\" ) , \"\" ) ) return def section ( rootLayoutItem , sectionPath ) : sectionItem = rootLayoutItem if sectionPath != \"\" : for sectionName in sectionPath . split ( \"\" ) : childSectionItem = sectionItem . child ( sectionName ) if childSectionItem is None : childSectionItem = _SectionLayoutItem ( sectionName ) sectionItem . append ( childSectionItem ) sectionItem = childSectionItem return sectionItem layout = _SectionLayoutItem ( \"\" ) for sectionPath in GafferUI . PlugLayout . layoutSections ( self . __parent ) : if sectionPath == \"\" and isinstance ( self . __parent , Gaffer . Node ) : continue sectionItem = section ( layout , sectionPath ) for plug in GafferUI . PlugLayout . layoutOrder ( self . __parent , section = sectionPath ) : sectionItem . append ( _PlugLayoutItem ( plug ) ) emptySections = _metadata ( self . getPlugParent ( ) , \"\" ) emptySectionIndices = _metadata ( self . getPlugParent ( ) , \"\" ) if emptySections and emptySectionIndices : for sectionPath , sectionIndex in zip ( emptySections , emptySectionIndices ) : parentPath , unused , sectionName = sectionPath . rpartition ( \"\" ) parentSection = section ( layout , parentPath ) if parentSection . child ( sectionName ) is None : parentSection . insert ( sectionIndex , _SectionLayoutItem ( sectionName ) ) if len ( layout ) == and isinstance ( self . __parent , Gaffer . Node ) : layout . append ( _SectionLayoutItem ( \"\" ) ) expandedPaths = self . __pathListing . getExpandedPaths ( ) self . __pathListing . setPath ( self . __LayoutPath ( layout , \"\" ) ) self . __pathListing . setExpandedPaths ( expandedPaths ) @ GafferUI . LazyMethod ( ) def __updatePathLazily ( self ) : self . __updatePath ( ) def __updateMetadata ( self ) : emptySections = IECore . StringVectorData ( ) emptySectionIndices = IECore . IntVectorData ( ) def walk ( layoutItem , path = \"\" , index = ) : for childItem in layoutItem : if isinstance ( childItem , _PlugLayoutItem ) : Gaffer . Metadata . registerPlugValue ( childItem . plug , \"\" , path ) Gaffer . Metadata . registerPlugValue ( childItem . plug , \"\" , index ) index += elif isinstance ( childItem , _SectionLayoutItem ) : childPath = path + \"\" + childItem . name ( ) if path else childItem . name ( ) if len ( childItem ) : index = walk ( childItem , childPath , index ) else : emptySections . append ( childPath ) emptySectionIndices . append ( layoutItem . index ( childItem ) ) return index with Gaffer . BlockedConnection ( self . __plugMetadataChangedConnection ) : walk ( self . __pathListing . getPath ( ) . copy ( ) . setFromString ( \"\" ) . item ( ) ) _registerMetadata ( self . getPlugParent ( ) , \"\" , emptySections ) _registerMetadata ( self . getPlugParent ( ) , \"\" , emptySectionIndices ) def __childAddedOrRemoved ( self , parent , child ) : assert ( parent . isSame ( self . __parent ) ) self . __updateChildNameChangedConnection ( child ) self . __updatePathLazily ( ) def __childNameChanged ( self , child ) : selection = self . getSelection ( ) self . __updatePath ( ) if isinstance ( selection , Gaffer . Plug ) and child . isSame ( selection ) : self . setSelection ( selection ) def __updateChildNameChangedConnection ( self , child ) : if self . __parent . isSame ( child . parent ( ) ) : if child not in self . __childNameChangedConnections : self . __childNameChangedConnections [ child ] = child . nameChangedSignal ( ) . connect ( Gaffer . WeakMethod ( self . __childNameChanged ) ) else : if child in self . __childNameChangedConnections : del self . __childNameChangedConnections [ child ] def __dragEnter ( self , listing , event ) : if event . sourceWidget is not self . __pathListing : return False if not isinstance ( event . data , IECore . StringVectorData ) : return False dragPath = self . __pathListing . getPath ( ) . copy ( ) . setFromString ( event . data [ ] ) self . __dragItem = dragPath . item ( ) self . __pathListing . setPathExpanded ( dragPath , False ) return True def __dragMove ( self , listing , event ) : if self . __dragItem is None : return False targetPath = self . __pathListing . pathAt ( event . line . p0 ) if targetPath is not None : targetItem = targetPath . item ( ) ", "answer": "if targetItem is not None :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " \"\"\"\"\"\" from __future__ import division import zipfile import os from x84 . bbs import getsession , getterminal , echo , getch , syncterm_setfont from x84 . bbs import get_ini , DBProxy , Lightbar , LineEditor from x84 . bbs import send_modem , recv_modem from x84 . default . common import filesize DIZ_DB = '' ROOT = get_ini ( section = '' , key = '' ) or '' UPLOADS_DIR = os . path . join ( ROOT , '' ) COLOR_HIGHLIGHT = get_ini ( section = '' , key = '' ) or '' COLOR_BORDER = get_ini ( section = '' , key = '' , ) or '' SYNCTERM_FONT = get_ini ( section = '' , key = '' ) or '' FLAGGED_CHAR = get_ini ( section = '' , key = '' ) or u'' COLLY_EXTENSIONS = get_ini ( section = '' , key = '' , split = True ) or [ '' , '' , '' ] FLAGGED_DIRNAME = get_ini ( section = '' , key = '' ) or u'' . format ( os . path . sep ) COLLY_DECODING = get_ini ( section = '' , key = '' ) or '' class FileBrowser ( object ) : \"\"\"\"\"\" diz_location = last_diz_len = max_diz_width = max_diz_height = flagged_files = set ( ) diz_extractors = dict ( ) browser = FileBrowser ( ) def diz_from_dms ( binary , filename ) : \"\"\"\"\"\" import subprocess args = ( '' , filename ) proc = subprocess . Popen ( ( binary , ) + args , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) output , _ = proc . communicate ( ) if proc . returncode == : return output . decode ( '' ) else : return u'' def diz_from_lha ( binary , filename ) : \"\"\"\"\"\" import subprocess import tempfile import shutil description = u'' path = tempfile . mkdtemp ( prefix = '' ) args = ( '' . format ( path ) , filename ) proc = subprocess . Popen ( ( binary , ) + args , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) proc . wait ( ) dizfilename = os . path . join ( path , '' ) if proc . returncode == and os . path . isfile ( dizfilename ) : with open ( dizfilename , '' ) as dizfile : description = dizfile . read ( ) . decode ( '' ) try : shutil . rmtree ( path ) except OSError : pass return description def diz_from_zip ( filename , method = zipfile . ZIP_STORED ) : \"\"\"\"\"\" try : myzip = zipfile . ZipFile ( filename , compression = method , allowZip64 = True ) for cname in ( cname for cname in myzip . namelist ( ) if cname . lower ( ) == '' ) : return myzip . read ( cname ) . decode ( '' ) return u'' except zipfile . BadZipfile : return u'' except zipfile . LargeZipFile : return u'' except NotImplementedError : return u'' def get_diz_from_colly ( filepath ) : \"\"\"\"\"\" colly = open ( filepath , '' ) . read ( ) colly_diz_begin = '' colly_diz_end = '' pos = colly . find ( colly_diz_begin ) if pos > : colly = colly [ pos + len ( colly_diz_begin ) : ] pos = colly . find ( colly_diz_end ) if pos > : return colly [ : pos ] . splitlines ( ) return None def get_instructions ( term , is_sysop = None ) : \"\"\"\"\"\" return [ term . bold_blue_underline ( u'' ) , u'' , u'' . format ( term . reverse ( u'' ) ) , u'' . format ( term . reverse ( u'' ) ) , term . reverse ( u'' ) , u'' , u'' . format ( term . reverse ( u'' ) ) , u'' . format ( term . reverse ( u'' ) ) , u'' . format ( term . reverse ( u'' ) ) , u'' . format ( term . reverse ( u'' ) ) if is_sysop else u'' , u'' . format ( term . reverse ( u'' ) ) , u'' , u'' . format ( term . bold ( u'' ) ) , ] def edit_description ( filepath , db_desc ) : \"\"\"\"\"\" from x84 . bbs import gosub new_desc = None if filepath in db_desc : new_desc = u'' . join ( [ line . decode ( '' ) for line in db_desc [ filepath ] ] ) new_desc = gosub ( '' , continue_draft = new_desc ) if not new_desc : return with db_desc : db_desc [ filepath ] = new_desc . splitlines ( ) def download_files ( term , session , protocol = '' ) : \"\"\"\"\"\" if not len ( browser . flagged_files ) : return False echo ( term . clear ) flagged = browser . flagged_files . copy ( ) for fname in flagged : _fname = fname [ fname . rfind ( os . path . sep ) + : ] . decode ( '' ) echo ( term . bold_green ( u'' u'' . format ( protocol = protocol , _fname = _fname ) ) ) echo ( u'' ) fin = open ( fname , '' ) if not send_modem ( fin , protocol ) : echo ( term . bold_red ( u'' ) ) else : browser . flagged_files . remove ( fname ) session . user [ '' ] = browser . flagged_files echo ( term . bold ( u'' ) ) term . inkey ( ) def upload_files ( term , protocol = '' ) : \"\"\"\"\"\" echo ( term . clear ) while True : echo ( u'' ) led = LineEditor ( width = term . width - ) led . refresh ( ) inp = led . read ( ) led = None if inp : for illegal in ( os . path . sep , u'' , u'' , ) : if illegal in inp : echo ( term . bold_red ( u'' ) ) term . inkey ( ) return echo ( term . bold ( u'' . format ( protocol ) ) ) upload_filename = os . path . join ( UPLOADS_DIR , inp ) try : upload = open ( upload_filename , '' ) except IOError as err : echo ( term . bold_red ( '' . format ( err = err ) ) ) else : if not recv_modem ( upload , protocol ) : echo ( term . bold_red ( u'' ) ) os . unlink ( upload_filename ) else : echo ( term . bold_green ( u'' ) ) term . inkey ( ) else : return def draw_interface ( term , lightbar ) : \"\"\"\"\"\" lightbar . height = term . height lightbar . width = max ( , int ( term . width * ) ) browser . diz_location = lightbar . width + browser . max_diz_width = term . width - lightbar . width - browser . max_diz_height = term . height - echo ( u'' . join ( [ term . clear , lightbar . border ( ) , lightbar . refresh ( ) ] ) ) def clear_diz ( term ) : \"\"\"\"\"\" echo ( term . move ( , browser . diz_location ) ) for i in range ( browser . last_diz_len + ) : echo ( u'' . join ( ( term . move ( i , browser . diz_location ) , term . clear_eol ) ) ) def describe_file ( term , diz , directory , filename , isdir = None ) : \"\"\"\"\"\" if isdir or filename == u'' . format ( os . path . sep ) : description = u'' . format ( txt_Directory = term . bold ( u'' ) , filename = filename . decode ( '' ) ) else : _size = filesize ( os . path . join ( directory , filename ) ) _filename = ( filename [ len ( ROOT ) : ] . decode ( '' ) if directory == os . path . join ( ROOT , FLAGGED_DIRNAME ) else filename . decode ( '' ) ) description = ( u'' . format ( txt_Filename = term . bold ( u'' ) , filename = _filename , txt_Size = term . bold ( u'' ) , size = _size ) ) description = term . wrap ( description , browser . max_diz_width ) echo ( u'' . join ( ( term . move ( , browser . diz_location ) , u'' . join ( [ '' . format ( term . move_x ( browser . diz_location ) , line ) for line in description ] ) , term . move ( + len ( description ) , browser . diz_location ) ) ) ) wrapped_diz = [ ] for line in diz : wrapped_diz += term . wrap ( line , browser . max_diz_width ) wrapped_diz = wrapped_diz [ : browser . max_diz_height - len ( description ) + ] output = u'' for line in wrapped_diz : browser . last_diz_len += output = u'' . join ( ( output , term . move_x ( browser . diz_location ) , line , u'' ) ) echo ( output ) def mark_flagged ( directory , files ) : \"\"\"\"\"\" files_list = list ( ) for fname in files : prefix = u'' if os . path . join ( directory , fname ) in browser . flagged_files : prefix = FLAGGED_CHAR txt_fname = fname . strip ( ) . decode ( '' ) item = ( fname , ( u'' . format ( prefix = prefix , txt_fname = txt_fname ) ) ) files_list . append ( item ) return files_list def flagged_listdir ( ) : \"\"\"\"\"\" ", "answer": "files = [ u'' . format ("}, {"prompt": " class FixedValuePolicy ( object ) : def __init__ ( self , value ) : self . value = value def notify ( self ) : ", "answer": "pass "}, {"prompt": " from django . conf import settings POST_NAME_MIN_LENGTH = getattr ( settings , '' , ) SHORT_POST_MAX_LENGTH = getattr ( settings , '' , ) CUT_MAX_LENGTH = getattr ( settings , '' , ) CUT_TAG = getattr ( settings , '' , '' ) CUT_TAG_SYNONYMS = getattr ( settings , '' , [ '' ] ) ENABLE_USER_BLOG = getattr ( settings , '' , True ) ", "answer": "ENABLE_BLOGS = getattr ( settings , '' , True ) "}, {"prompt": " \"\"\"\"\"\" import os , time COLORS = { '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : } RESET = '' def print_queries ( filter = None ) : \"\"\"\"\"\" def wrapper1 ( func ) : def wrapper2 ( * args , ** kwargs ) : from django . db import connection sqltime , longest , numshown = , , initqueries = len ( connection . queries ) starttime = time . time ( ) result = func ( * args , ** kwargs ) for query in connection . queries [ initqueries : ] : sqltime += float ( query [ '' ] . strip ( '' ) ) longest = max ( longest , float ( query [ '' ] . strip ( '' ) ) ) if not filter or filter in query [ '' ] : numshown += querystr = colored ( '' % query [ '' ] , '' ) querystr += colored ( query [ '' ] , '' ) print querystr numqueries = len ( connection . queries ) - initqueries numhidden = numqueries - numshown runtime = round ( time . time ( ) - starttime , ) ", "answer": "proctime = round ( runtime - sqltime , )"}, {"prompt": " from pyalgotrade import strategy from pyalgotrade . barfeed import yahoofeed from pyalgotrade . technical import ma class MyStrategy ( strategy . BacktestingStrategy ) : def __init__ ( self , feed , instrument ) : ", "answer": "super ( MyStrategy , self ) . __init__ ( feed )"}, {"prompt": " import os import codecs try : from setuptools import setup , find_packages , Command except ImportError : from ez_setup import use_setuptools use_setuptools ( ) from setuptools import setup , find_packages , Command from distutils . command . install_data import install_data from distutils . command . install import INSTALL_SCHEMES import sys import ghettoq packages , data_files = [ ] , [ ] root_dir = os . path . dirname ( __file__ ) if root_dir != '' : os . chdir ( root_dir ) src_dir = \"\" install_requires = [ ] ", "answer": "if sys . version_info < ( , ) :"}, {"prompt": " from distutils . core import setup setup ( name = '' , version = '' , description = '' , ", "answer": "author = '' ,"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import dimagi . utils . couch . migration class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . CharField ( max_length = , null = True , db_index = True ) ) , ( '' , models . CharField ( max_length = , null = True , db_index = True ) ) , ( '' , models . CharField ( max_length = , null = True ) ) , ( '' , models . CharField ( max_length = , null = True , db_index = True ) ) , ( '' , models . CharField ( max_length = , null = True , db_index = True ) ) , ( '' , models . CharField ( max_length = , null = True ) ) , ", "answer": "( '' , models . CharField ( max_length = , null = True ) ) ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import logging logger = logging . getLogger ( __name__ ) from . . core import validation from . . core . validation . warnings import EMPTY_LAYOUT , BOTH_CHILD_AND_ROOT from . . core . properties import abstract from . . core . properties import Int , Instance , List from . component import Component @ abstract class Layout ( Component ) : \"\"\"\"\"\" width = Int ( help = \"\"\"\"\"\" ) ", "answer": "height = Int ( help = \"\"\"\"\"\" )"}, {"prompt": " import contextlib import errno import functools ", "answer": "import os"}, {"prompt": " from gevent import monkey monkey . patch_all ( ) import sys import click from bottle import static_file , Bottle , run , view from bottle import TEMPLATE_PATH as T from bottle . ext . websocket import GeventWebSocketServer from bottle . ext . auth . decorator import login from gevent . pywsgi import WSGIServer from geventwebsocket . handler import WebSocketHandler from beaker . middleware import SessionMiddleware from mining . controllers . api import api_app from mining . controllers . data import data_app from mining . utils import conf from mining . auth import auth from mining . settings import TEMPLATE_PATH , STATIC_PATH from mining . celeryc import celery_app from mining . bin . scheduler import scheduler_app from mining . bin . demo . build_admin import build reload ( sys ) sys . setdefaultencoding ( '' ) T . insert ( , TEMPLATE_PATH ) session_opts = { '' : '' , '' : '' , '' : '' , '' : , '' : True } app = SessionMiddleware ( Bottle ( ) , session_opts ) app . wrap_app . mount ( '' , api_app ) app . wrap_app . mount ( '' , data_app ) app . wrap_app . install ( auth ) @ app . wrap_app . route ( '' , name = '' ) def static ( path ) : yield static_file ( path , root = STATIC_PATH ) @ app . wrap_app . route ( '' ) @ login ( ) @ view ( '' ) def index ( ) : return { '' : app . wrap_app . get_url , '' : conf ( '' ) [ '' ] , '' : conf ( '' ) [ '' ] } @ app . wrap_app . route ( '' ) @ view ( '' ) def login ( ) : return { '' : app . wrap_app . get_url , '' : conf ( '' ) [ '' ] } @ click . group ( ) def cmds ( ) : pass @ cmds . command ( ) @ click . option ( '' , type = int , help = u'' ) ", "answer": "@ click . option ( '' , type = str , help = u'' )"}, {"prompt": " import numpy as np import theano import theano . tensor as T import layers import cc_layers import custom import load_data import realtime_augmentation as ra import time import csv import os import cPickle as pickle from datetime import datetime , timedelta BATCH_SIZE = NUM_INPUT_FEATURES = LEARNING_RATE_SCHEDULE = { : , : , : , } MOMENTUM = WEIGHT_DECAY = CHUNK_SIZE = NUM_CHUNKS = VALIDATE_EVERY = NUM_CHUNKS_NONORM = GEN_BUFFER_SIZE = TARGET_PATH = \"\" ANALYSIS_PATH = \"\" print \"\" input_sizes = [ ( , ) , ( , ) ] ds_transforms = [ ra . build_ds_transform ( , target_size = input_sizes [ ] ) , ra . build_ds_transform ( , target_size = input_sizes [ ] ) + ra . build_augmentation_transform ( rotation = ) ] num_input_representations = len ( ds_transforms ) augmentation_params = { '' : ( / , ) , '' : ( , ) , '' : ( , ) , '' : ( - , ) , '' : True , } augmented_data_gen = ra . realtime_augmented_data_gen ( num_chunks = NUM_CHUNKS , chunk_size = CHUNK_SIZE , augmentation_params = augmentation_params , ds_transforms = ds_transforms , target_sizes = input_sizes , processor_class = ra . LoadAndProcessPysexCenteringRescaling ) post_augmented_data_gen = ra . post_augment_brightness_gen ( augmented_data_gen , std = ) train_gen = load_data . buffered_gen_mp ( post_augmented_data_gen , buffer_size = GEN_BUFFER_SIZE ) y_train = np . load ( \"\" ) train_ids = load_data . train_ids test_ids = load_data . test_ids num_train = len ( train_ids ) num_test = len ( test_ids ) num_valid = num_train // num_train -= num_valid y_valid = y_train [ num_train : ] y_train = y_train [ : num_train ] valid_ids = train_ids [ num_train : ] train_ids = train_ids [ : num_train ] train_indices = np . arange ( num_train ) valid_indices = np . arange ( num_train , num_train + num_valid ) test_indices = np . arange ( num_test ) def create_train_gen ( ) : \"\"\"\"\"\" data_gen_train = ra . realtime_fixed_augmented_data_gen ( train_indices , '' , ds_transforms = ds_transforms , chunk_size = CHUNK_SIZE , target_sizes = input_sizes , processor_class = ra . LoadAndProcessFixedPysexCenteringRescaling ) return load_data . buffered_gen_mp ( data_gen_train , buffer_size = GEN_BUFFER_SIZE ) def create_valid_gen ( ) : data_gen_valid = ra . realtime_fixed_augmented_data_gen ( valid_indices , '' , ds_transforms = ds_transforms , chunk_size = CHUNK_SIZE , target_sizes = input_sizes , processor_class = ra . LoadAndProcessFixedPysexCenteringRescaling ) return load_data . buffered_gen_mp ( data_gen_valid , buffer_size = GEN_BUFFER_SIZE ) def create_test_gen ( ) : data_gen_test = ra . realtime_fixed_augmented_data_gen ( test_indices , '' , ds_transforms = ds_transforms , chunk_size = CHUNK_SIZE , target_sizes = input_sizes , processor_class = ra . LoadAndProcessFixedPysexCenteringRescaling ) return load_data . buffered_gen_mp ( data_gen_test , buffer_size = GEN_BUFFER_SIZE ) print \"\" start_time = time . time ( ) xs_valid = [ [ ] for _ in xrange ( num_input_representations ) ] for data , length in create_valid_gen ( ) : for x_valid_list , x_chunk in zip ( xs_valid , data ) : x_valid_list . append ( x_chunk [ : length ] ) xs_valid = [ np . vstack ( x_valid ) for x_valid in xs_valid ] xs_valid = [ x_valid . transpose ( , , , ) for x_valid in xs_valid ] print \"\" % ( time . time ( ) - start_time ) print \"\" l0 = layers . Input2DLayer ( BATCH_SIZE , NUM_INPUT_FEATURES , input_sizes [ ] [ ] , input_sizes [ ] [ ] ) l0_45 = layers . Input2DLayer ( BATCH_SIZE , NUM_INPUT_FEATURES , input_sizes [ ] [ ] , input_sizes [ ] [ ] ) l0r = layers . MultiRotSliceLayer ( [ l0 , l0_45 ] , part_size = , include_flip = True ) l0s = cc_layers . ShuffleBC01ToC01BLayer ( l0r ) l1a = cc_layers . CudaConvnetConv2DLayer ( l0s , n_filters = , filter_size = , weights_std = , init_bias_value = , dropout = , partial_sum = , untie_biases = True ) l1 = cc_layers . CudaConvnetPooling2DLayer ( l1a , pool_size = ) l2a = cc_layers . CudaConvnetConv2DLayer ( l1 , n_filters = , filter_size = , weights_std = , init_bias_value = , dropout = , partial_sum = , untie_biases = True ) l2 = cc_layers . CudaConvnetPooling2DLayer ( l2a , pool_size = ) l3a = cc_layers . CudaConvnetConv2DLayer ( l2 , n_filters = , filter_size = , weights_std = , init_bias_value = , dropout = , partial_sum = , untie_biases = True ) l3b = cc_layers . CudaConvnetConv2DLayer ( l3a , n_filters = , filter_size = , pad = , weights_std = , init_bias_value = , dropout = , partial_sum = , untie_biases = True ) l3 = cc_layers . CudaConvnetPooling2DLayer ( l3b , pool_size = ) l3s = cc_layers . ShuffleC01BToBC01Layer ( l3 ) j3 = layers . MultiRotMergeLayer ( l3s , num_views = ) l4a = layers . DenseLayer ( j3 , n_outputs = , weights_std = , init_bias_value = , dropout = , nonlinearity = layers . identity ) l4b = layers . FeatureMaxPoolingLayer ( l4a , pool_size = , feature_dim = , implementation = '' ) l4c = layers . DenseLayer ( l4b , n_outputs = , weights_std = , init_bias_value = , dropout = , nonlinearity = layers . identity ) l4 = layers . FeatureMaxPoolingLayer ( l4c , pool_size = , feature_dim = , implementation = '' ) l5 = layers . DenseLayer ( l4 , n_outputs = , weights_std = , init_bias_value = , dropout = , nonlinearity = layers . identity ) l6 = custom . OptimisedDivGalaxyOutputLayer ( l5 ) train_loss_nonorm = l6 . error ( normalisation = False ) train_loss = l6 . error ( ) valid_loss = l6 . error ( dropout_active = False ) all_parameters = layers . all_parameters ( l6 ) all_bias_parameters = layers . all_bias_parameters ( l6 ) xs_shared = [ theano . shared ( np . zeros ( ( , , , ) , dtype = theano . config . floatX ) ) for _ in xrange ( num_input_representations ) ] y_shared = theano . shared ( np . zeros ( ( , ) , dtype = theano . config . floatX ) ) learning_rate = theano . shared ( np . array ( LEARNING_RATE_SCHEDULE [ ] , dtype = theano . config . floatX ) ) idx = T . lscalar ( '' ) givens = { l0 . input_var : xs_shared [ ] [ idx * BATCH_SIZE : ( idx + ) * BATCH_SIZE ] , l0_45 . input_var : xs_shared [ ] [ idx * BATCH_SIZE : ( idx + ) * BATCH_SIZE ] , l6 . target_var : y_shared [ idx * BATCH_SIZE : ( idx + ) * BATCH_SIZE ] , } updates_nonorm = layers . gen_updates_nesterov_momentum_no_bias_decay ( train_loss_nonorm , all_parameters , all_bias_parameters , learning_rate = learning_rate , momentum = MOMENTUM , weight_decay = WEIGHT_DECAY ) updates = layers . gen_updates_nesterov_momentum_no_bias_decay ( train_loss , all_parameters , all_bias_parameters , learning_rate = learning_rate , momentum = MOMENTUM , weight_decay = WEIGHT_DECAY ) train_nonorm = theano . function ( [ idx ] , train_loss_nonorm , givens = givens , updates = updates_nonorm ) train_norm = theano . function ( [ idx ] , train_loss , givens = givens , updates = updates ) compute_loss = theano . function ( [ idx ] , valid_loss , givens = givens ) compute_output = theano . function ( [ idx ] , l6 . predictions ( dropout_active = False ) , givens = givens , on_unused_input = '' ) compute_features = theano . function ( [ idx ] , l4 . output ( dropout_active = False ) , givens = givens , on_unused_input = '' ) print \"\" start_time = time . time ( ) prev_time = start_time num_batches_valid = x_valid . shape [ ] // BATCH_SIZE losses_train = [ ] losses_valid = [ ] param_stds = [ ] for e in xrange ( NUM_CHUNKS ) : print \"\" % ( e + , NUM_CHUNKS ) chunk_data , chunk_length = train_gen . next ( ) y_chunk = chunk_data . pop ( ) xs_chunk = chunk_data xs_chunk = [ x_chunk . transpose ( , , , ) for x_chunk in xs_chunk ] if e in LEARNING_RATE_SCHEDULE : current_lr = LEARNING_RATE_SCHEDULE [ e ] learning_rate . set_value ( LEARNING_RATE_SCHEDULE [ e ] ) print \"\" % current_lr if e >= NUM_CHUNKS_NONORM : train = train_norm else : train = train_nonorm print \"\" for x_shared , x_chunk in zip ( xs_shared , xs_chunk ) : x_shared . set_value ( x_chunk ) y_shared . set_value ( y_chunk ) num_batches_chunk = x_chunk . shape [ ] // BATCH_SIZE print \"\" losses = [ ] for b in xrange ( num_batches_chunk ) : loss = train ( b ) losses . append ( loss ) mean_train_loss = np . sqrt ( np . mean ( losses ) ) print \"\" % mean_train_loss losses_train . append ( mean_train_loss ) param_stds . append ( [ p . std ( ) for p in layers . get_param_values ( l6 ) ] ) if ( ( e + ) % VALIDATE_EVERY ) == : print print \"\" print \"\" for x_shared , x_valid in zip ( xs_shared , xs_valid ) : x_shared . set_value ( x_valid ) y_shared . set_value ( y_valid ) print \"\" losses = [ ] for b in xrange ( num_batches_valid ) : loss = compute_loss ( b ) losses . append ( loss ) mean_valid_loss = np . sqrt ( np . mean ( losses ) ) print \"\" % mean_valid_loss losses_valid . append ( mean_valid_loss ) now = time . time ( ) time_since_start = now - start_time time_since_prev = now - prev_time prev_time = now est_time_left = time_since_start * ( float ( NUM_CHUNKS - ( e + ) ) / float ( e + ) ) eta = datetime . now ( ) + timedelta ( seconds = est_time_left ) eta_str = eta . strftime ( \"\" ) print \"\" % ( load_data . hms ( time_since_start ) , time_since_prev ) print \"\" % ( load_data . hms ( est_time_left ) , eta_str ) print del chunk_data , xs_chunk , x_chunk , y_chunk , xs_valid , x_valid print \"\" predictions_list = [ ] for b in xrange ( num_batches_valid ) : predictions = compute_output ( b ) predictions_list . append ( predictions ) all_predictions = np . vstack ( predictions_list ) all_predictions [ all_predictions > ] = all_predictions [ all_predictions < ] = print \"\" % ANALYSIS_PATH with open ( ANALYSIS_PATH , '' ) as f : pickle . dump ( { '' : valid_ids [ : num_batches_valid * BATCH_SIZE ] , '' : all_predictions , '' : y_valid , '' : mean_train_loss , '' : mean_valid_loss , '' : time_since_start , '' : losses_train , '' : losses_valid , '' : layers . get_param_values ( l6 ) , ", "answer": "'' : param_stds ,"}, {"prompt": " \"\"\"\"\"\" import logging import threading log = logging . getLogger ( __name__ ) class SingletonMetaclass ( type ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals import concurrent . futures import contextlib import json import logging import multiprocessing import pkgutil import re try : import urllib . request as urllib_request except ImportError : import urllib2 as urllib_request import xml . parsers . expat try : ", "answer": "import xmlrpc . client as xmlrpc_client"}, {"prompt": " from . . utils import TranspileTestCase , BuiltinFunctionTestCase ", "answer": "class RoundTests ( TranspileTestCase ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " try : from itertools import izip except ImportError : izip = zip import numpy as np from . accuracy_cython import compute_rank_violations def read_analogy_file ( filename ) : \"\"\"\"\"\" section = None with open ( filename , '' ) as questions_file : for line in questions_file : if line . startswith ( '' ) : section = line [ : ] . replace ( '' , '' ) continue else : words = line . replace ( '' , '' ) . split ( '' ) yield section , words def construct_analogy_test_set ( test_examples , dictionary , ignore_missing = False ) : \"\"\"\"\"\" test = [ ] for example in test_examples : try : ", "answer": "test . append ( [ dictionary [ word ] for word in example ] )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( primary_key = True , verbose_name = '' , auto_created = True , serialize = False ) ) , ( '' , models . FileField ( null = True , blank = True , upload_to = '' ) ) , ] , options = { } , ", "answer": "bases = ( models . Model , ) ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from . alias_list_panel import AliasListPanel from . analyzer_list_panel import AnalyzerListPanel from . doc_type_list_panel import DocTypeListPanel from . field_list_panel import FieldListPanel from . index_list_panel import IndexListPanel from . index_template_list_panel import IndexTemplateListPanel from . repository_list_panel import RepositoryListPanel from . script_list_panel import ScriptListPanel from . search_template_list_panel import SearchTemplateListPanel from . snapshot_list_panel import SnapshotListPanel from . switch_server_list_panel import SwitchServerListPanel from . warmer_list_panel import WarmerListPanel __all__ = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ", "answer": "\"\" ,"}, {"prompt": " import os import socket import unittest import doctest def docs_path ( * parts ) : ", "answer": "return os . path . join ( os . path . dirname ( os . path . dirname ( __file__ ) ) , * parts )"}, {"prompt": " import logging import re import time from django . utils . translation import ugettext as _ from desktop . lib . exceptions_renderable import PopupException from desktop . lib . i18n import force_unicode from desktop . lib . rest . http_client import RestException from desktop . models import DefaultConfiguration from notebook . data_export import download as spark_download from notebook . connectors . base import Api , QueryError , SessionExpired , _get_snippet_session LOG = logging . getLogger ( __name__ ) try : from spark . conf import LIVY_SERVER_SESSION_KIND from spark . job_server_api import get_api as get_spark_api except ImportError , e : LOG . exception ( '' ) class SparkConfiguration ( object ) : APP_NAME = '' PROPERTIES = [ { \"\" : \"\" , \"\" : _ ( \"\" ) , \"\" : _ ( \"\" ) , \"\" : \"\" , \"\" : False , \"\" : True , \"\" : [ ] , } , { \"\" : \"\" , \"\" : _ ( \"\" ) , \"\" : _ ( \"\" ) , \"\" : \"\" , \"\" : False , \"\" : True , \"\" : [ ] , } , { \"\" : \"\" , \"\" : _ ( \"\" ) , \"\" : _ ( \"\" ) , \"\" : \"\" , \"\" : False , \"\" : True , \"\" : [ ] , } , { \"\" : \"\" , \"\" : _ ( \"\" ) , \"\" : _ ( \"\" ) , \"\" : \"\" , \"\" : False , \"\" : False , \"\" : '' , } , { \"\" : \"\" , ", "answer": "\"\" : _ ( \"\" ) ,"}, {"prompt": " \"\"\"\"\"\" from collections import defaultdict from itertools import izip import re default_charset = \"\"\"\"\"\" _dewhite = re . compile ( r\"\" ) _char = r\"\" ", "answer": "_char_map = re . compile ( \"\" + _char + \"\" + _char + \"\" )"}, {"prompt": " import fixtures import constants from authomatic . providers import oauth2 conf = fixtures . get_configuration ( '' ) CONFIG = { '' : '' , '' : '' , '' : '' , '' : [ '' , ] , '' : , '' : , '' : oauth2 . Eventbrite , '' : oauth2 . Eventbrite . user_info_scope , '' : { '' : None , '' : None , '' : None , '' : conf . user_email , '' : conf . user_first_name , '' : None , '' : conf . user_id , '' : conf . user_last_name , '' : None , '' : None , '' : None , ", "answer": "'' : conf . user_name ,"}, {"prompt": " def pytest_configure ( ) : from django . conf import settings print ( \"\" ) settings . configure ( DEBUG_PROPAGATE_EXCEPTIONS = True , DATABASES = { '' : { '' : '' , '' : '' } } , SITE_ID = , SECRET_KEY = '' , USE_I18N = True , USE_L10N = True , STATIC_URL = '' , ROOT_URLCONF = '' , TEMPLATE_LOADERS = ( '' , '' , ) , MIDDLEWARE_CLASSES = ( '' , '' , '' , '' , '' , ) , INSTALLED_APPS = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , ) , PASSWORD_HASHERS = ( '' , '' , '' , '' , '' , '' , ) , ) try : import oauth_provider import oauth2 except ImportError : pass else : settings . INSTALLED_APPS += ( '' , ) ", "answer": "try :"}, {"prompt": " from chainer import cuda from chainer import optimizer class SGD ( optimizer . GradientMethod ) : \"\"\"\"\"\" def __init__ ( self , lr = ) : self . lr = lr def update_one_cpu ( self , param , state ) : param . data -= self . lr * param . grad ", "answer": "def update_one_gpu ( self , param , state ) :"}, {"prompt": " from multiprocessing import Process from contextlib import contextmanager from . models import BaseModel from . exceptions import NotFound from . globals import SwappableDict , cosmos db = SwappableDict ( ) class DBModel ( BaseModel ) : @ classmethod def get_by_id ( cls , id ) : try : return db [ cls . table_name ] [ id ] except KeyError : raise NotFound @ classmethod def get_list ( cls , ** kwargs ) : if not kwargs : return sorted ( db [ cls . table_name ] . items ( ) ) ret = [ ] for id , rep in db [ cls . table_name ] . items ( ) : keep = True for key , val in kwargs . items ( ) : if rep [ key ] != val : keep = False break if keep : ret . append ( ( id , rep ) ) return sorted ( ret ) @ classmethod def create ( cls , ** patch ) : id = str ( len ( db [ cls . table_name ] ) ) db [ cls . table_name ] [ id ] = patch return id , patch @ classmethod def update ( cls , id , ** patch ) : rep = db [ cls . table_name ] [ id ] rep . update ( patch ) return rep @ classmethod def delete ( cls , id ) : if id not in db [ cls . table_name ] : raise NotFound del db [ cls . table_name ] [ id ] @ contextmanager def served_api ( api , port , ** kwargs ) : from time import sleep p = Process ( target = api . run , args = ( port , ) , kwargs = kwargs ) p . start ( ) sleep ( ) try : with cosmos . swap ( { } ) : yield except Exception as e : raise e finally : p . terminate ( ) ", "answer": "class WildcardClass ( object ) :"}, {"prompt": " from __future__ import absolute_import , division , print_function import pandas as pd import numpy as np ", "answer": "from . core import tokenize , DataFrame"}, {"prompt": " from __future__ import unicode_literals from django . db import migrations , models import social . apps . django_app . default . fields class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AlterField ( model_name = '' , name = '' , field = social . apps . django_app . default . fields . JSONField ( default = { } ) , ) , ", "answer": "] "}, {"prompt": " from contextlib import contextmanager from django . contrib . sites . models import Site from django . core import mail from django . db import transaction from django . utils . functional import LazyObject def get_current_site ( ) : if Site . _meta . installed : return Site . objects . get_current ( ) return None def in_transaction ( test_ignore = True ) : result = transaction . is_managed ( ) if test_ignore : result = result and not hasattr ( mail , '' ) return result @ contextmanager def patch ( namespace , name , function ) : \"\"\"\"\"\" if isinstance ( namespace , LazyObject ) : if namespace . _wrapped is None : namespace . _setup ( ) namespace = namespace . _wrapped ", "answer": "try :"}, {"prompt": " import copy import six from nailgun import consts from nailgun . extensions . network_manager . objects . serializers import network_configuration from . import base as base_tests from . . objects import adapters from . . objects import relations class TestUpgradeHelperCloneCluster ( base_tests . BaseCloneClusterTest ) : def setUp ( self ) : super ( TestUpgradeHelperCloneCluster , self ) . setUp ( ) self . orig_net_manager = self . src_cluster . get_network_manager ( ) self . serialize_nets = network_configuration . NeutronNetworkConfigurationSerializer . serialize_for_cluster self . public_net_data = { \"\" : \"\" , \"\" : \"\" , \"\" : [ [ \"\" , \"\" ] ] , } def test_create_cluster_clone ( self ) : new_cluster = self . helper . create_cluster_clone ( self . src_cluster , self . data ) src_cluster_data = self . src_cluster . get_create_data ( ) new_cluster_data = new_cluster . get_create_data ( ) for key , value in src_cluster_data . items ( ) : if key in ( \"\" , \"\" ) : continue self . assertEqual ( value , new_cluster_data [ key ] ) def test_copy_attributes ( self ) : new_cluster = self . helper . create_cluster_clone ( self . src_cluster , self . data ) self . assertNotEqual ( self . src_cluster . generated_attrs , new_cluster . generated_attrs ) attrs = copy . deepcopy ( self . src_cluster . editable_attrs ) attrs [ \"\" ] [ \"\" ] [ \"\" ] = \"\" attrs [ \"\" ] [ \"\" ] [ \"\" ] = \"\" self . src_cluster . editable_attrs = attrs self . helper . copy_attributes ( self . src_cluster , new_cluster ) self . assertEqual ( self . src_cluster . generated_attrs , new_cluster . generated_attrs ) editable_attrs = self . src_cluster . editable_attrs for section , params in six . iteritems ( new_cluster . editable_attrs ) : if section == \"\" : continue for key , value in six . iteritems ( params ) : if key == \"\" : continue self . assertEqual ( editable_attrs [ section ] [ key ] [ \"\" ] , value [ \"\" ] ) def update_public_net_params ( self , networks ) : pub_net = self . _get_pub_net ( networks ) pub_net . update ( self . public_net_data ) self . orig_net_manager . update ( networks ) def _get_pub_net ( self , networks ) : return next ( net for net in networks [ '' ] if net [ '' ] == consts . NETWORKS . public ) def test_copy_network_config ( self ) : new_cluster = self . helper . create_cluster_clone ( self . src_cluster , self . data ) nets = self . serialize_nets ( self . src_cluster . cluster ) self . update_public_net_params ( nets ) self . helper . copy_network_config ( self . src_cluster , new_cluster ) new_nets = self . serialize_nets ( new_cluster . cluster ) public_net = self . _get_pub_net ( new_nets ) self . assertEqual ( public_net [ '' ] , self . public_net_data [ '' ] ) self . assertEqual ( public_net [ '' ] , self . public_net_data [ '' ] ) self . assertEqual ( public_net [ '' ] , ", "answer": "self . public_net_data [ '' ] )"}, {"prompt": " import oslo_i18n _translators = oslo_i18n . TranslatorFactory ( domain = '' ) _ = _translators . primary _LI = _translators . log_info _LW = _translators . log_warning _LE = _translators . log_error ", "answer": "_LC = _translators . log_critical "}, {"prompt": " DOIT_CONFIG = { '' : , '' : [ '' , '' ] } def start ( name ) : print ( \"\" % name ) def stop ( name ) : ", "answer": "print ( \"\" % name )"}, {"prompt": " import numpy as np def growcut_python ( image , state , state_next , window_radius ) : changes = height = image . shape [ ] width = image . shape [ ] for j in xrange ( width ) : for i in xrange ( height ) : winning_colony = state [ i , j , ] defense_strength = state [ i , j , ] for jj in xrange ( max ( j - window_radius , ) , min ( j + window_radius + , width ) ) : for ii in xrange ( max ( i - window_radius , ) , min ( i + window_radius + , height ) ) : if ii != i or jj != j : d = image [ i , j , : ] - image [ ii , jj , : ] s = np . sum ( d ** ) gval = - np . sqrt ( s ) / np . sqrt ( ) attack_strength = gval * state [ ii , jj , ] ", "answer": "if attack_strength > defense_strength :"}, {"prompt": " \"\"\"\"\"\" import sys , random , logging import asyncoro def client_proc ( server , coro = None ) : for i in range ( ) : asyncoro . logger . debug ( '' % i ) ", "answer": "server . send ( i )"}, {"prompt": " \"\"\"\"\"\" revision = '' down_revision = '' from alembic import op def upgrade ( ) : op . create_unique_constraint ( '' , '' , [ '' , '' ] ) def downgrade ( ) : ", "answer": "op . drop_constraint ( '' , '' ) "}, {"prompt": " from flask import Flask from flask import request from flask import jsonify import json import subprocess app = Flask ( __name__ ) config = None @ app . route ( '' , methods = [ '' ] ) def hook_listen ( ) : if request . method == '' : token = request . args . get ( '' ) if token == config [ '' ] : hook = request . args . get ( '' ) if hook : hook_value = config [ '' ] . get ( hook ) if hook_value : try : subprocess . call ( hook_value ) return jsonify ( success = True ) , except OSError as e : return jsonify ( success = False , error = str ( e ) ) , ", "answer": "else :"}, {"prompt": " import sys import os lxVersion = '' lxServer = '' lxPackage = '' lxPreviousPackage = '' lxUserSettingPath = os . path . join ( os . path . expanduser ( '' ) , '' ) lxInfo = { '' : { '' : '' , '' : lxVersion , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : { '' : { '' : '' , '' : '' } , '' : { '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' , '' : [ '' , '' ] } , '' : { '' : '' , '' : '' } } } , '' : { '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' , } , '' : { '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } } , '' : { '' : { '' : '' , '' : [ { '' : , '' : '' } , { '' : , '' : '' } , { '' : , '' : '' } ] } } } , '' : { '' : '' , '' : '' } } , '' : { '' : '' , ", "answer": "'' : lxVersion ,"}, {"prompt": " import unittest from nose . tools import ( assert_is_not_none , assert_true , assert_raises , assert_equal ) import io import pickle import numpy from sknn . mlp import Regressor as MLPR from sknn . mlp import Layer as L , Convolution as C class TestConvolution ( unittest . TestCase ) : def _run ( self , nn , a_in = None , fit = True ) : assert_true ( nn . is_convolution ( ) ) if a_in is None : a_in = numpy . zeros ( ( , , , ) ) a_out = numpy . zeros ( ( , ) ) if fit is True : nn . fit ( a_in , a_out ) a_test = nn . predict ( a_in ) assert_equal ( type ( a_out ) , type ( a_in ) ) return a_test def test_MissingLastDim ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) ) , L ( \"\" ) ] , n_iter = ) , a_in = numpy . zeros ( ( , , ) ) ) def test_SquareKernel ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) ) , L ( \"\" ) ] , n_iter = ) ) def test_KernelPooling ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) , pool_shape = ( , ) ) , L ( \"\" ) ] , n_iter = ) ) def test_VerticalKernel ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) , border_mode = '' ) , L ( \"\" ) ] , n_iter = ) ) def test_VerticalVerbose ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) , border_mode = '' ) , L ( \"\" ) ] , n_iter = , verbose = , valid_size = ) ) def test_HorizontalKernel ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) , border_mode = '' ) , L ( \"\" ) ] , n_iter = ) ) def test_ValidationSize ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) ) , L ( \"\" ) ] , n_iter = , valid_size = ) ) def test_ValidationSet ( self ) : v_in = numpy . zeros ( ( , , , ) ) v_out = numpy . zeros ( ( , ) ) self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) ) , L ( \"\" ) ] , n_iter = , valid_set = ( v_in , v_out ) ) ) def test_MultipleLayers ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) ) , C ( \"\" , channels = , kernel_shape = ( , ) ) , C ( \"\" , channels = , kernel_shape = ( , ) ) , L ( \"\" ) ] , n_iter = ) ) def test_PoolingMaxType ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) , pool_shape = ( , ) , pool_type = '' ) , L ( \"\" ) ] , n_iter = ) ) def test_PoolingMeanType ( self ) : self . _run ( MLPR ( layers = [ C ( \"\" , channels = , kernel_shape = ( , ) , pool_shape = ( , ) , pool_type = '' ) , L ( \"\" ) ] , n_iter = ) ) class TestUpscaling ( unittest . TestCase ) : def _run ( self , nn , scale ) : assert_true ( nn . is_convolution ( ) ) a_in = numpy . zeros ( ( , , , ) ) a_out = numpy . zeros ( ( , * scale , * scale , ) ) nn . fit ( a_in , a_out ) a_test = nn . predict ( a_in ) assert_equal ( type ( a_out ) , type ( a_in ) ) ", "answer": "return a_test"}, {"prompt": " import os import sys from flask import Flask , render_template , request sys . path . append ( os . path . abspath ( os . path . join ( __file__ , '' ) ) ) from ovsdb_client import OVSDBClient app = Flask ( __name__ ) @ app . route ( '' ) def index ( ) : client = OVSDBClient ( '' , ) query = { '' : , '' : '' , '' : [ '' , { '' : '' , '' : '' , '' : [ ] } ] } response = client . request ( query ) return render_template ( '' , stamps = response [ '' ] [ ] [ '' ] ) @ app . route ( '' ) def view ( ) : client = OVSDBClient ( '' , ) query = { '' : , '' : '' , '' : [ ", "answer": "'' ,"}, {"prompt": " import boto from boto . s3 . key import Key from boto . s3 . connection import OrdinaryCallingFormat from django . conf import settings import urllib def _ensure_bucket_exists ( s3 , bucket ) : try : s3 . create_bucket ( bucket ) except boto . exception . S3ResponseError : pass else : print \"\" % bucket if settings . AWS_ENABLED : if settings . AWS_S3_FAKE_S3 is None : _s3 = boto . connect_s3 ( settings . AWS_ACCESS_KEY_ID , settings . AWS_SECRET_ACCESS_KEY ) else : host , port = ( settings . AWS_S3_FAKE_S3 . split ( '' , ) + [ ] ) [ : ] port = int ( port ) _s3 = boto . connect_s3 ( \"\" , \"\" , is_secure = False , port = port , host = host , calling_format = OrdinaryCallingFormat ( ) ) _ensure_bucket_exists ( _s3 , settings . AWS_S3_SOURCE_BUCKET ) _ensure_bucket_exists ( _s3 , settings . AWS_S3_EXPORT_BUCKET ) _ensure_bucket_exists ( _s3 , settings . AWS_S3_BUILDS_BUCKET ) _buckets = { '' : _s3 . get_bucket ( settings . AWS_S3_SOURCE_BUCKET ) , '' : _s3 . get_bucket ( settings . AWS_S3_EXPORT_BUCKET ) , '' : _s3 . get_bucket ( settings . AWS_S3_BUILDS_BUCKET ) , } else : _s3 = None _buckets = None def _requires_aws ( fn ) : if settings . AWS_ENABLED : return fn else : def complain ( * args , ** kwargs ) : raise Exception ( \"\" % fn . __name__ ) return complain @ _requires_aws def read_file ( bucket_name , path ) : bucket = _buckets [ bucket_name ] key = bucket . get_key ( path ) return key . get_contents_as_string ( ) @ _requires_aws def read_file_to_filesystem ( bucket_name , path , destination ) : bucket = _buckets [ bucket_name ] key = bucket . get_key ( path ) key . get_contents_to_filename ( destination ) @ _requires_aws def delete_file ( bucket_name , path ) : bucket = _buckets [ bucket_name ] key = bucket . get_key ( path ) key . delete ( ) @ _requires_aws def save_file ( bucket_name , path , value , public = False , content_type = '' ) : bucket = _buckets [ bucket_name ] key = Key ( bucket ) key . key = path if public : policy = '' else : policy = '' key . set_contents_from_string ( value , policy = policy , headers = { '' : content_type } ) @ _requires_aws def upload_file ( bucket_name , dest_path , src_path , public = False , content_type = '' , download_filename = None ) : bucket = _buckets [ bucket_name ] key = Key ( bucket ) key . key = dest_path if public : policy = '' else : policy = '' headers = { '' : content_type } if download_filename is not None : headers [ '' ] = '' % download_filename . replace ( '' , '' ) key . set_contents_from_filename ( src_path , policy = policy , headers = headers ) ", "answer": "@ _requires_aws"}, {"prompt": " from construct import * from construct import adapters from tensor . protocol . sflow . protocol import utils class IPv4Header ( object ) : def __init__ ( self , data ) : ip = Struct ( \"\" , EmbeddedBitStruct ( Const ( Nibble ( \"\" ) , ) , Nibble ( \"\" ) , ) , BitStruct ( \"\" , Bits ( \"\" , ) , Flag ( \"\" ) , Flag ( \"\" ) , Flag ( \"\" ) , Flag ( \"\" ) , Padding ( ) , ) , UBInt16 ( \"\" ) , UBInt16 ( \"\" ) , UBInt16 ( \"\" ) , UBInt8 ( \"\" ) , Enum ( UBInt8 ( \"\" ) , UDP = , TCP = , HOPOPT = , ICMP = , ", "answer": "IGMP = ,"}, {"prompt": " import unittest from lib . doi import DOI class TestDOI ( unittest . TestCase ) : def setUp ( self ) : self . valid_doi = \"\" self . valid_doi_with_protocol = \"\" self . invalid_doi = \"\" self . valid_doi_organization = \"\" def test_set_identifier_on_creation ( self ) : try : doi = DOI ( self . valid_doi ) doi = DOI ( self . valid_doi_organization ) except Exception : self . fail ( \"\" ) def test_set_no_identifier_on_creation ( self ) : try : doi = DOI ( ) except Exception : self . fail ( \"\" ) def test_set_invalid_identifier_on_creation ( self ) : self . assertRaises ( ValueError , DOI , self . invalid_doi ) def test_query_url_of_undefined_doi_object ( self ) : doi = DOI ( ) self . assertEqual ( doi . get_URL ( ) , None ) def test_query_url_of_undefined_doi_object ( self ) : doi = DOI ( ) ", "answer": "self . assertEqual ( doi . get_identifier ( ) , doi . UNKNOWN_IDENTIFIER )"}, {"prompt": " \"\"\"\"\"\" from collections import OrderedDict , Sequence from functools import wraps from itertools import compress from weakref import WeakKeyDictionary , ref from six . moves . _thread import allocate_lock as Lock from toolz . sandbox import unzip class lazyval ( object ) : \"\"\"\"\"\" def __init__ ( self , get ) : self . _get = get self . _cache = WeakKeyDictionary ( ) def __get__ ( self , instance , owner ) : if instance is None : return self try : return self . _cache [ instance ] except KeyError : self . _cache [ instance ] = val = self . _get ( instance ) return val def __set__ ( self , instance , value ) : raise AttributeError ( \"\" ) def __delitem__ ( self , instance ) : del self . _cache [ instance ] class classlazyval ( lazyval ) : \"\"\"\"\"\" def __get__ ( self , instance , owner ) : return super ( classlazyval , self ) . __get__ ( owner , owner ) def _weak_lru_cache ( maxsize = ) : \"\"\"\"\"\" def decorating_function ( user_function , tuple = tuple , sorted = sorted , len = len , KeyError = KeyError ) : hits , misses = [ ] , [ ] kwd_mark = ( object ( ) , ) lock = Lock ( ) if maxsize is None : cache = _WeakArgsDict ( ) @ wraps ( user_function ) def wrapper ( * args , ** kwds ) : key = args if kwds : key += kwd_mark + tuple ( sorted ( kwds . items ( ) ) ) try : result = cache [ key ] hits [ ] += return result except KeyError : pass result = user_function ( * args , ** kwds ) cache [ key ] = result misses [ ] += return result else : cache = _WeakArgsOrderedDict ( ) cache_popitem = cache . popitem cache_renew = cache . move_to_end @ wraps ( user_function ) def wrapper ( * args , ** kwds ) : key = args if kwds : key += kwd_mark + tuple ( sorted ( kwds . items ( ) ) ) with lock : try : ", "answer": "result = cache [ key ]"}, {"prompt": " from sellmo . utils . forms import FormFactory from django import forms from django . utils . translation import ugettext_lazy as _ from . models import Attribute class ProductAttributeFormMixin ( object ) : def __init__ ( self , * args , ** kwargs ) : ", "answer": "initial = { }"}, {"prompt": " try : from ConfigParser import SafeConfigParser except ImportError : from configparser import ConfigParser as SafeConfigParser def get_metadata_and_options ( ) : config = SafeConfigParser ( ) config . read ( [ '' , '' ] ) metadata = dict ( config . items ( '' ) ) options = dict ( config . items ( '' ) ) metadata [ '' ] = list ( filter ( None , metadata [ '' ] . split ( '' ) ) ) metadata [ '' ] = list ( filter ( None , metadata [ '' ] . split ( '' ) ) ) return metadata , options def enabled ( options , option ) : value = options [ option ] s = value . lower ( ) if s in ( '' , '' , '' , '' ) : return True elif s in ( '' , '' , '' , '' ) : ", "answer": "return False"}, {"prompt": " \"\"\"\"\"\" __copyright__ = \"\"\"\"\"\" __version__ = '' import sys , string , os , re try : DEV_NULL = os . devnull except AttributeError : if sys . platform in ( '' , '' , '' , '' ) : DEV_NULL = '' else : DEV_NULL = '' _libc_search = re . compile ( r'' '' '' '' '' ) def libc_ver ( executable = sys . executable , lib = '' , version = '' , chunksize = ) : \"\"\"\"\"\" if executable == sys . executable : return ( \"\" , \"\" ) if hasattr ( os . path , '' ) : executable = os . path . realpath ( executable ) f = open ( executable , '' ) binary = f . read ( chunksize ) pos = while : m = _libc_search . search ( binary , pos ) if not m : binary = f . read ( chunksize ) if not binary : break pos = continue libcinit , glibc , glibcversion , so , threads , soversion = m . groups ( ) if libcinit and not lib : lib = '' elif glibc : if lib != '' : lib = '' version = glibcversion elif glibcversion > version : version = glibcversion elif so : if lib != '' : lib = '' if soversion and soversion > version : version = soversion if threads and version [ - len ( threads ) : ] != threads : version = version + threads pos = m . end ( ) f . close ( ) return lib , version def _dist_try_harder ( distname , version , id ) : \"\"\"\"\"\" if os . path . exists ( '' ) : info = open ( '' ) . readlines ( ) distname = '' for line in info : tv = string . split ( line ) if len ( tv ) == : tag , value = tv else : continue if tag == '' : version = string . strip ( value ) elif tag == '' : values = string . split ( value , '' ) id = values [ ] return distname , version , id if os . path . exists ( '' ) : info = open ( '' ) . readlines ( ) for line in info : pkg = string . split ( line , '' ) if len ( pkg ) >= and pkg [ ] == '' : return '' , pkg [ ] , id if os . path . isdir ( '' ) : verfiles = os . listdir ( '' ) for n in range ( len ( verfiles ) - , - , - ) : if verfiles [ n ] [ : ] != '' : del verfiles [ n ] if verfiles : verfiles . sort ( ) distname = '' version = verfiles [ - ] [ : ] return distname , version , id return distname , version , id _release_filename = re . compile ( r'' ) _lsb_release_version = re . compile ( r'' '' '' '' ) _release_version = re . compile ( r'' '' '' '' ) _supported_dists = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) def _parse_release_file ( firstline ) : version = '' id = '' m = _lsb_release_version . match ( firstline ) if m is not None : return tuple ( m . groups ( ) ) m = _release_version . match ( firstline ) if m is not None : return tuple ( m . groups ( ) ) l = string . split ( string . strip ( firstline ) ) if l : version = l [ ] if len ( l ) > : id = l [ ] return '' , version , id def linux_distribution ( distname = '' , version = '' , id = '' , supported_dists = _supported_dists , full_distribution_name = ) : \"\"\"\"\"\" try : etc = os . listdir ( '' ) except os . error : return distname , version , id etc . sort ( ) for file in etc : m = _release_filename . match ( file ) if m is not None : _distname , dummy = m . groups ( ) if _distname in supported_dists : distname = _distname break else : return _dist_try_harder ( distname , version , id ) f = open ( '' + file , '' ) firstline = f . readline ( ) f . close ( ) _distname , _version , _id = _parse_release_file ( firstline ) if _distname and full_distribution_name : distname = _distname if _version : version = _version if _id : id = _id return distname , version , id def dist ( distname = '' , version = '' , id = '' , supported_dists = _supported_dists ) : \"\"\"\"\"\" return linux_distribution ( distname , version , id , supported_dists = supported_dists , full_distribution_name = ) class _popen : \"\"\"\"\"\" tmpfile = '' pipe = None bufsize = None mode = '' ", "answer": "def __init__ ( self , cmd , mode = '' , bufsize = None ) :"}, {"prompt": " from datetime import date from wtforms import Form from wtforms . fields import DateField from wtforms_test import FormTestCase from tests import MultiDict from wtforms_components import DateRange class TestDateRangeValidator ( FormTestCase ) : def init_form ( self , ** kwargs ) : class ModelTestForm ( Form ) : date = DateField ( validators = [ DateRange ( ** kwargs ) ] ) self . form_class = ModelTestForm return self . form_class def test_date_greater_than_validator ( self ) : form_class = self . init_form ( min = date ( , , ) ) form = form_class ( MultiDict ( date = '' ) ) form . validate ( ) error_msg = u'' assert form . errors [ '' ] == [ error_msg ] def test_date_less_than_validator ( self ) : form_class = self . init_form ( max = date ( , , ) ) form = form_class ( MultiDict ( date = '' ) ) ", "answer": "form . validate ( )"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from django . db import models from cmdb . models import ConfigurationItem class Package ( models . Model ) : Name = models . CharField ( max_length = ) ", "answer": "Version = models . CharField ( max_length = )"}, {"prompt": " from atom . api import Typed from enaml . application import Application from enaml . workbench . extension import Extension from enaml . workbench . plugin import Plugin from . action_item import ActionItem from . autostart import Autostart from . branding import Branding from . menu_helper import create_menus from . menu_item import MenuItem from . window_model import WindowModel from . workspace import Workspace import enaml with enaml . imports ( ) : from . workbench_window import WorkbenchWindow ACTIONS_POINT = u'' APPLICATION_FACTORY_POINT = u'' BRANDING_POINT = u'' WINDOW_FACTORY_POINT = u'' WORKSPACES_POINT = u'' AUTOSTART_POINT = u'' class UIPlugin ( Plugin ) : \"\"\"\"\"\" def start ( self ) : \"\"\"\"\"\" self . _create_application ( ) self . _create_model ( ) self . _create_window ( ) self . _bind_observers ( ) self . _start_autostarts ( ) def stop ( self ) : \"\"\"\"\"\" self . _stop_autostarts ( ) self . _unbind_observers ( ) self . _destroy_window ( ) self . _release_model ( ) self . _release_application ( ) @ property def window ( self ) : \"\"\"\"\"\" return self . _window @ property def workspace ( self ) : \"\"\"\"\"\" return self . _model . workspace def show_window ( self ) : \"\"\"\"\"\" self . _window . show ( ) def hide_window ( self ) : \"\"\"\"\"\" self . _window . hide ( ) def start_application ( self ) : \"\"\"\"\"\" self . _application . start ( ) def stop_application ( self ) : \"\"\"\"\"\" self . _application . stop ( ) def close_window ( self ) : \"\"\"\"\"\" self . _window . close ( ) def close_workspace ( self ) : \"\"\"\"\"\" self . _workspace_extension = None self . _model . workspace . stop ( ) self . _model . workspace . workbench = None self . _model . workspace = Workspace ( ) def select_workspace ( self , extension_id ) : \"\"\"\"\"\" target = None workbench = self . workbench point = workbench . get_extension_point ( WORKSPACES_POINT ) for extension in point . extensions : if extension . qualified_id == extension_id : target = extension break if target is None : msg = \"\" raise ValueError ( msg % extension_id ) if target is self . _workspace_extension : return old_workspace = self . _model . workspace old_workspace . stop ( ) old_workspace . workbench = None self . _workspace_extension = target new_workspace = self . _create_workspace ( target ) new_workspace . workbench = workbench new_workspace . start ( ) self . _model . workspace = new_workspace _application = Typed ( Application ) _window = Typed ( WorkbenchWindow ) _model = Typed ( WindowModel ) _branding_extension = Typed ( Extension ) _workspace_extension = Typed ( Extension ) _action_extensions = Typed ( dict , ( ) ) def _create_application ( self ) : \"\"\"\"\"\" if Application . instance ( ) is not None : self . _application = Application . instance ( ) return workbench = self . workbench point = workbench . get_extension_point ( APPLICATION_FACTORY_POINT ) extensions = point . extensions if not extensions : msg = \"\" raise RuntimeError ( msg % APPLICATION_FACTORY_POINT ) extension = extensions [ - ] if extension . factory is None : msg = \"\" raise ValueError ( msg % extension . qualified_id ) application = extension . factory ( ) if not isinstance ( application , Application ) : msg = \"\" args = ( extension . qualified_id , type ( application ) . __name__ ) raise TypeError ( msg % args ) self . _application = application def _create_model ( self ) : \"\"\"\"\"\" self . _model = WindowModel ( ) self . _refresh_branding ( ) self . _refresh_actions ( ) def _create_window ( self ) : \"\"\"\"\"\" workbench = self . workbench point = workbench . get_extension_point ( WINDOW_FACTORY_POINT ) extensions = point . extensions if not extensions : msg = \"\" raise RuntimeError ( msg % WINDOW_FACTORY_POINT ) extension = extensions [ - ] if extension . factory is None : msg = \"\" raise ValueError ( msg % extension . qualified_id ) window = extension . factory ( workbench ) if not isinstance ( window , WorkbenchWindow ) : msg = \"\" args = ( extension . qualified_id , type ( window ) . __name__ ) raise TypeError ( msg % args ) window . workbench = workbench window . window_model = self . _model self . _window = window def _create_workspace ( self , extension ) : \"\"\"\"\"\" if extension . factory is None : msg = \"\" raise ValueError ( msg % extension . qualified_id ) workspace = extension . factory ( self . workbench ) if not isinstance ( workspace , Workspace ) : msg = \"\" args = ( extension . qualified_id , type ( workspace ) . __name__ ) raise TypeError ( msg % args ) return workspace def _create_action_items ( self , extension ) : \"\"\"\"\"\" workbench = self . workbench menu_items = extension . get_children ( MenuItem ) action_items = extension . get_children ( ActionItem ) if extension . factory : ", "answer": "for item in extension . factory ( workbench ) :"}, {"prompt": " '''''' from kivy . properties import ListProperty , ObservableDict , ObjectProperty from kivy . event import EventDispatcher from functools import partial __all__ = ( '' , '' ) def recondition_slice_assign ( val , last_len , new_len ) : if not isinstance ( val , slice ) : return slice ( val , val + ) diff = new_len - last_len start , stop , step = val . start , val . stop , val . step if stop <= start : return slice ( , ) if step is not None and step != : assert last_len == new_len if stop < : stop = max ( , last_len + stop ) stop = min ( last_len , stop ) if start < : start = max ( , last_len + start ) start = min ( last_len , start ) return slice ( start , stop , step ) if start < : start = last_len + start if stop < : stop = last_len + stop if ( start < or stop < or start > last_len or stop > last_len or new_len != last_len ) : return None return slice ( start , stop ) class RecycleDataModelBehavior ( object ) : \"\"\"\"\"\" __events__ = ( \"\" , ) recycleview = ObjectProperty ( None , allownone = True ) '''''' def attach_recycleview ( self , rv ) : '''''' self . recycleview = rv if rv : self . fbind ( '' , rv . refresh_from_data ) def detach_recycleview ( self ) : '''''' rv = self . recycleview if rv : self . funbind ( '' , rv . refresh_from_data ) self . recycleview = None def on_data_changed ( self , * largs , ** kwargs ) : pass class RecycleDataModel ( RecycleDataModelBehavior , EventDispatcher ) : '''''' data = ListProperty ( [ ] ) '''''' _last_len = def __init__ ( self , ** kwargs ) : self . fbind ( '' , self . _on_data_callback ) super ( RecycleDataModel , self ) . __init__ ( ** kwargs ) def __getitem__ ( self , index ) : return self . data [ index ] @ property ", "answer": "def observable_dict ( self ) :"}, {"prompt": " from __future__ import print_function , division , absolute_import from datashape . dispatch import dispatch from . coretypes import * from . predicates import isdimension from . util import dshape import sys from datetime import date , time , datetime __all__ = [ '' , '' ] basetypes = np . generic , int , float , str , date , time , datetime @ dispatch ( np . dtype , basetypes ) def validate ( schema , value ) : return np . issubdtype ( type ( value ) , schema ) @ dispatch ( CType , basetypes ) def validate ( schema , value ) : return validate ( to_numpy_dtype ( schema ) , value ) @ dispatch ( DataShape , ( tuple , list ) ) def validate ( schema , value ) : head = schema [ ] return ( ( len ( schema ) == and validate ( head , value ) ) or ( isdimension ( head ) and ( isinstance ( head , Var ) or int ( head ) == len ( value ) ) and all ( validate ( DataShape ( * schema [ : ] ) , item ) for item in value ) ) ) @ dispatch ( DataShape , object ) def validate ( schema , value ) : if len ( schema ) == : return validate ( schema [ ] , value ) @ dispatch ( Record , dict ) def validate ( schema , d ) : return all ( validate ( sch , d . get ( k ) ) for k , sch in schema . parameters [ ] ) @ dispatch ( Record , ( tuple , list ) ) def validate ( schema , seq ) : return all ( validate ( sch , item ) for ( k , sch ) , item in zip ( schema . parameters [ ] , seq ) ) @ dispatch ( str , object ) def validate ( schema , value ) : return validate ( dshape ( schema ) , value ) @ dispatch ( type , object ) def validate ( schema , value ) : return isinstance ( value , schema ) @ dispatch ( tuple , object ) ", "answer": "def validate ( schemas , value ) :"}, {"prompt": " import eventlet import os import sys from oslo_config import cfg from eventlet import wsgi from st2common import log as logging from st2common . service_setup import setup as common_setup from st2common . service_setup import teardown as common_teardown from st2common . util . monkey_patch import monkey_patch from st2common . constants . auth import VALID_MODES from st2auth import config config . register_opts ( ) from st2auth import app __all__ = [ '' ] monkey_patch ( ) LOG = logging . getLogger ( __name__ ) def _setup ( ) : common_setup ( service = '' , config = config , setup_db = True , register_mq_exchanges = False , register_signal_handlers = True , register_internal_trigger_types = False , run_migrations = False ) if cfg . CONF . auth . mode not in VALID_MODES : raise ValueError ( '' % ( '' . join ( VALID_MODES ) ) ) def _run_server ( ) : host = cfg . CONF . auth . host port = cfg . CONF . auth . port use_ssl = cfg . CONF . auth . use_ssl cert_file_path = os . path . realpath ( cfg . CONF . auth . cert ) key_file_path = os . path . realpath ( cfg . CONF . auth . key ) if use_ssl and not os . path . isfile ( cert_file_path ) : raise ValueError ( '' % ( cert_file_path ) ) if use_ssl and not os . path . isfile ( key_file_path ) : raise ValueError ( '' % ( key_file_path ) ) socket = eventlet . listen ( ( host , port ) ) if use_ssl : socket = eventlet . wrap_ssl ( socket , ", "answer": "certfile = cert_file_path ,"}, {"prompt": " \"\"\"\"\"\" __revision__ = \"\" import re import os . path import SCons . Action import SCons . Defaults import SCons . Scanner . Fortran import SCons . Tool import SCons . Util def isfortran ( env , source ) : \"\"\"\"\"\" try : fsuffixes = env [ '' ] except KeyError : return if not source : return for s in source : if s . sources : ext = os . path . splitext ( str ( s . sources [ ] ) ) [ ] if ext in fsuffixes : return return def _fortranEmitter ( target , source , env ) : node = source [ ] . rfile ( ) if not node . exists ( ) and not node . is_derived ( ) : print \"\" + str ( node . name ) return ( [ ] , [ ] ) mod_regex = \"\"\"\"\"\" cre = re . compile ( mod_regex , re . M ) modules = cre . findall ( node . get_text_contents ( ) ) modules = SCons . Util . unique ( modules ) suffix = env . subst ( '' , target = target , source = source ) moddir = env . subst ( '' , target = target , source = source ) modules = [ x . lower ( ) + suffix for x in modules ] for m in modules : target . append ( env . fs . File ( m , moddir ) ) return ( target , source ) def FortranEmitter ( target , source , env ) : target , source = _fortranEmitter ( target , source , env ) return SCons . Defaults . StaticObjectEmitter ( target , source , env ) def ShFortranEmitter ( target , source , env ) : target , source = _fortranEmitter ( target , source , env ) return SCons . Defaults . SharedObjectEmitter ( target , source , env ) def ComputeFortranSuffixes ( suffixes , ppsuffixes ) : \"\"\"\"\"\" assert len ( suffixes ) > s = suffixes [ ] sup = s . upper ( ) upper_suffixes = [ _ . upper ( ) for _ in suffixes ] if SCons . Util . case_sensitive_suffixes ( s , sup ) : ppsuffixes . extend ( upper_suffixes ) else : suffixes . extend ( upper_suffixes ) def CreateDialectActions ( dialect ) : \"\"\"\"\"\" CompAction = SCons . Action . Action ( '' % dialect , '' % dialect ) CompPPAction = SCons . Action . Action ( '' % dialect , '' % dialect ) ShCompAction = SCons . Action . Action ( '' % dialect , '' % dialect ) ShCompPPAction = SCons . Action . Action ( '' % dialect , '' % dialect ) return CompAction , CompPPAction , ShCompAction , ShCompPPAction def DialectAddToEnv ( env , dialect , suffixes , ppsuffixes , support_module = ) : \"\"\"\"\"\" ComputeFortranSuffixes ( suffixes , ppsuffixes ) fscan = SCons . Scanner . Fortran . FortranScan ( \"\" % dialect ) for suffix in suffixes + ppsuffixes : SCons . Tool . SourceFileScanner . add_scanner ( suffix , fscan ) env . AppendUnique ( FORTRANSUFFIXES = suffixes + ppsuffixes ) compaction , compppaction , shcompaction , shcompppaction = CreateDialectActions ( dialect ) static_obj , shared_obj = SCons . Tool . createObjBuilders ( env ) for suffix in suffixes : static_obj . add_action ( suffix , compaction ) shared_obj . add_action ( suffix , shcompaction ) static_obj . add_emitter ( suffix , FortranEmitter ) shared_obj . add_emitter ( suffix , ShFortranEmitter ) for suffix in ppsuffixes : static_obj . add_action ( suffix , compppaction ) shared_obj . add_action ( suffix , shcompppaction ) static_obj . add_emitter ( suffix , FortranEmitter ) shared_obj . add_emitter ( suffix , ShFortranEmitter ) if '' % dialect not in env : env [ '' % dialect ] = SCons . Util . CLVar ( '' ) if '' % dialect not in env : env [ '' % dialect ] = SCons . Util . CLVar ( '' % dialect ) if '' % dialect not in env : env [ '' % dialect ] = '' if '' % dialect not in env : env [ '' % dialect ] = '' env [ '' % dialect ] = '' % ( dialect , dialect , dialect ) if support_module == : env [ '' % dialect ] = '' % ( dialect , dialect , dialect ) env [ '' % dialect ] = '' % ( dialect , dialect , dialect ) env [ '' % dialect ] = '' % ( dialect , dialect , dialect ) env [ '' % dialect ] = '' % ( dialect , dialect , dialect ) else : env [ '' % dialect ] = '' % ( dialect , dialect , dialect ) env [ '' % dialect ] = '' % ( dialect , dialect , dialect ) env [ '' % dialect ] = '' % ( dialect , dialect , dialect ) env [ '' % dialect ] = '' % ( dialect , dialect , dialect ) def add_fortran_to_env ( env ) : \"\"\"\"\"\" try : FortranSuffixes = env [ '' ] except KeyError : FortranSuffixes = [ '' , '' , '' ] try : FortranPPSuffixes = env [ '' ] except KeyError : FortranPPSuffixes = [ '' , '' ] DialectAddToEnv ( env , \"\" , FortranSuffixes , FortranPPSuffixes , support_module = ) env [ '' ] = '' env [ '' ] = '' env [ '' ] = '' env [ '' ] = '' env [ '' ] = '' env [ '' ] = '' def add_f77_to_env ( env ) : \"\"\"\"\"\" try : F77Suffixes = env [ '' ] except KeyError : F77Suffixes = [ '' ] try : F77PPSuffixes = env [ '' ] except KeyError : F77PPSuffixes = [ ] DialectAddToEnv ( env , \"\" , F77Suffixes , F77PPSuffixes ) def add_f90_to_env ( env ) : \"\"\"\"\"\" try : F90Suffixes = env [ '' ] except KeyError : F90Suffixes = [ '' ] try : F90PPSuffixes = env [ '' ] except KeyError : F90PPSuffixes = [ ] DialectAddToEnv ( env , \"\" , F90Suffixes , F90PPSuffixes , support_module = ) def add_f95_to_env ( env ) : \"\"\"\"\"\" try : F95Suffixes = env [ '' ] except KeyError : F95Suffixes = [ '' ] try : F95PPSuffixes = env [ '' ] except KeyError : F95PPSuffixes = [ ] DialectAddToEnv ( env , \"\" , F95Suffixes , F95PPSuffixes , support_module = ) def add_f03_to_env ( env ) : \"\"\"\"\"\" try : F03Suffixes = env [ '' ] except KeyError : F03Suffixes = [ '' ] try : F03PPSuffixes = env [ '' ] except KeyError : F03PPSuffixes = [ ] DialectAddToEnv ( env , \"\" , F03Suffixes , F03PPSuffixes , support_module = ) def add_all_to_env ( env ) : \"\"\"\"\"\" add_fortran_to_env ( env ) add_f77_to_env ( env ) add_f90_to_env ( env ) ", "answer": "add_f95_to_env ( env )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " import itertools from ... error import GraphQLError from ... language import ast from ... language . printer import print_ast from ... pyutils . default_ordered_dict import DefaultOrderedDict from ... pyutils . pair_set import PairSet from ... type . definition import ( GraphQLInterfaceType , GraphQLObjectType , get_named_type ) from ... utils . type_comparators import is_equal_type from ... utils . type_from_ast import type_from_ast from . base import ValidationRule class OverlappingFieldsCanBeMerged ( ValidationRule ) : __slots__ = '' , def __init__ ( self , context ) : super ( OverlappingFieldsCanBeMerged , self ) . __init__ ( context ) self . compared_set = PairSet ( ) def find_conflicts ( self , field_map ) : conflicts = [ ] for response_name , fields in field_map . items ( ) : field_len = len ( fields ) if field_len <= : continue for field_a in fields : for field_b in fields : conflict = self . find_conflict ( response_name , field_a , field_b ) if conflict : conflicts . append ( conflict ) return conflicts def find_conflict ( self , response_name , field1 , field2 ) : parent_type1 , ast1 , def1 = field1 parent_type2 , ast2 , def2 = field2 if ast1 is ast2 : return if parent_type1 != parent_type2 and isinstance ( parent_type1 , GraphQLObjectType ) and isinstance ( parent_type2 , GraphQLObjectType ) : return if self . compared_set . has ( ast1 , ast2 ) : return self . compared_set . add ( ast1 , ast2 ) name1 = ast1 . name . value name2 = ast2 . name . value if name1 != name2 : return ( ( response_name , '' . format ( name1 , name2 ) ) , [ ast1 ] , [ ast2 ] ) type1 = def1 and def1 . type type2 = def2 and def2 . type if type1 and type2 and not self . same_type ( type1 , type2 ) : return ( ( response_name , '' . format ( type1 , type2 ) ) , [ ast1 ] , [ ast2 ] ) if not self . same_arguments ( ast1 . arguments , ast2 . arguments ) : return ( ( response_name , '' ) , [ ast1 ] , [ ast2 ] ) selection_set1 = ast1 . selection_set selection_set2 = ast2 . selection_set if selection_set1 and selection_set2 : visited_fragment_names = set ( ) subfield_map = self . collect_field_asts_and_defs ( get_named_type ( type1 ) , selection_set1 , visited_fragment_names ) subfield_map = self . collect_field_asts_and_defs ( get_named_type ( type2 ) , selection_set2 , visited_fragment_names , subfield_map ) conflicts = self . find_conflicts ( subfield_map ) if conflicts : return ( ( response_name , [ conflict [ ] for conflict in conflicts ] ) , tuple ( itertools . chain ( [ ast1 ] , * [ conflict [ ] for conflict in conflicts ] ) ) , tuple ( itertools . chain ( [ ast2 ] , * [ conflict [ ] for conflict in conflicts ] ) ) ) def leave_SelectionSet ( self , node , key , parent , path , ancestors ) : field_map = self . collect_field_asts_and_defs ( self . context . get_parent_type ( ) , node ) conflicts = self . find_conflicts ( field_map ) if conflicts : for ( reason_name , reason ) , fields1 , fields2 in conflicts : self . context . report_error ( ", "answer": "GraphQLError ("}, {"prompt": " \"\"\"\"\"\" import itertools try : import unittest2 as unittest except ImportError : import unittest import see def union ( * sets ) : return set ( itertools . chain ( * sets ) ) SIGN_OPS = set ( [ '' , '' ] ) NUMBER_OPS = set ( '' . split ( ) ) NUMBER_ASSIGN_OPS = set ( ) BITWISE_OPS = set ( '' . split ( ) ) BITWISE_ASSIGN_OPS = set ( op + '' for op in BITWISE_OPS ) COMPARE_OPS = set ( '' . split ( ) ) MATRIX_OPS = set ( [ '' ] ) MATRIX_ASSIGN_OPS = set ( [ '' ] ) ALL_OPS = union ( SIGN_OPS , NUMBER_OPS , NUMBER_ASSIGN_OPS , BITWISE_OPS , BITWISE_ASSIGN_OPS , ", "answer": "COMPARE_OPS ,"}, {"prompt": " from bottle import HTTPResponse import base64 from collections import namedtuple from conans . server . rest . bottle_plugins . authorization_header import AuthorizationHeader ", "answer": "from conans . util . files import decode_text"}, {"prompt": " import sys , os ", "answer": "from _pwuid_cffi import ffi , lib"}, {"prompt": " \"\"\"\"\"\" import base64 from decimal import Decimal as _Decimal import isodate import six from zeep . xsd . types import SimpleType class String ( SimpleType ) : name = '' def xmlvalue ( self , value ) : return six . text_type ( value ) def pythonvalue ( self , value ) : return value class Boolean ( SimpleType ) : name = '' def xmlvalue ( self , value ) : return '' if value else '' def pythonvalue ( self , value ) : \"\"\"\"\"\" return value in ( '' , '' ) class Decimal ( SimpleType ) : name = '' def xmlvalue ( self , value ) : return str ( value ) def pythonvalue ( self , value ) : return _Decimal ( value ) class Float ( SimpleType ) : name = '' def xmlvalue ( self , value ) : return str ( value ) . upper ( ) def pythonvalue ( self , value ) : return float ( value ) class Double ( SimpleType ) : ", "answer": "name = ''"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = ) , keep_default = False ) db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( '' , '' ) db . delete_column ( '' , '' ) models = { '' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' } ) ,"}, {"prompt": " import logging from airflow . exceptions import AirflowException from airflow . hooks import HttpHook from airflow . models import BaseOperator from airflow . utils . decorators import apply_defaults class SimpleHttpOperator ( BaseOperator ) : \"\"\"\"\"\" template_fields = ( '' , '' , ) template_ext = ( ) ui_color = '' @ apply_defaults def __init__ ( self , endpoint , method = '' , data = None , headers = None , response_check = None , extra_options = None , http_conn_id = '' , * args , ** kwargs ) : super ( SimpleHttpOperator , self ) . __init__ ( * args , ** kwargs ) self . http_conn_id = http_conn_id self . method = method self . endpoint = endpoint self . headers = headers or { } self . data = data or { } self . response_check = response_check ", "answer": "self . extra_options = extra_options or { }"}, {"prompt": " from __future__ import print_function import numpy as np from numba import cuda from numba import unittest_support as unittest from numba . config import ENABLE_CUDASIM sum_reduce = cuda . Reduce ( lambda a , b : a + b ) class TestReduction ( unittest . TestCase ) : def _sum_reduce ( self , n ) : A = ( np . arange ( n , dtype = np . float64 ) + ) expect = A . sum ( ) got = sum_reduce ( A ) self . assertEqual ( expect , got ) def test_sum_reduce ( self ) : if ENABLE_CUDASIM : test_sizes = [ , ] else : test_sizes = [ , , , , , , , , , , , , , , ] for n in test_sizes : self . _sum_reduce ( n ) def test_empty_array_host ( self ) : A = ( np . arange ( , dtype = np . float64 ) + ) expect = A . sum ( ) got = sum_reduce ( A ) self . assertEqual ( expect , got ) def test_empty_array_device ( self ) : A = ( np . arange ( , dtype = np . float64 ) + ) dA = cuda . to_device ( A ) ", "answer": "expect = A . sum ( )"}, {"prompt": " \"\"\"\"\"\" class DatabaseError ( Exception ) : pass class IntegrityError ( DatabaseError ) : pass class NotSupportedError ( Exception ) : pass class CouldBeSupportedError ( NotSupportedError ) : ", "answer": "pass"}, {"prompt": " \"\"\"\"\"\" import warnings from graphy import graphy_test from graphy import pie_chart from graphy . backends import google_chart_api from graphy . backends . google_chart_api import base_encoder_test class PieChartTest ( base_encoder_test . BaseChartTest ) : def tearDown ( self ) : warnings . resetwarnings ( ) super ( PieChartTest , self ) . tearDown ( ) def GetChart ( self , * args , ** kwargs ) : return google_chart_api . PieChart ( * args , ** kwargs ) def AddToChart ( self , chart , points , color = None , label = None ) : return chart . AddSegment ( points [ ] , color = color , label = label ) def testCanRemoveDefaultFormatters ( self ) : pass def testChartType ( self ) : self . chart . display . is3d = False self . assertEqual ( self . Param ( '' ) , '' ) self . chart . display . is3d = True self . assertEqual ( self . Param ( '' ) , '' ) def testEmptyChart ( self ) : self . assertEqual ( self . Param ( '' ) , '' ) self . assertEqual ( self . Param ( '' ) , '' ) self . assertEqual ( self . Param ( '' ) , '' ) ", "answer": "def testChartCreation ( self ) :"}, {"prompt": " from awscli . testutils import BaseAWSCommandParamsTest import awscli . clidriver class TestAddPermission ( BaseAWSCommandParamsTest ) : ", "answer": "prefix = ''"}, {"prompt": " from . layout import * ", "answer": "from . nx_pylab import *"}, {"prompt": " from aliyunsdkcore . request import RpcRequest class UpdateGroupRequest ( RpcRequest ) : def __init__ ( self ) : RpcRequest . __init__ ( self , '' , '' , '' ) self . set_protocol_type ( '' ) ; ", "answer": "def get_GroupName ( self ) :"}, {"prompt": " \"\"\"\"\"\" from xml . dom . minidom import Element , Text from twisted . trial . unittest import TestCase from twisted . lore . docbook import DocbookSpitter class DocbookSpitterTests ( TestCase ) : \"\"\"\"\"\" def test_li ( self ) : \"\"\"\"\"\" output = [ ] spitter = DocbookSpitter ( output . append ) li = Element ( '' ) li . appendChild ( Element ( '' ) ) text = Text ( ) text . data = '' li . appendChild ( text ) ", "answer": "spitter . visitNode ( li )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " \"\"\"\"\"\" import pandas as pd import glob df = pd . read_csv ( '' , sep = \"\" ) df . columns = [ '' , '' , '' , '' , '' , '' , '' , '' ] files = glob . glob ( '' ) for path_file in files : year = str ( path_file [ - : - ] ) ", "answer": "if ( year != '' ) :"}, {"prompt": " \"\"\"\"\"\" from django . core . urlresolvers import reverse from django . contrib . auth . models import AnonymousUser , Permission from django . contrib . contenttypes . models import ContentType from django . test . utils import override_settings from mock import patch from open_connect . context_processors . connect_processor import connect_processor from open_connect . media . models import Image from open_connect . connectmessages . tests import ConnectMessageTestCase from open_connect . connect_core . utils . basetests import ConnectTestMixin class TestConnectProcessor ( ConnectTestMixin , ConnectMessageTestCase ) : \"\"\"\"\"\" def create_object_patch ( self , obj , name ) : \"\"\"\"\"\" patcher = patch . object ( obj , name ) thing = patcher . start ( ) self . addCleanup ( patcher . stop ) return thing def test_authenticated_nav ( self ) : \"\"\"\"\"\" user = self . create_user ( ) request = self . request_factory . get ( '' ) request . user = user response = connect_processor ( request ) self . assertEqual ( response [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ ] [ '' ] , reverse ( '' ) ) self . assertEqual ( response [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ ] [ '' ] , reverse ( '' ) ) self . assertEqual ( response [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ ] [ '' ] , reverse ( '' ) ) self . assertEqual ( response [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ ] [ '' ] , reverse ( '' ) ) self . assertEqual ( response [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ ] [ '' ] , reverse ( '' , args = ( user . uuid , ) ) ) self . assertEqual ( response [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ ] [ '' ] , reverse ( '' ) ) @ override_settings ( LOGIN_URL = '' ) def test_unauthenticated_nav ( self ) : \"\"\"\"\"\" request = self . request_factory . get ( '' ) request . user = AnonymousUser ( ) response = connect_processor ( request ) self . assertEqual ( response [ '' ] , [ ] ) self . assertEqual ( response [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ ] [ '' ] , '' ) def test_is_moderator ( self ) : \"\"\"\"\"\" request = self . request_factory . get ( '' ) request . user = self . superuser mock_get_moderation_tasks = self . create_object_patch ( self . request . user , '' ) mock_get_moderation_tasks . return_value = True response = connect_processor ( self . request ) self . assertEqual ( response [ '' ] [ - ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ - ] [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ - ] [ '' ] [ ] [ '' ] , reverse ( '' ) ) self . assertEqual ( response [ '' ] [ - ] [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ - ] [ '' ] [ ] [ '' ] , reverse ( '' ) ) self . assertEqual ( response [ '' ] [ - ] [ '' ] [ ] [ '' ] , '' ) self . assertEqual ( response [ '' ] [ - ] [ '' ] [ ] [ '' ] , reverse ( '' ) ) @ override_settings ( BRAND_TITLE = '' ) def test_brand_title ( self ) : \"\"\"\"\"\" response = connect_processor ( self . request ) self . assertEqual ( response [ '' ] , '' ) def test_user_has_access_to_admin_gallery ( self ) : \"\"\"\"\"\" content_type = ContentType . objects . get_for_model ( Image ) ", "answer": "permission = Permission . objects . get ("}, {"prompt": " \"\"\"\"\"\" import os import sys import signal import socket import logging import multiprocessing import subprocess import tornado from framework . dependency_management . dependency_resolver import BaseComponent from framework . dependency_management . component_initialiser import ComponentInitialiser from framework . utils import FileOperations , catch_io_errors , OutputCleaner , OWTFLogger from framework . interface import server , cli from framework . http . proxy import proxy , transaction_logger from framework . plugin import worker_manager from framework . lib . formatters import ConsoleFormatter , FileFormatter class Core ( BaseComponent ) : \"\"\"\"\"\" COMPONENT_NAME = \"\" def __init__ ( self ) : \"\"\"\"\"\" self . register_in_service_locator ( ) self . file_handler = catch_io_errors ( logging . FileHandler ) self . db = self . get_component ( \"\" ) self . config = self . get_component ( \"\" ) self . db_config = self . get_component ( \"\" ) self . error_handler = self . get_component ( \"\" ) self . create_dirs ( ) self . pnh_log_file ( ) self . enable_logging ( ) self . tor_process = None def create_dirs ( self ) : \"\"\"\"\"\" if not os . path . exists ( self . config . FrameworkConfigGetLogsDir ( ) ) : FileOperations . create_missing_dirs ( self . config . FrameworkConfigGetLogsDir ( ) ) self . create_temp_storage_dirs ( ) def create_temp_storage_dirs ( self ) : \"\"\"\"\"\" tmp_dir = os . path . join ( '' , '' ) if not os . path . exists ( tmp_dir ) : tmp_dir = os . path . join ( tmp_dir , str ( self . config . OwtfPid ) ) if not os . path . exists ( tmp_dir ) : FileOperations . make_dirs ( tmp_dir ) def clean_temp_storage_dirs ( self ) : \"\"\"\"\"\" curr_tmp_dir = os . path . join ( '' , '' , str ( self . config . OwtfPid ) ) new_tmp_dir = os . path . join ( '' , '' , '' % self . config . OwtfPid ) if os . path . exists ( curr_tmp_dir ) and os . access ( curr_tmp_dir , os . W_OK ) : os . rename ( curr_tmp_dir , new_tmp_dir ) def pnh_log_file ( self ) : self . path = self . config . FrameworkConfigGet ( '' ) self . mode = \"\" try : if os . path . isfile ( self . path ) : pass else : with FileOperations . open ( self . path , self . mode , owtf_clean = False ) : pass except IOError as e : OWTFLogger . log ( \"\" . format ( e . errno , e . strerror ) ) raise def write_event ( self , content , mode ) : self . content = content self . mode = mode self . file_path = self . config . FrameworkConfigGet ( '' ) if ( os . path . isfile ( self . file_path ) and os . access ( self . file_path , os . W_OK ) ) : try : with FileOperations . open ( self . file_path , self . mode , owtf_clean = False ) as log_file : log_file . write ( self . content ) log_file . write ( \"\" ) return True except IOError : return False def get_command ( self , argv ) : \"\"\"\"\"\" return \"\" . join ( argv ) . replace ( argv [ ] , os . path . basename ( argv [ ] ) ) def start_botnet_mode ( self , options ) : ComponentInitialiser . intialise_proxy_manager ( options ) def start_proxy ( self , options ) : if True : try : temp_socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) temp_socket . bind ( ( self . db_config . Get ( '' ) , int ( self . db_config . Get ( '' ) ) ) ) temp_socket . close ( ) except socket . error : self . error_handler . FrameworkAbort ( \"\" + self . db_config . Get ( '' ) + \"\" + self . db_config . Get ( \"\" ) + \"\" ) self . ProxyProcess = proxy . ProxyProcess ( ) self . ProxyProcess . initialize ( options [ '' ] , options [ '' ] ) self . TransactionLogger = transaction_logger . TransactionLogger ( cache_dir = self . db_config . Get ( '' ) ) logging . warn ( \"\" , self . db_config . Get ( '' ) , self . db_config . Get ( \"\" ) ) self . ProxyProcess . start ( ) logging . debug ( \"\" ) self . TransactionLogger . start ( ) logging . debug ( \"\" , self . db_config . Get ( \"\" ) ) else : ComponentInitialiser . initialisation_phase_3 ( options [ '' ] ) def enable_logging ( self , ** kwargs ) : \"\"\"\"\"\" process_name = kwargs . get ( \"\" , multiprocessing . current_process ( ) . name ) logger = logging . getLogger ( ) logger . setLevel ( logging . DEBUG ) file_handler = self . file_handler ( self . config . FrameworkConfigGetLogPath ( process_name ) , mode = \"\" ) file_handler . setLevel ( logging . DEBUG ) file_handler . setFormatter ( FileFormatter ( ) ) stream_handler = logging . StreamHandler ( sys . stdout ) stream_handler . setLevel ( logging . INFO ) stream_handler . setFormatter ( ConsoleFormatter ( ) ) logger . handlers = [ file_handler , stream_handler ] def disable_console_logging ( self , ** kwargs ) : \"\"\"\"\"\" logger = logging . getLogger ( ) if isinstance ( logger . handlers [ - ] , logging . StreamHandler ) : logger . removeHandler ( logger . handlers [ - ] ) def start ( self , options ) : \"\"\"\"\"\" if self . initialise_framework ( options ) : if not options [ '' ] : return self . run_server ( ) else : return self . run_cli ( ) def initialise_framework ( self , options ) : self . ProxyMode = options [ \"\" ] logging . info ( \"\" ) proxy_infos = [ self . db_config . Get ( '' ) , self . db_config . Get ( '' ) ] ComponentInitialiser . initialisation_phase_3 ( proxy_infos , options ) self . initialise_plugin_handler_and_params ( options ) if options [ '' ] : self . PluginHandler . show_plugin_list ( options [ '' ] ) self . finish ( ) self . config . ProcessOptions ( options ) command = self . get_command ( options [ '' ] ) self . start_botnet_mode ( options ) self . start_proxy ( options ) self . error_handler . SetCommand ( OutputCleaner . anonymise_command ( command ) ) return True def initialise_plugin_handler_and_params ( self , options ) : self . PluginHandler = self . get_component ( \"\" ) self . PluginParams = self . get_component ( \"\" ) self . WorkerManager = worker_manager . WorkerManager ( keep_working = not options [ '' ] ) def run_server ( self ) : \"\"\"\"\"\" ", "answer": "self . interface_server = server . InterfaceServer ( )"}, {"prompt": " import json import urllib import urllib2 class Request : ", "answer": "def _request ( self , url , data , action , content_type ) :"}, {"prompt": " from sqlalchemy . engine import create_engine from sqlalchemy . orm import scoped_session , create_session from sqlalchemy . ext . declarative import declarative_base ", "answer": "engine = None"}, {"prompt": " import testify as T from testify . contrib . doctestcase import DocTestCase class TurtleTestCase ( T . TestCase ) : @ T . setup def build_turtle ( self ) : self . leonardo = T . turtle . Turtle ( ) def test_call ( self ) : \"\"\"\"\"\" ret = self . leonardo ( ) assert ret T . assert_length ( self . leonardo . returns , ) T . assert_call ( self . leonardo , ) T . assert_equal ( ret , self . leonardo . returns [ ] ) def test_attribute ( self ) : \"\"\"\"\"\" assert self . leonardo . is_awesome ( ) . and_can_chain ( ) . whatever_he_wants ( ) def test_call_record ( self ) : \"\"\"\"\"\" self . leonardo ( , , , quatro = ) T . assert_length ( self . leonardo . calls , ) T . assert_call ( self . leonardo , , , , , quatro = ) self . leonardo ( , six = ) T . assert_call ( self . leonardo , , , six = ) def test_attribute_setting ( self ) : \"\"\"\"\"\" self . leonardo . color = \"\" T . assert_equal ( self . leonardo . color , \"\" ) def test_attribute_persistence ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" from rasterio . dtypes import uint8 class Profile : \"\"\"\"\"\" driver = None defaults = { } def __call__ ( self , ** kwargs ) : \"\"\"\"\"\" if kwargs . get ( '' , self . driver ) != self . driver : raise ValueError ( \"\" ) profile = self . defaults . copy ( ) profile . update ( ** kwargs ) profile [ '' ] = self . driver return profile class DefaultGTiffProfile ( Profile ) : \"\"\"\"\"\" driver = '' defaults = { '' : '' , '' : True , '' : , '' : , '' : '' , '' : , '' : uint8 } ", "answer": "default_gtiff_profile = DefaultGTiffProfile ( ) "}, {"prompt": " import sublime , os , re , importlib from sublime import Region from subprocess import Popen , PIPE def is_file ( message , args , pipeline_data ) : \"\"\"\"\"\" file = message . get ( \"\" , None ) if file : cwd = message [ \"\" ] if os . path . isfile ( file ) : message [ '' ] = file return file elif cwd : relative_path = os . path . normpath ( cwd + '' + file ) if os . path . isfile ( relative_path ) : message [ '' ] = relative_path return relative_path return None def is_dir ( message , args , pipeline_data ) : \"\"\"\"\"\" file = message . get ( \"\" , None ) if file : cwd = message [ \"\" ] if os . path . isdir ( file ) : return file message [ '' ] = file elif cwd : relative_path = os . path . normpath ( cwd + '' + file ) if os . path . isfile ( relative_path ) : message [ '' ] = relative_path return relative_path return None def pattern ( message , args , pipeline_data ) : \"\"\"\"\"\" text = message . get ( \"\" , None ) pattern = args [ ] if text != None : return re . search ( pattern , text ) return None def open_in_tab ( message , args , pipeline_data ) : \"\"\"\"\"\" cwd = message [ '' ] command = message [ '' ] window = sublime . active_window ( ) if os . path . isfile ( command ) : tab = window . open_file ( command ) return tab else : p = Popen ( [ command ] , shell = True , cwd = cwd , stdout = PIPE , stderr = PIPE ) out , err = p . communicate ( ) if out : data = out . decode ( encoding = '' ) tab = window . new_file ( ) tab . set_scratch ( True ) edit_token = message [ '' ] tab . insert ( edit_token , , data ) return tab def open_in_external_program ( message , args , pipeline_data ) : \"\"\"\"\"\" cwd = message [ '' ] command = message [ '' ] return Popen ( [ command ] , shell = True , cwd = cwd , close_fds = True ) def prepare_command ( message , args , pipeline_data ) : \"\"\"\"\"\" command = args [ ] if \"\" in pipeline_data : match = pipeline_data [ \"\" ] for idx , val in enumerate ( match . groups ( ) ) : group = idx + command = command . replace ( \"\" + str ( group ) , val ) for group , val in match . groupdict ( ) . items ( ) : command = command . replace ( \"\" + group , val ) command = command . replace ( \"\" , message [ '' ] ) message [ '' ] = command return command def extract_jump ( message , args , pipeline_data ) : \"\"\"\"\"\" text = message . get ( \"\" , None ) if text != None : match = re . search ( \"\" , text ) if match : message [ '' ] = text [ : match . span ( ) [ ] ] return ( match . group ( ) , match . group ( ) ) return ( None , None ) def jump ( message , args , pipeline_data ) : \"\"\"\"\"\" jump_type , jump_location = pipeline_data . get ( \"\" ) window = sublime . active_window ( ) view = window . active_view ( ) location = if jump_type == \"\" : for result in window . lookup_symbol_in_open_files ( jump_location ) : view_file = view . file_name ( ) result_file = result [ ] if os . name == '' : if not result_file . startswith ( \"\" ) : result_file = result_file [ : ] result_file = result_file [ : ] + \"\" + result_file [ : ] result_file = os . path . normpath ( result_file ) if view_file == result_file : location = view . text_point ( result [ ] [ ] - , result [ ] [ ] - ) break pass elif jump_type == \"\" : sel = view . sel ( ) current_pos = view . sel ( ) [ ] if len ( sel ) > else sublime . Region ( , ) next_pos = view . find ( jump_location , current_pos . b + ) if next_pos . a == - : next_pos = view . find ( jump_location , ) if next_pos . a != - : location = next_pos . a elif jump_type == \"\" : location = view . text_point ( int ( jump_location ) - , ) view . sel ( ) . clear ( ) view . sel ( ) . add ( Region ( location ) ) view . show ( location ) return location def extern ( message , args , pipeline_data ) : \"\"\"\"\"\" module_name , function_name = args [ : ] module = importlib . import_module ( module_name ) command = module . __dict__ . get ( function_name , None ) if command : return command ( message , args [ : ] , pipeline_data ) else : return None def print_pipeline ( message , args , pipeline_data ) : \"\"\"\"\"\" print ( \"\" , message ) print ( \"\" , pipeline_data ) return True def strip ( message , args , pipeline_data ) : \"\"\"\"\"\" chars = args [ ] message [ '' ] = message [ '' ] . strip ( chars ) return chars def list_dir ( message , args , pipeline_data ) : \"\"\"\"\"\" ", "answer": "cwd = message [ '' ]"}, {"prompt": " \"\"\"\"\"\" from flask import g from mongoengine . connection import ConnectionError from py . test import fixture , exit from tentd import create_app from tentd . documents import collections , Entity , Post , Follower , Following def pytest_report_header ( config ) : from tentd import __version__ return \"\" . format ( __version__ ) def pytest_addoption ( parser ) : \"\"\"\"\"\" parser . addoption ( '' , action = '' , default = '' , help = \"\" ) parser . addoption ( '' , action = '' , help = \"\" ) def pytest_configure ( config ) : \"\"\"\"\"\" if not config . getoption ( '' ) : from warnings import resetwarnings , filterwarnings filterwarnings ( action = '' , module = '' ) def pytest_generate_tests ( metafunc ) : \"\"\"\"\"\" if '' in metafunc . fixturenames : metafunc . parametrize ( '' , { '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , '' , '' ) , } [ metafunc . config . getoption ( '' ) ] , indirect = True , scope = \"\" ) def pytest_runtest_teardown ( item , nextitem ) : \"\"\"\"\"\" if '' in item . fixturenames : for collection in collections : collection . drop_collection ( ) def pytest_runtest_makereport ( item , call ) : \"\"\"\"\"\" if hasattr ( call . excinfo , '' ) : if call . excinfo . type is ConnectionError : exit ( \"\" ) @ fixture def app ( request ) : \"\"\"\"\"\" config = { '' : True , '' : True , '' : True , '' : False , '' : '' , '' : { '' : '' , } , '' : request . param , '' : '' , } app = create_app ( config ) app . client = app . test_client ( ) app . test_mode = request . param ctx = app . test_request_context ( ) ctx . push ( ) request . addfinalizer ( ctx . pop ) return app @ fixture def entity ( request , app ) : name = app . user_name if app . user_mode == '' else '' g . entity = Entity . new ( name = name , identity = \"\" , servers = [ \"\" ] ) . save ( ) @ request . addfinalizer def delete_entity ( ) : if hasattr ( g , '' ) : del g . entity return g . entity @ fixture def post ( request , entity ) : \"\"\"\"\"\" schema = '' post = Post ( entity = entity , schema = schema ) post . new_version ( content = { '' : \"\" , '' : [ , ] , } , mention = [ ] ) post . new_version ( content = { '' : \"\" , '' : [ , ] , } , mention = [ ] ) post . new_version ( content = { '' : \"\" , '' : [ , ] } , mentions = [ { '' : '' } ] ) post . save ( ) post = Post . objects . get ( entity = entity , schema = schema ) request . addfinalizer ( post . delete ) return post @ fixture def follower ( request , entity ) : \"\"\"\"\"\" ", "answer": "follower = Follower ("}, {"prompt": " SQL_PORT = ZMQ_RPC_PORT = HTTP_PORT = ", "answer": "HTTPS_PORT = "}, {"prompt": " \"\"\"\"\"\" import logging from fabric . context_managers import settings , hide , shell_env from fabric . decorators import task , runs_once from fabric . operations import sudo , put , os , local from fabric . state import env from fabric . tasks import execute ", "answer": "from fabric . utils import abort"}, {"prompt": " __all__ = ( '' , ", "answer": ") "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import numpy import numpy . random import random import json import time from datetime import datetime import requests from scipy . linalg import norm import time from multiprocessing import Pool import os HOSTNAME = os . environ . get ( '' , '' ) + '' + os . environ . get ( '' , '' ) def run_all ( assert_200 ) : app_id = '' num_arms = true_means = numpy . array ( range ( num_arms ) ) / float ( num_arms ) total_pulls_per_client = num_experiments = num_clients = pool = Pool ( processes = num_clients ) n = num_arms delta = supported_alg_ids = [ '' , '' , '' ] alg_list = [ ] for alg_id in supported_alg_ids : alg_item = { } alg_item [ '' ] = alg_id alg_item [ '' ] = alg_id alg_item [ '' ] = { } alg_list . append ( alg_item ) params = { } params [ '' ] = [ ] for algorithm in alg_list : params [ '' ] . append ( { '' : algorithm [ '' ] , '' : / len ( alg_list ) } ) algorithm_management_settings = { } algorithm_management_settings [ '' ] = '' algorithm_management_settings [ '' ] = params initExp_args_dict = { } initExp_args_dict [ '' ] = { } initExp_args_dict [ '' ] [ '' ] = n initExp_args_dict [ '' ] [ '' ] = delta initExp_args_dict [ '' ] [ '' ] = '' initExp_args_dict [ '' ] [ '' ] = algorithm_management_settings initExp_args_dict [ '' ] [ '' ] = alg_list initExp_args_dict [ '' ] [ '' ] = '' initExp_args_dict [ '' ] [ '' ] = '' initExp_args_dict [ '' ] [ '' ] = '' initExp_args_dict [ '' ] [ '' ] = '' initExp_args_dict [ '' ] = app_id initExp_args_dict [ '' ] = '' initExp_args_dict [ '' ] = '' exp_info = [ ] for ell in range ( num_experiments ) : url = \"\" + HOSTNAME + \"\" response = requests . post ( url , json . dumps ( initExp_args_dict ) , headers = { '' : '' } ) print \"\" , response . text , response . status_code if assert_200 : assert response . status_code is initExp_response_dict = json . loads ( response . text ) exp_uid = initExp_response_dict [ '' ] exp_key = initExp_response_dict [ '' ] exp_info . append ( { '' : exp_uid , '' : exp_key } ) url = \"\" + HOSTNAME + \"\" + exp_uid + \"\" + exp_key response = requests . get ( url ) print \"\" , response . text , response . status_code if assert_200 : assert response . status_code is initExp_response_dict = json . loads ( response . text ) participants = [ ] pool_args = [ ] for i in range ( num_clients ) : participant_uid = '' % random . randrange ( ** ) participants . append ( participant_uid ) experiment = numpy . random . choice ( exp_info ) exp_uid = experiment [ '' ] exp_key = experiment [ '' ] pool_args . append ( ( exp_uid , exp_key , participant_uid , total_pulls_per_client , true_means , assert_200 ) ) results = pool . map ( simulate_one_client , pool_args ) for result in results : print result def simulate_one_client ( input_args ) : exp_uid , exp_key , participant_uid , total_pulls , true_means , assert_200 = input_args avg_response_time = getQuery_times = [ ] processAnswer_times = [ ] for t in range ( total_pulls ) : print t , participant_uid getQuery_args_dict = { } getQuery_args_dict [ '' ] = exp_uid getQuery_args_dict [ '' ] = exp_key getQuery_args_dict [ '' ] = { } getQuery_args_dict [ '' ] [ '' ] = participant_uid url = '' + HOSTNAME + '' response , dt = timeit ( requests . post ) ( url , json . dumps ( getQuery_args_dict ) , headers = { '' : '' } ) print \"\" , response . text , response . status_code if assert_200 : assert response . status_code is print \"\" , dt getQuery_times . append ( dt ) print query_dict = json . loads ( response . text ) query_uid = query_dict [ '' ] targets = query_dict [ '' ] for target in targets : if target [ '' ] == '' : index_left = target [ '' ] if target [ '' ] == '' : index_right = target [ '' ] if target [ '' ] == : index_painted = target [ '' ] ts = time . time ( ) time . sleep ( avg_response_time * numpy . random . rand ( ) ) reward_left = true_means [ index_left ] + numpy . random . randn ( ) * reward_right = true_means [ index_right ] + numpy . random . randn ( ) * if reward_left > reward_right : index_winner = index_left ", "answer": "else :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Tangible ( )"}, {"prompt": " \"\"\"\"\"\" \"\"\"\"\"\" import os import sys import re import logging from floyd . helpers . dateformat import * try : import memcache except ImportError : memcache = { } try : import jinja2 except ImportError : logging . info ( '' ) logging . info ( sys . path ) raise NotFound ( '' ) _jinja_env = None _jinja_loaders = { } class JinjaEnviroment ( jinja2 . Environment ) : def join_path ( self , template , parent = None ) : if '' in template : sep , template = template . split ( '' , ) return \"\" % ( sep , parent , template ) elif '' in parent : return os . path . normpath ( os . path . join ( parent , '' , template ) ) elif parent . endswith ( '' ) : return template return \"\" % ( parent , template ) class MemcacheBytecodeCache ( jinja2 . BytecodeCache ) : def __init__ ( self , client = None , prefix = '' , timeout = None ) : self . client = memcache self . prefix = prefix self . timeout = timeout def load_bytecode ( self , bucket ) : code = self . client . get ( self . prefix + bucket . key ) if code is not None : bucket . bytecode_from_string ( code ) def dump_bytecode ( self , bucket ) : args = ( self . prefix + bucket . key , bucket . bytecode_to_string ( ) ) if self . timeout is not None : args += ( self . timeout , ) self . client . set ( * args ) class CompiledLoader ( jinja2 . BaseLoader ) : \"\"\"\"\"\" def load ( self , env , name , glob = { } ) : source , filename , uptodate = self . get_source ( environment , name ) code = compile ( source , filename , '' ) return env . template_class . from_code ( env , code , glob , uptodate ) class SubdirLoader ( jinja2 . BaseLoader ) : \"\"\"\"\"\" def __init__ ( self , mapping , delimiter = '' ) : self . mapping = mapping self . delimiter = delimiter def get_source ( self , environment , template ) : try : prefix , name = template . split ( self . delimiter , ) loader = self . mapping [ prefix ] except ( ValueError , KeyError ) : raise jinja2 . TemplateNotFound ( template ) try : return loader . get_source ( environment , name ) except jinja2 . TemplateNotFound : raise jinja2 . TemplateNotFound ( template ) def list_templates ( self ) : result = [ ] for prefix , loader in self . mapping . iteritems ( ) : for template in loader . list_templates ( ) : result . append ( prefix + self . delimiter + template ) return result def setup_cache ( ) : pass def setup ( template_paths = { } , autoescape = False , cache_size = , auto_reload = True , bytecode_cache = True ) : \"\"\"\"\"\" global _jinja_env , _jinja_loaders if not _jinja_env : _jinja_env = JinjaEnviroment ( autoescape = autoescape , cache_size = cache_size , auto_reload = auto_reload , bytecode_cache = None ) if type ( template_paths ) == type ( '' ) : template_paths = { '' : template_paths } if len ( template_paths ) < : logging . exception ( '' ) return False if len ( template_paths ) == : template_set_name = template_paths . keys ( ) [ ] tp = template_paths [ template_set_name ] if tp in _jinja_loaders : _jinja_env . loader = _jinja_loaders [ tp ] else : _jinja_env . loader = _jinja_loaders [ tp ] = jinja2 . FileSystemLoader ( tp ) return True if len ( template_paths ) > : loaders = { } for dirn , path in template_paths . items ( ) : loaders [ dirn ] = jinja2 . FileSystemLoader ( path ) _jinja_env . loader = SubdirLoader ( loaders ) return True logging . error ( '' ) logging . error ( _jinja_loaders ) def render ( template_name , template_vars = { } , template_set = '' , template_theme = None , template_extension = '' , template_content = None ) : \"\"\"\"\"\" global _jinja_env if not _jinja_env : raise '' try : _jinja_env . filters [ '' ] = timesince ", "answer": "_jinja_env . filters [ '' ] = timeuntil"}, {"prompt": " from __future__ import absolute_import , division , print_function INCLUDES = \"\"\"\"\"\" TYPES = \"\"\"\"\"\" FUNCTIONS = \"\"\"\"\"\" MACROS = \"\"\"\"\"\" ", "answer": "CUSTOMIZATIONS = \"\"\"\"\"\" "}, {"prompt": " import django from django . conf . urls import include , url from django . contrib import admin admin . autodiscover ( ) urlpatterns = [ url ( r'' , include ( '' ) ) , url ( r'' , include ( '' ) ) , url ( r'' , include ( admin . site . urls ) ) , ", "answer": "url ( r'' , include ( '' ) ) ,"}, {"prompt": " class DummyHashAnnouncer ( object ) : def __init__ ( self , * args ) : pass def run_manage_loop ( self ) : pass ", "answer": "def stop ( self ) :"}, {"prompt": " import time from django . http import HttpResponseNotAllowed , HttpResponseForbidden , HttpResponse , HttpResponseBadRequest from django . core . urlresolvers import reverse from django . core . cache import cache from django import get_version as django_version from django . core . mail import send_mail , mail_admins from django . conf import settings from django . utils . translation import ugettext as _ from django . template import loader , TemplateDoesNotExist from django . contrib . sites . models import Site from decorator import decorator from datetime import datetime , timedelta __version__ = '' def get_version ( ) : return __version__ def format_error ( error ) : return u\"\" % ( get_version ( ) , django_version ( ) , error ) class rc_factory ( object ) : \"\"\"\"\"\" CODES = dict ( ALL_OK = ( '' , ) , CREATED = ( '' , ) , DELETED = ( '' , ) , BAD_REQUEST = ( '' , ) , FORBIDDEN = ( '' , ) , NOT_FOUND = ( '' , ) , DUPLICATE_ENTRY = ( '' , ) , NOT_HERE = ( '' , ) , INTERNAL_ERROR = ( '' , ) , NOT_IMPLEMENTED = ( '' , ) , THROTTLED = ( '' , ) ) def __getattr__ ( self , attr ) : \"\"\"\"\"\" try : ( r , c ) = self . CODES . get ( attr ) except TypeError : raise AttributeError ( attr ) class HttpResponseWrapper ( HttpResponse ) : \"\"\"\"\"\" def _set_content ( self , content ) : \"\"\"\"\"\" if not isinstance ( content , basestring ) and hasattr ( content , '' ) : self . _container = content self . _is_string = False else : self . _container = [ content ] self . _is_string = True content = property ( HttpResponse . _get_content , _set_content ) return HttpResponseWrapper ( r , content_type = '' , status = c ) rc = rc_factory ( ) class FormValidationError ( Exception ) : def __init__ ( self , form ) : self . form = form class HttpStatusCode ( Exception ) : def __init__ ( self , response ) : self . response = response def validate ( v_form , operation = '' ) : @ decorator def wrap ( f , self , request , * a , ** kwa ) : form = v_form ( getattr ( request , operation ) ) if form . is_valid ( ) : setattr ( request , '' , form ) return f ( self , request , * a , ** kwa ) else : raise FormValidationError ( form ) return wrap def throttle ( max_requests , timeout = * , extra = '' ) : \"\"\"\"\"\" @ decorator def wrap ( f , self , request , * args , ** kwargs ) : if request . user . is_authenticated ( ) : ident = request . user . username else : ident = request . META . get ( '' , None ) if hasattr ( request , '' ) : \"\"\"\"\"\" ident += '' % str ( request . throttle_extra ) if ident : \"\"\"\"\"\" ident += '' % extra now = time . time ( ) count , expiration = cache . get ( ident , ( , None ) ) if expiration is None : expiration = now + timeout if count >= max_requests and expiration > now : t = rc . THROTTLED wait = int ( expiration - now ) t . content = '' % wait t [ '' ] = wait return t cache . set ( ident , ( count + , expiration ) , ( expiration - now ) ) return f ( self , request , * args , ** kwargs ) return wrap def coerce_put_post ( request ) : \"\"\"\"\"\" if request . method == \"\" : if hasattr ( request , '' ) : del request . _post del request . _files try : request . method = \"\" request . _load_post_and_files ( ) request . method = \"\" except AttributeError : request . META [ '' ] = '' request . _load_post_and_files ( ) request . META [ '' ] = '' request . PUT = request . POST class MimerDataException ( Exception ) : \"\"\"\"\"\" pass class Mimer ( object ) : TYPES = dict ( ) def __init__ ( self , request ) : self . request = request def is_multipart ( self ) : content_type = self . content_type ( ) if content_type is not None : return content_type . lstrip ( ) . startswith ( '' ) return False def loader_for_type ( self , ctype ) : \"\"\"\"\"\" for loadee , mimes in Mimer . TYPES . iteritems ( ) : for mime in mimes : if ctype . startswith ( mime ) : return loadee def content_type ( self ) : \"\"\"\"\"\" type_formencoded = \"\" ctype = self . request . META . get ( '' , type_formencoded ) if type_formencoded in ctype : return None return ctype def translate ( self ) : \"\"\"\"\"\" ctype = self . content_type ( ) self . request . content_type = ctype if not self . is_multipart ( ) and ctype : loadee = self . loader_for_type ( ctype ) if loadee : try : self . request . data = loadee ( self . request . raw_post_data ) self . request . POST = self . request . PUT = dict ( ) except ( TypeError , ValueError ) : raise MimerDataException else : self . request . data = None return self . request @ classmethod def register ( cls , loadee , types ) : cls . TYPES [ loadee ] = types @ classmethod def unregister ( cls , loadee ) : return cls . TYPES . pop ( loadee ) def translate_mime ( request ) : request = Mimer ( request ) . translate ( ) def require_mime ( * mimes ) : \"\"\"\"\"\" @ decorator def wrap ( f , self , request , * args , ** kwargs ) : m = Mimer ( request ) realmimes = set ( ) rewrite = { '' : '' , '' : '' , '' : '' , '' : '' } for idx , mime in enumerate ( mimes ) : realmimes . add ( rewrite . get ( mime , mime ) ) if not m . content_type ( ) in realmimes : return rc . BAD_REQUEST return f ( self , request , * args , ** kwargs ) return wrap require_extended = require_mime ( '' , '' , '' , '' ) def send_consumer_mail ( consumer ) : \"\"\"\"\"\" try : subject = settings . PISTON_OAUTH_EMAIL_SUBJECTS [ consumer . status ] except AttributeError : subject = \"\" % Site . objects . get_current ( ) . name if consumer . status == \"\" : subject += \"\" elif consumer . status == \"\" : subject += \"\" elif consumer . status == \"\" : subject += \"\" else : subject += \"\" template = \"\" % consumer . status try : body = loader . render_to_string ( template , { '' : consumer , '' : consumer . user } ) except TemplateDoesNotExist : \"\"\"\"\"\" return try : ", "answer": "sender = settings . PISTON_FROM_EMAIL"}, {"prompt": " import abc from distutils . spawn import find_executable import six from st2actions . runners import ActionRunner __all__ = [ '' , '' , '' ] WINEXE_EXISTS = find_executable ( '' ) is not None SMBCLIENT_EXISTS = find_executable ( '' ) is not None ERROR_CODE_TO_MESSAGE_MAP = { '' : '' , '' : '' , '' : '' , '' : '' } @ six . add_metaclass ( abc . ABCMeta ) class BaseWindowsRunner ( ActionRunner ) : def _verify_winexe_exists ( self ) : if not WINEXE_EXISTS : msg = ( '' '' ) raise Exception ( msg ) def _verify_smbclient_exists ( self ) : if not SMBCLIENT_EXISTS : msg = ( '' '' ) raise Exception ( msg ) def _get_winexe_command_args ( self , host , username , password , command , domain = None ) : args = [ '' ] args += [ '' , '' ] if domain : args += [ '' , '' % ( domain , username , password ) ] else : ", "answer": "args += [ '' , '' % ( username , password ) ]"}, {"prompt": " \"\"\"\"\"\" ", "answer": "cases = ["}, {"prompt": " import datetime import json import pytz from django . http import HttpRequest , QueryDict , Http404 from django . test import Client , TestCase from mock import patch from rest_framework . request import Request from rest_framework . authtoken . models import Token from periods import models as period_models , views from periods . serializers import FlowEventSerializer from periods . tests . factories import FlowEventFactory , UserFactory class TestFlowEventViewSet ( TestCase ) : def setUp ( self ) : self . view_set = views . FlowEventViewSet ( ) self . view_set . format_kwarg = '' self . period = FlowEventFactory ( ) FlowEventFactory ( timestamp = pytz . utc . localize ( datetime . datetime ( , , ) ) ) self . request = Request ( HttpRequest ( ) ) self . request . __setattr__ ( '' , self . period . user ) self . view_set . request = self . request def test_list ( self ) : response = self . view_set . list ( self . request ) self . assertEqual ( , len ( response . data ) ) self . assertEqual ( self . period . id , response . data [ ] [ '' ] ) def test_perform_create ( self ) : serializer = FlowEventSerializer ( data = { '' : datetime . datetime ( , , ) } ) serializer . is_valid ( ) self . view_set . perform_create ( serializer ) self . assertEqual ( self . request . user , serializer . instance . user ) class TestStatisticsViewSet ( TestCase ) : def setUp ( self ) : self . view_set = views . StatisticsViewSet ( ) self . view_set . format_kwarg = '' self . period = FlowEventFactory ( ) self . period2 = FlowEventFactory ( timestamp = pytz . utc . localize ( datetime . datetime ( , , ) ) ) self . request = Request ( HttpRequest ( ) ) self . request . __setattr__ ( '' , self . period . user ) self . view_set . request = self . request def test_retrieve_other_user ( self ) : self . view_set . kwargs = { '' : self . period2 . user . statistics . pk } try : self . view_set . retrieve ( self . request ) self . fail ( \"\" ) except Http404 : pass @ patch ( '' ) def test_list_no_params ( self , mock_today ) : mock_today . return_value = pytz . utc . localize ( datetime . datetime ( , , ) ) self . view_set . kwargs = { '' : self . request . user . statistics . pk } response = self . view_set . list ( self . request ) self . assertEqual ( , len ( response . data ) ) self . assertEqual ( , response . data [ '' ] ) self . assertEqual ( self . period . timestamp . date ( ) , response . data [ '' ] ) self . assertEqual ( , response . data [ '' ] ) def test_list_with_min_timestamp ( self ) : http_request = HttpRequest ( ) http_request . GET = QueryDict ( u'' ) request = Request ( http_request ) request . __setattr__ ( '' , self . period . user ) self . view_set . kwargs = { '' : self . request . user . statistics . pk } response = self . view_set . list ( request ) self . assertEqual ( , len ( response . data ) ) self . assertEqual ( , response . data [ '' ] ) self . assertEqual ( self . period . timestamp . date ( ) , response . data [ '' ] ) self . assertEqual ( , response . data [ '' ] ) class TestApiAuthenticate ( TestCase ) : def setUp ( self ) : self . client = Client ( ) self . url_path = '' self . data = { \"\" : \"\" , \"\" : \"\" } def test_api_authenticate_get ( self ) : response = self . client . get ( self . url_path ) self . assertEqual ( , response . status_code ) def test_api_authenticate_not_json ( self ) : response = self . client . post ( self . url_path , data = '' , content_type = '' ) self . assertEqual ( , response . status_code ) self . assertEqual ( b'' , response . content ) def test_api_authenticate_missing_fields ( self ) : response = self . client . post ( self . url_path , data = json . dumps ( { } ) , content_type = '' ) self . assertEqual ( , response . status_code ) self . assertEqual ( b'' , response . content ) def test_api_authenticate_failure ( self ) : response = self . client . post ( self . url_path , data = json . dumps ( self . data ) , content_type = '' ) self . assertEqual ( , response . status_code ) self . assertEqual ( b'' , response . content ) @ patch ( '' ) def test_api_authenticate_success ( self , mock_authenticate ) : user = UserFactory ( ) mock_authenticate . return_value = user response = self . client . post ( self . url_path , data = json . dumps ( self . data ) , content_type = '' ) self . assertContains ( response , user . auth_token . key ) class TestViews ( TestCase ) : maxDiff = None def setUp ( self ) : self . period = FlowEventFactory ( ) FlowEventFactory ( user = self . period . user , timestamp = pytz . utc . localize ( datetime . datetime ( , , ) ) ) self . request = HttpRequest ( ) self . request . user = self . period . user self . request . META [ '' ] = '' self . request . META [ '' ] = '' @ patch ( '' ) def test_period_form_no_parameters ( self , mock_today ) : mock_today . return_value = pytz . utc . localize ( datetime . datetime ( , , ) ) response = views . period_form ( self . request , mock_today ) self . assertContains ( response , '' ) self . assertContains ( response , '' '' ) self . assertContains ( response , '' ) self . assertContains ( response , '' ) def test_period_form_with_timestamp ( self ) : self . request . GET = QueryDict ( '' ) response = views . period_form ( self . request ) self . assertContains ( response , '' ) self . assertContains ( response , '' '' ) self . assertContains ( response , '' ) self . assertContains ( response , '' ) @ patch ( '' ) def test_period_form_invalid_period_id ( self , mock_today ) : mock_today . return_value = pytz . utc . localize ( datetime . datetime ( , , ) ) response = views . period_form ( self . request , ) self . assertContains ( response , '' ) self . assertContains ( response , '' '' ) self . assertContains ( response , '' ) self . assertContains ( response , '' ) def test_period_form_existing_period ( self ) : response = views . period_form ( self . request , self . period . id ) self . assertContains ( response , '' ) self . assertContains ( response , '' '' ) self . assertContains ( response , '' ) self . assertContains ( response , '' ) def test_calendar ( self ) : response = views . calendar ( self . request ) self . assertContains ( response , '' ) self . assertContains ( response , '' ) def test_cycle_length_frequency_no_data ( self ) : period_models . FlowEvent . objects . all ( ) . delete ( ) response = views . cycle_length_frequency ( self . request ) result = json . loads ( response . content . decode ( '' ) ) self . assertEqual ( { } , result ) def test_cycle_length_frequency ( self ) : response = views . cycle_length_frequency ( self . request ) result = json . loads ( response . content . decode ( '' ) ) self . assertEqual ( { '' : [ [ , ] ] } , result ) def test_cycle_length_history_no_data ( self ) : period_models . FlowEvent . objects . all ( ) . delete ( ) response = views . cycle_length_history ( self . request ) result = json . loads ( response . content . decode ( '' ) ) self . assertEqual ( { } , result ) def test_cycle_length_history ( self ) : response = views . cycle_length_history ( self . request ) result = json . loads ( response . content . decode ( '' ) ) self . assertEqual ( { '' : [ [ '' , ] ] } , result ) def test_qigong_cycles_no_birth_date ( self ) : self . request . user . birth_date = None self . request . user . save ( ) response = views . qigong_cycles ( self . request ) result = json . loads ( response . content . decode ( '' ) ) self . assertEqual ( { } , result ) @ patch ( '' ) def test_qigong_cycles ( self , mock_today ) : mock_today . return_value = pytz . utc . localize ( datetime . datetime ( , , ) ) response = views . qigong_cycles ( self . request ) result = json . loads ( response . content . decode ( '' ) ) expected = { '' : [ [ '' , ] , [ '' , ] , [ '' , ] , [ '' , ] , [ '' , ] ] , ", "answer": "'' : [ [ '' , ] ,"}, {"prompt": " from ginga . misc import Bunch ", "answer": "class PluginError ( Exception ) :"}, {"prompt": " \"\"\"\"\"\" import logging import time try : import simplejson as json except ImportError : import json import requests from solumclient . openstack . common . apiclient import exceptions from solumclient . openstack . common . gettextutils import _ from solumclient . openstack . common import importutils _logger = logging . getLogger ( __name__ ) class HTTPClient ( object ) : \"\"\"\"\"\" user_agent = \"\" def __init__ ( self , auth_plugin , region_name = None , endpoint_type = \"\" , original_ip = None , verify = True , cert = None , timeout = None , timings = False , keyring_saver = None , debug = False , user_agent = None , http = None ) : self . auth_plugin = auth_plugin self . endpoint_type = endpoint_type self . region_name = region_name self . original_ip = original_ip self . timeout = timeout self . verify = verify self . cert = cert self . keyring_saver = keyring_saver self . debug = debug self . user_agent = user_agent or self . user_agent self . times = [ ] self . timings = timings self . http = http or requests . Session ( ) self . cached_token = None def _http_log_req ( self , method , url , kwargs ) : if not self . debug : return string_parts = [ \"\" , \"\" % method , \"\" % url , ] for element in kwargs [ '' ] : header = \"\" % ( element , kwargs [ '' ] [ element ] ) ", "answer": "string_parts . append ( header )"}, {"prompt": " from xierpa3 . toolbox . transformer import TX from xierpa3 . attributes . attribute import Attribute def asValue ( value ) : if isinstance ( value , Value ) : return value . value return TX . px ( value ) ", "answer": "class Value ( Attribute ) :"}, {"prompt": " from quandl . connection import Connection from quandl . api_config import ApiConfig from quandl . errors . quandl_error import ( QuandlError , LimitExceededError , InternalServerError , AuthenticationError , ForbiddenError , InvalidRequestError , NotFoundError , ServiceUnavailableError ) import unittest2 from test . helpers . httpretty_extension import httpretty import json from mock import patch , call class ConnectionTest ( unittest2 . TestCase ) : @ httpretty . activate def test_quandl_exceptions ( self ) : quandl_errors = [ ( '' , , LimitExceededError ) , ( '' , , InternalServerError ) , ( '' , , AuthenticationError ) , ( '' , , ForbiddenError ) , ", "answer": "( '' , , InvalidRequestError ) ,"}, {"prompt": " from setuptools import setup , find_packages try : import multiprocessing except ImportError : ", "answer": "pass"}, {"prompt": " import sys import unittest try : import StringIO as io except ImportError : import io from resync . resource import Resource from resync . list_base_with_index import ListBaseWithIndex , ListBaseIndexError from resync . sitemap import Sitemap , SitemapIndexError etree_error_class = None if ( sys . version_info < ( , ) ) : ", "answer": "from xml . parsers . expat import ExpatError"}, {"prompt": " \"\"\"\"\"\" import time import re import hashlib import getopt import socket from twisted . python import log from twisted . internet import reactor from cowrie . core . honeypot import HoneyPotCommand commands = { } class command_ssh ( HoneyPotCommand ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import sys if sys . version_info < ( , ) : from urllib2 import urlopen else : from urllib . request import urlopen import io ", "answer": "from colorthief import ColorThief"}, {"prompt": " import sys import os import shlex extensions = [ '' , '' ] releases_github_path = '' releases_debug = True templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' author = u'' language = None exclude_patterns = [ ] pygments_style = '' todo_include_todos = False on_rtd = os . environ . get ( '' , None ) == '' if not on_rtd : import sphinx_rtd_theme html_theme = '' html_theme_path = [ sphinx_rtd_theme . get_html_theme_path ( ) ] htmlhelp_basename = '' latex_elements = { } latex_documents = [ ( master_doc , '' , u'' , u'' , '' ) , ] man_pages = [ ( master_doc , '' , u'' , [ author ] , ) ] texinfo_documents = [ ( master_doc , '' , u'' , author , '' , '' , ", "answer": "'' ) ,"}, {"prompt": " \"\"\"\"\"\" try : import simplejson as json except ImportError : import json from base64 import b64encode from django . http import HttpResponse from django . contrib . auth import authenticate from django . views . decorators . csrf import csrf_exempt from . exceptions import OAuth2Exception from . consts import ACCESS_TOKEN_EXPIRATION , REFRESH_TOKEN_LENGTH from . consts import AUTHENTICATION_METHOD , MAC , BEARER , MAC_KEY_LENGTH from . consts import REFRESHABLE from . lib . uri import normalize from . models import Client , AccessRange , Code , AccessToken , TimestampGenerator from . models import KeyGenerator class AccessTokenException ( OAuth2Exception ) : \"\"\"\"\"\" pass class UnvalidatedRequest ( OAuth2Exception ) : \"\"\"\"\"\" pass class InvalidRequest ( AccessTokenException ) : \"\"\"\"\"\" error = '' class InvalidClient ( AccessTokenException ) : \"\"\"\"\"\" error = '' class UnauthorizedClient ( AccessTokenException ) : \"\"\"\"\"\" error = '' class InvalidGrant ( AccessTokenException ) : \"\"\"\"\"\" error = '' class UnsupportedGrantType ( AccessTokenException ) : \"\"\"\"\"\" error = '' class InvalidScope ( AccessTokenException ) : \"\"\"\"\"\" error = '' @ csrf_exempt def handler ( request ) : \"\"\"\"\"\" return TokenGenerator ( ) ( request ) class TokenGenerator ( object ) : \"\"\"\"\"\" valid = False code = None client = None access_token = None user = None error = None request = None def __init__ ( self , scope = None , authentication_method = AUTHENTICATION_METHOD , refreshable = REFRESHABLE ) : self . refreshable = refreshable if authentication_method not in [ BEARER , MAC ] : raise OAuth2Exception ( \"\" \"\" ) self . authentication_method = authentication_method if scope is None : self . authorized_scope = None elif isinstance ( scope , AccessRange ) : self . authorized_scope = set ( [ scope . key ] ) else : self . authorized_scope = set ( [ x . key for x in scope ] ) @ csrf_exempt def __call__ ( self , request ) : \"\"\"\"\"\" self . grant_type = request . REQUEST . get ( '' ) self . client_id = request . REQUEST . get ( '' ) self . client_secret = request . POST . get ( '' ) self . scope = request . REQUEST . get ( '' ) if self . scope is not None : self . scope = set ( self . scope . split ( ) ) self . code_key = request . REQUEST . get ( '' ) self . redirect_uri = request . REQUEST . get ( '' ) self . refresh_token = request . REQUEST . get ( '' ) self . email = request . REQUEST . get ( '' ) self . username = request . REQUEST . get ( '' ) self . password = request . REQUEST . get ( '' ) self . callback = request . REQUEST . get ( '' ) self . request = request try : self . validate ( ) except AccessTokenException , e : return self . error_response ( ) return self . grant_response ( ) def validate ( self ) : \"\"\"\"\"\" try : self . _validate ( ) except AccessTokenException , e : self . error = e raise e self . valid = True def _validate ( self ) : \"\"\"\"\"\" if self . grant_type is None : raise InvalidRequest ( '' ) if self . grant_type not in [ \"\" , \"\" , \"\" , \"\" ] : raise UnsupportedGrantType ( '' % self . grant_type ) if self . client_id is None : raise InvalidRequest ( '' ) try : self . client = Client . objects . get ( key = self . client_id ) except Client . DoesNotExist : raise InvalidClient ( \"\" % self . client_id ) if self . scope is not None : access_ranges = AccessRange . objects . filter ( key__in = self . scope ) access_ranges = set ( access_ranges . values_list ( '' , flat = True ) ) difference = access_ranges . symmetric_difference ( self . scope ) if len ( difference ) != : raise InvalidScope ( \"\" \"\" % '' . join ( difference ) ) if self . grant_type == \"\" : self . _validate_authorization_code ( ) elif self . grant_type == \"\" : self . _validate_refresh_token ( ) elif self . grant_type == \"\" : self . _validate_password ( ) elif self . grant_type == \"\" : self . _validate_client_credentials ( ) else : raise UnsupportedGrantType ( '' ) def _validate_access_credentials ( self ) : \"\"\"\"\"\" if self . client_secret is None and \"\" in self . request . META : authorization = self . request . META [ \"\" ] auth_type , auth_value = authorization . split ( ) [ : ] if auth_type . lower ( ) == \"\" : credentials = \"\" % ( self . client . key , self . client . secret ) if auth_value != b64encode ( credentials ) : raise InvalidClient ( '' ) else : raise InvalidClient ( '' ) elif self . client_secret != self . client . secret : raise InvalidClient ( '' ) def _validate_client_credentials ( self ) : \"\"\"\"\"\" self . _validate_access_credentials ( ) def _validate_authorization_code ( self ) : \"\"\"\"\"\" if self . code_key is None : raise InvalidRequest ( '' ) self . _validate_access_credentials ( ) try : self . code = Code . objects . get ( key = self . code_key ) except Code . DoesNotExist : raise InvalidRequest ( '' % self . code_key ) now = TimestampGenerator ( ) ( ) if self . code . expire < now : raise InvalidGrant ( \"\" ) self . scope = set ( [ x . key for x in self . code . scope . all ( ) ] ) if self . redirect_uri is None : raise InvalidRequest ( '' ) if normalize ( self . redirect_uri ) != normalize ( self . code . redirect_uri ) : raise InvalidRequest ( \"\" ) def _validate_password ( self ) : \"\"\"\"\"\" if self . username is None and self . email is None : raise InvalidRequest ( '' ) if self . password is None : raise InvalidRequest ( '' ) if self . scope is not None : access_ranges = AccessRange . objects . filter ( key__in = self . scope ) access_ranges = set ( access_ranges . values_list ( '' , flat = True ) ) difference = access_ranges . symmetric_difference ( self . scope ) if len ( difference ) != : raise InvalidScope ( \"\"\"\"\"\" % '' . join ( difference ) ) if self . authorized_scope is not None : new_scope = self . scope - self . authorized_scope if len ( new_scope ) > : raise InvalidScope ( \"\" % '' . join ( new_scope ) ) if \"\" in self . request . META : authorization = self . request . META [ \"\" ] auth_type , auth_value = authorization . split ( ) [ : ] if auth_type . lower ( ) == \"\" : credentials = \"\" % ( self . client . key , self . client . secret ) if auth_value != b64encode ( credentials ) : raise InvalidClient ( '' ) else : raise InvalidClient ( '' ) else : raise InvalidClient ( '' ) if self . username is not None : user = authenticate ( username = self . username , password = self . password ) else : user = authenticate ( email = self . email , password = self . password ) if user is not None : if not user . is_active : raise InvalidRequest ( '' ) else : raise InvalidRequest ( '' ) self . user = user def _validate_refresh_token ( self ) : \"\"\"\"\"\" if self . refresh_token is None : raise InvalidRequest ( '' ) try : self . access_token = AccessToken . objects . get ( refresh_token = self . refresh_token ) except AccessToken . DoesNotExist : raise InvalidRequest ( '' % self . refresh_token ) self . _validate_access_credentials ( ) if not self . access_token . refreshable : raise InvalidGrant ( \"\" ) if self . scope is not None : access_ranges = set ( [ x . key for x in self . access_token . scope . all ( ) ] ) new_scope = self . scope - access_ranges if len ( new_scope ) > : raise InvalidScope ( \"\" \"\" % new_scope ) def error_response ( self ) : \"\"\"\"\"\" if self . error is not None : e = self . error else : e = InvalidRequest ( \"\" ) data = { '' : e . error , '' : u'' % e . message } json_data = json . dumps ( data ) if self . callback is not None : json_data = \"\" % ( self . callback , json_data ) return HttpResponse ( content = json_data , content_type = '' ) else : response = HttpResponse ( content = json_data , content_type = '' ) if isinstance ( self . error , InvalidClient ) : response . status_code = else : response . status_code = return response def grant_response ( self ) : \"\"\"\"\"\" if not self . valid : raise UnvalidatedRequest ( \"\" \"\" ) if self . grant_type == \"\" : access_token = self . _get_authorization_code_token ( ) elif self . grant_type == \"\" : access_token = self . _get_refresh_token ( ) elif self . grant_type == \"\" : access_token = self . _get_password_token ( ) elif self . grant_type == \"\" : access_token = self . _get_client_credentials_token ( ) data = { '' : access_token . token , '' : ACCESS_TOKEN_EXPIRATION } if self . authentication_method == MAC : data [ \"\" ] = \"\" data [ \"\" ] = access_token . mac_key data [ \"\" ] = \"\" elif self . authentication_method == BEARER : data [ \"\" ] = \"\" if access_token . refreshable : data [ '' ] = access_token . refresh_token if self . scope is not None : data [ '' ] = '' . join ( self . scope ) json_data = json . dumps ( data ) if self . callback is not None : json_data = \"\" % ( self . callback , json_data ) response = HttpResponse ( content = json_data , content_type = '' ) response [ '' ] = '' return response def _get_authorization_code_token ( self ) : \"\"\"\"\"\" access_token = AccessToken . objects . create ( user = self . code . user , client = self . client , refreshable = self . refreshable ) if self . authentication_method == MAC : access_token . mac_key = KeyGenerator ( MAC_KEY_LENGTH ) ( ) access_ranges = AccessRange . objects . filter ( key__in = self . scope ) if self . scope else [ ] access_token . scope = access_ranges access_token . save ( ) self . code . delete ( ) return access_token def _get_password_token ( self ) : \"\"\"\"\"\" access_token = AccessToken . objects . create ( user = self . user , client = self . client , refreshable = self . refreshable ) if self . authentication_method == MAC : access_token . mac_key = KeyGenerator ( MAC_KEY_LENGTH ) ( ) ", "answer": "access_ranges = AccessRange . objects . filter ( key__in = self . scope ) if self . scope else [ ]"}, {"prompt": " import datetime import json from pkg_resources import iter_entry_points import sqlalchemy as sql from moai . utils import check_type def get_database ( uri , config = None ) : prefix = uri . split ( '' ) [ ] for entry_point in iter_entry_points ( group = '' , name = prefix ) : dbclass = entry_point . load ( ) try : return dbclass ( uri , config ) except TypeError : return dbclass ( uri ) raise ValueError ( '' % prefix ) class SQLDatabase ( object ) : \"\"\"\"\"\" def __init__ ( self , dburi = None ) : self . _uri = dburi self . _db = self . _connect ( ) self . _records = self . _db . tables [ '' ] self . _sets = self . _db . tables [ '' ] self . _setrefs = self . _db . tables [ '' ] self . _reset_cache ( ) def _connect ( self ) : dburi = self . _uri if dburi is None : dburi = '' engine = sql . create_engine ( dburi ) db = sql . MetaData ( engine ) sql . Table ( '' , db , sql . Column ( '' , sql . Unicode , primary_key = True ) , sql . Column ( '' , sql . DateTime , index = True ) , sql . Column ( '' , sql . Boolean ) , sql . Column ( '' , sql . String ) ) sql . Table ( '' , db , sql . Column ( '' , sql . Unicode , primary_key = True ) , sql . Column ( '' , sql . Boolean ) , sql . Column ( '' , sql . Unicode ) , sql . Column ( '' , sql . Unicode ) ) sql . Table ( '' , db , sql . Column ( '' , sql . Integer , sql . ForeignKey ( '' ) , index = True , primary_key = True ) , sql . Column ( '' , sql . Integer , sql . ForeignKey ( '' ) , index = True , primary_key = True ) ) db . create_all ( ) return db def flush ( self ) : oai_ids = set ( ) for row in sql . select ( [ self . _records . c . record_id ] ) . execute ( ) : oai_ids . add ( row [ ] ) for row in sql . select ( [ self . _sets . c . set_id ] ) . execute ( ) : oai_ids . add ( row [ ] ) deleted_records = [ ] deleted_sets = [ ] deleted_setrefs = [ ] inserted_records = [ ] inserted_sets = [ ] inserted_setrefs = [ ] for oai_id , item in self . _cache [ '' ] . items ( ) : if oai_id in oai_ids : deleted_records . append ( oai_id ) item [ '' ] = oai_id inserted_records . append ( item ) for oai_id , item in self . _cache [ '' ] . items ( ) : if oai_id in oai_ids : deleted_sets . append ( oai_id ) item [ '' ] = oai_id inserted_sets . append ( item ) for record_id , set_ids in self . _cache [ '' ] . items ( ) : deleted_setrefs . append ( record_id ) for set_id in set_ids : inserted_setrefs . append ( { '' : record_id , '' : set_id } ) if deleted_records : self . _records . delete ( self . _records . c . record_id == sql . bindparam ( '' ) ) . execute ( [ { '' : rid } for rid in deleted_records ] ) if deleted_sets : self . _sets . delete ( self . _sets . c . set_id == sql . bindparam ( '' ) ) . execute ( [ { '' : sid } for sid in deleted_sets ] ) if deleted_setrefs : self . _setrefs . delete ( self . _setrefs . c . record_id == sql . bindparam ( '' ) ) . execute ( [ { '' : rid } for rid in deleted_setrefs ] ) if inserted_records : self . _records . insert ( ) . execute ( inserted_records ) if inserted_sets : self . _sets . insert ( ) . execute ( inserted_sets ) if inserted_setrefs : self . _setrefs . insert ( ) . execute ( inserted_setrefs ) self . _reset_cache ( ) def _reset_cache ( self ) : self . _cache = { '' : { } , '' : { } , '' : { } } def update_record ( self , oai_id , modified , deleted , sets , metadata ) : check_type ( oai_id , unicode , prefix = \"\" % oai_id , suffix = '' ) check_type ( modified , datetime . datetime , prefix = \"\" % oai_id , suffix = '' ) check_type ( deleted , bool , prefix = \"\" % oai_id , suffix = '' ) check_type ( sets , dict , unicode_values = True , recursive = True , prefix = \"\" % oai_id , suffix = '' ) check_type ( metadata , dict , prefix = \"\" % oai_id , suffix = '' ) def date_handler ( obj ) : if hasattr ( obj , '' ) : return obj . isoformat ( ) else : raise TypeError , '' % ( type ( obj ) , repr ( obj ) ) metadata = json . dumps ( metadata , default = date_handler ) self . _cache [ '' ] [ oai_id ] = ( dict ( modified = modified , deleted = deleted , ", "answer": "metadata = metadata ) )"}, {"prompt": " import logging from synapse . api . errors import StoreError from synapse . util . logcontext import LoggingContext , PreserveLoggingContext from synapse . util . caches . dictionary_cache import DictionaryCache from synapse . util . caches . descriptors import Cache from synapse . util . caches import intern_dict import synapse . metrics from twisted . internet import defer import sys import time import threading import os CACHE_SIZE_FACTOR = float ( os . environ . get ( \"\" , ) ) logger = logging . getLogger ( __name__ ) sql_logger = logging . getLogger ( \"\" ) transaction_logger = logging . getLogger ( \"\" ) perf_logger = logging . getLogger ( \"\" ) metrics = synapse . metrics . get_metrics_for ( \"\" ) sql_scheduling_timer = metrics . register_distribution ( \"\" ) sql_query_timer = metrics . register_distribution ( \"\" , labels = [ \"\" ] ) sql_txn_timer = metrics . register_distribution ( \"\" , labels = [ \"\" ] ) class LoggingTransaction ( object ) : \"\"\"\"\"\" __slots__ = [ \"\" , \"\" , \"\" , \"\" ] def __init__ ( self , txn , name , database_engine , after_callbacks ) : object . __setattr__ ( self , \"\" , txn ) object . __setattr__ ( self , \"\" , name ) object . __setattr__ ( self , \"\" , database_engine ) object . __setattr__ ( self , \"\" , after_callbacks ) def call_after ( self , callback , * args ) : \"\"\"\"\"\" self . after_callbacks . append ( ( callback , args ) ) def __getattr__ ( self , name ) : return getattr ( self . txn , name ) def __setattr__ ( self , name , value ) : setattr ( self . txn , name , value ) def execute ( self , sql , * args ) : self . _do_execute ( self . txn . execute , sql , * args ) def executemany ( self , sql , * args ) : self . _do_execute ( self . txn . executemany , sql , * args ) def _do_execute ( self , func , sql , * args ) : sql_logger . debug ( \"\" , self . name , sql ) sql = self . database_engine . convert_param_style ( sql ) if args : try : sql_logger . debug ( \"\" , self . name , args [ ] ) except : pass start = time . time ( ) * try : return func ( sql , * args ) except Exception as e : logger . debug ( \"\" , self . name , e ) raise finally : msecs = ( time . time ( ) * ) - start sql_logger . debug ( \"\" , self . name , msecs ) sql_query_timer . inc_by ( msecs , sql . split ( ) [ ] ) class PerformanceCounters ( object ) : def __init__ ( self ) : self . current_counters = { } self . previous_counters = { } def update ( self , key , start_time , end_time = None ) : if end_time is None : end_time = time . time ( ) * duration = end_time - start_time count , cum_time = self . current_counters . get ( key , ( , ) ) count += cum_time += duration self . current_counters [ key ] = ( count , cum_time ) return end_time def interval ( self , interval_duration , limit = ) : counters = [ ] for name , ( count , cum_time ) in self . current_counters . items ( ) : prev_count , prev_time = self . previous_counters . get ( name , ( , ) ) counters . append ( ( ( cum_time - prev_time ) / interval_duration , count - prev_count , name ) ) self . previous_counters = dict ( self . current_counters ) counters . sort ( reverse = True ) top_n_counters = \"\" . join ( \"\" % ( name , count , * ratio ) for ratio , count , name in counters [ : limit ] ) return top_n_counters class SQLBaseStore ( object ) : _TXN_ID = def __init__ ( self , hs ) : self . hs = hs self . _db_pool = hs . get_db_pool ( ) self . _clock = hs . get_clock ( ) self . _previous_txn_total_time = self . _current_txn_total_time = self . _previous_loop_ts = self . _txn_perf_counters = PerformanceCounters ( ) self . _get_event_counters = PerformanceCounters ( ) self . _get_event_cache = Cache ( \"\" , keylen = , lru = True , max_entries = hs . config . event_cache_size ) self . _state_group_cache = DictionaryCache ( \"\" , * CACHE_SIZE_FACTOR ) self . _event_fetch_lock = threading . Condition ( ) self . _event_fetch_list = [ ] self . _event_fetch_ongoing = self . _pending_ds = [ ] self . database_engine = hs . database_engine def start_profiling ( self ) : self . _previous_loop_ts = self . _clock . time_msec ( ) def loop ( ) : curr = self . _current_txn_total_time prev = self . _previous_txn_total_time self . _previous_txn_total_time = curr time_now = self . _clock . time_msec ( ) time_then = self . _previous_loop_ts self . _previous_loop_ts = time_now ratio = ( curr - prev ) / ( time_now - time_then ) top_three_counters = self . _txn_perf_counters . interval ( time_now - time_then , limit = ) top_3_event_counters = self . _get_event_counters . interval ( time_now - time_then , limit = ) perf_logger . info ( \"\" , ratio * , top_three_counters , top_3_event_counters ) self . _clock . looping_call ( loop , ) def _new_transaction ( self , conn , desc , after_callbacks , logging_context , func , * args , ** kwargs ) : start = time . time ( ) * txn_id = self . _TXN_ID self . _TXN_ID = ( self . _TXN_ID + ) % ( sys . maxint - ) name = \"\" % ( desc , txn_id , ) transaction_logger . debug ( \"\" , name ) try : i = N = while True : try : txn = conn . cursor ( ) txn = LoggingTransaction ( txn , name , self . database_engine , after_callbacks ) r = func ( txn , * args , ** kwargs ) conn . commit ( ) return r except self . database_engine . module . OperationalError as e : logger . warn ( \"\" , name , e , i , N ) if i < N : i += try : conn . rollback ( ) except self . database_engine . module . Error as e1 : logger . warn ( \"\" , name , e1 , ) continue raise except self . database_engine . module . DatabaseError as e : if self . database_engine . is_deadlock ( e ) : logger . warn ( \"\" , name , i , N ) if i < N : i += try : conn . rollback ( ) except self . database_engine . module . Error as e1 : logger . warn ( \"\" , name , e1 , ) continue raise except Exception as e : logger . debug ( \"\" , name , e ) raise finally : end = time . time ( ) * duration = end - start if logging_context is not None : logging_context . add_database_transaction ( duration ) transaction_logger . debug ( \"\" , name , duration ) self . _current_txn_total_time += duration self . _txn_perf_counters . update ( desc , start , end ) sql_txn_timer . inc_by ( duration , desc ) @ defer . inlineCallbacks def runInteraction ( self , desc , func , * args , ** kwargs ) : \"\"\"\"\"\" current_context = LoggingContext . current_context ( ) start_time = time . time ( ) * after_callbacks = [ ] def inner_func ( conn , * args , ** kwargs ) : with LoggingContext ( \"\" ) as context : sql_scheduling_timer . inc_by ( time . time ( ) * - start_time ) if self . database_engine . is_connection_closed ( conn ) : logger . debug ( \"\" ) conn . reconnect ( ) current_context . copy_to ( context ) return self . _new_transaction ( conn , desc , after_callbacks , current_context , func , * args , ** kwargs ) with PreserveLoggingContext ( ) : result = yield self . _db_pool . runWithConnection ( inner_func , * args , ** kwargs ) for after_callback , after_args in after_callbacks : after_callback ( * after_args ) defer . returnValue ( result ) @ defer . inlineCallbacks def runWithConnection ( self , func , * args , ** kwargs ) : \"\"\"\"\"\" current_context = LoggingContext . current_context ( ) start_time = time . time ( ) * def inner_func ( conn , * args , ** kwargs ) : with LoggingContext ( \"\" ) as context : sql_scheduling_timer . inc_by ( time . time ( ) * - start_time ) if self . database_engine . is_connection_closed ( conn ) : logger . debug ( \"\" ) conn . reconnect ( ) current_context . copy_to ( context ) return func ( conn , * args , ** kwargs ) with PreserveLoggingContext ( ) : result = yield self . _db_pool . runWithConnection ( inner_func , * args , ** kwargs ) defer . returnValue ( result ) @ staticmethod def cursor_to_dict ( cursor ) : \"\"\"\"\"\" col_headers = list ( column [ ] for column in cursor . description ) results = list ( intern_dict ( dict ( zip ( col_headers , row ) ) ) for row in cursor . fetchall ( ) ) return results def _execute ( self , desc , decoder , query , * args ) : \"\"\"\"\"\" def interaction ( txn ) : txn . execute ( query , args ) if decoder : return decoder ( txn ) else : return txn . fetchall ( ) return self . runInteraction ( desc , interaction ) @ defer . inlineCallbacks def _simple_insert ( self , table , values , or_ignore = False , desc = \"\" ) : \"\"\"\"\"\" try : yield self . runInteraction ( desc , ", "answer": "self . _simple_insert_txn , table , values ,"}, {"prompt": " import csv import io import os from django import forms from django . http import HttpResponse from django . shortcuts import render_to_response from django . template import RequestContext import tempfile class MsgForm ( forms . Form ) : subject = forms . CharField ( max_length = ) message = forms . CharField ( ) f = forms . FileField ( ) def home ( request ) : from django . conf import settings print ( settings . SOME_VALUE ) subject = None ", "answer": "message = None"}, {"prompt": " import os , sys try : from setuptools import setup , find_packages except ImportError : sys . stdout . write ( \"\" ) sys . exit ( ) VERSION = '' README = os . path . join ( os . path . dirname ( __file__ ) , '' ) ", "answer": "CHANGES = os . path . join ( os . path . dirname ( __file__ ) , '' )"}, {"prompt": " \"\"\"\"\"\" import sys ", "answer": "import unittest"}, {"prompt": " \"\"\"\"\"\" import cgi , sys from owslib . util import openURL try : from urllib import urlencode except ImportError : from urllib . parse import urlencode from owslib . etree import etree from owslib . namespaces import Namespaces from owslib . util import which_etree , findall MYNS = Namespaces ( ) ", "answer": "XS_NAMESPACE = MYNS . get_namespace ( '' )"}, {"prompt": " from setuptools import setup , find_packages import dbbackup def get_requirements ( ) : return open ( '' ) . read ( ) . splitlines ( ) def get_test_requirements ( ) : return open ( '' ) . read ( ) . splitlines ( ) keywords = [ '' , '' , '' , '' , '' , '' '' , ] setup ( ", "answer": "name = '' ,"}, {"prompt": " import numpy as np def top_n ( score_matrix , n , excludes = [ ] , keep_order = False ) : '''''' score_array = np . squeeze ( np . asarray ( score_matrix ) ) score_array [ excludes ] = - if not keep_order : ", "answer": "top_n_indexes = score_array . argsort ( ) [ : : - ] [ : n ] . tolist ( )"}, {"prompt": " \"\"\"\"\"\" import sys import traceback import unittest from StringIO import StringIO from unittest2 import util from unittest2 . compatibility import wraps __unittest = True def failfast ( method ) : @ wraps ( method ) def inner ( self , * args , ** kw ) : if getattr ( self , '' , False ) : self . stop ( ) return method ( self , * args , ** kw ) return inner STDOUT_LINE = '' STDERR_LINE = '' class TestResult ( unittest . TestResult ) : \"\"\"\"\"\" _previousTestClass = None _moduleSetUpFailed = False def __init__ ( self ) : self . failfast = False self . failures = [ ] self . errors = [ ] self . testsRun = self . skipped = [ ] self . expectedFailures = [ ] self . unexpectedSuccesses = [ ] self . shouldStop = False self . buffer = False self . _stdout_buffer = None self . _stderr_buffer = None self . _original_stdout = sys . stdout self . _original_stderr = sys . stderr self . _mirrorOutput = False def startTest ( self , test ) : \"\" self . testsRun += self . _mirrorOutput = False if self . buffer : if self . _stderr_buffer is None : self . _stderr_buffer = StringIO ( ) self . _stdout_buffer = StringIO ( ) sys . stdout = self . _stdout_buffer sys . stderr = self . _stderr_buffer def startTestRun ( self ) : \"\"\"\"\"\" def stopTest ( self , test ) : \"\"\"\"\"\" if self . buffer : if self . _mirrorOutput : output = sys . stdout . getvalue ( ) error = sys . stderr . getvalue ( ) if output : if not output . endswith ( '' ) : output += '' self . _original_stdout . write ( STDOUT_LINE % output ) if error : if not error . endswith ( '' ) : error += '' self . _original_stderr . write ( STDERR_LINE % error ) sys . stdout = self . _original_stdout sys . stderr = self . _original_stderr self . _stdout_buffer . seek ( ) self . _stdout_buffer . truncate ( ) self . _stderr_buffer . seek ( ) self . _stderr_buffer . truncate ( ) self . _mirrorOutput = False def stopTestRun ( self ) : \"\"\"\"\"\" @ failfast def addError ( self , test , err ) : \"\"\"\"\"\" self . errors . append ( ( test , self . _exc_info_to_string ( err , test ) ) ) self . _mirrorOutput = True @ failfast def addFailure ( self , test , err ) : \"\"\"\"\"\" self . failures . append ( ( test , self . _exc_info_to_string ( err , test ) ) ) self . _mirrorOutput = True def addSuccess ( self , test ) : \"\" pass def addSkip ( self , test , reason ) : \"\"\"\"\"\" self . skipped . append ( ( test , reason ) ) def addExpectedFailure ( self , test , err ) : \"\"\"\"\"\" self . expectedFailures . append ( ( test , self . _exc_info_to_string ( err , test ) ) ) @ failfast def addUnexpectedSuccess ( self , test ) : \"\"\"\"\"\" self . unexpectedSuccesses . append ( test ) def wasSuccessful ( self ) : \"\" return ( len ( self . failures ) + len ( self . errors ) == ) def stop ( self ) : \"\" self . shouldStop = True def _exc_info_to_string ( self , err , test ) : \"\"\"\"\"\" exctype , value , tb = err while tb and self . _is_relevant_tb_level ( tb ) : tb = tb . tb_next if exctype is test . failureException : length = self . _count_relevant_tb_levels ( tb ) msgLines = traceback . format_exception ( exctype , value , tb , length ) else : msgLines = traceback . format_exception ( exctype , value , tb ) if self . buffer : output = sys . stdout . getvalue ( ) error = sys . stderr . getvalue ( ) if output : if not output . endswith ( '' ) : output += '' msgLines . append ( STDOUT_LINE % output ) if error : if not error . endswith ( '' ) : error += '' ", "answer": "msgLines . append ( STDERR_LINE % error )"}, {"prompt": " \"\"\"\"\"\" from googleads import dfp CUSTOM_FIELD_ID = '' DROP_DOWN_CUSTOM_FIELD_ID = '' CUSTOM_FIELD_OPTION_ID = '' LINE_ITEM_ID = '' def main ( client , custom_field_id , drop_down_custom_field_id , custom_field_option_id , line_item_id ) : custom_field_service = client . GetService ( '' , version = '' ) line_item_service = client . GetService ( '' , version = '' ) custom_field_values = [ { '' : '' , '' : { '' : '' , '' : custom_field_id } } ] custom_field_query = '' custom_field_statement = dfp . FilterStatement ( custom_field_query , custom_field_values , ) custom_field = custom_field_service . getCustomFieldsByStatement ( custom_field_statement . ToStatement ( ) ) [ '' ] [ ] drop_down_custom_field_values = [ { '' : '' , '' : { '' : '' , '' : drop_down_custom_field_id } } ] drop_down_custom_field_query = '' drop_down_custom_field_statement = dfp . FilterStatement ( drop_down_custom_field_query , drop_down_custom_field_values , ) drop_down_custom_field = custom_field_service . getCustomFieldsByStatement ( drop_down_custom_field_statement . ToStatement ( ) ) [ '' ] [ ] line_item_values = [ { '' : '' , '' : { '' : '' , '' : line_item_id } } ] line_item_query = '' line_item_statement = dfp . FilterStatement ( line_item_query , line_item_values , ) ", "answer": "line_item = line_item_service . getLineItemsByStatement ("}, {"prompt": " from . . ndtypes import Float64 , make_array_type from seq_expr import SeqExpr class ArrayExpr ( SeqExpr ) : \"\"\"\"\"\" def __init__ ( self , array , type = None , source_info = None ) : self . array = array self . type = type self . source_info = source_info def children ( self ) : yield self . array class Array ( ArrayExpr ) : def __init__ ( self , elts , type = None , source_info = None ) : self . elts = tuple ( elts ) self . type = type self . source_info = source_info def __str__ ( self ) : return \"\" % \"\" . join ( str ( e ) for e in self . elts ) def children ( self ) : return self . elts def __hash__ ( self ) : return hash ( self . elts ) class Slice ( ArrayExpr ) : def __init__ ( self , start , stop , step , type = None , source_info = None ) : self . start = start self . stop = stop self . step = step self . type = type self . source_info = source_info def __str__ ( self ) : return \"\" % ( self . start . short_str ( ) , self . stop . short_str ( ) , self . step . short_str ( ) ) def __repr__ ( self ) : return str ( self ) def children ( self ) : yield self . start yield self . stop yield self . step def __eq__ ( self , other ) : return other . __class__ is Slice and other . start == self . start and other . stop == self . stop and other . step == self . step def __hash__ ( self ) : return hash ( ( self . start , self . stop , self . step ) ) class ConstArray ( ArrayExpr ) : def __init__ ( self , shape , value , type = None , source_info = None ) : self . shape = shape self . value = value self . type = type self . source_info = source_info def children ( self ) : yield self . shape yield self . value class DiagonalArray ( ArrayExpr ) : \"\"\"\"\"\" def __init__ ( self , shape , value , offset = None , type = None , source_info = None ) : self . shape = shape self . value = value self . offset = offset self . type = type self . source_info = source_info def __str__ ( self ) : return \"\" % ( self . shape , self . value , self . offset ) def children ( self ) : yield self . shape yield self . value if self . offset is not None : yield self . offset class ExtractDiagonal ( ArrayExpr ) : \"\"\"\"\"\" pass class ConstArrayLike ( ArrayExpr ) : \"\"\"\"\"\" def __init__ ( self , array , value , type = None , source_info = None ) : self . array = array self . value = value self . type = type self . source_info = source_info def children ( self ) : yield self . array yield self . value class Range ( ArrayExpr ) : def __init__ ( self , start , stop , step , type = None , source_info = None ) : self . start = start self . stop = stop self . step = step self . type = type self . source_info = source_info def children ( self ) : yield self . start yield self . stop yield self . step def __str__ ( self ) : return \"\" % ( self . start , self . stop , self . step ) class AllocArray ( ArrayExpr ) : \"\"\"\"\"\" def __init__ ( self , shape , elt_type , type = None , order = \"\" , source_info = None ) : self . shape = shape self . elt_type = elt_type self . type = type self . source_info = source_info assert order == \"\" , \"\" % order self . order = order def children ( self ) : yield self . shape def __str__ ( self ) : return \"\" % ( self . shape , self . elt_type ) class ArrayView ( ArrayExpr ) : \"\"\"\"\"\" def __init__ ( self , data , shape , strides , offset , size , type = None , source_info = None ) : self . data = data self . shape = shape self . strides = strides self . offset = offset self . size = size self . type = type self . source_info = source_info def __str__ ( self ) : return \"\" % ( self . data , self . shape , self . strides , self . offset , self . size ) def children ( self ) : yield self . data yield self . shape yield self . strides yield self . offset yield self . size class Ravel ( ArrayExpr ) : def children ( self ) : return ( self . array , ) def __str__ ( self ) : ", "answer": "return \"\" % self . array"}, {"prompt": " import logging from flask import ( flash , redirect , send_file , jsonify , make_response , url_for , session , abort ) from . _compat import as_unicode from . filemanager import uuid_originalname from . widgets import GroupFormListWidget , ListMasterWidget from . baseviews import BaseView , BaseCRUDView , BaseFormView , expose , expose_api from . security . decorators import has_access , permission_name , has_access_api from . urltools import * from . const import FLAMSG_ERR_SEC_ACCESS_DENIED log = logging . getLogger ( __name__ ) class IndexView ( BaseView ) : \"\"\"\"\"\" route_base = '' default_view = '' index_template = '' @ expose ( '' ) def index ( self ) : self . update_redirect ( ) return self . render_template ( self . index_template , appbuilder = self . appbuilder ) class UtilView ( BaseView ) : \"\"\"\"\"\" route_base = '' default_view = '' @ expose ( '' ) def back ( self ) : return redirect ( self . get_redirect ( ) ) class SimpleFormView ( BaseFormView ) : \"\"\"\"\"\" @ expose ( \"\" , methods = [ '' ] ) @ has_access def this_form_get ( self ) : self . _init_vars ( ) form = self . form . refresh ( ) self . form_get ( form ) widgets = self . _get_edit_widget ( form = form ) self . update_redirect ( ) return self . render_template ( self . form_template , title = self . form_title , widgets = widgets , appbuilder = self . appbuilder ) @ expose ( \"\" , methods = [ '' ] ) @ has_access def this_form_post ( self ) : self . _init_vars ( ) form = self . form . refresh ( ) if form . validate_on_submit ( ) : response = self . form_post ( form ) if not response : return redirect ( self . get_redirect ( ) ) return response else : widgets = self . _get_edit_widget ( form = form ) return self . render_template ( self . form_template , title = self . form_title , widgets = widgets , appbuilder = self . appbuilder ) class PublicFormView ( BaseFormView ) : \"\"\"\"\"\" @ expose ( \"\" , methods = [ '' ] ) def this_form_get ( self ) : self . _init_vars ( ) form = self . form . refresh ( ) self . form_get ( form ) widgets = self . _get_edit_widget ( form = form ) self . update_redirect ( ) return self . render_template ( self . form_template , title = self . form_title , widgets = widgets , appbuilder = self . appbuilder ) @ expose ( \"\" , methods = [ '' ] ) def this_form_post ( self ) : self . _init_vars ( ) form = self . form . refresh ( ) if form . validate_on_submit ( ) : response = self . form_post ( form ) if not response : return redirect ( self . get_redirect ( ) ) return response else : widgets = self . _get_edit_widget ( form = form ) return self . render_template ( self . form_template , title = self . form_title , widgets = widgets , appbuilder = self . appbuilder ) class RestCRUDView ( BaseCRUDView ) : \"\"\"\"\"\" def _search_form_json ( self ) : pass def _get_api_urls ( self , api_urls = None ) : \"\"\"\"\"\" view_name = self . __class__ . __name__ api_urls = api_urls or { } api_urls [ '' ] = url_for ( view_name + \"\" ) api_urls [ '' ] = url_for ( view_name + \"\" , pk = \"\" ) api_urls [ '' ] = url_for ( view_name + \"\" ) api_urls [ '' ] = url_for ( view_name + \"\" , pk = \"\" ) return api_urls def _get_modelview_urls ( self , modelview_urls = None ) : view_name = self . __class__ . __name__ modelview_urls = modelview_urls or { } modelview_urls [ '' ] = url_for ( view_name + \"\" , pk = \"\" ) modelview_urls [ '' ] = url_for ( view_name + \"\" ) modelview_urls [ '' ] = url_for ( view_name + \"\" , pk = \"\" ) return modelview_urls @ expose ( '' , methods = [ '' ] ) @ has_access_api @ permission_name ( '' ) def api ( self ) : view_name = self . __class__ . __name__ api_urls = self . _get_api_urls ( ) modelview_urls = self . _get_modelview_urls ( ) can_show = self . appbuilder . sm . has_access ( '' , view_name ) can_edit = self . appbuilder . sm . has_access ( '' , view_name ) can_add = self . appbuilder . sm . has_access ( '' , view_name ) can_delete = self . appbuilder . sm . has_access ( '' , view_name ) form_fields = { } search_filters = { } dict_filters = self . _filters . get_search_filters ( ) form = self . search_form . refresh ( ) for col in self . search_columns : form_fields [ col ] = form [ col ] ( ) search_filters [ col ] = [ as_unicode ( flt . name ) for flt in dict_filters [ col ] ] ret_json = jsonify ( can_show = can_show , can_add = can_add , can_edit = can_edit , can_delete = can_delete , label_columns = self . _label_columns_json ( ) , list_columns = self . list_columns , order_columns = self . order_columns , page_size = self . page_size , modelview_name = view_name , api_urls = api_urls , search_filters = search_filters , search_fields = form_fields , modelview_urls = modelview_urls ) response = make_response ( ret_json , ) response . headers [ '' ] = \"\" return response @ expose_api ( name = '' , url = '' , methods = [ '' ] ) @ has_access_api @ permission_name ( '' ) def api_read ( self ) : \"\"\"\"\"\" if get_order_args ( ) . get ( self . __class__ . __name__ ) : order_column , order_direction = get_order_args ( ) . get ( self . __class__ . __name__ ) else : order_column , order_direction = '' , '' page = get_page_args ( ) . get ( self . __class__ . __name__ ) page_size = get_page_size_args ( ) . get ( self . __class__ . __name__ ) get_filter_args ( self . _filters ) joined_filters = self . _filters . get_joined_filters ( self . _base_filters ) count , lst = self . datamodel . query ( joined_filters , order_column , order_direction , page = page , page_size = page_size ) result = self . datamodel . get_values_json ( lst , self . list_columns ) pks = self . datamodel . get_keys ( lst ) ret_json = jsonify ( label_columns = self . _label_columns_json ( ) , list_columns = self . list_columns , order_columns = self . order_columns , page = page , page_size = page_size , count = count , modelview_name = self . __class__ . __name__ , pks = pks , result = result ) response = make_response ( ret_json , ) response . headers [ '' ] = \"\" return response @ expose_api ( name = '' , url = '' , methods = [ '' ] ) @ has_access_api @ permission_name ( '' ) def api_create ( self ) : is_valid_form = True get_filter_args ( self . _filters ) exclude_cols = self . _filters . get_relation_cols ( ) form = self . add_form . refresh ( ) self . _fill_form_exclude_cols ( exclude_cols , form ) if form . validate ( ) : item = self . datamodel . obj ( ) ", "answer": "form . populate_obj ( item )"}, {"prompt": " import toto import cPickle as pickle import zlib ", "answer": "import logging"}, {"prompt": " \"\"\"\"\"\" from pyjamas import DOM from pyjamas import Factory from pyjamas . ui import Event from ButtonBase import ButtonBase from pyjamas . ui import Focus from UIObject import UIObject class Face : STYLENAME_HTML_FACE = \"\" def __init__ ( self , button , delegateTo = None ) : \"\"\"\"\"\" self . button = button self . delegateTo = delegateTo self . face = None self . id = None self . name = \"\" def getName ( self ) : \"\"\"\"\"\" return self . name def getFaceID ( self ) : \"\"\"\"\"\" return self . id def setName ( self , name ) : \"\"\"\"\"\" self . name = name return def setFaceID ( self , face_id ) : \"\"\"\"\"\" self . id = face_id return def getHTML ( self ) : \"\"\"\"\"\" return DOM . getInnerHTML ( self . getFace ( ) ) def getText ( self ) : \"\"\"\"\"\" return DOM . getInnerText ( self . getFace ( ) ) def setHTML ( self , html ) : \"\"\"\"\"\" self . face = DOM . createDiv ( ) UIObject . setStyleName ( self . button , self . face , self . STYLENAME_HTML_FACE , True ) DOM . setInnerHTML ( self . face , html ) self . button . updateButtonFace ( ) def setImage ( self , image ) : \"\"\"\"\"\" self . face = image . getElement ( ) self . button . updateButtonFace ( ) def setText ( self , text ) : \"\"\"\"\"\" self . face = DOM . createDiv ( ) UIObject . setStyleName ( self . button , self . face , self . STYLENAME_HTML_FACE , True ) DOM . setInnerText ( self . face , text ) self . button . updateButtonFace ( ) def toString ( self ) : return self . getName ( ) def getFace ( self ) : \"\"\"\"\"\" if self . face is not None : return self . face if self . delegateTo is not None : return self . delegateTo . getFace ( ) self . face = DOM . createDiv ( ) return self . face class CustomButton ( ButtonBase ) : \"\"\"\"\"\" STYLENAME_DEFAULT = \"\" DOWN_ATTRIBUTE = HOVERING_ATTRIBUTE = DISABLED_ATTRIBUTE = UP = DOWN = DOWN_ATTRIBUTE UP_HOVERING = HOVERING_ATTRIBUTE DOWN_HOVERING = DOWN_ATTRIBUTE | HOVERING_ATTRIBUTE UP_DISABLED = DISABLED_ATTRIBUTE DOWN_DISABLED = DOWN | DISABLED_ATTRIBUTE \"\"\"\"\"\" def __init__ ( self , upImageText = None , downImageText = None , listener = None , ** kwargs ) : \"\"\"\"\"\" if not kwargs . has_key ( '' ) : kwargs [ '' ] = self . STYLENAME_DEFAULT if kwargs . has_key ( '' ) : element = kwargs . pop ( '' ) else : element = Focus . createFocusable ( ) ButtonBase . __init__ ( self , element , ** kwargs ) self . curFace = None self . curFaceElement = None self . up = None self . down = None self . downHovering = None self . upHovering = None self . upDisabled = None self . downDisabled = None self . isCapturing = False self . isFocusing = False self . allowClick = False self . setUpFace ( self . createFace ( None , \"\" , self . UP ) ) if downImageText is None and listener is None : listener = upImageText upImageText = None if upImageText and isinstance ( upImageText , basestring ) : upText = upImageText upImage = None else : upImage = upImageText upText = None if downImageText and isinstance ( downImageText , basestring ) : downText = downImageText downImage = None else : downImage = downImageText downText = None if upImage is not None : self . getUpFace ( ) . setImage ( upImage ) if upText is not None : self . getUpFace ( ) . setText ( upText ) if downImage is not None : self . getDownFace ( ) . setImage ( downImage ) if downText is not None : self . getDownFace ( ) . setText ( downText ) self . sinkEvents ( Event . ONCLICK | Event . MOUSEEVENTS | Event . FOCUSEVENTS | Event . KEYEVENTS ) if listener is not None : self . addClickListener ( listener ) def updateButtonFace ( self ) : if self . curFace is not None and self . curFace . getFace ( ) == self . getFace ( ) : self . setCurrentFaceElement ( self . face ) def getDownDisabledFace ( self ) : \"\"\"\"\"\" if self . downDisabled is None : self . setDownDisabledFace ( self . createFace ( self . getDownFace ( ) , \"\" , self . DOWN_DISABLED ) ) return self . downDisabled def getDownFace ( self ) : \"\"\"\"\"\" if self . down is None : self . setDownFace ( self . createFace ( self . getUpFace ( ) , \"\" , self . DOWN ) ) return self . down def getDownHoveringFace ( self ) : \"\"\"\"\"\" if self . downHovering is None : self . setDownHoveringFace ( self . createFace ( self . getDownFace ( ) , \"\" , self . DOWN_HOVERING ) ) return self . downHovering def getHTML ( self ) : \"\"\"\"\"\" return self . getCurrentFace ( ) . getHTML ( ) def getTabIndex ( self ) : return Focus . getTabIndex ( self . getElement ( ) ) def getText ( self ) : \"\"\"\"\"\" return self . getCurrentFace ( ) . getText ( ) def getUpDisabledFace ( self ) : \"\"\"\"\"\" if self . upDisabled is None : self . setUpDisabledFace ( self . createFace ( self . getUpFace ( ) , \"\" , self . UP_DISABLED ) ) return self . upDisabled def getUpFace ( self ) : \"\"\"\"\"\" return self . up def getUpHoveringFace ( self ) : \"\"\"\"\"\" if self . upHovering is None : self . setUpHoveringFace ( self . createFace ( self . getUpFace ( ) , \"\" , self . UP_HOVERING ) ) return self . upHovering def onBrowserEvent ( self , event ) : if not self . isEnabled ( ) : return event_type = DOM . eventGetType ( event ) if event_type == \"\" : if not self . allowClick : DOM . eventStopPropagation ( event ) return elif event_type == \"\" : if DOM . eventGetButton ( event ) == Event . BUTTON_LEFT : self . setFocus ( True ) self . onClickStart ( ) DOM . setCapture ( self . getElement ( ) ) self . isCapturing = True DOM . eventPreventDefault ( event ) elif event_type == \"\" : if self . isCapturing : self . isCapturing = False DOM . releaseCapture ( self . getElement ( ) ) if self . isHovering ( ) and DOM . eventGetButton ( event ) == Event . BUTTON_LEFT : self . onClick ( ) elif event_type == \"\" : if self . isCapturing : DOM . eventPreventDefault ( event ) elif event_type == \"\" : to = DOM . eventGetToElement ( event ) if ( DOM . isOrHasChild ( self . getElement ( ) , DOM . eventGetTarget ( event ) ) and ( to is None or not DOM . isOrHasChild ( self . getElement ( ) , to ) ) ) : if self . isCapturing : self . onClickCancel ( ) self . setHovering ( False ) elif event_type == \"\" : if DOM . isOrHasChild ( self . getElement ( ) , DOM . eventGetTarget ( event ) ) : self . setHovering ( True ) if self . isCapturing : self . onClickStart ( ) elif event_type == \"\" : if self . isFocusing : self . isFocusing = False self . onClickCancel ( ) elif event_type == \"\" : if self . isCapturing : self . isCapturing = False self . onClickCancel ( ) ButtonBase . onBrowserEvent ( self , event ) if ( DOM . eventGetTypeInt ( event ) & Event . KEYEVENTS ) == : return keyCode = DOM . eventGetKeyCode ( event ) if event_type == \"\" : if keyCode == '' : self . isFocusing = True self . onClickStart ( ) elif event_type == \"\" : if self . isFocusing and keyCode == '' : self . isFocusing = False self . onClick ( ) elif event_type == \"\" : if keyCode == '' or keyCode == '' : self . onClickStart ( ) self . onClick ( ) def setAccessKey ( self , key ) : pass def setEnabled ( self , enabled ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import httplib from testcases import TestServerTestCase from django . utils import simplejson as json class HTTPTestCase ( TestServerTestCase ) : def setUp ( self ) : self . start_test_server ( address = '' , port = ) def tearDown ( self ) : self . stop_test_server ( ) def get_connection ( self ) : return httplib . HTTPConnection ( '' , ) def test_get_apis_json ( self ) : connection = self . get_connection ( ) connection . request ( '' , '' , headers = { '' : '' } ) response = connection . getresponse ( ) connection . close ( ) data = response . read ( ) self . assertEqual ( response . status , ) self . assertEqual ( data , '' ) def test_get_apis_xml ( self ) : connection = self . get_connection ( ) connection . request ( '' , '' , headers = { '' : '' } ) ", "answer": "response = connection . getresponse ( )"}, {"prompt": " import os . path import subprocess import yaml def find_modified_deliverable_files ( reporoot ) : \"\" results = subprocess . check_output ( [ '' , '' , '' , '' , '' ] , cwd = reporoot , ) filenames = [ l . strip ( ) for l in results . splitlines ( ) if l . startswith ( '' ) ] return filenames def get_modified_deliverable_file_content ( reporoot , filenames ) : \"\"\"\"\"\" deliverable_files = filenames if not deliverable_files : deliverable_files = find_modified_deliverable_files ( reporoot ) for basename in deliverable_files : ", "answer": "filename = os . path . join ( reporoot , basename )"}, {"prompt": " \"\"\"\"\"\" from . . phonemetadata import NumberFormat , PhoneNumberDesc , PhoneMetadata PHONE_METADATA_GE = PhoneMetadata ( id = '' , country_code = , international_prefix = '' , general_desc = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , fixed_line = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , ", "answer": "mobile = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) ,"}, {"prompt": " \"\"\"\"\"\" from webob . datetime_utils import * from webob . util import rfc_reference __all__ = [ '' , '' , '' , '' , '' , '' ] def etag_property ( key , default , rfc_section ) : doc = \"\" % key doc += rfc_reference ( key , rfc_section ) doc += \"\" def fget ( req ) : value = req . environ . get ( key ) if not value : return default elif value == '' : return AnyETag else : return ETagMatcher . parse ( value ) def fset ( req , val ) : if val is None : req . environ [ key ] = None else : req . environ [ key ] = str ( val ) def fdel ( req ) : del req . environ [ key ] return property ( fget , fset , fdel , doc = doc ) class _AnyETag ( object ) : \"\"\"\"\"\" def __repr__ ( self ) : return '' def __nonzero__ ( self ) : return False def __contains__ ( self , other ) : return True def weak_match ( self , other ) : return True def __str__ ( self ) : return '' AnyETag = _AnyETag ( ) class _NoETag ( object ) : \"\"\"\"\"\" def __repr__ ( self ) : return '' def __nonzero__ ( self ) : return False def __contains__ ( self , other ) : return False def weak_match ( self , other ) : return False def __str__ ( self ) : return '' NoETag = _NoETag ( ) class ETagMatcher ( object ) : \"\"\"\"\"\" def __init__ ( self , etags , weak_etags = ( ) ) : self . etags = etags self . weak_etags = weak_etags def __contains__ ( self , other ) : return other in self . etags or other in self . weak_etags def weak_match ( self , other ) : if other . lower ( ) . startswith ( '' ) : other = other [ : ] return other in self . etags or other in self . weak_etags def __repr__ ( self ) : return '' % ( '' . join ( self . etags ) ) def parse ( cls , value ) : \"\"\"\"\"\" results = [ ] weak_results = [ ] while value : if value . lower ( ) . startswith ( '' ) : weak = True value = value [ : ] else : weak = False if value . startswith ( '' ) : try : etag , rest = value [ : ] . split ( '' , ) except ValueError : etag = value . strip ( '' ) rest = '' else : rest = rest . strip ( '' ) else : if '' in value : etag , rest = value . split ( '' , ) rest = rest . strip ( ) else : etag = value rest = '' if etag == '' : return AnyETag if etag : if weak : weak_results . append ( etag ) else : results . append ( etag ) value = rest ", "answer": "return cls ( results , weak_results )"}, {"prompt": " from uuid import uuid4 from random import randrange from django . conf import settings from django . db import models , IntegrityError from django . utils . translation import ugettext_lazy as _ from django . utils . encoding import python_2_unicode_compatible from . fields import URLSchemeField from . settings import REGISTRY_TOKEN_TYPE , TOKEN_TYPE_BEARER USER_MODEL = getattr ( settings , '' , '' ) @ python_2_unicode_compatible class Scope ( models . Model ) : STATUS_ENABLED = STATUS_DISABLED = STATUS_CHOICES = ( ( STATUS_ENABLED , _ ( '' ) ) , ( STATUS_DISABLED , _ ( '' ) ) , ) identifier = models . CharField ( _ ( '' ) , max_length = , help_text = _ ( '' ) , unique = True ) title = models . CharField ( _ ( '' ) , max_length = , help_text = _ ( '' ) ) status = models . PositiveIntegerField ( _ ( '' ) , db_index = True , choices = STATUS_CHOICES , default = STATUS_ENABLED ) class Meta ( object ) : verbose_name = _ ( '' ) verbose_name_plural = _ ( '' ) ordering = [ '' ] def __str__ ( self ) : return '' % self . identifier @ python_2_unicode_compatible class Client ( models . Model ) : TYPE_CONFIDENTIAL = '''''' TYPE_PUBLIC = '''''' TYPE_CHOICES = ( ( TYPE_CONFIDENTIAL , _ ( '' ) ) , ( TYPE_PUBLIC , _ ( '' ) ) , ) date_registered = models . DateTimeField ( _ ( '' ) , auto_now_add = True ) title = models . CharField ( _ ( '' ) , max_length = , unique = True ) user = models . ForeignKey ( USER_MODEL , verbose_name = _ ( '' ) , help_text = _ ( '' ) ) description = models . TextField ( _ ( '' ) , max_length = ) link = models . URLField ( _ ( '' ) , help_text = _ ( '' ) , null = True , blank = True ) identifier = models . CharField ( _ ( '' ) , max_length = , help_text = _ ( '' ) , unique = True , blank = True ) token_lifetime = models . IntegerField ( _ ( '' ) , help_text = _ ( '' ) , null = True , blank = True ) password = models . CharField ( _ ( '' ) , max_length = , help_text = _ ( '' '' ) , blank = True ) ", "answer": "type = models . IntegerField ("}, {"prompt": " from BeautifulSoup import BeautifulSoup import re import os import sys import string openclosetags = re . compile ( '''''' , re . DOTALL ) spaces = re . compile ( '''''' , re . DOTALL ) badtags = re . compile ( '''''' ) spaces = re . compile ( '''''' , re . DOTALL ) files = [ ] files . append ( '' ) for file in files : filecontents = open ( file ) . read ( ) soup = BeautifulSoup ( filecontents ) for s in soup . findAll ( '' ) : name = '' synopsis = '' try : name = openclosetags . sub ( '' , str ( s . findAll ( '' ) [ ] ) ) synopsis = openclosetags . sub ( '' , str ( s . findNextSiblings ( '' ) [ ] ) ) . replace ( \"\" , \"\" ) desc = openclosetags . sub ( '' , spaces . sub ( '' , badtags . sub ( '' , str ( s ) ) ) ) . replace ( \"\" , \"\" ) ", "answer": "url = \"\" % ( name )"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models from django . conf import settings from south import modelsinspector try : from django . contrib . auth import get_user_model UserModel = get_user_model ( ) except ImportError : from django . contrib . auth . models import User as UserModel user_model = getattr ( settings , '' , '' ) class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ user_model ] ) ) , ( '' , self . gf ( '' ) ( ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) def backwards ( self , orm ) : db . delete_table ( '' ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , user_model : { '' : modelsinspector . get_model_meta ( UserModel ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' } ) ,"}, {"prompt": " class Counter ( object ) : \"\"\"\"\"\" def __init__ ( self , database , name ) : \"\"\"\"\"\" self . database = database self . name = name self . key = '' % self . name if self . key not in self . database : self . database [ self . key ] = def decr ( self , decr_by = ) : return self . database . decr ( self . key , decr_by ) def incr ( self , incr_by = ) : return self . database . incr ( self . key , incr_by ) def value ( self ) : return int ( self . database [ self . key ] ) def _op ( self , method , other ) : if isinstance ( other , Counter ) : other = other . value ( ) if not isinstance ( other , int ) : raise TypeError ( '' % other ) method ( other ) return self def __iadd__ ( self , other ) : return self . _op ( self . incr , other ) def __isub__ ( self , other ) : return self . _op ( self . decr , other ) __add__ = __iadd__ ", "answer": "__sub__ = __isub__ "}, {"prompt": " from aliyunsdkcore . request import RoaRequest class DescribeResourceTypeTemplateRequest ( RoaRequest ) : ", "answer": "def __init__ ( self ) :"}, {"prompt": " __author__ = '' from random import choice from . nonsuicide import NonSuicidePlayer class KillingPlayer ( NonSuicidePlayer ) : \"\"\"\"\"\" def getAction ( self ) : p = self . game . getKilling ( self . color ) if len ( p ) > : ", "answer": "return [ self . color , choice ( p ) ]"}, {"prompt": " \"\"\"\"\"\" import textwrap import _ssl from _ssl import OPENSSL_VERSION_NUMBER , OPENSSL_VERSION_INFO , OPENSSL_VERSION from _ssl import SSLError from _ssl import CERT_NONE , CERT_OPTIONAL , CERT_REQUIRED from _ssl import RAND_status , RAND_egd , RAND_add from _ssl import SSL_ERROR_ZERO_RETURN , SSL_ERROR_WANT_READ , SSL_ERROR_WANT_WRITE , SSL_ERROR_WANT_X509_LOOKUP , SSL_ERROR_SYSCALL , SSL_ERROR_SSL , SSL_ERROR_WANT_CONNECT , SSL_ERROR_EOF , SSL_ERROR_INVALID_ERROR_CODE from _ssl import PROTOCOL_SSLv3 , PROTOCOL_SSLv23 , PROTOCOL_TLSv1 _PROTOCOL_NAMES = { PROTOCOL_TLSv1 : \"\" , PROTOCOL_SSLv23 : \"\" , PROTOCOL_SSLv3 : \"\" , } try : from _ssl import PROTOCOL_SSLv2 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2 except ImportError : _SSLv2_IF_EXISTS = None else : _PROTOCOL_NAMES [ PROTOCOL_SSLv2 ] = \"\" from socket import socket , _fileobject , _delegate_methods , error as socket_error from socket import getnameinfo as _getnameinfo ", "answer": "from socket import SOL_SOCKET , SO_TYPE , SOCK_STREAM"}, {"prompt": " try : from urllib . request import HTTPError from urllib . parse import urlparse , parse_qs except ImportError : from urllib2 import HTTPError from urlparse import urlparse , parse_qs from lxml import etree from lxml . builder import E from . xml import namespaces , OUT , SP , SEARCH , SQ USER_PATH = '' PEOPLE_WEBSERVICE = '' SEARCH_WEBSERVICE = '' class SharePointUsers ( object ) : def __init__ ( self , opener ) : self . opener = opener self . _users = { } self . _user_searches = { } self . _resolved_principals = { } def __getitem__ ( self , key ) : key = int ( key ) if key not in self . _users : url = self . opener . base_url + USER_PATH . format ( key ) try : data = self . opener . open ( url ) except HTTPError as e : if e . code == : self . _users [ key ] = None else : raise else : props = etree . parse ( data ) . xpath ( '' , namespaces = namespaces ) self . _users [ key ] = SharePointUser ( key , props ) if self . _users [ key ] is None : raise KeyError ( key ) return self . _users [ key ] def resolve_principal ( self , principal ) : return self . resolve_principals ( [ principal ] ) [ ] def resolve_principals ( self , principals ) : principals_to_resolve = set ( p for p in principals if p not in self . _resolved_principals ) if principals_to_resolve : xml = SP . ResolvePrincipals ( SP . principalKeys ( * ( SP . string ( p ) for p in principals_to_resolve ) ) ) xml . append ( SP . principalType ( '' ) ) result = self . opener . post_soap ( PEOPLE_WEBSERVICE , xml ) for principal_info in result . xpath ( '' , namespaces = namespaces ) : user_id = int ( principal_info . find ( '' , namespaces = namespaces ) . text ) account_name = principal_info . find ( '' , namespaces = namespaces ) . text display_name = principal_info . find ( '' , namespaces = namespaces ) display_name = display_name . text if display_name is not None else '' if user_id == - : raise ValueError ( \"\" . format ( account_name , display_name ) ) self . _resolved_principals [ account_name ] = self [ user_id ] return [ self . _resolved_principals . get ( p ) for p in principals ] def search ( self , name , max_results = None ) : if name in self . _user_searches : return self . _user_searches [ name ] query = SQ . QueryPacket ( E . Query ( E . Context ( E . QueryText ( '' + name , type = '' ) , ) ) , ) xml = SEARCH . Query ( SEARCH . queryXml ( etree . tostring ( query ) ) ) results = self . opener . post_soap ( SEARCH_WEBSERVICE , xml , soapaction = '' ) results = etree . fromstring ( results . find ( '' , namespaces = namespaces ) . text ) account_names = [ ] for result in results . xpath ( '' , namespaces = namespaces ) : link = result . xpath ( '' , namespaces = namespaces ) [ ] . text account_name = parse_qs ( urlparse ( link ) . query ) [ '' ] [ ] account_names . append ( account_name ) users = self . resolve_principals ( account_names ) self . _user_searches [ name ] = users return users def as_xml ( self , user_ids , ** kwargs ) : xml = OUT . users ( ) for user_id in user_ids : xml . append ( self [ user_id ] . as_xml ( ) ) return xml class SharePointUser ( object ) : def __init__ ( self , id , props ) : self . _props = props self . _data = { } self . id = id prefix = '' + namespaces [ '' ] + '' for prop in props : tag = prop . tag ns , local = tag [ : ] . split ( '' , ) name = tag . split ( '' , ) [ - ] if prop . attrib . get ( '' . format ( namespaces [ '' ] ) ) == '' : value = None else : value = prop . text self . _data [ ( ns , local ) ] = value if not tag . startswith ( prefix ) : continue setattr ( self , name , value ) def __getitem__ ( self , key ) : return self . _data [ key ] def __repr__ ( self ) : return \"\" . format ( self . Name ) def __unicode__ ( self ) : ", "answer": "return self . Name"}, {"prompt": " class MobsterConfigDict ( dict ) : \"\"\"\"\"\" CONFIG_DEFAULTS = { '' : , '' : False } _instance = None def __new__ ( cls , * args , ** kwargs ) : \"\"\"\"\"\" if not cls . _instance : cls . _instance = super ( MobsterConfigDict , cls ) . __new__ ( cls , * args , ** kwargs ) return cls . _instance else : raise Exception ( \"\" \"\" ) def __init__ ( self ) : dict . __init__ ( self , MobsterConfigDict . CONFIG_DEFAULTS ) def __setitem__ ( self , key , val ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import absolute_import , unicode_literals ", "answer": "from decimal import Decimal , ROUND_HALF_UP"}, {"prompt": " from __future__ import print_function import aerospike import sys from optparse import OptionParser usage = \"\" optparser = OptionParser ( usage = usage , add_help_option = False ) optparser . add_option ( \"\" , dest = \"\" , action = \"\" , help = \"\" ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , metavar = \"\" , help = \"\" ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , metavar = \"\" , help = \"\" ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , default = \"\" , metavar = \"\" , help = \"\" ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , default = , metavar = \"\" , help = \"\" ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , default = \"\" , metavar = \"\" , help = \"\" ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , default = \"\" , metavar = \"\" , help = \"\" ) optparser . add_option ( \"\" , dest = \"\" , type = \"\" , default = , metavar = \"\" , help = \"\" ) optparser . add_option ( \"\" , dest = \"\" , type = \"\" , default = , metavar = \"\" , help = \"\" ) ( options , args ) = optparser . parse_args ( ) if options . help : optparser . print_help ( ) print ( ) ", "answer": "sys . exit ( )"}, {"prompt": " '''''' import unittest import StringIO import ngsutils . fastq . tag from ngsutils . fastq import FASTQ class TagTest ( unittest . TestCase ) : def testPrefix ( self ) : fq = StringIO . StringIO ( '''''' ) out = StringIO . StringIO ( '' ) ngsutils . fastq . tag . fastq_tag ( FASTQ ( fileobj = fq ) , prefix = '' , quiet = True , out = out ) self . assertEqual ( out . getvalue ( ) , '''''' ) def testSuffix ( self ) : ", "answer": "fq = StringIO . StringIO ( '''''' )"}, {"prompt": " import subprocess import click from catwatch . lib . db_seed import seed_database from catwatch . app import create_app from catwatch . extensions import db app = create_app ( ) db . app = app SQLALCHEMY_DATABASE_URI = app . config . get ( '' , None ) class PostgresDatabase ( object ) : def __init__ ( self , databases ) : self . _config = _parse_database_uri ( SQLALCHEMY_DATABASE_URI ) self . _psql = '' self . _createdb = '' self . _dropdb = '' self . _container = _get_postgres_container ( ) self . _docker_exec = '' . format ( self . _container ) self . databases = databases if databases == ( ) : self . databases = [ self . _config . get ( '' ) ] @ property def config ( self ) : \"\"\"\"\"\" return self . _config @ property def container ( self ) : \"\"\"\"\"\" return self . _container def psql ( self , command ) : \"\"\"\"\"\" pg = '' . format ( self . _psql , command ) shell_command = '' . format ( self . _docker_exec , pg ) return subprocess . call ( shell_command , shell = True ) def _user ( self ) : \"\"\"\"\"\" create_role = \"\" . format ( self . config . get ( '' ) , self . config . get ( '' ) ) return self . psql ( create_role ) def list ( self ) : \"\"\"\"\"\" return self . psql ( '' ) def create ( self ) : \"\"\"\"\"\" self . _user ( ) for database in self . databases : pg = '' . format ( self . _createdb , database ) command = '' . format ( self . _docker_exec , pg ) subprocess . call ( command , shell = True ) return None def drop ( self ) : \"\"\"\"\"\" for database in self . databases : pg = '' . format ( self . _dropdb , database ) command = '' . format ( self . _docker_exec , pg ) subprocess . call ( command , shell = True ) return None def _parse_database_uri ( uri ) : \"\"\"\"\"\" db_engine = { } uri_parts = uri . split ( '' ) db_engine [ '' ] = uri_parts [ ] uri_without_protocol_parts = uri_parts [ ] . split ( '' ) user_and_pass = uri_without_protocol_parts [ ] . split ( '' ) domain_and_db = uri_without_protocol_parts [ ] . split ( '' ) db_engine [ '' ] = user_and_pass [ ] db_engine [ '' ] = user_and_pass [ ] db_engine [ '' ] = domain_and_db [ ] . split ( '' ) [ ] db_engine [ '' ] = domain_and_db [ ] . split ( '' ) [ ] db_engine [ '' ] = domain_and_db [ ] return db_engine def _get_postgres_container ( ) : \"\"\"\"\"\" find_container = '''''' container_id = subprocess . check_output ( find_container , shell = True ) [ : - ] return container_id @ click . group ( ) def cli ( ) : \"\"\"\"\"\" pass @ click . command ( ) def list ( ) : \"\"\"\"\"\" database = PostgresDatabase ( ( ) ) database . list ( ) @ click . command ( ) @ click . argument ( '' ) def psql ( command ) : \"\"\"\"\"\" database = PostgresDatabase ( ( ) ) database . psql ( command ) @ click . command ( ) @ click . argument ( '' , nargs = - ) def create ( databases ) : \"\"\"\"\"\" database = PostgresDatabase ( databases ) database . create ( ) return db . create_all ( ) @ click . command ( ) @ click . argument ( '' , nargs = - ) def drop ( databases ) : \"\"\"\"\"\" database = PostgresDatabase ( databases ) database . drop ( ) return None @ click . command ( ) @ click . argument ( '' , nargs = - ) @ click . pass_context def reset ( ctx , databases ) : \"\"\"\"\"\" ctx . invoke ( drop , databases = databases ) ctx . invoke ( create , databases = databases ) ctx . invoke ( seed ) return None @ click . command ( ) def init ( ) : \"\"\"\"\"\" db . drop_all ( ) return db . create_all ( ) @ click . command ( ) def seed ( ) : \"\"\"\"\"\" return seed_database ( ) cli . add_command ( list ) cli . add_command ( psql ) cli . add_command ( create ) cli . add_command ( drop ) cli . add_command ( reset ) ", "answer": "cli . add_command ( init )"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " class LibPngPackage ( Package ) : ", "answer": "def __init__ ( self ) :"}, {"prompt": " from __future__ import unicode_literals from reviewboard . accounts . backends import get_enabled_auth_backends from reviewboard . accounts . models import Profile def auth_backends ( request ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import print_function from __future__ import absolute_import import warnings import tables from tables import IsDescription , StringCol , BoolCol , IntCol , FloatCol from tables . node import NotLoggedMixin from tables . path import join_path from tables . tests import common from tables . tests . common import unittest from tables . tests . common import PyTablesTestCase as TestCase from six . moves import range class BasicTestCase ( common . TempFileMixin , TestCase ) : \"\"\"\"\"\" _reopen_flag = False \"\"\"\"\"\" def _do_reopen ( self ) : if self . _reopen_flag : self . _reopen ( '' ) def setUp ( self ) : super ( BasicTestCase , self ) . setUp ( ) h5file = self . h5file root = h5file . root h5file . create_array ( root , '' , [ , ] , title = \"\" ) h5file . create_array ( root , '' , [ ] , \"\" ) group = h5file . create_group ( root , '' , \"\" ) h5file . create_array ( group , '' , [ ] , \"\" ) h5file . create_array ( group , '' , [ ] , \"\" ) h5file . create_group ( root , '' , \"\" ) h5file . create_group ( group , '' , \"\" ) def test00_simple ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertEqual ( self . h5file . _curaction , ) self . assertEqual ( self . h5file . _curmark , ) self . _do_reopen ( ) self . h5file . redo ( ) if common . verbose : print ( \"\" , self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray . title , \"\" ) self . assertEqual ( self . h5file . _curaction , ) self . assertEqual ( self . h5file . _curmark , ) def test01_twice ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . _do_reopen ( ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertEqual ( self . h5file . _curaction , ) self . assertEqual ( self . h5file . _curmark , ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray2 . title , \"\" ) self . assertEqual ( self . h5file . _curaction , ) self . assertEqual ( self . h5file . _curmark , ) def test02_twice2 ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . _do_reopen ( ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . assertEqual ( self . h5file . _curaction , ) self . assertEqual ( self . h5file . _curmark , ) self . h5file . undo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertEqual ( self . h5file . _curaction , ) self . assertEqual ( self . h5file . _curmark , ) self . h5file . undo ( ) self . assertEqual ( self . h5file . _curaction , ) self . assertEqual ( self . h5file . _curmark , ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . _do_reopen ( ) self . assertEqual ( self . h5file . _curaction , ) self . assertEqual ( self . h5file . _curmark , ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray2 . title , \"\" ) self . assertEqual ( self . h5file . _curaction , ) self . assertEqual ( self . h5file . _curmark , ) def test03_6times3marks ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . _do_reopen ( ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . undo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . _do_reopen ( ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray3 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray4 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray5 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray6 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray1 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray2 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray3 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray4 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray5 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray6 . title , \"\" ) def test04_6times3marksro ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) if common . verbose : print ( \"\" , self . h5file . walk_nodes ( ) ) self . h5file . mark ( ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . h5file . undo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . _do_reopen ( ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray5 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray6 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray1 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray2 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray5 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray6 . title , \"\" ) def test05_destructive ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray1 . title , \"\" ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray3 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray3 . title , \"\" ) def test05b_destructive ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . _do_reopen ( ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . _do_reopen ( ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . assertTrue ( \"\" in self . h5file ) self . h5file . undo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray1 . title , \"\" ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray3 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray3 . title , \"\" ) self . assertTrue ( \"\" not in self . h5file ) def test05c_destructive ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . assertTrue ( \"\" in self . h5file ) self . h5file . undo ( ) self . _do_reopen ( ) self . h5file . undo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) def test05d_destructive ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . _do_reopen ( ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . assertTrue ( \"\" in self . h5file ) self . _do_reopen ( ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) def test05e_destructive ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . _do_reopen ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) def test05f_destructive ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ ] ) self . h5file . undo ( ) self . _do_reopen ( ) self . assertTrue ( '' not in self . h5file ) newarr = self . h5file . create_array ( '' , '' , [ ] ) self . h5file . undo ( ) self . assertTrue ( '' not in self . h5file ) self . _do_reopen ( ) self . h5file . redo ( ) self . assertTrue ( '' in self . h5file ) if not self . _reopen_flag : self . assertTrue ( self . h5file . root . newarray is newarr ) def test06_totalunwind ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . _do_reopen ( ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) def test07_totalrewind ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . _do_reopen ( ) self . h5file . redo ( - ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray2 . title , \"\" ) def test08_marknames ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( \"\" ) self . _do_reopen ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( \"\" ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . undo ( \"\" ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . _do_reopen ( ) self . h5file . redo ( - ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray3 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray4 . read ( ) , [ , ] ) def test08_initialmark ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) initmid = self . h5file . get_current_mark ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( initmid ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( - ) self . _do_reopen ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray2 . title , \"\" ) def test09_marknames ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( \"\" ) with self . assertRaises ( tables . UndoRedoError ) : self . h5file . undo ( \"\" ) self . h5file . redo ( \"\" ) self . _do_reopen ( ) with self . assertRaises ( tables . UndoRedoError ) : self . h5file . redo ( \"\" ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) def test10_goto ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . _do_reopen ( ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . _do_reopen ( ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . goto ( \"\" ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . goto ( \"\" ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . _do_reopen ( ) self . h5file . goto ( \"\" ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . goto ( - ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray3 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray4 . read ( ) , [ , ] ) def test10_gotoint ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . _do_reopen ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . mark ( \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . goto ( ) self . _do_reopen ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . goto ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . _do_reopen ( ) self . h5file . goto ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . goto ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . _do_reopen ( ) self . h5file . goto ( - ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray3 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray4 . read ( ) , [ , ] ) def test11_contiguous ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) m1 = self . h5file . mark ( ) m2 = self . h5file . mark ( ) self . assertNotEqual ( m1 , m2 ) self . _do_reopen ( ) self . h5file . undo ( m1 ) self . assertEqual ( self . h5file . get_current_mark ( ) , m1 ) self . h5file . redo ( m2 ) self . assertEqual ( self . h5file . get_current_mark ( ) , m2 ) self . h5file . goto ( m1 ) self . assertEqual ( self . h5file . get_current_mark ( ) , m1 ) self . h5file . goto ( m2 ) self . assertEqual ( self . h5file . get_current_mark ( ) , m2 ) self . h5file . goto ( - ) self . _do_reopen ( ) self . assertEqual ( self . h5file . get_current_mark ( ) , m2 ) self . h5file . goto ( ) self . assertEqual ( self . h5file . get_current_mark ( ) , ) def test12_keepMark ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ ] ) mid = self . h5file . mark ( ) self . assertTrue ( mid is not None ) self . _do_reopen ( ) self . h5file . undo ( ) self . assertEqual ( self . h5file . get_current_mark ( ) , ) self . assertTrue ( '' not in self . h5file ) def test13_severalEnableDisable ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ ] ) self . h5file . undo ( ) self . _do_reopen ( ) self . assertEqual ( self . h5file . get_current_mark ( ) , ) self . assertTrue ( '' not in self . h5file ) self . h5file . disable_undo ( ) self . h5file . create_array ( '' , '' , [ ] ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ ] ) mid = self . h5file . mark ( ) self . h5file . create_array ( '' , '' , [ ] ) self . h5file . undo ( ) self . assertEqual ( self . h5file . get_current_mark ( ) , mid ) self . assertTrue ( '' not in self . h5file ) self . assertTrue ( '' in self . h5file ) self . assertTrue ( '' in self . h5file ) self . assertTrue ( '' not in self . h5file ) self . _do_reopen ( ) self . h5file . disable_undo ( ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ ] ) self . h5file . create_array ( '' , '' , [ ] ) self . assertTrue ( '' in self . h5file ) self . assertTrue ( '' in self . h5file ) self . assertTrue ( '' in self . h5file ) self . assertTrue ( '' in self . h5file ) self . h5file . undo ( ) self . _do_reopen ( ) self . assertTrue ( '' not in self . h5file ) self . assertTrue ( '' in self . h5file ) self . assertTrue ( '' in self . h5file ) self . assertTrue ( '' not in self . h5file ) self . h5file . disable_undo ( ) class PersistenceTestCase ( BasicTestCase ) : \"\"\"\"\"\" _reopen_flag = True class CreateArrayTestCase ( common . TempFileMixin , TestCase ) : \"\"\"\"\"\" def setUp ( self ) : super ( CreateArrayTestCase , self ) . setUp ( ) h5file = self . h5file root = h5file . root h5file . create_array ( root , '' , [ , ] , title = \"\" ) h5file . create_array ( root , '' , [ ] , \"\" ) group = h5file . create_group ( root , '' , \"\" ) h5file . create_array ( group , '' , [ ] , \"\" ) h5file . create_array ( group , '' , [ ] , \"\" ) h5file . create_group ( root , '' , \"\" ) h5file . create_group ( group , '' , \"\" ) def test00 ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) def test01 ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray2 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) def test02 ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray2 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray3 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . otherarray3 . read ( ) , [ , ] ) def test03 ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . create_array ( '' , '' , [ , ] , \"\" ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . otherarray1 . title , \"\" ) self . assertEqual ( self . h5file . root . agroup . otherarray2 . title , \"\" ) self . assertEqual ( self . h5file . root . agroup . agroup3 . otherarray3 . title , \"\" ) self . assertEqual ( self . h5file . root . otherarray1 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . agroup . otherarray2 . read ( ) , [ , ] ) self . assertEqual ( self . h5file . root . agroup . agroup3 . otherarray3 . read ( ) , [ , ] ) class CreateGroupTestCase ( common . TempFileMixin , TestCase ) : \"\"\"\"\"\" def setUp ( self ) : super ( CreateGroupTestCase , self ) . setUp ( ) h5file = self . h5file root = h5file . root h5file . create_array ( root , '' , [ , ] , title = \"\" ) h5file . create_array ( root , '' , [ ] , \"\" ) group = h5file . create_group ( root , '' , \"\" ) h5file . create_array ( group , '' , [ ] , \"\" ) h5file . create_array ( group , '' , [ ] , \"\" ) h5file . create_group ( root , '' , \"\" ) h5file . create_group ( group , '' , \"\" ) def test00 ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_group ( '' , '' , \"\" ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . othergroup1 . _v_title , \"\" ) def test01 ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_group ( '' , '' , \"\" ) self . h5file . create_group ( '' , '' , \"\" ) self . h5file . undo ( ) self . assertTrue ( \"\" not in self . h5file ) self . assertTrue ( \"\" not in self . h5file ) self . h5file . redo ( ) self . assertTrue ( \"\" in self . h5file ) self . assertTrue ( \"\" in self . h5file ) self . assertEqual ( self . h5file . root . othergroup1 . _v_title , \"\" ) self . assertEqual ( self . h5file . root . othergroup2 . _v_title , \"\" ) def test02 ( self ) : \"\"\"\"\"\" if common . verbose : print ( '' , '' * ) print ( \"\" % self . __class__ . __name__ ) self . h5file . enable_undo ( ) self . h5file . create_group ( '' , '' , \"\" ) self . h5file . create_group ( '' , '' , \"\" ) self . h5file . create_group ( '' , '' , \"\" ) self . h5file . undo ( ) ", "answer": "self . assertTrue ( \"\" not in self . h5file )"}, {"prompt": " import os os . environ [ '' ] = os . environ . get ( '' , '' ) from tests import base def setUpModule ( ) : \"\"\"\"\"\" base . enabledPlugins . append ( '' ) base . enabledPlugins . append ( '' ) base . enabledPlugins . append ( '' ) base . enabledPlugins . append ( '' ) base . startServer ( False ) def tearDownModule ( ) : \"\"\"\"\"\" base . stopServer ( ) class SourceTestCase ( base . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" super ( SourceTestCase , self ) . setUp ( ) self . _user = self . model ( '' ) . createUser ( '' , '' , '' , '' , '' ) def testSource ( self ) : \"\"\"\"\"\" path = '' params = { '' : self . _user [ '' ] , } response = self . request ( path = path , method = '' , params = params ) self . assertStatusOk ( response ) folder = response . json [ '' ] self . assertEquals ( folder , None ) response = self . request ( path = path , method = '' , params = params ) self . assertStatus ( response , ) response = self . request ( path = path , method = '' , params = params , user = self . _user ) self . assertStatusOk ( response ) folder = response . json [ '' ] self . assertNotEquals ( folder , None ) self . assertEquals ( folder [ '' ] , '' ) self . assertEquals ( folder [ '' ] , str ( self . _user [ '' ] ) ) response = self . request ( path = path , method = '' , params = params ) self . assertStatusOk ( response ) folder = response . json [ '' ] self . assertEquals ( folder , None ) response = self . request ( path = path , method = '' , params = params , user = self . _user ) self . assertStatusOk ( response ) folder = response . json [ '' ] self . assertNotEquals ( folder , None ) self . assertEquals ( folder [ '' ] , '' ) self . assertEquals ( folder [ '' ] , str ( self . _user [ '' ] ) ) params = { '' : '' , '' : folder [ '' ] } ", "answer": "response = self . request ( path = '' , method = '' , params = params ,"}, {"prompt": " \"\"\"\"\"\" import abc import os from dfvfs . credentials import manager as credentials_manager from dfvfs . lib import definitions from dfvfs . lib import errors from dfvfs . helpers import source_scanner from dfvfs . helpers import windows_path_resolver from dfvfs . path import factory as path_spec_factory from dfvfs . resolver import resolver from dfvfs . volume import tsk_volume_system from dfvfs . volume import vshadow_volume_system class VolumeScannerMediator ( object ) : \"\"\"\"\"\" @ abc . abstractmethod def GetPartitionIdentifiers ( self , volume_system , volume_identifiers ) : \"\"\"\"\"\" @ abc . abstractmethod def GetVSSStoreIdentifiers ( self , volume_system , volume_identifiers ) : \"\"\"\"\"\" @ abc . abstractmethod def UnlockEncryptedVolume ( self , source_scanner_object , scan_context , locked_scan_node , credentials ) : \"\"\"\"\"\" class VolumeScanner ( object ) : \"\"\"\"\"\" def __init__ ( self , mediator = None ) : \"\"\"\"\"\" super ( VolumeScanner , self ) . __init__ ( ) self . _mediator = mediator self . _source_path = None self . _source_scanner = source_scanner . SourceScanner ( ) self . _source_type = None self . _vss_stores = None def _GetTSKPartitionIdentifiers ( self , scan_node ) : \"\"\"\"\"\" if not scan_node or not scan_node . path_spec : raise errors . ScannerError ( u'' ) volume_system = tsk_volume_system . TSKVolumeSystem ( ) volume_system . Open ( scan_node . path_spec ) volume_identifiers = self . _source_scanner . GetVolumeIdentifiers ( volume_system ) if not volume_identifiers : raise errors . ScannerError ( u'' ) if not self . _mediator or len ( volume_identifiers ) == : return volume_identifiers try : return self . _mediator . GetPartitionIdentifiers ( volume_system , volume_identifiers ) except KeyboardInterrupt : raise errors . ScannerError ( u'' ) def _GetVSSStoreIdentifiers ( self , scan_node ) : \"\"\"\"\"\" if not scan_node or not scan_node . path_spec : raise errors . ScannerError ( u'' ) volume_system = vshadow_volume_system . VShadowVolumeSystem ( ) volume_system . Open ( scan_node . path_spec ) volume_identifiers = self . _source_scanner . GetVolumeIdentifiers ( volume_system ) if not self . _mediator and not volume_identifiers : return [ ] try : return self . _mediator . GetVSSStoreIdentifiers ( volume_system , volume_identifiers ) except KeyboardInterrupt : raise errors . UserAbort ( u'' ) def _ScanFileSystem ( self , file_system_scan_node , base_path_specs ) : \"\"\"\"\"\" if not file_system_scan_node or not file_system_scan_node . path_spec : raise errors . ScannerError ( u'' ) base_path_specs . append ( file_system_scan_node . path_spec ) def _ScanVolume ( self , scan_context , volume_scan_node , base_path_specs ) : \"\"\"\"\"\" if not volume_scan_node or not volume_scan_node . path_spec : raise errors . ScannerError ( u'' ) if len ( volume_scan_node . sub_nodes ) == : self . _ScanVolumeScanNode ( scan_context , volume_scan_node , base_path_specs ) else : for sub_scan_node in volume_scan_node . sub_nodes : self . _ScanVolumeScanNode ( scan_context , sub_scan_node , base_path_specs ) def _ScanVolumeScanNode ( self , scan_context , volume_scan_node , base_path_specs ) : \"\"\"\"\"\" if not volume_scan_node or not volume_scan_node . path_spec : raise errors . ScannerError ( u'' ) scan_node = volume_scan_node while len ( scan_node . sub_nodes ) == : if scan_node . type_indicator == definitions . TYPE_INDICATOR_VSHADOW : location = getattr ( scan_node . path_spec , u'' , None ) if location == u'' : break scan_node = scan_node . sub_nodes [ ] if scan_node . type_indicator in definitions . ENCRYPTED_VOLUME_TYPE_INDICATORS : self . _ScanVolumeScanNodeEncrypted ( scan_context , scan_node , base_path_specs ) elif scan_node . type_indicator == definitions . TYPE_INDICATOR_VSHADOW : self . _ScanVolumeScanNodeVSS ( scan_node , base_path_specs ) elif scan_node . type_indicator in definitions . FILE_SYSTEM_TYPE_INDICATORS : self . _ScanFileSystem ( scan_node , base_path_specs ) def _ScanVolumeScanNodeEncrypted ( self , scan_context , volume_scan_node , base_path_specs ) : \"\"\"\"\"\" result = not scan_context . IsLockedScanNode ( volume_scan_node . path_spec ) if not result : credentials = credentials_manager . CredentialsManager . GetCredentials ( volume_scan_node . path_spec ) result = self . _mediator . GetEncryptedVolumeCredential ( self . _source_scanner , scan_context , volume_scan_node , credentials ) if result : ", "answer": "self . _source_scanner . Scan ("}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . delete_column ( '' , '' ) def backwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( null = True , blank = True ) , keep_default = False ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' } ) ,"}, {"prompt": " import os from os import path import sys try : import simplejson as json except ImportError : import json from . detector import Detector from . lang_detect_exception import ErrorCode , LangDetectException from . utils . lang_profile import LangProfile class DetectorFactory ( object ) : '''''' seed = None def __init__ ( self ) : self . word_lang_prob_map = { } self . langlist = [ ] def load_profile ( self , profile_directory ) : list_files = os . listdir ( profile_directory ) if not list_files : raise LangDetectException ( ErrorCode . NeedLoadProfileError , '' + profile_directory ) langsize , index = len ( list_files ) , for filename in list_files : if filename . startswith ( '' ) : continue filename = path . join ( profile_directory , filename ) if not path . isfile ( filename ) : continue f = None try : if sys . version_info [ ] < : f = open ( filename , '' ) else : f = open ( filename , '' , encoding = '' ) json_data = json . load ( f ) profile = LangProfile ( ** json_data ) self . add_profile ( profile , index , langsize ) index += except IOError : raise LangDetectException ( ErrorCode . FileLoadError , '' % filename ) except : raise LangDetectException ( ErrorCode . FormatError , '' % filename ) finally : if f : f . close ( ) def load_json_profile ( self , json_profiles ) : langsize , index = len ( json_profiles ) , if langsize < : raise LangDetectException ( ErrorCode . NeedLoadProfileError , '' ) for json_profile in json_profiles : try : json_data = json . loads ( json_profile ) profile = LangProfile ( ** json_data ) self . add_profile ( profile , index , langsize ) index += except : raise LangDetectException ( ErrorCode . FormatError , '' ) def add_profile ( self , profile , index , langsize ) : lang = profile . name if lang in self . langlist : raise LangDetectException ( ErrorCode . DuplicateLangError , '' ) self . langlist . append ( lang ) for word in profile . freq : if word not in self . word_lang_prob_map : self . word_lang_prob_map [ word ] = [ ] * langsize length = len ( word ) if <= length <= : prob = * profile . freq . get ( word ) / profile . n_words [ length - ] self . word_lang_prob_map [ word ] [ index ] = prob def clear ( self ) : self . langlist = [ ] self . word_lang_prob_map = { } def create ( self , alpha = None ) : '''''' detector = self . _create_detector ( ) if alpha is not None : detector . set_alpha ( alpha ) return detector ", "answer": "def _create_detector ( self ) :"}, {"prompt": " import sys if __name__ == '' : import cProfile ", "answer": "import pytest"}, {"prompt": " import sys import os ", "answer": "LICENSE = \"\"\"\"\"\""}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) ", "answer": "result . template = \"\""}, {"prompt": " from __future__ import print_function , unicode_literals from datetime import datetime from django . core import mail from django . core . urlresolvers import reverse from django . test import TestCase from django . test . client import Client from corehq import toggles from corehq . apps . users . models import WebUser from corehq . apps . domain . models import Domain , TransferDomainRequest from corehq . apps . domain . forms import TransferDomainForm , TransferDomainFormErrors from corehq . apps . domain . views import TransferDomainView from corehq . apps . domain . exceptions import InactiveTransferDomainException class BaseDomainTest ( TestCase ) : def setUp ( self ) : self . client = Client ( ) self . domain = Domain ( name = \"\" , is_active = True ) self . domain . save ( ) toggles . TRANSFER_DOMAIN . set ( \"\" . format ( domain = self . domain . name ) , True ) self . username = '' self . password = '' self . user = WebUser . create ( self . domain . name , self . username , self . password ) self . user . set_role ( self . domain . name , '' ) self . user . save ( ) self . another_domain = Domain ( name = '' , is_active = True ) self . another_domain . save ( ) self . mugglename = '' self . muggle = WebUser . create ( self . another_domain . name , self . mugglename , self . password ) self . muggle . save ( ) def tearDown ( self ) : self . user . delete ( ) self . domain . delete ( ) self . muggle . delete ( ) self . another_domain . delete ( ) class TestTransferDomainForm ( BaseDomainTest ) : def test_valid_data ( self ) : data = { '' : self . mugglename , '' : self . domain . name , } form = TransferDomainForm ( self . domain . name , self . user . username , data ) self . assertTrue ( form . is_valid ( ) , form . errors ) transfer = form . save ( ) self . assertEqual ( transfer . to_username , self . mugglename ) self . assertEqual ( transfer . domain , self . domain . name ) self . assertEqual ( transfer . from_username , self . username ) def test_invalid_user_data ( self ) : data = { '' : '' , '' : '' , } form = TransferDomainForm ( self . domain . name , self . user . username , data ) self . assertFalse ( form . is_valid ( ) ) self . assertEqual ( form . errors , { '' : [ TransferDomainFormErrors . USER_DNE ] , '' : [ TransferDomainFormErrors . DOMAIN_MISMATCH ] , } ) class TestTransferDomainModel ( BaseDomainTest ) : def setUp ( self ) : super ( TestTransferDomainModel , self ) . setUp ( ) self . transfer = TransferDomainRequest ( to_username = self . mugglename , from_username = self . username , domain = self . domain . name ) self . transfer . save ( ) def tearDown ( self ) : super ( TestTransferDomainModel , self ) . tearDown ( ) self . transfer . delete ( ) def test_domain_transfer_inactive ( self ) : self . transfer . active = False self . transfer . save ( ) with self . assertRaises ( InactiveTransferDomainException ) : self . transfer . transfer_domain ( ) with self . assertRaises ( InactiveTransferDomainException ) : self . transfer . send_transfer_request ( ) def test_domain_transfer ( self ) : self . transfer . transfer_domain ( ) self . assertFalse ( self . transfer . active ) self . assertFalse ( self . transfer . from_user . is_member_of ( self . domain ) ) self . assertTrue ( self . transfer . to_user . is_member_of ( self . domain ) ) def test_send_transfer_request ( self ) : self . transfer . send_transfer_request ( ) self . assertIsNotNone ( self . transfer . transfer_guid ) self . assertEqual ( len ( mail . outbox ) , , \"\" ) def test_get_active_transfer ( self ) : res = TransferDomainRequest . get_active_transfer ( self . domain , self . user . username ) self . assertIsNotNone ( res ) newer = TransferDomainRequest ( to_username = self . mugglename , from_username = self . username , request_time = datetime . utcnow ( ) , domain = self . domain . name ) newer . save ( ) res = TransferDomainRequest . get_active_transfer ( self . domain , self . user . username ) self . assertEqual ( res . pk , newer . pk ) self . assertFalse ( TransferDomainRequest . objects . get ( pk = self . transfer . pk ) . active ) class TestTransferDomainViews ( BaseDomainTest ) : def setUp ( self ) : super ( TestTransferDomainViews , self ) . setUp ( ) self . transfer = TransferDomainRequest ( to_username = self . mugglename , from_username = self . username , domain = self . domain . name ) self . transfer . save ( ) self . transfer . send_transfer_request ( ) self . rando = WebUser . create ( self . domain . name , '' , self . password ) def tearDown ( self ) : super ( TestTransferDomainViews , self ) . tearDown ( ) self . transfer . delete ( ) ", "answer": "self . rando . delete ( )"}, {"prompt": " \"\"\"\"\"\" from twisted . internet import task , reactor from media_nommer . conf import settings from media_nommer . utils import logger from media_nommer . feederd . job_cache import JobCache from media_nommer . feederd . ec2_instance_manager import EC2InstanceManager from media_nommer . feederd import job_state_notifier def threaded_check_for_job_state_changes ( ) : \"\"\"\"\"\" changed_jobs = JobCache . refresh_jobs_with_state_changes ( ) for job in changed_jobs : job_state_notifier . send_notification ( job ) JobCache . uncache_finished_jobs ( ) def task_check_for_job_state_changes ( ) : \"\"\"\"\"\" reactor . callInThread ( threaded_check_for_job_state_changes ) def threaded_prune_jobs ( ) : \"\"\"\"\"\" JobCache . abandon_stale_jobs ( ) JobCache . uncache_finished_jobs ( ) def task_prune_jobs ( ) : \"\"\"\"\"\" ", "answer": "reactor . callInThread ( threaded_prune_jobs )"}, {"prompt": " from south . utils import datetime_utils as datetime from south . db import db from south . v2 import DataMigration from django . db import models from django . db . models import Q class Migration ( DataMigration ) : def forwards ( self , orm ) : url = \"\" for jt in orm . JailTemplate . objects . filter ( Q ( jt_name__startswith = '' ) | Q ( jt_name__startswith = '' ) | Q ( jt_name__startswith = '' ) ) : jt . delete ( ) for jt in orm . JailTemplate . objects . all ( ) : jt . jt_system = False jt . save ( ) for arch in ( '' , '' ) : for name in ( '' , '' ) : if arch == '' : name = '' % name jt = orm . JailTemplate ( ) jt . jt_name = name jt . jt_os = '' jt . jt_arch = arch jt . jt_url = '' % ( ", "answer": "url , arch , name"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import django . core . files . storage import datetime class Migration ( migrations . Migration ) : dependencies = [ ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . DateTimeField ( auto_now = True , verbose_name = '' ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' ) ) , ] , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . IntegerField ( default = , verbose_name = '' ) ) , ( '' , models . DateTimeField ( verbose_name = '' ) ) , ( '' , models . DateTimeField ( auto_now_add = True , verbose_name = '' ) ) , ( '' , models . DateTimeField ( auto_now = True , verbose_name = '' ) ) , ( '' , models . FileField ( storage = django . core . files . storage . FileSystemStorage ( location = b'' ) , null = True , upload_to = b'' ) ) , ( '' , models . CharField ( default = b'' , max_length = , verbose_name = '' , choices = [ ( b'' , '' ) , ( b'' , '' ) , ( b'' , '' ) ] ) ) , ] , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . DateTimeField ( default = datetime . datetime ( , , , , , , ) , verbose_name = '' ) ) , ( '' , models . DateTimeField ( verbose_name = '' ) ) , ( '' , models . DecimalField ( verbose_name = '' , max_digits = , decimal_places = ) ) , ( '' , models . BooleanField ( default = False , verbose_name = '' ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' ) ) , ] , options = { '' : ( ( '' , '' ) , ( '' , '' ) ) , } , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . DateTimeField ( auto_now = True , verbose_name = '' ) ) , ( '' , models . DateTimeField ( auto_now_add = True , verbose_name = '' ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' , blank = True ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' , blank = True ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' , blank = True ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' , blank = True ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' ) ) , ", "answer": "( '' , models . CharField ( max_length = , verbose_name = '' ) ) ,"}, {"prompt": " import abc import six from rally . common import broker from rally . common . i18n import _ from rally . common import logging from rally . common import utils from rally import consts from rally import osclients from rally . plugins . openstack . scenarios . nova import utils as nova_utils from rally . plugins . openstack . scenarios . vm import vmtasks from rally . task import context from rally . task import types LOG = logging . getLogger ( __name__ ) @ six . add_metaclass ( abc . ABCMeta ) @ context . configure ( name = \"\" , order = , hidden = True ) class BaseCustomImageGenerator ( context . Context ) : \"\"\"\"\"\" CONFIG_SCHEMA = { \"\" : \"\" , \"\" : consts . JSON_SCHEMA , \"\" : { \"\" : { \"\" : \"\" , \"\" : { \"\" : { \"\" : \"\" } } } , \"\" : { \"\" : \"\" , \"\" : { \"\" : { \"\" : \"\" } } } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" , \"\" : , \"\" : } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" , \"\" : , } } , \"\" : [ \"\" , \"\" ] , \"\" : False } DEFAULT_CONFIG = { \"\" : \"\" , \"\" : , \"\" : } @ logging . log_task_wrapper ( LOG . info , _ ( \"\" ) ) def setup ( self ) : \"\"\"\"\"\" if \"\" in self . context : user = self . context [ \"\" ] [ ] tenant = self . context [ \"\" ] [ user [ \"\" ] ] nics = None if \"\" in tenant : nics = [ { \"\" : tenant [ \"\" ] [ ] [ \"\" ] } ] custom_image = self . create_one_image ( user , nics = nics ) self . make_image_public ( custom_image ) for tenant in self . context [ \"\" ] . values ( ) : tenant [ \"\" ] = custom_image else : def publish ( queue ) : users = self . context . get ( \"\" , [ ] ) for user , tenant_id in utils . iterate_per_tenants ( users ) : queue . append ( ( user , tenant_id ) ) def consume ( cache , args ) : user , tenant_id = args tenant = self . context [ \"\" ] [ tenant_id ] tenant [ \"\" ] = self . create_one_image ( user ) broker . run ( publish , consume , self . config [ \"\" ] ) def create_one_image ( self , user , ** kwargs ) : \"\"\"\"\"\" clients = osclients . Clients ( user [ \"\" ] ) image_id = types . ImageResourceType . transform ( clients = clients , resource_config = self . config [ \"\" ] ) flavor_id = types . FlavorResourceType . transform ( clients = clients , resource_config = self . config [ \"\" ] ) vm_scenario = vmtasks . VMTasks ( self . context , clients = clients ) server , fip = vm_scenario . _boot_server_with_fip ( image = image_id , flavor = flavor_id , floating_network = self . config . get ( \"\" ) , userdata = self . config . get ( \"\" ) , key_name = user [ \"\" ] [ \"\" ] , security_groups = [ user [ \"\" ] [ \"\" ] ] , ** kwargs ) try : LOG . debug ( \"\" , server , fip [ \"\" ] ) self . customize_image ( server , fip , user ) LOG . debug ( \"\" , server ) vm_scenario . _stop_server ( server ) ", "answer": "LOG . debug ( \"\" , server )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import json import time import mock import six from six . moves import http_client from ironicclient . common import filecache from ironicclient . common import http from ironicclient import exc from ironicclient . tests . unit import utils DEFAULT_TIMEOUT = DEFAULT_HOST = '' DEFAULT_PORT = '' def _get_error_body ( faultstring = None , debuginfo = None ) : error_body = { '' : faultstring , '' : debuginfo } raw_error_body = json . dumps ( error_body ) body = { '' : raw_error_body } raw_body = json . dumps ( body ) return raw_body def _session_client ( ** kwargs ) : return http . SessionClient ( os_ironic_api_version = '' , api_version_select_state = '' , max_retries = , retry_interval = , auth = None , interface = '' , service_type = '' , region_name = '' , endpoint = '' % ( DEFAULT_HOST , DEFAULT_PORT ) , ** kwargs ) class VersionNegotiationMixinTest ( utils . BaseTestCase ) : def setUp ( self ) : super ( VersionNegotiationMixinTest , self ) . setUp ( ) self . test_object = http . VersionNegotiationMixin ( ) self . test_object . os_ironic_api_version = '' self . test_object . api_version_select_state = '' self . test_object . endpoint = \"\" self . mock_mcu = mock . MagicMock ( ) self . test_object . _make_connection_url = self . mock_mcu self . response = utils . FakeResponse ( { } , status = http_client . NOT_ACCEPTABLE ) self . test_object . get_server = mock . MagicMock ( return_value = ( '' , '' ) ) def test__generic_parse_version_headers_has_headers ( self ) : response = { '' : '' , '' : '' , } expected = ( '' , '' ) result = self . test_object . _generic_parse_version_headers ( response . get ) self . assertEqual ( expected , result ) def test__generic_parse_version_headers_missing_headers ( self ) : response = { } expected = ( None , None ) result = self . test_object . _generic_parse_version_headers ( response . get ) self . assertEqual ( expected , result ) @ mock . patch . object ( filecache , '' , autospec = True ) def test_negotiate_version_bad_state ( self , mock_save_data ) : self . test_object . api_version_select_state = '' self . assertRaises ( RuntimeError , self . test_object . negotiate_version , None , None ) self . assertEqual ( , mock_save_data . call_count ) @ mock . patch . object ( filecache , '' , autospec = True ) @ mock . patch . object ( http . VersionNegotiationMixin , '' , autospec = True ) def test_negotiate_version_server_older ( self , mock_pvh , mock_save_data ) : latest_ver = '' mock_pvh . return_value = ( '' , latest_ver ) mock_conn = mock . MagicMock ( ) result = self . test_object . negotiate_version ( mock_conn , self . response ) self . assertEqual ( latest_ver , result ) self . assertEqual ( , mock_pvh . call_count ) host , port = http . get_server ( self . test_object . endpoint ) mock_save_data . assert_called_once_with ( host = host , port = port , data = latest_ver ) @ mock . patch . object ( filecache , '' , autospec = True ) @ mock . patch . object ( http . VersionNegotiationMixin , '' , autospec = True ) def test_negotiate_version_server_newer ( self , mock_pvh , mock_save_data ) : mock_pvh . return_value = ( '' , '' ) mock_conn = mock . MagicMock ( ) result = self . test_object . negotiate_version ( mock_conn , self . response ) self . assertEqual ( '' , result ) self . assertEqual ( , mock_pvh . call_count ) mock_save_data . assert_called_once_with ( host = DEFAULT_HOST , port = DEFAULT_PORT , data = '' ) @ mock . patch . object ( filecache , '' , autospec = True ) @ mock . patch . object ( http . VersionNegotiationMixin , '' , autospec = True ) @ mock . patch . object ( http . VersionNegotiationMixin , '' , autospec = True ) def test_negotiate_version_server_no_version_on_error ( self , mock_pvh , mock_msr , mock_save_data ) : mock_pvh . side_effect = iter ( [ ( None , None ) , ( '' , '' ) ] ) mock_conn = mock . MagicMock ( ) result = self . test_object . negotiate_version ( mock_conn , self . response ) self . assertEqual ( '' , result ) self . assertTrue ( mock_msr . called ) self . assertEqual ( , mock_pvh . call_count ) self . assertEqual ( , mock_save_data . call_count ) @ mock . patch . object ( filecache , '' , autospec = True ) @ mock . patch . object ( http . VersionNegotiationMixin , '' , autospec = True ) def test_negotiate_version_server_explicit_too_high ( self , mock_pvh , mock_save_data ) : mock_pvh . return_value = ( '' , '' ) mock_conn = mock . MagicMock ( ) self . test_object . api_version_select_state = '' self . test_object . os_ironic_api_version = '' self . assertRaises ( exc . UnsupportedVersion , self . test_object . negotiate_version , mock_conn , self . response ) self . assertEqual ( , mock_pvh . call_count ) self . assertEqual ( , mock_save_data . call_count ) @ mock . patch . object ( filecache , '' , autospec = True ) @ mock . patch . object ( http . VersionNegotiationMixin , '' , autospec = True ) def test_negotiate_version_server_explicit_not_supported ( self , mock_pvh , mock_save_data ) : mock_pvh . return_value = ( '' , '' ) mock_conn = mock . MagicMock ( ) self . test_object . api_version_select_state = '' self . test_object . os_ironic_api_version = '' self . assertRaises ( exc . UnsupportedVersion , self . test_object . negotiate_version , mock_conn , self . response ) self . assertEqual ( , mock_pvh . call_count ) self . assertEqual ( , mock_save_data . call_count ) def test_get_server ( self ) : host = '' port = '' endpoint = '' % ( host , port ) self . assertEqual ( ( host , port ) , http . get_server ( endpoint ) ) class HttpClientTest ( utils . BaseTestCase ) : def test_url_generation_trailing_slash_in_base ( self ) : client = http . HTTPClient ( '' ) url = client . _make_connection_url ( '' ) self . assertEqual ( '' , url ) def test_url_generation_without_trailing_slash_in_base ( self ) : client = http . HTTPClient ( '' ) url = client . _make_connection_url ( '' ) self . assertEqual ( '' , url ) def test_url_generation_without_prefix_slash_in_path ( self ) : client = http . HTTPClient ( '' ) url = client . _make_connection_url ( '' ) self . assertEqual ( '' , url ) def test_server_exception_empty_body ( self ) : error_body = _get_error_body ( ) client = http . HTTPClient ( '' ) client . session = utils . FakeSession ( { '' : '' } , six . StringIO ( error_body ) , version = , ", "answer": "status_code = http_client . INTERNAL_SERVER_ERROR )"}, {"prompt": " \"\"\"\"\"\" __author__ = '' class Solution : def trailingZeroes ( self , n ) : \"\"\"\"\"\" cnt = while n : ", "answer": "n /= "}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from troposphere import Template , Ref , Output , Parameter from troposphere . dynamodb import ( Key , AttributeDefinition , ProvisionedThroughput , Projection ) from troposphere . dynamodb import Table , GlobalSecondaryIndex template = Template ( ) template . add_description ( \"\" \"\" ) readunits = template . add_parameter ( Parameter ( \"\" , Description = \"\" , Type = \"\" , Default = \"\" , MinValue = \"\" , MaxValue = \"\" , ConstraintDescription = \"\" ) ) writeunits = template . add_parameter ( Parameter ( \"\" , Description = \"\" , ", "answer": "Type = \"\" ,"}, {"prompt": " from datetime import datetime import sublime from sublime_plugin import ApplicationCommand def increment_seconds ( ) : if sublime . task_timer_time is not None : td = datetime . now ( ) - sublime . task_timer_time sublime . task_timer_seconds += ( td . microseconds + ( td . seconds + td . days * * ) * ** ) / ** def report_time ( ) : has_run = hasattr ( sublime , '' ) if has_run is False or ( has_run and sublime . task_timer_seconds == ) : sublime . status_message ( '' ) return seconds = sublime . task_timer_seconds hours = seconds // minutes = ( seconds % ) // seconds = seconds % output = [ ] if hours > : output . append ( '' % hours ) elif hours == : output . append ( '' ) if minutes > : output . append ( '' % minutes ) elif minutes == : output . append ( '' ) if seconds > : output . append ( '' % seconds ) elif seconds == : output . append ( '' ) sublime . status_message ( '' . join ( output ) ) class TaskTimerStartCommand ( ApplicationCommand ) : def run ( self ) : if not hasattr ( sublime , '' ) : sublime . task_timer_seconds = sublime . task_timer_time = datetime . now ( ) class TaskTimerPauseCommand ( ApplicationCommand ) : \"\"\"\"\"\" def run ( self ) : try : increment_seconds ( ) report_time ( ) sublime . task_timer_time = None except : sublime . status_message ( \"\" ) class TaskTimerStopCommand ( ApplicationCommand ) : \"\"\"\"\"\" ", "answer": "def run ( self ) :"}, {"prompt": " from django . test import TestCase from autofixture . values import Values class ValuesTests ( TestCase ) : def test_init ( self ) : values = Values ( { '' : , '' : } , a = , b = ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) values = Values ( values ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) class Data : a = b = _c = values = Values ( Data , a = ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) values = Values ( Data ( ) , a = ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) values = Values ( Values ( a = , c = ) , a = , b = ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) def test_add_operation ( self ) : values = Values ( a = , b = ) values = values + { '' : , '' : } self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) def test_radd_operation ( self ) : values = Values ( a = , b = ) values = { '' : , '' : } + values self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) def test_iadd_operation ( self ) : values = Values ( a = , b = ) values += { '' : , '' : } self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) def test_subclassing ( self ) : class AB ( Values ) : a = b = values = AB ( ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertRaises ( KeyError , values . __getitem__ , '' ) self . assertRaises ( AttributeError , getattr , values , '' ) self . assertRaises ( AttributeError , getattr , values , '' ) ", "answer": "self . assertRaises ( AttributeError , getattr , values , '' )"}, {"prompt": " \"\"\"\"\"\" from . base import BaseCache from . storage . mongodict import MongoDict , MongoPickleDict class MongoCache ( BaseCache ) : \"\"\"\"\"\" def __init__ ( self , db_name = '' , ** options ) : \"\"\"\"\"\" super ( MongoCache , self ) . __init__ ( ** options ) self . responses = MongoPickleDict ( db_name , '' , options . get ( '' ) ) ", "answer": "self . keys_map = MongoDict ( db_name , '' , self . responses . connection ) "}, {"prompt": " from test . test_support import verbose , verify , TestFailed import sys import new class Eggs : def get_yolks ( self ) : return self . yolks print '' m = new . module ( '' ) if verbose : print m m . Eggs = Eggs sys . modules [ '' ] = m import Spam def get_more_yolks ( self ) : return self . yolks + print '' C = new . classobj ( '' , ( Spam . Eggs , ) , { '' : get_more_yolks } ) if verbose : print C print '' c = new . instance ( C , { '' : } ) if verbose : print c o = new . instance ( C ) verify ( o . __dict__ == { } , \"\" ) del o o = new . instance ( C , None ) verify ( o . __dict__ == { } , \"\" ) del o def break_yolks ( self ) : ", "answer": "self . yolks = self . yolks - "}, {"prompt": " \"\"\"\"\"\" from django . db import models class Journal ( models . Model ) : pass class Order ( models . Model ) : date_field = models . DateField ( ) char_field = models . CharField ( max_length = ) int_field = models . IntegerField ( ) ", "answer": "decimal_field = models . IntegerField ( )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Tangible ( )"}, {"prompt": " from src . platform . jboss . interfaces import JINTERFACES from src . platform . jboss . authenticate import checkAuth from src . module . deploy_utils import parse_war_path from os . path import abspath from log import LOG import utility versions = [ \"\" , \"\" , '' , '' ] title = JINTERFACES . MM def deploy ( fingerengine , fingerprint ) : \"\"\"\"\"\" war_file = abspath ( fingerengine . options . deploy ) ", "answer": "war_name = parse_war_path ( war_file )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " import argparse import os import service_config import subprocess import sys import urlparse import deploy_utils from log import Log ALL_JOBS = [ \"\" ] def _get_chronos_service_config ( args ) : args . chronos_config = deploy_utils . get_service_config ( args ) def generate_zk_jaas_config ( args ) : if not deploy_utils . is_security_enabled ( args ) : return \"\" config_dict = args . chronos_config . configuration . generated_files [ \"\" ] for key , value in config_dict . items ( ) [ : ] : if value != \"\" and value != \"\" and value . find ( \"\" ) == - : config_dict [ key ] = \"\" + value + \"\" header_line = config_dict [ \"\" ] return \"\" % ( header_line , \"\" . join ( [ \"\" % ( key , value ) for ( key , value ) in config_dict . iteritems ( ) if key != config_dict . keys ( ) [ ] ] ) ) def generate_configs ( args , job_name , host_id , instance_id ) : chronos_cfg_dict = args . chronos_config . configuration . generated_files [ \"\" ] hosts = args . chronos_config . jobs [ job_name ] . hosts chronos_cfg = deploy_utils . generate_properties_file ( args , chronos_cfg_dict ) config_files = { \"\" : chronos_cfg , \"\" : generate_zk_jaas_config ( args ) , } config_files . update ( args . chronos_config . configuration . raw_files ) return config_files def generate_run_scripts_params ( args , host , job_name , host_id , instance_id ) : job = args . chronos_config . jobs [ job_name ] supervisor_client = deploy_utils . get_supervisor_client ( host , \"\" , args . chronos_config . cluster . name , job_name , instance_id = instance_id ) artifact_and_version = \"\" + args . chronos_config . cluster . version jar_dirs = \"\" log_level = deploy_utils . get_service_log_level ( args , args . chronos_config ) params = job . get_arguments ( args , args . chronos_config . cluster , args . chronos_config . jobs , args . chronos_config . arguments_dict , job_name , host_id , instance_id ) script_dict = { \"\" : artifact_and_version , \"\" : job_name , \"\" : jar_dirs , \"\" : supervisor_client . get_run_dir ( ) , \"\" : params , } return script_dict def generate_start_script ( args , host , job_name , host_id , instance_id ) : script_params = generate_run_scripts_params ( args , host , job_name , host_id , instance_id ) return deploy_utils . create_run_script ( \"\" % deploy_utils . get_template_dir ( ) , script_params ) def install ( args ) : _get_chronos_service_config ( args ) deploy_utils . install_service ( args , \"\" , args . chronos_config , \"\" ) def cleanup ( args ) : _get_chronos_service_config ( args ) cleanup_token = deploy_utils . confirm_cleanup ( args , \"\" , args . chronos_config ) for job_name in args . job or ALL_JOBS : hosts = args . chronos_config . jobs [ job_name ] . hosts args . task_map = deploy_utils . parse_args_host_and_task ( args , hosts ) for host_id in args . task_map . keys ( ) or hosts . keys ( ) : for instance_id in args . task_map . get ( host_id ) or range ( hosts [ host_id ] . instance_num ) : instance_id = - if not deploy_utils . is_multiple_instances ( host_id , hosts ) else instance_id deploy_utils . cleanup_job ( \"\" , args . chronos_config , hosts [ host_id ] . ip , job_name , instance_id , cleanup_token ) def bootstrap_job ( args , host , job_name , host_id , instance_id , cleanup_token ) : args . chronos_config . parse_generated_config_files ( args , job_name , host_id , instance_id ) deploy_utils . bootstrap_job ( args , \"\" , \"\" , args . chronos_config , host , job_name , instance_id , cleanup_token , '' ) start_job ( args , host , job_name , host_id , instance_id ) def bootstrap ( args ) : _get_chronos_service_config ( args ) cleanup_token = deploy_utils . confirm_bootstrap ( \"\" , args . chronos_config ) for job_name in args . job or ALL_JOBS : hosts = args . chronos_config . jobs [ job_name ] . hosts args . task_map = deploy_utils . parse_args_host_and_task ( args , hosts ) for host_id in args . task_map . keys ( ) or hosts . keys ( ) : for instance_id in args . task_map . get ( host_id ) or range ( hosts [ host_id ] . instance_num ) : instance_id = - if not deploy_utils . is_multiple_instances ( host_id , hosts ) else instance_id bootstrap_job ( args , hosts [ host_id ] . ip , job_name , host_id , instance_id , cleanup_token ) def start_job ( args , host , job_name , host_id , instance_id ) : args . chronos_config . parse_generated_config_files ( args , job_name , host_id , instance_id ) config_files = generate_configs ( args , job_name , host_id , instance_id ) start_script = generate_start_script ( args , host , job_name , host_id , instance_id ) http_url = deploy_utils . get_http_service_uri ( host , args . chronos_config . jobs [ job_name ] . base_port , instance_id ) deploy_utils . start_job ( args , \"\" , \"\" , args . chronos_config , host , job_name , instance_id , start_script , http_url , ** config_files ) def start ( args ) : if not args . skip_confirm : deploy_utils . confirm_start ( args ) _get_chronos_service_config ( args ) for job_name in args . job or ALL_JOBS : hosts = args . chronos_config . jobs [ job_name ] . hosts args . task_map = deploy_utils . parse_args_host_and_task ( args , hosts ) for host_id in args . task_map . keys ( ) or hosts . keys ( ) : for instance_id in args . task_map . get ( host_id ) or range ( hosts [ host_id ] . instance_num ) : instance_id = - if not deploy_utils . is_multiple_instances ( host_id , hosts ) else instance_id start_job ( args , hosts [ host_id ] . ip , job_name , host_id , instance_id ) def stop_job ( args , host , job_name , instance_id ) : deploy_utils . stop_job ( \"\" , args . chronos_config , host , job_name , instance_id ) def stop ( args ) : if not args . skip_confirm : deploy_utils . confirm_stop ( args ) _get_chronos_service_config ( args ) for job_name in args . job or ALL_JOBS : hosts = args . chronos_config . jobs [ job_name ] . hosts args . task_map = deploy_utils . parse_args_host_and_task ( args , hosts ) for host_id in args . task_map . keys ( ) or hosts . keys ( ) : for instance_id in args . task_map . get ( host_id ) or range ( hosts [ host_id ] . instance_num ) : instance_id = - if not deploy_utils . is_multiple_instances ( host_id , hosts ) else instance_id stop_job ( args , hosts [ host_id ] . ip , job_name , instance_id ) def restart ( args ) : if not args . skip_confirm : deploy_utils . confirm_restart ( args ) _get_chronos_service_config ( args ) for job_name in args . job or ALL_JOBS : ", "answer": "hosts = args . chronos_config . jobs [ job_name ] . hosts"}, {"prompt": " import unittest from smtproutes import Route , RoutingException from smtproutes . sender_auth import DKIMAuth , GmailSPFAuth , SenderAuthException from smtproutes . decorators import route class TestRoute ( unittest . TestCase ) : def setUp ( self ) : self . valid_dkim_eml = file ( '' ) . read ( ) self . invalid_dkim_eml = file ( '' ) . read ( ) def test_route_regexes_extracted_from_methods_on_class_inheriting_from_Route ( self ) : class RouteImpl ( Route ) : def route1 ( self , route = r'' ) : pass def route2 ( self , route = r'' ) : pass route = RouteImpl ( ) route . _initialize ( ) self . assertTrue ( '' in route . _routes ) self . assertTrue ( '' in route . _routes ) def test_calling_route_with_a_matching_regex_results_in_the_appropriate_route_being_invoked ( self ) : class RouteImpl ( Route ) : def route1 ( self , route = r'' ) : self . bar = '' def route2 ( self , route = r'' ) : self . bar = '' message = '' route = RouteImpl ( ) route . _initialize ( ) route . _route ( message_data = message ) self . assertEqual ( '' , route . bar ) def test_route_decorator_can_be_used_to_define_endpoint_rather_than_kwarg ( self ) : class RouteImpl ( Route ) : @ route ( '' ) def route1 ( self ) : self . bar = '' @ route ( '' ) def route2 ( self ) : self . bar = '' message = '' r = RouteImpl ( ) r . _initialize ( ) r . _route ( message_data = message ) self . assertEqual ( '' , r . bar ) def test_a_cc_field_that_matches_a_route_causes_the_route_to_be_triggered ( self ) : class RouteImpl ( Route ) : @ route ( r'' ) def route1 ( self ) : self . bar = '' @ route ( r'' ) def route2 ( self ) : self . bar = '' message = '' r = RouteImpl ( ) r . _initialize ( ) r . _route ( message_data = message ) self . assertEqual ( '' , r . bar ) def test_a_bcc_field_that_matches_a_route_causes_the_route_to_be_triggered ( self ) : class RouteImpl ( Route ) : @ route ( r'' ) def route1 ( self ) : self . bar = '' @ route ( r'' ) def route2 ( self ) : self . bar = '' message = '' r = RouteImpl ( ) r . _initialize ( ) r . _route ( message_data = message ) self . assertEqual ( '' , r . bar ) def test_x_forwarded_to_address_is_treated_as_to_address ( self ) : class RouteImpl ( Route ) : @ route ( r'' ) def route1 ( self ) : self . bar = '' message = '' r = RouteImpl ( ) r . _initialize ( ) r . _route ( message ) self . assertEqual ( r . tos [ ] . email , '' ) def test_a_routing_exception_should_be_raised_if_the_route_is_not_found ( self ) : class RouteImpl ( Route ) : pass message = '' route = RouteImpl ( ) route . _initialize ( ) try : route . _route ( message_data = message ) self . assertTrue ( False ) except RoutingException , re : self . assertTrue ( '' in str ( re ) ) self . assertTrue ( True ) def test_named_groups_stored_as_instance_variables_on_route ( self ) : class RouteImpl ( Route ) : def route ( self , route = r'' ) : self . called = True message = '' route = RouteImpl ( ) route . _initialize ( ) route . _route ( message_data = message ) self . assertEqual ( route . user , '' ) self . assertEqual ( route . folder , '' ) self . assertEqual ( route . called , True ) def test_instance_variables_populated_based_on_email_message ( self ) : class RouteImpl ( Route ) : def route ( self , route = r'' ) : self . called = True message = '' route = RouteImpl ( ) route . _initialize ( ) route . _route ( message_data = message ) self . assertTrue ( route . message ) self . assertEqual ( route . tos [ ] . email , '' ) self . assertEqual ( route . tos [ ] . email , '' ) self . assertEqual ( route . mailfrom . email , '' ) self . assertEqual ( route . ccs [ ] . email , '' ) ", "answer": "self . assertEqual ( route . ccs [ ] . email , '' )"}, {"prompt": " import os import multiprocessing from progressbar import ( ProgressBar , Bar , ETA , FileTransferSpeed ) from lacli . log import getLogger from abc import ABCMeta , abstractmethod from logutils . queue import QueueListener class queueHandler ( object ) : def __enter__ ( self ) : q = multiprocessing . Queue ( ) self . listener = QueueListener ( q , self ) self . listener . start ( ) return q def __exit__ ( self , type , value , traceback ) : self . listener . stop ( ) class BaseProgressHandler ( queueHandler , ProgressBar ) : __metaclass__ = ABCMeta def __init__ ( self , * args , ** kwargs ) : self . tx = { } self . progress = kwargs . pop ( '' , ) super ( BaseProgressHandler , self ) . __init__ ( * args , ** kwargs ) def update_current ( self , msg ) : self . tx [ msg [ '' ] ] = int ( msg [ '' ] ) return sum ( self . tx . values ( ) ) def save_current ( self ) : self . progress += sum ( self . tx . values ( ) ) self . tx = { } def handle ( self , msg ) : if '' in msg : self . update ( self . progress + self . update_current ( msg ) ) elif '' in msg : self . keydone ( msg ) self . save_current ( ) def __enter__ ( self ) : q = super ( BaseProgressHandler , self ) . __enter__ ( ) progressToQueue ( q ) self . start ( initval = self . progress ) return q @ abstractmethod def keydone ( self , msg ) : getLogger ( ) . debug ( \"\" . format ( msg ) ) class StateProgressHandler ( BaseProgressHandler ) : uploads = { } def __init__ ( self , state = None , ** kwargs ) : assert state is not None , \"\" self . state = state progress = kwargs . pop ( '' , ) for seq , key in enumerate ( self . state . keys ) : ", "answer": "progress += key [ '' ]"}, {"prompt": " from __future__ import absolute_import , print_function , division import theano ", "answer": "import theano . tensor as T"}, {"prompt": " try : from setuptools import setup installer = '' except ImportError : from distutils . core import setup installer = '' ", "answer": "options = dict ("}, {"prompt": " \"\"\"\"\"\" import encoder import filecmp import json import os import re import subprocess class FileCodec ( encoder . Codec ) : \"\"\"\"\"\" def __init__ ( self , name , formatter = None ) : super ( FileCodec , self ) . __init__ ( name , formatter = formatter ) self . extension = '' def _EncodeFile ( self , parameters , bitrate , videofile , encodedfile ) : commandline = self . EncodeCommandLine ( parameters , bitrate , videofile , encodedfile ) print commandline with open ( os . path . devnull , '' ) as nullinput : times_start = os . times ( ) returncode = subprocess . call ( commandline , shell = True , stdin = nullinput ) times_end = os . times ( ) subprocess_cpu = times_end [ ] - times_start [ ] elapsed_clock = times_end [ ] - times_start [ ] print \"\" % ( subprocess_cpu , elapsed_clock ) if returncode : raise Exception ( \"\" % returncode ) return ( subprocess_cpu , elapsed_clock ) def _DecodeFile ( self , videofile , encodedfile , workdir ) : tempyuvfile = os . path . join ( workdir , videofile . basename + '' ) if os . path . isfile ( tempyuvfile ) : print \"\" , tempyuvfile os . unlink ( tempyuvfile ) commandline = self . DecodeCommandLine ( videofile , encodedfile , tempyuvfile ) print commandline with open ( os . path . devnull , '' ) as nullinput : subprocess_cpu_start = os . times ( ) [ ] returncode = subprocess . call ( commandline , shell = True , stdin = nullinput ) if returncode : raise Exception ( '' % returncode ) subprocess_cpu = os . times ( ) [ ] - subprocess_cpu_start print \"\" % subprocess_cpu commandline = encoder . Tool ( \"\" ) + \"\" % ( videofile . filename , tempyuvfile , videofile . width , videofile . height ) print commandline psnr = subprocess . check_output ( commandline , shell = True , stdin = nullinput ) commandline = [ '' , tempyuvfile ] md5 = subprocess . check_output ( commandline , shell = False ) yuv_md5 = md5 . split ( '' ) [ ] os . unlink ( tempyuvfile ) return psnr , subprocess_cpu , yuv_md5 def Execute ( self , parameters , bitrate , videofile , workdir ) : encodedfile = os . path . join ( workdir , '' % ( videofile . basename , self . extension ) ) subprocess_cpu , elapsed_clock = self . _EncodeFile ( parameters , bitrate , videofile , encodedfile ) result = { } result [ '' ] = subprocess_cpu ", "answer": "result [ '' ] = elapsed_clock"}, {"prompt": " import SimpleCV as cv def main ( ) : cam = cv . Camera ( ) disp = cv . Display ( ) while disp . isNotDone ( ) : if disp . mouseLeft : print '' break img = cam . getImage ( ) img = img . colorDistance ( cv . Color . YELLOW ) img *= blobs = img . findBlobs ( ) blobs . sort ( key = lambda b : - b . mArea ) blobs [ ] . draw ( ) print '' img . save ( disp ) ", "answer": "if __name__ == '' :"}, {"prompt": " import sys import json import numpy as np import pylab def plot ( X , Y , theory , data , err ) : pylab . subplot ( , , ) pylab . pcolormesh ( X , Y , data ) pylab . subplot ( , , ) pylab . pcolormesh ( X , Y , theory ) pylab . subplot ( , , ) pylab . pcolormesh ( X , Y , ( data - theory ) / ( err + ) ) def load_results ( filename ) : \"\"\"\"\"\" data = json . load ( open ( filename ) ) data . update ( ( k , np . array ( data [ k ] ) ) for k in ( '' , '' , '' , '' , '' ) ) ", "answer": "return data"}, {"prompt": " import simplejson as json import time import random from optparse import OptionParser import client FAKE_SIGS = [ \"\" , ", "answer": "\"\" ,"}, {"prompt": " from __future__ import unicode_literals from django . contrib import admin from django . utils . translation import ugettext_lazy as _ from cms . admin . placeholderadmin import ( FrontendEditableAdminMixin , ) from parler . forms import TranslatableModelForm from parler . admin import TranslatableAdmin from aldryn_apphooks_config . admin import BaseAppHookConfig , ModelAppHookConfig from aldryn_people . models import Person from aldryn_reversion . admin import VersionedPlaceholderAdminMixin from aldryn_translation_tools . admin import AllTranslationsMixin from . import models def make_published ( modeladmin , request , queryset ) : queryset . update ( is_published = True ) make_published . short_description = _ ( \"\" ) def make_unpublished ( modeladmin , request , queryset ) : queryset . update ( is_published = False ) make_unpublished . short_description = _ ( \"\" ) def make_featured ( modeladmin , request , queryset ) : queryset . update ( is_featured = True ) make_featured . short_description = _ ( \"\" ) def make_not_featured ( modeladmin , request , queryset ) : queryset . update ( is_featured = False ) make_not_featured . short_description = _ ( \"\" ) class ArticleAdminForm ( TranslatableModelForm ) : class Meta : model = models . Article fields = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] def __init__ ( self , * args , ** kwargs ) : super ( ArticleAdminForm , self ) . __init__ ( * args , ** kwargs ) qs = models . Article . objects if self . instance . app_config_id : qs = models . Article . objects . filter ( app_config = self . instance . app_config ) elif '' in kwargs and '' in kwargs [ '' ] : qs = models . Article . objects . filter ( app_config = kwargs [ '' ] [ '' ] ) if self . instance . pk : qs = qs . exclude ( pk = self . instance . pk ) if '' in self . fields : self . fields [ '' ] . queryset = qs self . fields [ '' ] . widget . can_add_related = False if ( '' in self . fields and hasattr ( self . fields [ '' ] , '' ) ) : self . fields [ '' ] . widget . can_add_related = False class ArticleAdmin ( AllTranslationsMixin , VersionedPlaceholderAdminMixin , FrontendEditableAdminMixin , ModelAppHookConfig , TranslatableAdmin ) : form = ArticleAdminForm list_display = ( '' , '' , '' , '' , '' ) list_filter = [ '' , ] actions = ( make_featured , make_not_featured , make_published , make_unpublished , ) fieldsets = ( ( None , { '' : ( '' , '' , '' , '' , '' , '' , '' , ) } ) , ( '' , { '' : ( '' , ) , '' : ( '' , '' , '' , '' , ) } ) , ( '' , { '' : ( '' , ) , '' : ( '' , '' , '' , '' , '' , ) } ) , ", "answer": ")"}, {"prompt": " \"\"\"\"\"\" import inspect import sys import six from congressclient . openstack . common . gettextutils import _ class ClientException ( Exception ) : \"\"\"\"\"\" pass class MissingArgs ( ClientException ) : \"\"\"\"\"\" def __init__ ( self , missing ) : self . missing = missing msg = _ ( \"\" ) % \"\" . join ( missing ) super ( MissingArgs , self ) . __init__ ( msg ) class ValidationError ( ClientException ) : \"\"\"\"\"\" pass class UnsupportedVersion ( ClientException ) : \"\"\"\"\"\" pass class CommandError ( ClientException ) : \"\"\"\"\"\" pass class AuthorizationFailure ( ClientException ) : \"\"\"\"\"\" pass class ConnectionRefused ( ClientException ) : \"\"\"\"\"\" pass class AuthPluginOptionsMissing ( AuthorizationFailure ) : \"\"\"\"\"\" def __init__ ( self , opt_names ) : super ( AuthPluginOptionsMissing , self ) . __init__ ( _ ( \"\" ) % \"\" . join ( opt_names ) ) self . opt_names = opt_names class AuthSystemNotFound ( AuthorizationFailure ) : \"\"\"\"\"\" def __init__ ( self , auth_system ) : super ( AuthSystemNotFound , self ) . __init__ ( _ ( \"\" ) % repr ( auth_system ) ) self . auth_system = auth_system class NoUniqueMatch ( ClientException ) : \"\"\"\"\"\" pass class EndpointException ( ClientException ) : \"\"\"\"\"\" pass class EndpointNotFound ( EndpointException ) : \"\"\"\"\"\" pass class AmbiguousEndpoints ( EndpointException ) : \"\"\"\"\"\" def __init__ ( self , endpoints = None ) : super ( AmbiguousEndpoints , self ) . __init__ ( _ ( \"\" ) % repr ( endpoints ) ) self . endpoints = endpoints class HttpError ( ClientException ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) def __init__ ( self , message = None , details = None , response = None , request_id = None , url = None , method = None , http_status = None ) : self . http_status = http_status or self . http_status self . message = message or self . message self . details = details self . request_id = request_id self . response = response self . url = url self . method = method formatted_string = \"\" % ( self . message , self . http_status ) if request_id : formatted_string += \"\" % request_id super ( HttpError , self ) . __init__ ( formatted_string ) class HTTPRedirection ( HttpError ) : \"\"\"\"\"\" message = _ ( \"\" ) class HTTPClientError ( HttpError ) : \"\"\"\"\"\" message = _ ( \"\" ) class HttpServerError ( HttpError ) : \"\"\"\"\"\" message = _ ( \"\" ) class MultipleChoices ( HTTPRedirection ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class BadRequest ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class Unauthorized ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class PaymentRequired ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class Forbidden ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class NotFound ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class MethodNotAllowed ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class NotAcceptable ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class ProxyAuthenticationRequired ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class RequestTimeout ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class Conflict ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class Gone ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class LengthRequired ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class PreconditionFailed ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class RequestEntityTooLarge ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) def __init__ ( self , * args , ** kwargs ) : try : self . retry_after = int ( kwargs . pop ( '' ) ) except ( KeyError , ValueError ) : self . retry_after = super ( RequestEntityTooLarge , self ) . __init__ ( * args , ** kwargs ) class RequestUriTooLong ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class UnsupportedMediaType ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class RequestedRangeNotSatisfiable ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class ExpectationFailed ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class UnprocessableEntity ( HTTPClientError ) : \"\"\"\"\"\" http_status = message = _ ( \"\" ) class InternalServerError ( HttpServerError ) : \"\"\"\"\"\" ", "answer": "http_status = "}, {"prompt": " from setuptools import setup , find_packages CLASSIFIERS = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] setup ( name = '' , version = '' , description = '' , author = '' , author_email = '' , url = '' , packages = find_packages ( exclude = [ \"\" , ] ) , install_requires = [ '' , '' , ] , license = '' , platforms = [ '' ] , ", "answer": "classifiers = CLASSIFIERS ,"}, {"prompt": " import time import random import hashlib from social . utils import setting_name , module_member from social . store import OpenIdStore , OpenIdSessionWrapper from social . pipeline import DEFAULT_AUTH_PIPELINE , DEFAULT_DISCONNECT_PIPELINE from social . pipeline . utils import partial_from_session , partial_to_session class BaseTemplateStrategy ( object ) : def __init__ ( self , strategy ) : self . strategy = strategy def render ( self , tpl = None , html = None , context = None ) : if not tpl and not html : raise ValueError ( '' ) context = context or { } if tpl : return self . render_template ( tpl , context ) else : return self . render_string ( html , context ) def render_template ( self , tpl , context ) : raise NotImplementedError ( '' ) def render_string ( self , html , context ) : raise NotImplementedError ( '' ) class BaseStrategy ( object ) : ALLOWED_CHARS = '' '' '' DEFAULT_TEMPLATE_STRATEGY = BaseTemplateStrategy def __init__ ( self , storage = None , tpl = None ) : self . storage = storage self . tpl = ( tpl or self . DEFAULT_TEMPLATE_STRATEGY ) ( self ) def setting ( self , name , default = None , backend = None ) : names = [ setting_name ( name ) , name ] if backend : names . insert ( , setting_name ( backend . name , name ) ) for name in names : try : return self . get_setting ( name ) except ( AttributeError , KeyError ) : pass return default def create_user ( self , * args , ** kwargs ) : return self . storage . user . create_user ( * args , ** kwargs ) def get_user ( self , * args , ** kwargs ) : return self . storage . user . get_user ( * args , ** kwargs ) def session_setdefault ( self , name , value ) : self . session_set ( name , value ) return self . session_get ( name ) def openid_session_dict ( self , name ) : return OpenIdSessionWrapper ( self . session_setdefault ( name , { } ) ) def to_session_value ( self , val ) : return val def from_session_value ( self , val ) : return val def partial_to_session ( self , next , backend , request = None , * args , ** kwargs ) : return partial_to_session ( self , next , backend , request = request , * args , ** kwargs ) def partial_from_session ( self , session ) : return partial_from_session ( self , session ) def clean_partial_pipeline ( self , name = '' ) : self . session_pop ( name ) def openid_store ( self ) : return OpenIdStore ( self ) def get_pipeline ( self ) : return self . setting ( '' , DEFAULT_AUTH_PIPELINE ) def get_disconnect_pipeline ( self ) : return self . setting ( '' , DEFAULT_DISCONNECT_PIPELINE ) def random_string ( self , length = , chars = ALLOWED_CHARS ) : try : random . SystemRandom ( ) except NotImplementedError : key = self . setting ( '' , '' ) seed = '' . format ( random . getstate ( ) , time . time ( ) , key ) random . seed ( hashlib . sha256 ( seed . encode ( ) ) . digest ( ) ) return '' . join ( [ random . choice ( chars ) for i in range ( length ) ] ) def absolute_uri ( self , path = None ) : uri = self . build_absolute_uri ( path ) if uri and self . setting ( '' ) : uri = uri . replace ( '' , '' ) return uri def get_language ( self ) : \"\"\"\"\"\" return '' def send_email_validation ( self , backend , email ) : ", "answer": "email_validation = self . setting ( '' )"}, {"prompt": " from django_tables . base import BaseTable , Rows , TableOptions __all__ = ( '' , ) class SQLTableOptions ( TableOptions ) : def __init__ ( self , options = None ) : super ( SQLTableOptions , self ) . __init__ ( options ) self . columns = getattr ( options , '' , None ) self . exclude = getattr ( options , '' , None ) class SQLRows ( Rows ) : def __init__ ( self , * args , ** kwargs ) : super ( SQLRows , self ) . __init__ ( * args , ** kwargs ) def _reset ( self ) : self . _length = None def __len__ ( self ) : \"\"\"\"\"\" if getattr ( self , '' , None ) is None : self . _length = self . table . data . count ( ) return self . _length count = __len__ class SQLTable ( BaseTable ) : rows_class = SQLRows def __init__ ( self , data = None , * args , ** kwargs ) : if data is None : raise ValueError ( \"\" ) else : self . queryset = data super ( SQLTable , self ) . __init__ ( self . queryset , * args , ** kwargs ) def _validate_column_name ( self , name , purpose ) : return True def _build_snapshot ( self ) : \"\"\"\"\"\" self . _columns . _reset ( ) self . _rows . _reset ( ) qs = self . queryset if self . order_by : ", "answer": "actual_order_by = self . _resolve_sort_directions ( self . order_by )"}, {"prompt": " import time import UserManager import UserInfo from Session import Session from Log import Log import UCache import Config import MsgBox import xmpp import modes import Util import traceback import os from xmpp . features import NoRoute __disco_info_ns__ = '' __disco_items_ns__ = '' __vcard_ns__ = '' STEAL_AFTER_SEEN = def elem_to_str ( elem ) : return \"\" % ( elem . tag , elem . attrib , elem . text ) class XMPPServer ( xmpp . Plugin ) : \"\"\"\"\"\" def __init__ ( self , rosters , host ) : self . probed = False self . _closed = False self . rosters = rosters self . _session = None self . rosters . set_resources ( self . get_resources ( ) ) self . _fixedjid = UCache . UCache . formalize_jid ( unicode ( self . authJID ) ) self . _userid = self . _fixedjid . partition ( '' ) [ ] . encode ( \"\" ) if ( not self . rosters . allow_login ( self . authJID . bare ) ) : Log . warn ( \"\" % self . _userid ) self . stream_error ( '' , '' ) return Log . info ( \"\" % unicode ( self . authJID ) ) if self . authJID . resource [ : - ] != \"\" and len ( self . authJID . resource ) > : try : routes = self . routes ( self . authJID . bare ) for route in routes : jid = route [ ] if jid . resource [ : - ] == self . authJID . resource [ : - ] : if jid . resource != self . authJID . resource : Log . info ( \"\" % ( jid . full , route [ ] ) ) route [ ] . stream_error ( '' , '' ) else : Log . info ( \"\" % ( jid . full , route [ ] ) ) except NoRoute : pass Log . debug ( \"\" % self . authJID . full ) self . _user = UserManager . UserManager . LoadUser ( self . _userid ) if ( self . _user == None ) : raise Exception ( \"\" ) self . _peer_addr = self . getpeername ( ) self . _session = Session ( self . _user , self . _peer_addr [ ] ) self . _session . RecordLogin ( ) self . _userinfo = self . _session . Register ( ) self . _loginid = self . _session . utmpent self . _hostname = host self . bind ( xmpp . ReceivedCloseStream , self . recv_close ) self . bind ( xmpp . StreamClosed , self . stream_closed ) self . bind ( xmpp . SentCloseStream , self . sent_close ) self . rosters . register_conn ( self ) msgbox = MsgBox . MsgBox ( self . _userid ) if self . rosters . get_xmpp_read ( self . _user . GetUID ( ) ) is None : self . rosters . set_xmpp_read ( self . _user . GetUID ( ) , msgbox . GetMsgCount ( all = False ) - msgbox . GetUnreadCount ( ) ) self . check_msg ( ) def get_loginid ( self ) : return self . _loginid def recv_close ( self ) : Log . debug ( \"\" % self . authJID . full ) return self . close ( ) def stream_closed ( self ) : Log . debug ( \"\" % self . authJID . full ) return self . close ( ) def sent_close ( self ) : Log . debug ( \"\" % self . authJID . full ) return self . close ( ) def close ( self ) : if ( self . _closed ) : Log . debug ( \"\" ) return self . _closed = True Log . info ( \"\" % unicode ( self . authJID ) ) if ( self . _session ) : self . _session . Unregister ( ) self . unbind_res ( ) self . rosters . unregister_conn ( self ) @ xmpp . iq ( '' ) def ping ( self , iq ) : \"\"\"\"\"\" self . refresh ( ) return self . iq ( '' , iq ) @ xmpp . stanza ( '' ) def message ( self , elem ) : \"\"\"\"\"\" to_jid = elem . get ( '' ) from_jid = elem . get ( '' ) if ( from_jid == None ) : return text_body = None for child in elem : if ( child . tag . endswith ( '' ) ) : text_body = child . text if ( text_body == None ) : return ret = self . rosters . send_msg ( from_jid , to_jid , text_body ) if ( ret <= ) : Log . warn ( \"\" % ( to_jid , from_jid , ret ) ) errors = { - : \"\" , - : \"\" , - : \"\" , - : \"\" , - : \"\" , - : \"\" , - : \"\" } if ( ret in errors ) : elem = self . E . message ( { '' : to_jid , '' : from_jid , '' : '' } , self . E . body ( errors [ ret ] ) ) self . recv ( from_jid , elem ) def make_jid ( self , userid ) : return \"\" % ( userid , self . _hostname ) def refresh ( self ) : self . _userinfo . freshtime = int ( time . time ( ) ) self . _userinfo . save ( ) def ping_result ( self , iq ) : self . refresh ( ) def ping_client ( self ) : try : pingelem = self . E . ping ( xmlns = '' ) return self . iq ( '' , self . ping_result , pingelem ) except Exception as e : Log . debug ( \"\" % ( self . authJID , e ) ) Log . debug ( traceback . format_exc ( ) ) return False def get_uid ( self ) : return self . _user . GetUID ( ) def recv_msg ( self , from_ , msgtext ) : elem = self . E . message ( { '' : from_ , '' : unicode ( self . authJID ) } , self . E . body ( msgtext ) ) self . recv ( unicode ( self . authJID ) , elem ) def check_msg ( self ) : Log . debug ( \"\" % self . _userid ) msgbox = MsgBox . MsgBox ( self . _userid ) msg_count = msgbox . GetMsgCount ( all = False ) my_pid = os . getpid ( ) xmpp_read = self . rosters . get_xmpp_read ( self . _user . GetUID ( ) ) if xmpp_read > msg_count : xmpp_read = Log . debug ( \"\" % ( msg_count , xmpp_read ) ) self . rosters . set_xmpp_read ( self . _user . GetUID ( ) , msg_count ) if xmpp_read < msg_count : return xmpp_read else : return - def deliver_msg ( self , start ) : Log . debug ( \"\" % unicode ( self . authJID ) ) msgbox = MsgBox . MsgBox ( self . _userid ) msg_count = msgbox . GetMsgCount ( all = False ) my_pid = os . getpid ( ) for i in range ( start , msg_count ) : msghead = msgbox . LoadMsgHead ( i , all = False ) if msghead . topid == my_pid : msgtext = msgbox . LoadMsgText ( msghead ) self . recv_msg ( self . make_jid ( msghead . id ) , msgtext ) def steal_msg ( self ) : Log . debug ( \"\" % self . _userid ) msgbox = MsgBox . MsgBox ( self . _userid ) msg_count = msgbox . GetMsgCount ( all = False ) msg_unread = msgbox . GetUnreadCount ( ) read_count = msg_count - msg_unread my_pid = os . getpid ( ) term_read = self . rosters . get_term_read ( self . get_uid ( ) ) term_stealed = self . rosters . get_term_stealed ( self . get_uid ( ) ) all_xmpp = True new_unread = { } for i in range ( read_count - , msg_count ) : if i < : continue msghead = msgbox . LoadMsgHead ( i , all = False ) if i >= read_count and all_xmpp : if msghead . topid == my_pid : msgbox . GetUnreadMsg ( ) else : all_xmpp = False if msghead . topid == my_pid : continue if i < read_count : session = self . rosters . find_session ( self . authJID . bare , msghead . topid ) if session is None or session . get_mode ( ) != modes . MSG : continue Log . debug ( \"\" % i ) if msghead . topid not in new_unread : Log . debug ( \"\" % ( msghead . topid , i ) ) new_unread [ msghead . topid ] = i final_unread = { } to_steal = { } to_steal_begin = msg_count for pid in term_read : if pid in new_unread : if new_unread [ pid ] == term_read [ pid ] [ ] : final_unread [ pid ] = ( term_read [ pid ] [ ] , term_read [ pid ] [ ] + ) Log . debug ( \"\" % ( new_unread [ pid ] , pid , term_read [ pid ] [ ] + ) ) if final_unread [ pid ] [ ] > STEAL_AFTER_SEEN : to_steal [ pid ] = final_unread [ pid ] Log . debug ( \"\" % ( to_steal [ pid ] [ ] , pid ) ) if pid in term_stealed : steal_begin = max ( final_unread [ pid ] [ ] , term_stealed [ pid ] + ) else : steal_begin = final_unread [ pid ] [ ] if steal_begin < to_steal_begin : to_steal_begin = steal_begin else : final_unread [ pid ] = ( new_unread [ pid ] , ) Log . debug ( \"\" % ( term_read [ pid ] [ ] , new_unread [ pid ] , pid ) ) else : Log . debug ( \"\" % pid ) pass for pid in new_unread : if pid not in term_read : ", "answer": "Log . debug ( \"\" % ( new_unread [ pid ] , pid ) )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from django import template"}, {"prompt": " from __future__ import absolute_import from traits . testing . unittest_tools import unittest from . . api import HasTraits , Instance , Str , Any , Property class Foo ( HasTraits ) : s = Str class ClassWithAny ( HasTraits ) : x = Property _x = Any def _get_x ( self ) : return self . _x def _set_x ( self , x ) : self . _x = x class ClassWithInstance ( HasTraits ) : x = Property _x = Instance ( Foo ) def _get_x ( self ) : return self . _x def _set_x ( self , x ) : self . _x = x class ClassWithClassAttribute ( HasTraits ) : name = '' foo = Str class BazAny ( HasTraits ) : other = Any class BarAny ( HasTraits ) : ", "answer": "other = Any"}, {"prompt": " GitHubTarballPackage ( '' , '' , '' , '' , ", "answer": "configure = ''"}, {"prompt": " import sys import unittest from libcloud . utils . py3 import httplib from libcloud . dns . types import RecordType , ZoneDoesNotExistError from libcloud . dns . types import RecordDoesNotExistError from libcloud . dns . drivers . route53 import Route53DNSDriver from libcloud . test import MockHttp from libcloud . test . file_fixtures import DNSFileFixtures from libcloud . test . secrets import DNS_PARAMS_ROUTE53 class Route53Tests ( unittest . TestCase ) : def setUp ( self ) : Route53DNSDriver . connectionCls . conn_classes = ( Route53MockHttp , Route53MockHttp ) Route53MockHttp . type = None self . driver = Route53DNSDriver ( * DNS_PARAMS_ROUTE53 ) def test_list_record_types ( self ) : record_types = self . driver . list_record_types ( ) self . assertEqual ( len ( record_types ) , ) self . assertTrue ( RecordType . A in record_types ) def test_list_zones ( self ) : zones = self . driver . list_zones ( ) self . assertEqual ( len ( zones ) , ) zone = zones [ ] self . assertEqual ( zone . id , '' ) self . assertEqual ( zone . type , '' ) self . assertEqual ( zone . domain , '' ) def test_list_records ( self ) : zone = self . driver . list_zones ( ) [ ] records = self . driver . list_records ( zone = zone ) self . assertEqual ( len ( records ) , ) record = records [ ] self . assertEqual ( record . name , '' ) self . assertEqual ( record . id , '' ) self . assertEqual ( record . type , RecordType . A ) self . assertEqual ( record . data , '' ) self . assertEqual ( record . extra [ '' ] , ) record = records [ ] self . assertEqual ( record . type , RecordType . MX ) self . assertEqual ( record . data , '' ) self . assertEqual ( record . extra [ '' ] , ) record = records [ ] self . assertEqual ( record . type , RecordType . MX ) self . assertEqual ( record . data , '' ) self . assertEqual ( record . extra [ '' ] , ) record = records [ ] self . assertEqual ( record . type , RecordType . SRV ) self . assertEqual ( record . data , '' ) self . assertEqual ( record . extra [ '' ] , ) self . assertEqual ( record . extra [ '' ] , ) self . assertEqual ( record . extra [ '' ] , ) def test_get_zone ( self ) : zone = self . driver . get_zone ( zone_id = '' ) self . assertEqual ( zone . id , '' ) self . assertEqual ( zone . type , '' ) self . assertEqual ( zone . domain , '' ) def test_get_record ( self ) : record = self . driver . get_record ( zone_id = '' , record_id = '' ) self . assertEqual ( record . name , '' ) self . assertEqual ( record . type , RecordType . CNAME ) self . assertEqual ( record . data , '' ) def test_list_records_zone_does_not_exist ( self ) : zone = self . driver . list_zones ( ) [ ] Route53MockHttp . type = '' try : self . driver . list_records ( zone = zone ) except ZoneDoesNotExistError : e = sys . exc_info ( ) [ ] self . assertEqual ( e . zone_id , zone . id ) else : self . fail ( '' ) def test_get_zone_does_not_exist ( self ) : Route53MockHttp . type = '' try : self . driver . get_zone ( zone_id = '' ) except ZoneDoesNotExistError : e = sys . exc_info ( ) [ ] self . assertEqual ( e . zone_id , '' ) else : self . fail ( '' ) def test_get_record_zone_does_not_exist ( self ) : Route53MockHttp . type = '' try : self . driver . get_record ( zone_id = '' , record_id = '' ) except ZoneDoesNotExistError : pass else : self . fail ( '' ) def test_get_record_record_does_not_exist ( self ) : Route53MockHttp . type = '' rid = '' try : self . driver . get_record ( zone_id = '' , record_id = rid ) except RecordDoesNotExistError : pass else : self . fail ( '' ) def test_create_zone ( self ) : zone = self . driver . create_zone ( domain = '' , type = '' , ttl = None , extra = None ) self . assertEqual ( zone . id , '' ) self . assertEqual ( zone . domain , '' ) def test_create_record ( self ) : zone = self . driver . list_zones ( ) [ ] record = self . driver . create_record ( name = '' , zone = zone , type = RecordType . A , data = '' , extra = { '' : } ) self . assertEqual ( record . id , '' ) self . assertEqual ( record . name , '' ) self . assertEqual ( record . zone , zone ) self . assertEqual ( record . type , RecordType . A ) self . assertEqual ( record . data , '' ) def test_create_record_zone_name ( self ) : zone = self . driver . list_zones ( ) [ ] record = self . driver . create_record ( name = '' , zone = zone , type = RecordType . A , data = '' , extra = { '' : } ) self . assertEqual ( record . id , '' ) self . assertEqual ( record . name , '' ) self . assertEqual ( record . zone , zone ) self . assertEqual ( record . type , RecordType . A ) self . assertEqual ( record . data , '' ) def test_create_multi_value_record ( self ) : zone = self . driver . list_zones ( ) [ ] records = self . driver . ex_create_multi_value_record ( name = '' , zone = zone , type = RecordType . A , data = '' , extra = { '' : } ) self . assertEqual ( len ( records ) , ) self . assertEqual ( records [ ] . id , '' ) self . assertEqual ( records [ ] . id , '' ) self . assertEqual ( records [ ] . name , '' ) self . assertEqual ( records [ ] . name , '' ) self . assertEqual ( records [ ] . zone , zone ) self . assertEqual ( records [ ] . zone , zone ) self . assertEqual ( records [ ] . type , RecordType . A ) self . assertEqual ( records [ ] . type , RecordType . A ) self . assertEqual ( records [ ] . data , '' ) self . assertEqual ( records [ ] . data , '' ) def test_update_record ( self ) : zone = self . driver . list_zones ( ) [ ] record = self . driver . list_records ( zone = zone ) [ ] params = { '' : record , '' : '' , '' : RecordType . A , '' : '' , '' : { '' : } } updated_record = self . driver . update_record ( ** params ) self . assertEqual ( record . data , '' ) self . assertEqual ( updated_record . id , '' ) self . assertEqual ( updated_record . name , '' ) self . assertEqual ( updated_record . zone , record . zone ) self . assertEqual ( updated_record . type , RecordType . A ) self . assertEqual ( updated_record . data , '' ) def test_delete_zone ( self ) : zone = self . driver . list_zones ( ) [ ] status = self . driver . delete_zone ( zone = zone ) self . assertTrue ( status ) def test_delete_zone_does_not_exist ( self ) : zone = self . driver . list_zones ( ) [ ] Route53MockHttp . type = '' try : self . driver . delete_zone ( zone = zone ) except ZoneDoesNotExistError : e = sys . exc_info ( ) [ ] self . assertEqual ( e . zone_id , zone . id ) else : self . fail ( '' ) def test_delete_record ( self ) : zone = self . driver . list_zones ( ) [ ] record = self . driver . list_records ( zone = zone ) [ ] status = self . driver . delete_record ( record = record ) self . assertTrue ( status ) def test_delete_record_does_not_exist ( self ) : zone = self . driver . list_zones ( ) [ ] record = self . driver . list_records ( zone = zone ) [ ] Route53MockHttp . type = '' try : self . driver . delete_record ( record = record ) except RecordDoesNotExistError : e = sys . exc_info ( ) [ ] self . assertEqual ( e . record_id , record . id ) else : self . fail ( '' ) class Route53MockHttp ( MockHttp ) : fixtures = DNSFileFixtures ( '' ) def _2012_02_29_hostedzone_47234 ( self , method , url , body , headers ) : body = self . fixtures . load ( '' ) return ( httplib . OK , body , { } , httplib . responses [ httplib . OK ] ) def _2012_02_29_hostedzone ( self , method , url , body , headers ) : if method == \"\" : body = self . fixtures . load ( \"\" ) return ( httplib . CREATED , body , { } , httplib . responses [ httplib . OK ] ) body = self . fixtures . load ( '' ) return ( httplib . OK , body , { } , httplib . responses [ httplib . OK ] ) def _2012_02_29_hostedzone_47234_rrset ( self , method , url , body , headers ) : body = self . fixtures . load ( '' ) return ( httplib . OK , body , { } , httplib . responses [ httplib . OK ] ) def _2012_02_29_hostedzone_47234_rrset_ZONE_DOES_NOT_EXIST ( self , method , url , body , headers ) : body = self . fixtures . load ( '' ) return ( httplib . NOT_FOUND , body , ", "answer": "{ } , httplib . responses [ httplib . NOT_FOUND ] )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , unicode_literals import warnings from django . core . exceptions import ValidationError , NON_FIELD_ERRORS , FieldError from django . forms . fields import Field , ChoiceField from django . forms . forms import BaseForm , get_declared_fields from django . forms . formsets import BaseFormSet , formset_factory from django . forms . util import ErrorList from django . forms . widgets import ( SelectMultiple , HiddenInput , MultipleHiddenInput , media_property , CheckboxSelectMultiple ) from django . utils . encoding import smart_text , force_text from django . utils . datastructures import SortedDict from django . utils import six from django . utils . text import get_text_list , capfirst from django . utils . translation import ugettext_lazy as _ , ugettext , string_concat __all__ = ( '' , '' , '' , '' , '' , '' , '' , '' , ) ALL_FIELDS = '' def construct_instance ( form , instance , fields = None , exclude = None ) : \"\"\"\"\"\" from django . db import models opts = instance . _meta cleaned_data = form . cleaned_data file_field_list = [ ] for f in opts . fields : if not f . editable or isinstance ( f , models . AutoField ) or not f . name in cleaned_data : continue if fields is not None and f . name not in fields : continue if exclude and f . name in exclude : continue if isinstance ( f , models . FileField ) : file_field_list . append ( f ) else : f . save_form_data ( instance , cleaned_data [ f . name ] ) for f in file_field_list : f . save_form_data ( instance , cleaned_data [ f . name ] ) return instance def save_instance ( form , instance , fields = None , fail_message = '' , commit = True , exclude = None , construct = True ) : \"\"\"\"\"\" if construct : instance = construct_instance ( form , instance , fields , exclude ) opts = instance . _meta if form . errors : raise ValueError ( \"\" \"\" % ( opts . object_name , fail_message ) ) def save_m2m ( ) : cleaned_data = form . cleaned_data for f in opts . many_to_many + opts . virtual_fields : if not hasattr ( f , '' ) : continue if fields and f . name not in fields : continue if exclude and f . name in exclude : continue if f . name in cleaned_data : f . save_form_data ( instance , cleaned_data [ f . name ] ) if commit : instance . save ( ) save_m2m ( ) else : form . save_m2m = save_m2m return instance def model_to_dict ( instance , fields = None , exclude = None ) : \"\"\"\"\"\" from django . db . models . fields . related import ManyToManyField opts = instance . _meta data = { } for f in opts . concrete_fields + opts . virtual_fields + opts . many_to_many : if not getattr ( f , '' , False ) : continue if fields and not f . name in fields : continue if exclude and f . name in exclude : continue if isinstance ( f , ManyToManyField ) : if instance . pk is None : data [ f . name ] = [ ] else : data [ f . name ] = list ( f . value_from_object ( instance ) . values_list ( '' , flat = True ) ) else : data [ f . name ] = f . value_from_object ( instance ) return data def fields_for_model ( model , fields = None , exclude = None , widgets = None , formfield_callback = None , localized_fields = None , labels = None , help_texts = None , error_messages = None ) : \"\"\"\"\"\" field_list = [ ] ignored = [ ] opts = model . _meta from django . db . models . fields import Field as ModelField sortable_virtual_fields = [ f for f in opts . virtual_fields if isinstance ( f , ModelField ) ] for f in sorted ( opts . concrete_fields + sortable_virtual_fields + opts . many_to_many ) : if not getattr ( f , '' , False ) : continue if fields is not None and not f . name in fields : continue if exclude and f . name in exclude : continue kwargs = { } if widgets and f . name in widgets : kwargs [ '' ] = widgets [ f . name ] if localized_fields == ALL_FIELDS or ( localized_fields and f . name in localized_fields ) : kwargs [ '' ] = True if labels and f . name in labels : kwargs [ '' ] = labels [ f . name ] if help_texts and f . name in help_texts : kwargs [ '' ] = help_texts [ f . name ] if error_messages and f . name in error_messages : kwargs [ '' ] = error_messages [ f . name ] if formfield_callback is None : formfield = f . formfield ( ** kwargs ) elif not callable ( formfield_callback ) : raise TypeError ( '' ) else : formfield = formfield_callback ( f , ** kwargs ) if formfield : field_list . append ( ( f . name , formfield ) ) else : ignored . append ( f . name ) field_dict = SortedDict ( field_list ) if fields : field_dict = SortedDict ( [ ( f , field_dict . get ( f ) ) for f in fields if ( ( not exclude ) or ( exclude and f not in exclude ) ) and ( f not in ignored ) ] ) return field_dict class ModelFormOptions ( object ) : def __init__ ( self , options = None ) : self . model = getattr ( options , '' , None ) self . fields = getattr ( options , '' , None ) self . exclude = getattr ( options , '' , None ) self . widgets = getattr ( options , '' , None ) self . localized_fields = getattr ( options , '' , None ) self . labels = getattr ( options , '' , None ) self . help_texts = getattr ( options , '' , None ) self . error_messages = getattr ( options , '' , None ) class ModelFormMetaclass ( type ) : def __new__ ( cls , name , bases , attrs ) : formfield_callback = attrs . pop ( '' , None ) try : parents = [ b for b in bases if issubclass ( b , ModelForm ) ] except NameError : parents = None declared_fields = get_declared_fields ( bases , attrs , False ) new_class = super ( ModelFormMetaclass , cls ) . __new__ ( cls , name , bases , attrs ) if not parents : return new_class if '' not in attrs : new_class . media = media_property ( new_class ) opts = new_class . _meta = ModelFormOptions ( getattr ( new_class , '' , None ) ) for opt in [ '' , '' , '' ] : value = getattr ( opts , opt ) if isinstance ( value , six . string_types ) and value != ALL_FIELDS : msg = ( \"\" \"\" % { '' : new_class . __name__ , '' : opt , '' : value , } ) raise TypeError ( msg ) if opts . model : if opts . fields is None and opts . exclude is None : warnings . warn ( \"\" \"\" \"\" % name , PendingDeprecationWarning , stacklevel = ) if opts . fields == ALL_FIELDS : opts . fields = None fields = fields_for_model ( opts . model , opts . fields , opts . exclude , opts . widgets , formfield_callback , opts . localized_fields , opts . labels , opts . help_texts , opts . error_messages ) none_model_fields = [ k for k , v in six . iteritems ( fields ) if not v ] missing_fields = set ( none_model_fields ) - set ( declared_fields . keys ( ) ) if missing_fields : message = '' message = message % ( '' . join ( missing_fields ) , opts . model . __name__ ) raise FieldError ( message ) fields . update ( declared_fields ) else : fields = declared_fields new_class . declared_fields = declared_fields new_class . base_fields = fields return new_class class BaseModelForm ( BaseForm ) : def __init__ ( self , data = None , files = None , auto_id = '' , prefix = None , initial = None , error_class = ErrorList , label_suffix = None , empty_permitted = False , instance = None ) : opts = self . _meta if opts . model is None : raise ValueError ( '' ) if instance is None : self . instance = opts . model ( ) object_data = { } else : self . instance = instance object_data = model_to_dict ( instance , opts . fields , opts . exclude ) if initial is not None : object_data . update ( initial ) self . _validate_unique = False super ( BaseModelForm , self ) . __init__ ( data , files , auto_id , prefix , object_data , error_class , label_suffix , empty_permitted ) def _update_errors ( self , errors ) : for field , messages in errors . error_dict . items ( ) : if field not in self . fields : continue field = self . fields [ field ] for message in messages : if isinstance ( message , ValidationError ) : if message . code in field . error_messages : message . message = field . error_messages [ message . code ] message_dict = errors . message_dict for k , v in message_dict . items ( ) : if k != NON_FIELD_ERRORS : self . _errors . setdefault ( k , self . error_class ( ) ) . extend ( v ) if k in self . cleaned_data : del self . cleaned_data [ k ] if NON_FIELD_ERRORS in message_dict : messages = message_dict [ NON_FIELD_ERRORS ] self . _errors . setdefault ( NON_FIELD_ERRORS , self . error_class ( ) ) . extend ( messages ) def _get_validation_exclusions ( self ) : \"\"\"\"\"\" exclude = [ ] for f in self . instance . _meta . fields : field = f . name if field not in self . fields : exclude . append ( f . name ) elif self . _meta . fields and field not in self . _meta . fields : exclude . append ( f . name ) elif self . _meta . exclude and field in self . _meta . exclude : exclude . append ( f . name ) elif field in self . _errors . keys ( ) : exclude . append ( f . name ) else : form_field = self . fields [ field ] field_value = self . cleaned_data . get ( field , None ) if not f . blank and not form_field . required and field_value in form_field . empty_values : exclude . append ( f . name ) return exclude def clean ( self ) : self . _validate_unique = True return self . cleaned_data def _post_clean ( self ) : opts = self . _meta self . instance = construct_instance ( self , self . instance , opts . fields , opts . exclude ) exclude = self . _get_validation_exclusions ( ) for f_name , field in self . fields . items ( ) : if isinstance ( field , InlineForeignKeyField ) : exclude . append ( f_name ) try : self . instance . full_clean ( exclude = exclude , validate_unique = False ) except ValidationError as e : self . _update_errors ( e ) if self . _validate_unique : self . validate_unique ( ) def validate_unique ( self ) : \"\"\"\"\"\" exclude = self . _get_validation_exclusions ( ) try : self . instance . validate_unique ( exclude = exclude ) except ValidationError as e : self . _update_errors ( e ) def save ( self , commit = True ) : \"\"\"\"\"\" if self . instance . pk is None : fail_message = '' else : fail_message = '' return save_instance ( self , self . instance , self . _meta . fields , fail_message , commit , self . _meta . exclude , construct = False ) save . alters_data = True class ModelForm ( six . with_metaclass ( ModelFormMetaclass , BaseModelForm ) ) : pass def modelform_factory ( model , form = ModelForm , fields = None , exclude = None , formfield_callback = None , widgets = None , localized_fields = None , labels = None , help_texts = None , error_messages = None ) : \"\"\"\"\"\" attrs = { '' : model } if fields is not None : attrs [ '' ] = fields if exclude is not None : attrs [ '' ] = exclude if widgets is not None : attrs [ '' ] = widgets if localized_fields is not None : attrs [ '' ] = localized_fields if labels is not None : attrs [ '' ] = labels if help_texts is not None : attrs [ '' ] = help_texts if error_messages is not None : attrs [ '' ] = error_messages parent = ( object , ) if hasattr ( form , '' ) : parent = ( form . Meta , object ) Meta = type ( str ( '' ) , parent , attrs ) class_name = model . __name__ + str ( '' ) form_class_attrs = { '' : Meta , '' : formfield_callback } if ( getattr ( Meta , '' , None ) is None and getattr ( Meta , '' , None ) is None ) : warnings . warn ( \"\" \"\" , PendingDeprecationWarning , stacklevel = ) return type ( form ) ( class_name , ( form , ) , form_class_attrs ) class BaseModelFormSet ( BaseFormSet ) : \"\"\"\"\"\" model = None def __init__ ( self , data = None , files = None , auto_id = '' , prefix = None , queryset = None , ** kwargs ) : self . queryset = queryset self . initial_extra = kwargs . pop ( '' , None ) defaults = { '' : data , '' : files , '' : auto_id , '' : prefix } defaults . update ( kwargs ) super ( BaseModelFormSet , self ) . __init__ ( ** defaults ) def initial_form_count ( self ) : \"\"\"\"\"\" if not ( self . data or self . files ) : return len ( self . get_queryset ( ) ) return super ( BaseModelFormSet , self ) . initial_form_count ( ) def _existing_object ( self , pk ) : if not hasattr ( self , '' ) : self . _object_dict = dict ( [ ( o . pk , o ) for o in self . get_queryset ( ) ] ) return self . _object_dict . get ( pk ) def _construct_form ( self , i , ** kwargs ) : if self . is_bound and i < self . initial_form_count ( ) : from django . db import connections pk_key = \"\" % ( self . add_prefix ( i ) , self . model . _meta . pk . name ) pk = self . data [ pk_key ] pk_field = self . model . _meta . pk pk = pk_field . get_db_prep_lookup ( '' , pk , connection = connections [ self . get_queryset ( ) . db ] ) if isinstance ( pk , list ) : pk = pk [ ] kwargs [ '' ] = self . _existing_object ( pk ) if i < self . initial_form_count ( ) and not kwargs . get ( '' ) : kwargs [ '' ] = self . get_queryset ( ) [ i ] if i >= self . initial_form_count ( ) and self . initial_extra : try : kwargs [ '' ] = self . initial_extra [ i - self . initial_form_count ( ) ] except IndexError : pass return super ( BaseModelFormSet , self ) . _construct_form ( i , ** kwargs ) def get_queryset ( self ) : if not hasattr ( self , '' ) : if self . queryset is not None : qs = self . queryset else : qs = self . model . _default_manager . get_queryset ( ) if not qs . ordered : qs = qs . order_by ( self . model . _meta . pk . name ) self . _queryset = qs return self . _queryset def save_new ( self , form , commit = True ) : \"\"\"\"\"\" return form . save ( commit = commit ) def save_existing ( self , form , instance , commit = True ) : \"\"\"\"\"\" return form . save ( commit = commit ) def save ( self , commit = True ) : \"\"\"\"\"\" if not commit : self . saved_forms = [ ] def save_m2m ( ) : for form in self . saved_forms : form . save_m2m ( ) self . save_m2m = save_m2m return self . save_existing_objects ( commit ) + self . save_new_objects ( commit ) save . alters_data = True def clean ( self ) : self . validate_unique ( ) def validate_unique ( self ) : all_unique_checks = set ( ) all_date_checks = set ( ) forms_to_delete = self . deleted_forms valid_forms = [ form for form in self . forms if form . is_valid ( ) and form not in forms_to_delete ] for form in valid_forms : exclude = form . _get_validation_exclusions ( ) unique_checks , date_checks = form . instance . _get_unique_checks ( exclude = exclude ) all_unique_checks = all_unique_checks . union ( set ( unique_checks ) ) all_date_checks = all_date_checks . union ( set ( date_checks ) ) errors = [ ] for uclass , unique_check in all_unique_checks : seen_data = set ( ) for form in valid_forms : row_data = tuple ( [ form . cleaned_data [ field ] for field in unique_check if field in form . cleaned_data ] ) if row_data and not None in row_data : if row_data in seen_data : errors . append ( self . get_unique_error_message ( unique_check ) ) form . _errors [ NON_FIELD_ERRORS ] = self . error_class ( [ self . get_form_error ( ) ] ) for field in unique_check : if field in form . cleaned_data : del form . cleaned_data [ field ] seen_data . add ( row_data ) for date_check in all_date_checks : seen_data = set ( ) uclass , lookup , field , unique_for = date_check for form in valid_forms : if ( form . cleaned_data and form . cleaned_data [ field ] is not None and form . cleaned_data [ unique_for ] is not None ) : if lookup == '' : date = form . cleaned_data [ unique_for ] date_data = ( date . year , date . month , date . day ) else : date_data = ( getattr ( form . cleaned_data [ unique_for ] , lookup ) , ) data = ( form . cleaned_data [ field ] , ) + date_data if data in seen_data : errors . append ( self . get_date_error_message ( date_check ) ) form . _errors [ NON_FIELD_ERRORS ] = self . error_class ( [ self . get_form_error ( ) ] ) del form . cleaned_data [ field ] seen_data . add ( data ) if errors : raise ValidationError ( errors ) def get_unique_error_message ( self , unique_check ) : if len ( unique_check ) == : return ugettext ( \"\" ) % { \"\" : unique_check [ ] , } else : return ugettext ( \"\" \"\" ) % { \"\" : get_text_list ( unique_check , six . text_type ( _ ( \"\" ) ) ) , } def get_date_error_message ( self , date_check ) : return ugettext ( \"\" \"\" ) % { '' : date_check [ ] , '' : date_check [ ] , '' : six . text_type ( date_check [ ] ) , } def get_form_error ( self ) : return ugettext ( \"\" ) def save_existing_objects ( self , commit = True ) : self . changed_objects = [ ] self . deleted_objects = [ ] if not self . initial_forms : return [ ] saved_instances = [ ] forms_to_delete = self . deleted_forms for form in self . initial_forms : pk_name = self . _pk_field . name raw_pk_value = form . _raw_value ( pk_name ) pk_value = form . fields [ pk_name ] . clean ( raw_pk_value ) pk_value = getattr ( pk_value , '' , pk_value ) obj = self . _existing_object ( pk_value ) if form in forms_to_delete : self . deleted_objects . append ( obj ) obj . delete ( ) continue if form . has_changed ( ) : self . changed_objects . append ( ( obj , form . changed_data ) ) saved_instances . append ( self . save_existing ( form , obj , commit = commit ) ) if not commit : self . saved_forms . append ( form ) return saved_instances def save_new_objects ( self , commit = True ) : self . new_objects = [ ] for form in self . extra_forms : if not form . has_changed ( ) : continue if self . can_delete and self . _should_delete_form ( form ) : continue self . new_objects . append ( self . save_new ( form , commit = commit ) ) if not commit : self . saved_forms . append ( form ) return self . new_objects def add_fields ( self , form , index ) : \"\"\"\"\"\" from django . db . models import AutoField , OneToOneField , ForeignKey self . _pk_field = pk = self . model . _meta . pk def pk_is_not_editable ( pk ) : return ( ( not pk . editable ) or ( pk . auto_created or isinstance ( pk , AutoField ) ) or ( pk . rel and pk . rel . parent_link and pk_is_not_editable ( pk . rel . to . _meta . pk ) ) ) if pk_is_not_editable ( pk ) or pk . name not in form . fields : if form . is_bound : pk_value = form . instance . pk else : try : if index is not None : pk_value = self . get_queryset ( ) [ index ] . pk else : pk_value = None except IndexError : pk_value = None if isinstance ( pk , OneToOneField ) or isinstance ( pk , ForeignKey ) : qs = pk . rel . to . _default_manager . get_queryset ( ) else : qs = self . model . _default_manager . get_queryset ( ) qs = qs . using ( form . instance . _state . db ) if form . _meta . widgets : widget = form . _meta . widgets . get ( self . _pk_field . name , HiddenInput ) else : widget = HiddenInput form . fields [ self . _pk_field . name ] = ModelChoiceField ( qs , initial = pk_value , required = False , widget = widget ) super ( BaseModelFormSet , self ) . add_fields ( form , index ) def modelformset_factory ( model , form = ModelForm , formfield_callback = None , formset = BaseModelFormSet , extra = , can_delete = False , can_order = False , max_num = None , fields = None , exclude = None , widgets = None , validate_max = False , localized_fields = None , labels = None , help_texts = None , error_messages = None ) : \"\"\"\"\"\" meta = getattr ( form , '' , None ) if meta is None : meta = type ( str ( '' ) , ( object , ) , { } ) if ( getattr ( meta , '' , fields ) is None and getattr ( meta , '' , exclude ) is None ) : warnings . warn ( \"\" \"\" , PendingDeprecationWarning , stacklevel = ) form = modelform_factory ( model , form = form , fields = fields , exclude = exclude , formfield_callback = formfield_callback , widgets = widgets , localized_fields = localized_fields , labels = labels , help_texts = help_texts , error_messages = error_messages ) FormSet = formset_factory ( form , formset , extra = extra , max_num = max_num , can_order = can_order , can_delete = can_delete , validate_max = validate_max ) FormSet . model = model return FormSet class BaseInlineFormSet ( BaseModelFormSet ) : \"\"\"\"\"\" def __init__ ( self , data = None , files = None , instance = None , save_as_new = False , prefix = None , queryset = None , ** kwargs ) : if instance is None : self . instance = self . fk . rel . to ( ) else : self . instance = instance self . save_as_new = save_as_new if queryset is None : queryset = self . model . _default_manager if self . instance . pk is not None : qs = queryset . filter ( ** { self . fk . name : self . instance } ) else : qs = queryset . none ( ) super ( BaseInlineFormSet , self ) . __init__ ( data , files , prefix = prefix , queryset = qs , ** kwargs ) def initial_form_count ( self ) : if self . save_as_new : return return super ( BaseInlineFormSet , self ) . initial_form_count ( ) def _construct_form ( self , i , ** kwargs ) : form = super ( BaseInlineFormSet , self ) . _construct_form ( i , ** kwargs ) if self . save_as_new : form . data [ form . add_prefix ( self . _pk_field . name ) ] = None form . data [ form . add_prefix ( self . fk . name ) ] = None fk_value = self . instance . pk if self . fk . rel . field_name != self . fk . rel . to . _meta . pk . name : fk_value = getattr ( self . instance , self . fk . rel . field_name ) fk_value = getattr ( fk_value , '' , fk_value ) setattr ( form . instance , self . fk . get_attname ( ) , fk_value ) return form @ classmethod def get_default_prefix ( cls ) : from django . db . models . fields . related import RelatedObject return RelatedObject ( cls . fk . rel . to , cls . model , cls . fk ) . get_accessor_name ( ) . replace ( '' , '' ) def save_new ( self , form , commit = True ) : obj = form . save ( commit = False ) pk_value = getattr ( self . instance , self . fk . rel . field_name ) setattr ( obj , self . fk . get_attname ( ) , getattr ( pk_value , '' , pk_value ) ) if commit : obj . save ( ) if commit and hasattr ( form , '' ) : form . save_m2m ( ) return obj def add_fields ( self , form , index ) : super ( BaseInlineFormSet , self ) . add_fields ( form , index ) if self . _pk_field == self . fk : name = self . _pk_field . name kwargs = { '' : True } else : name = self . fk . name kwargs = { '' : getattr ( form . fields . get ( name ) , '' , capfirst ( self . fk . verbose_name ) ) } if self . fk . rel . field_name != self . fk . rel . to . _meta . pk . name : kwargs [ '' ] = self . fk . rel . field_name form . fields [ name ] = InlineForeignKeyField ( self . instance , ** kwargs ) if form . _meta . fields : if isinstance ( form . _meta . fields , tuple ) : form . _meta . fields = list ( form . _meta . fields ) form . _meta . fields . append ( self . fk . name ) def get_unique_error_message ( self , unique_check ) : unique_check = [ field for field in unique_check if field != self . fk . name ] return super ( BaseInlineFormSet , self ) . get_unique_error_message ( unique_check ) def _get_foreign_key ( parent_model , model , fk_name = None , can_fail = False ) : \"\"\"\"\"\" from django . db . models import ForeignKey opts = model . _meta if fk_name : fks_to_parent = [ f for f in opts . fields if f . name == fk_name ] if len ( fks_to_parent ) == : fk = fks_to_parent [ ] if not isinstance ( fk , ForeignKey ) or ( fk . rel . to != parent_model and fk . rel . to not in parent_model . _meta . get_parent_list ( ) ) : raise Exception ( \"\" % ( fk_name , parent_model ) ) elif len ( fks_to_parent ) == : raise Exception ( \"\" % ( model , fk_name ) ) else : fks_to_parent = [ f for f in opts . fields if isinstance ( f , ForeignKey ) and ( f . rel . to == parent_model or f . rel . to in parent_model . _meta . get_parent_list ( ) ) ] if len ( fks_to_parent ) == : fk = fks_to_parent [ ] elif len ( fks_to_parent ) == : if can_fail : return raise Exception ( \"\" % ( model , parent_model ) ) else : raise Exception ( \"\" % ( model , parent_model ) ) return fk ", "answer": "def inlineformset_factory ( parent_model , model , form = ModelForm ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " DATABASES = { '' : { ", "answer": "'' : '' ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " \"\"\"\"\"\" import os import time import random import logging import requests import yaml import redis import gevent from gevent . pool import Pool , Group from gevent . timeout import Timeout from gevent import monkey from lxml import etree monkey . patch_all ( thread = False , select = False ) logging . basicConfig ( level = logging . INFO , format = '' , datefmt = '' ) class ProxyPool ( object ) : \"\"\"\"\"\" def __init__ ( self , configfile = '' ) : self . configs = self . _get_configs ( configfile ) self . rdb = redis . StrictRedis ( db = self . configs [ '' ] ) self . db_zproxy = self . configs [ '' ] self . pool = Pool ( self . configs [ '' ] ) self . group = Group ( ) self . wrong_value = self . configs [ '' ] self . init_value = self . configs [ '' ] def _get_configs ( self , configfile ) : \"\"\"\"\"\" configpath = os . path . join ( '' , configfile ) with open ( configpath , '' ) as fp : configs = yaml . load ( fp ) return configs def get_many ( self , num = , minscore = , maxscore = None ) : \"\"\"\"\"\" minscore = minscore maxscore = maxscore or self . init_value res = self . rdb . zrange ( self . db_zproxy , minscore , maxscore ) if res : random . shuffle ( res ) ", "answer": "if len ( res ) < num :"}, {"prompt": " \"\"\"\"\"\" try : import http . client as http_lib except ImportError : import httplib as http_lib from . import WSGI_HTTPConnection , WSGI_HTTPSConnection try : from http . client import ( HTTPConnection as OriginalHTTPConnection , HTTPSConnection as OriginalHTTPSConnection ) except ImportError : from httplib import ( HTTPConnection as OriginalHTTPConnection , HTTPSConnection as OriginalHTTPSConnection ) ", "answer": "HTTPInterceptorMixin = WSGI_HTTPConnection"}, {"prompt": " import six from oslo_serialization import jsonutils from nailgun . api . v1 . validators . base import BasicValidator from nailgun . db . sqlalchemy import models from nailgun import errors from nailgun . extensions . network_manager . validators . json_schema import ip_addr from nailgun import objects class IPAddrValidator ( BasicValidator ) : single_schema = ip_addr . IP_ADDR_UPDATE_SCHEMA collection_schema = ip_addr . IP_ADDRS_UPDATE_SCHEMA updatable_fields = ( \"\" , \"\" , \"\" , ) @ classmethod def _check_vip_name ( cls , data , cluster ) : network_roles = objects . Cluster . get_network_roles ( cluster ) allowed_vip_names = set ( ) for net_role in network_roles : vip_info = net_role . get ( '' , { } ) . get ( '' , [ ] ) allowed_vip_names . update ( vip [ '' ] for vip in vip_info ) if data [ '' ] not in allowed_vip_names : raise errors . InvalidData ( \"\" \"\" . format ( data [ '' ] , cluster . id ) ) @ classmethod def validate_create ( cls , data , cluster ) : if isinstance ( data , six . string_types ) : data = cls . validate_json ( data ) cls . validate_schema ( data , ip_addr . VIP_CREATE_SCHEMA ) if data . get ( '' ) is False : raise errors . InvalidData ( \"\" \"\" ) cls . _check_vip_name ( data , cluster ) network_id = data [ \"\" ] network_db = objects . NetworkGroup . get_by_uid ( network_id ) if network_db is None : raise errors . InvalidData ( \"\" . format ( data [ '' ] ) ) if network_db . nodegroup is None : raise errors . InvalidData ( \"\" \"\" . format ( network_db . id ) ) if network_db . nodegroup . cluster_id != cluster . id : raise errors . InvalidData ( \"\" \"\" \"\" . format ( network_id , cluster . id ) ) ip_db = objects . IPAddrCollection . get_all_by_addr ( data [ '' ] ) . first ( ) if ip_db is not None : raise errors . InvalidData ( \"\" . format ( data [ '' ] ) ) return data @ classmethod def validate_update ( cls , data , existing_obj ) : \"\"\"\"\"\" ", "answer": "if isinstance ( data , six . string_types ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " from django import template from django . template . loader import render_to_string from django . conf import settings from django . contrib . contenttypes . models import ContentType from django . contrib import comments from django . utils import six from django . utils . deprecation import RenameMethodsBase from django . utils . encoding import smart_text register = template . Library ( ) class RenameBaseCommentNodeMethods ( RenameMethodsBase ) : renamed_methods = ( ( '' , '' , PendingDeprecationWarning ) , ) class BaseCommentNode ( six . with_metaclass ( RenameBaseCommentNodeMethods , template . Node ) ) : \"\"\"\"\"\" @ classmethod def handle_token ( cls , parser , token ) : \"\"\"\"\"\" tokens = token . split_contents ( ) if tokens [ ] != '' : raise template . TemplateSyntaxError ( \"\" % tokens [ ] ) if len ( tokens ) == : if tokens [ ] != '' : raise template . TemplateSyntaxError ( \"\" % tokens [ ] ) return cls ( object_expr = parser . compile_filter ( tokens [ ] ) , as_varname = tokens [ ] , ) elif len ( tokens ) == : if tokens [ ] != '' : raise template . TemplateSyntaxError ( \"\" % tokens [ ] ) return cls ( ctype = BaseCommentNode . lookup_content_type ( tokens [ ] , tokens [ ] ) , object_pk_expr = parser . compile_filter ( tokens [ ] ) , as_varname = tokens [ ] ) else : raise template . TemplateSyntaxError ( \"\" % tokens [ ] ) @ staticmethod def lookup_content_type ( token , tagname ) : try : app , model = token . split ( '' ) return ContentType . objects . get_by_natural_key ( app , model ) except ValueError : raise template . TemplateSyntaxError ( \"\" % tagname ) except ContentType . DoesNotExist : raise template . TemplateSyntaxError ( \"\" % ( tagname , app , model ) ) def __init__ ( self , ctype = None , object_pk_expr = None , object_expr = None , as_varname = None , comment = None ) : if ctype is None and object_expr is None : raise template . TemplateSyntaxError ( \"\" ) self . comment_model = comments . get_model ( ) self . as_varname = as_varname self . ctype = ctype self . object_pk_expr = object_pk_expr self . object_expr = object_expr self . comment = comment def render ( self , context ) : qs = self . get_queryset ( context ) context [ self . as_varname ] = self . get_context_value_from_queryset ( context , qs ) return '' def get_queryset ( self , context ) : ctype , object_pk = self . get_target_ctype_pk ( context ) if not object_pk : return self . comment_model . objects . none ( ) qs = self . comment_model . objects . filter ( content_type = ctype , object_pk = smart_text ( object_pk ) , site__pk = settings . SITE_ID , ) field_names = [ f . name for f in self . comment_model . _meta . fields ] if '' in field_names : qs = qs . filter ( is_public = True ) if getattr ( settings , '' , True ) and '' in field_names : qs = qs . filter ( is_removed = False ) return qs def get_target_ctype_pk ( self , context ) : if self . object_expr : try : obj = self . object_expr . resolve ( context ) except template . VariableDoesNotExist : return None , None return ContentType . objects . get_for_model ( obj ) , obj . pk else : return self . ctype , self . object_pk_expr . resolve ( context , ignore_failures = True ) def get_context_value_from_queryset ( self , context , qs ) : \"\"\"\"\"\" raise NotImplementedError class CommentListNode ( BaseCommentNode ) : \"\"\"\"\"\" def get_context_value_from_queryset ( self , context , qs ) : return list ( qs ) class CommentCountNode ( BaseCommentNode ) : \"\"\"\"\"\" def get_context_value_from_queryset ( self , context , qs ) : return qs . count ( ) ", "answer": "class CommentFormNode ( BaseCommentNode ) :"}, {"prompt": " import os import unittest import IECore import Gaffer import GafferImage import GafferScene import GafferSceneTest @ unittest . skipIf ( \"\" in os . environ , \"\" ) class OpenGLRenderTest ( GafferSceneTest . SceneTestCase ) : def test ( self ) : self . assertFalse ( os . path . exists ( self . temporaryDirectory ( ) + \"\" ) ) s = Gaffer . ScriptNode ( ) s [ \"\" ] = GafferScene . Plane ( ) s [ \"\" ] [ \"\" ] [ \"\" ] . setValue ( IECore . V3f ( , , - ) ) s [ \"\" ] = GafferImage . ImageReader ( ) s [ \"\" ] [ \"\" ] . setValue ( os . path . expandvars ( \"\" ) ) s [ \"\" ] = GafferScene . OpenGLShader ( ) s [ \"\" ] . loadShader ( \"\" ) s [ \"\" ] [ \"\" ] [ \"\" ] . setInput ( s [ \"\" ] [ \"\" ] ) s [ \"\" ] [ \"\" ] [ \"\" ] . setValue ( ) s [ \"\" ] [ \"\" ] [ \"\" ] . setValue ( IECore . Color4f ( ) ) s [ \"\" ] = GafferScene . ShaderAssignment ( ) s [ \"\" ] [ \"\" ] . setInput ( s [ \"\" ] [ \"\" ] ) s [ \"\" ] [ \"\" ] . setInput ( s [ \"\" ] [ \"\" ] ) s [ \"\" ] = GafferScene . Outputs ( ) s [ \"\" ] . addOutput ( \"\" , IECore . Display ( ", "answer": "self . temporaryDirectory ( ) + \"\" ,"}, {"prompt": " import logging from django . utils . translation import ugettext import uuid from datetime import datetime , date , timedelta from django . template . loader import render_to_string from corehq . apps . accounting . models import ( SoftwarePlanEdition , DefaultProductPlan , BillingAccount , BillingAccountType , Subscription , SubscriptionAdjustmentMethod , Currency , SubscriptionType , PreOrPostPay ) from corehq . apps . registration . models import RegistrationRequest from dimagi . utils . couch import CriticalSection from dimagi . utils . name_to_url import name_to_url from dimagi . utils . web import get_ip , get_url_base , get_site_domain from django . conf import settings from django . core . urlresolvers import reverse from corehq . apps . domain . models import Domain from corehq . apps . users . models import WebUser , CouchUser , UserRole from corehq . apps . hqwebapp . tasks import send_html_email_async from dimagi . utils . couch . database import get_safe_write_kwargs from corehq . apps . hqwebapp . tasks import send_mail_async from corehq . apps . analytics . tasks import track_created_new_project_space_on_hubspot from corehq . apps . analytics . utils import get_meta def activate_new_user ( form , is_domain_admin = True , domain = None , ip = None ) : username = form . cleaned_data [ '' ] password = form . cleaned_data [ '' ] full_name = form . cleaned_data [ '' ] now = datetime . utcnow ( ) new_user = WebUser . create ( domain , username , password , is_admin = is_domain_admin ) new_user . first_name = full_name [ ] new_user . last_name = full_name [ ] new_user . email = username new_user . email_opt_out = False new_user . subscribed_to_commcare_users = False new_user . eula . signed = True new_user . eula . date = now new_user . eula . type = '' if ip : new_user . eula . user_ip = ip new_user . is_staff = False new_user . is_active = True new_user . is_superuser = False new_user . last_login = now new_user . date_joined = now new_user . last_password_set = now new_user . save ( ) return new_user def request_new_domain ( request , form , is_new_user = True ) : now = datetime . utcnow ( ) current_user = CouchUser . from_django_user ( request . user ) dom_req = RegistrationRequest ( ) if is_new_user : dom_req . request_time = now dom_req . request_ip = get_ip ( request ) dom_req . activation_guid = uuid . uuid1 ( ) . hex name = name_to_url ( form . cleaned_data [ '' ] , \"\" ) with CriticalSection ( [ '' . format ( name ) ] ) : name = Domain . generate_name ( name ) new_domain = Domain ( name = name , hr_name = form . cleaned_data [ '' ] , is_active = False , date_created = datetime . utcnow ( ) , creating_user = current_user . username , secure_submissions = True , ) if form . cleaned_data . get ( '' ) : new_domain . default_timezone = form . cleaned_data [ '' ] if not is_new_user : new_domain . is_active = True new_domain . save ( ** get_safe_write_kwargs ( ) ) if not new_domain . name : new_domain . name = new_domain . _id new_domain . save ( ) if is_new_user : create_30_day_advanced_trial ( new_domain ) UserRole . init_domain_with_presets ( new_domain . name ) dom_req . domain = new_domain . name if request . user . is_authenticated ( ) : if not current_user : current_user = WebUser ( ) current_user . sync_from_django_user ( request . user ) current_user . save ( ) current_user . add_domain_membership ( new_domain . name , is_admin = True ) current_user . save ( ) dom_req . requesting_user_username = request . user . username dom_req . new_user_username = request . user . username if is_new_user : dom_req . save ( ) send_domain_registration_email ( request . user . email , dom_req . domain , dom_req . activation_guid , request . user . get_full_name ( ) ) else : send_global_domain_registration_email ( request . user , new_domain . name ) send_new_request_update_email ( request . user , get_ip ( request ) , new_domain . name , is_new_user = is_new_user ) meta = get_meta ( request ) track_created_new_project_space_on_hubspot . delay ( current_user , request . COOKIES , meta ) return new_domain . name REGISTRATION_EMAIL_BODY_HTML = u\"\"\"\"\"\" REGISTRATION_EMAIL_BODY_PLAINTEXT = u\"\"\"\"\"\" WIKI_LINK = '' USERS_LINK = '' PRICING_LINK = '' def send_domain_registration_email ( recipient , domain_name , guid , full_name ) : DNS_name = get_site_domain ( ) registration_link = '' + DNS_name + reverse ( '' ) + guid + '' params = { \"\" : domain_name , \"\" : PRICING_LINK , \"\" : registration_link , \"\" : full_name , \"\" : USERS_LINK , \"\" : WIKI_LINK , '' : '' if settings . STATIC_CDN else '' + DNS_name , } message_plaintext = render_to_string ( '' , params ) message_html = render_to_string ( '' , params ) subject = ugettext ( '' ) try : send_html_email_async . delay ( subject , recipient , message_html , text_content = message_plaintext , email_from = settings . DEFAULT_FROM_EMAIL , ga_track = True ) except Exception : logging . warning ( \"\" % message_plaintext ) def send_global_domain_registration_email ( requesting_user , domain_name ) : DNS_name = get_site_domain ( ) registration_link = '' + DNS_name + reverse ( \"\" , args = [ domain_name ] ) message_plaintext = u\"\"\"\"\"\" + REGISTRATION_EMAIL_BODY_PLAINTEXT message_html = u\"\"\"\"\"\" + REGISTRATION_EMAIL_BODY_HTML params = { \"\" : requesting_user . first_name , \"\" : domain_name , \"\" : PRICING_LINK , \"\" : registration_link , \"\" : requesting_user . email , \"\" : USERS_LINK , \"\" : WIKI_LINK , } message_plaintext = message_plaintext . format ( ** params ) message_html = message_html . format ( ** params ) subject = '' . format ( ** locals ( ) ) try : send_html_email_async . delay ( subject , requesting_user . email , message_html , text_content = message_plaintext , email_from = settings . DEFAULT_FROM_EMAIL ) except Exception : logging . warning ( \"\" % message_plaintext ) def send_new_request_update_email ( user , requesting_ip , entity_name , entity_type = \"\" , is_new_user = False , is_confirming = False ) : entity_texts = { \"\" : [ \"\" , \"\" ] , \"\" : [ \"\" , \"\" ] } [ entity_type ] if is_confirming : message = \"\" % ( entity_texts [ ] , entity_name ) elif is_new_user : message = \"\" % ( entity_texts [ ] , entity_name ) else : message = \"\" % ( entity_texts [ ] , entity_name ) message = u\"\"\"\"\"\" % ( message , user . username , requesting_ip , entity_texts [ ] , get_url_base ( ) + \"\" % ( \"\" if entity_type == \"\" else \"\" , entity_name ) ) try : recipients = settings . NEW_DOMAIN_RECIPIENTS send_mail_async . delay ( u\"\" % ( entity_texts [ ] , entity_name ) , message , settings . SERVER_EMAIL , recipients ) except Exception : logging . warning ( \"\" % message ) def create_30_day_advanced_trial ( domain_obj ) : advanced_plan_version = DefaultProductPlan . get_default_plan_by_domain ( domain_obj , edition = SoftwarePlanEdition . ADVANCED , is_trial = True ) expiration_date = date . today ( ) + timedelta ( days = ) trial_account = BillingAccount . objects . get_or_create ( name = \"\" % domain_obj . name , currency = Currency . get_default ( ) , created_by_domain = domain_obj . name , account_type = BillingAccountType . TRIAL , pre_or_post_pay = PreOrPostPay . POSTPAY , ) [ ] trial_subscription = Subscription . new_domain_subscription ( trial_account , domain_obj . name , advanced_plan_version , date_end = expiration_date , ", "answer": "adjustment_method = SubscriptionAdjustmentMethod . TRIAL ,"}, {"prompt": " from distutils . core import setup import sys reload ( sys ) . setdefaultencoding ( \"\" ) version = '' setup ( ", "answer": "name = '' ,"}, {"prompt": " \"\"\"\"\"\" import unittest from foox . species . third import ( Genome , create_population , is_parallel , make_fitness_function , make_generate_function , make_halt_function , MAX_REWARD , REWARD_STEPWISE_MOTION ) CANTUS_FIRMUS = [ , , , , , , , , , , ] class TestCreatePopulation ( unittest . TestCase ) : \"\"\"\"\"\" def test_returns_valid_genomes ( self ) : \"\"\"\"\"\" result = create_population ( , CANTUS_FIRMUS ) self . assertEqual ( Genome , type ( result [ ] ) ) def test_returns_correct_number_of_genomes ( self ) : \"\"\"\"\"\" result = create_population ( , CANTUS_FIRMUS ) self . assertEqual ( , len ( result ) ) def test_uses_only_valid_intervals ( self ) : \"\"\"\"\"\" valid_even_beat_intervals = [ , , , , , ] valid_odd_beat_intervals = valid_even_beat_intervals + [ , , , ] result = create_population ( , CANTUS_FIRMUS ) for genome in result : for i in range ( len ( genome . chromosome ) ) : contrapunctus_note = genome . chromosome [ i ] cantus_firmus_note = CANTUS_FIRMUS [ i / ] interval = contrapunctus_note - cantus_firmus_note if i % : self . assertIn ( interval , valid_odd_beat_intervals ) else : self . assertIn ( interval , valid_even_beat_intervals ) def test_solutions_have_correct_number_of_notes ( self ) : \"\"\"\"\"\" result = create_population ( , CANTUS_FIRMUS ) expected_length = ( len ( CANTUS_FIRMUS ) * ) - for genome in result : self . assertEqual ( expected_length , len ( genome . chromosome ) ) class TestFitnessFunction ( unittest . TestCase ) : \"\"\"\"\"\" def test_make_fitness_function_returns_callable ( self ) : \"\"\"\"\"\" result = make_fitness_function ( CANTUS_FIRMUS ) self . assertTrue ( callable ( result ) ) def test_fitness_function_returns_float ( self ) : \"\"\"\"\"\" fitness_function = make_fitness_function ( CANTUS_FIRMUS ) genome = Genome ( [ , , ] ) result = fitness_function ( genome ) self . assertTrue ( float , type ( result ) ) def test_fitness_function_sets_fitness_on_genome ( self ) : \"\"\"\"\"\" fitness_function = make_fitness_function ( CANTUS_FIRMUS ) genome = Genome ( [ , , ] ) ", "answer": "self . assertEqual ( None , genome . fitness )"}, {"prompt": " import sys import random import itertools import unittest from sre_yield . fastdivmod import divmod_iter_chunking , divmod_iter_basic , powersum class FastDivmodTest ( unittest . TestCase ) : def test_divmod_iter_basic ( self ) : v = divmod_iter_basic ( , ) self . assertEqual ( [ , , , ] , list ( v ) ) def test_basics ( self ) : v = divmod_iter_chunking ( , , ) self . assertEqual ( [ , , , ] , list ( v ) ) ", "answer": "v = divmod_iter_chunking ( , , )"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " \"\"\"\"\"\" import os , sys import errno try : import fcntl except ImportError : skip = \"\" else : from twisted . internet import fdesc from twisted . python . util import untilConcludes ", "answer": "from twisted . trial import unittest"}, {"prompt": " from __future__ import absolute_import , division , print_function , unicode_literals from django . contrib . admin . options import ModelAdmin , csrf_protect_m from django . contrib . admin . views . main import SEARCH_VAR , ChangeList from django . core . exceptions import PermissionDenied from django . core . paginator import InvalidPage , Paginator from django . shortcuts import render from django . utils . encoding import force_text from django . utils . translation import ungettext from haystack import connections from haystack . query import SearchQuerySet from haystack . utils import get_model_ct_tuple def list_max_show_all ( changelist ) : \"\"\"\"\"\" try : from django . contrib . admin . views . main import MAX_SHOW_ALL_ALLOWED return MAX_SHOW_ALL_ALLOWED except ImportError : return changelist . list_max_show_all class SearchChangeList ( ChangeList ) : def __init__ ( self , ** kwargs ) : self . haystack_connection = kwargs . pop ( '' , '' ) super ( SearchChangeList , self ) . __init__ ( ** kwargs ) def get_results ( self , request ) : if not SEARCH_VAR in request . GET : return super ( SearchChangeList , self ) . get_results ( request ) sqs = SearchQuerySet ( self . haystack_connection ) . models ( self . model ) . auto_query ( request . GET [ SEARCH_VAR ] ) . load_all ( ) paginator = Paginator ( sqs , self . list_per_page ) result_count = paginator . count full_result_count = SearchQuerySet ( self . haystack_connection ) . models ( self . model ) . all ( ) . count ( ) can_show_all = result_count <= list_max_show_all ( self ) multi_page = result_count > self . list_per_page try : result_list = paginator . page ( self . page_num + ) . object_list result_list = [ result . object for result in result_list ] except InvalidPage : result_list = ( ) self . result_count = result_count self . full_result_count = full_result_count self . result_list = result_list self . can_show_all = can_show_all self . multi_page = multi_page self . paginator = paginator class SearchModelAdminMixin ( object ) : haystack_connection = '' @ csrf_protect_m def changelist_view ( self , request , extra_context = None ) : if not self . has_change_permission ( request , None ) : raise PermissionDenied if not SEARCH_VAR in request . GET : return super ( SearchModelAdminMixin , self ) . changelist_view ( request , extra_context ) if not self . model in connections [ self . haystack_connection ] . get_unified_index ( ) . get_indexed_models ( ) : return super ( SearchModelAdminMixin , self ) . changelist_view ( request , extra_context ) list_display = list ( self . list_display ) kwargs = { '' : self . haystack_connection , '' : request , '' : self . model , '' : list_display , '' : self . list_display_links , '' : self . list_filter , '' : self . date_hierarchy , '' : self . search_fields , '' : self . list_select_related , '' : self . list_per_page , '' : self . list_editable , '' : self } if hasattr ( self , '' ) : kwargs [ '' ] = self . list_max_show_all changelist = SearchChangeList ( ** kwargs ) formset = changelist . formset = None media = self . media actions = self . get_actions ( request ) if actions : action_form = self . action_form ( auto_id = None ) action_form . fields [ '' ] . choices = self . get_action_choices ( request ) else : action_form = None selection_note = ungettext ( '' , '' , len ( changelist . result_list ) ) selection_note_all = ungettext ( '' , '' , changelist . result_count ) context = { '' : force_text ( self . model . _meta . verbose_name_plural ) , '' : selection_note % { '' : len ( changelist . result_list ) } , '' : selection_note_all % { '' : changelist . result_count } , '' : changelist . title , '' : changelist . is_popup , '' : changelist , '' : media , '' : self . has_add_permission ( request ) , '' : getattr ( self . admin_site , '' , None ) , '' : self . model . _meta . app_label , '' : action_form , '' : self . actions_on_top , '' : self . actions_on_bottom , '' : getattr ( self , '' , ) , } context . update ( extra_context or { } ) request . current_app = self . admin_site . name app_name , model_name = get_model_ct_tuple ( self . model ) return render ( request , self . change_list_template or [ '' % ( app_name , model_name ) , '' % app_name , '' ] , context ) ", "answer": "class SearchModelAdmin ( SearchModelAdminMixin , ModelAdmin ) :"}, {"prompt": " \"\"\"\"\"\" import os import subprocess import re import diamond . collector import diamond . convertor from diamond . collector import str_to_bool class AmavisCollector ( diamond . collector . Collector ) : matchers = [ re . compile ( r'' r'' ) , re . compile ( r'' r'' ) , re . compile ( r'' r'' r'' ) , re . compile ( r'' r'' r'' ) , ] def get_default_config_help ( self ) : config_help = super ( AmavisCollector , self ) . get_default_config_help ( ) config_help . update ( { '' : '' , '' : '' , '' : '' , '' : '' , } ) return config_help def get_default_config ( self ) : config = super ( AmavisCollector , self ) . get_default_config ( ) config . update ( { '' : '' , '' : '' , '' : False , '' : '' , '' : '' , } ) return config def collect ( self ) : \"\"\"\"\"\" try : if str_to_bool ( self . config [ '' ] ) : cmdline = [ self . config [ '' ] , '' , self . config [ '' ] , '' , self . config [ '' ] , '' , '' ] else : cmdline = [ self . config [ '' ] , '' , '' ] agent = subprocess . Popen ( cmdline , stdout = subprocess . PIPE ) agent_out = agent . communicate ( ) [ ] lines = agent_out . strip ( ) . split ( os . linesep ) for line in lines : for rex in self . matchers : res = rex . match ( line ) if res : groups = res . groupdict ( ) name = groups [ '' ] for metric , value in groups . items ( ) : if metric == '' : continue mtype = '' precision = if metric in ( '' , '' ) : mtype = '' precision = self . publish ( \"\" . format ( name , metric ) , value , metric_type = mtype , precision = precision ) except OSError as err : self . log . error ( \"\" , ", "answer": "self . config [ '' ] ,"}, {"prompt": " \"\"\"\"\"\" import numpy as np import multiprocessing as mp from time import time from . modules import make_hdf5 , _ireader , _iwriter , _prepare_fHH , _write_fHH from tables import open_file from . elm import ELM class HPELM ( ELM ) : \"\"\"\"\"\" def train ( self , fX , fT , * args , ** kwargs ) : \"\"\"\"\"\" X , T = self . _checkdata ( fX , fT ) self . _train_parse_args ( args , kwargs ) istart = icount = np . inf if \"\" in kwargs . keys ( ) : istart = max ( , int ( kwargs [ \"\" ] ) ) if \"\" in kwargs . keys ( ) : icount = kwargs [ \"\" ] self . add_data ( X , T , istart = istart , icount = icount ) self . nnet . solve ( ) def add_data ( self , fX , fT , istart = , icount = np . inf , fHH = None , fHT = None ) : \"\"\"\"\"\" assert len ( self . nnet . neurons ) > , \"\" X , T = self . _checkdata ( fX , fT ) N = X . shape [ ] ", "answer": "_prepare_fHH ( fHH , fHT , self . nnet , self . precision )"}, {"prompt": " from pyface . qt import QtCore , QtGui from traits . api import Bool , Dict , Enum , Instance , provides , Unicode from pyface . i_confirmation_dialog import IConfirmationDialog , MConfirmationDialog from pyface . constant import CANCEL , YES , NO from pyface . image_resource import ImageResource from . dialog import Dialog , _RESULT_MAP @ provides ( IConfirmationDialog ) class ConfirmationDialog ( MConfirmationDialog , Dialog ) : \"\"\"\"\"\" cancel = Bool ( False ) default = Enum ( NO , YES , CANCEL ) image = Instance ( ImageResource ) message = Unicode informative = Unicode detail = Unicode no_label = Unicode yes_label = Unicode _button_result_map = Dict ( ) def _create_contents ( self , parent ) : pass def _create_control ( self , parent ) : dlg = QtGui . QMessageBox ( parent ) dlg . setWindowTitle ( self . title ) dlg . setText ( self . message ) dlg . setInformativeText ( self . informative ) dlg . setDetailedText ( self . detail ) if self . image is None : dlg . setIcon ( QtGui . QMessageBox . Warning ) else : dlg . setIconPixmap ( self . image . create_image ( ) ) if self . yes_label : btn = dlg . addButton ( self . yes_label , QtGui . QMessageBox . YesRole ) else : btn = dlg . addButton ( QtGui . QMessageBox . Yes ) self . _button_result_map [ btn ] = YES ", "answer": "if self . default == YES :"}, {"prompt": " import logging from invoke import task import IPython from okcupyd import db from okcupyd import util from okcupyd . db import mailbox , model from okcupyd . user import User log = logging . getLogger ( __name__ ) ", "answer": "@ task ( default = True )"}, {"prompt": " from libsaas . services import base from . resource import GoogleCalendarResource class AclResource ( GoogleCalendarResource ) : path = '' class Acls ( AclResource ) : def update ( self , * args , ** kwargs ) : raise base . MethodNotSupported ( ) def patch ( self , * args , ** kwargs ) : raise base . MethodNotSupported ( ) def delete ( self , * args , ** kwargs ) : ", "answer": "raise base . MethodNotSupported ( )"}, {"prompt": " import re import unittest from django . contrib . gis . gdal import HAS_GDAL from django . db import connection from django . test import mock , skipUnlessDBFeature from django . utils import six from . utils import SpatialRefSys , oracle , postgis , spatialite test_srs = ( { '' : , '' : ( '' , True ) , '' : , '' : '' , '' : r'' , '' : '' , '' : '' , '' : True , '' : False , '' : True , '' : ( , , ) , '' : ( , , ) , '' : re . sub ( '' , '' , \"\"\"\"\"\" ) } , { '' : , '' : ( '' , False ) , '' : , '' : ( '' '' ) , ", "answer": "'' : r''"}, {"prompt": " import os import tempfile import unittest import mock ", "answer": "import numpy"}, {"prompt": " __author__ = '' Handler_mapping = { } def handler ( cmdid ) : '''''' def _module_dec ( cls ) : Handler_mapping [ cmdid ] = cls ", "answer": "return cls"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) ", "answer": "result . template = \"\""}, {"prompt": " from nailgun . extensions . network_manager . validators . json_schema import networks NOVA_NETWORK_SCHEMA = { '' : '' , '' : { '' : { '' : '' , '' : networks . NETWORK_META } , '' : { '' : '' } } , '' : [ '' , '' ] } ", "answer": "NEUTRON_SCHEMA = {"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from datetime import datetime from django . test import TestCase from mock import MagicMock from corehq . apps . users . dbaccessors . all_commcare_users import delete_all_users from corehq . apps . users . models import CommCareUser from corehq . apps . domain . models import Domain from corehq . apps . fixtures . models import UserFixtureStatus , UserFixtureType class TestFixtureStatus ( TestCase ) : def setUp ( self ) : self . _delete_everything ( ) self . username = \"\" password = \"\" self . domain = Domain ( name = '' ) self . domain . save ( ) self . couch_user = CommCareUser . create ( self . domain . name , self . username , password ) self . couch_user . save ( ) def tearDown ( self ) : self . _delete_everything ( ) def _delete_everything ( self ) : delete_all_users ( ) ", "answer": "UserFixtureStatus . objects . all ( ) . delete ( )"}, {"prompt": " import re import sys from datetime import datetime , timedelta from whoosh . compat import string_type , iteritems from whoosh . qparser import plugins , syntax from whoosh . qparser . taggers import Tagger from whoosh . support . relativedelta import relativedelta from whoosh . support . times import ( adatetime , timespan , fill_in , is_void , TimeError , relative_days ) from whoosh . util import rcompile class DateParseError ( Exception ) : \"\" def print_debug ( level , msg , * args ) : if level > : print ( ( \"\" * ( level - ) ) + ( msg % args ) ) class Props ( object ) : \"\"\"\"\"\" def __init__ ( self , ** args ) : self . __dict__ = args def __repr__ ( self ) : return repr ( self . __dict__ ) def get ( self , key , default = None ) : return self . __dict__ . get ( key , default ) class ParserBase ( object ) : \"\"\"\"\"\" def to_parser ( self , e ) : if isinstance ( e , string_type ) : return Regex ( e ) else : return e def parse ( self , text , dt , pos = , debug = - ) : raise NotImplementedError def date_from ( self , text , dt = None , pos = , debug = - ) : if dt is None : dt = datetime . now ( ) d , pos = self . parse ( text , dt , pos , debug + ) return d class MultiBase ( ParserBase ) : \"\"\"\"\"\" def __init__ ( self , elements , name = None ) : \"\"\"\"\"\" self . elements = [ self . to_parser ( e ) for e in elements ] self . name = name def __repr__ ( self ) : return \"\" % ( self . __class__ . __name__ , self . name or '' , self . elements ) class Sequence ( MultiBase ) : \"\"\"\"\"\" def __init__ ( self , elements , sep = \"\" , name = None , progressive = False ) : \"\"\"\"\"\" super ( Sequence , self ) . __init__ ( elements , name ) self . sep_pattern = sep if sep : self . sep_expr = rcompile ( sep , re . IGNORECASE ) else : self . sep_expr = None self . progressive = progressive def parse ( self , text , dt , pos = , debug = - ) : d = adatetime ( ) first = True foundall = False failed = False print_debug ( debug , \"\" , self . name , self . sep_pattern , text [ pos : ] ) for e in self . elements : print_debug ( debug , \"\" , self . name , text [ pos : ] ) if self . sep_expr and not first : print_debug ( debug , \"\" , self . name ) m = self . sep_expr . match ( text , pos ) if m : pos = m . end ( ) else : print_debug ( debug , \"\" , self . name ) break print_debug ( debug , \"\" , self . name , e , pos ) try : at , newpos = e . parse ( text , dt , pos = pos , debug = debug + ) except TimeError : failed = True break print_debug ( debug , \"\" , self . name , at ) if not at : break pos = newpos print_debug ( debug , \"\" , self . name , at , d ) try : d = fill_in ( d , at ) except TimeError : print_debug ( debug , \"\" , self . name ) failed = True break print_debug ( debug , \"\" , self . name , d ) first = False else : foundall = True if not failed and ( foundall or ( not first and self . progressive ) ) : print_debug ( debug , \"\" , self . name , d ) return ( d , pos ) else : print_debug ( debug , \"\" , self . name ) return ( None , None ) class Combo ( Sequence ) : \"\"\"\"\"\" def __init__ ( self , elements , fn = None , sep = \"\" , min = , max = , name = None ) : \"\"\"\"\"\" super ( Combo , self ) . __init__ ( elements , sep = sep , name = name ) self . fn = fn self . min = min self . max = max def parse ( self , text , dt , pos = , debug = - ) : dates = [ ] first = True print_debug ( debug , \"\" , self . name , self . sep_pattern , text [ pos : ] ) for e in self . elements : if self . sep_expr and not first : print_debug ( debug , \"\" , self . name , text [ pos : ] ) m = self . sep_expr . match ( text , pos ) if m : pos = m . end ( ) else : print_debug ( debug , \"\" , self . name ) return ( None , None ) print_debug ( debug , \"\" , self . name , e ) try : at , pos = e . parse ( text , dt , pos , debug + ) except TimeError : at , pos = None , None print_debug ( debug , \"\" , self . name , at ) if at is None : return ( None , None ) first = False if is_void ( at ) : continue if len ( dates ) == self . max : print_debug ( debug , \"\" , self . name , self . max ) return ( None , None ) dates . append ( at ) print_debug ( debug , \"\" , self . name , dates ) if len ( dates ) < self . min : print_debug ( debug , \"\" , self . name , self . min ) return ( None , None ) return ( self . dates_to_timespan ( dates ) , pos ) def dates_to_timespan ( self , dates ) : if self . fn : return self . fn ( dates ) elif len ( dates ) == : return timespan ( dates [ ] , dates [ ] ) else : raise DateParseError ( \"\" % ( dates , ) ) class Choice ( MultiBase ) : \"\"\"\"\"\" def parse ( self , text , dt , pos = , debug = - ) : print_debug ( debug , \"\" , self . name , text [ pos : ] ) for e in self . elements : print_debug ( debug , \"\" , self . name , e ) try : d , newpos = e . parse ( text , dt , pos , debug + ) except TimeError : d , newpos = None , None if d : print_debug ( debug , \"\" , self . name ) return ( d , newpos ) print_debug ( debug , \"\" , self . name ) return ( None , None ) class Bag ( MultiBase ) : \"\"\"\"\"\" def __init__ ( self , elements , sep = \"\" , onceper = True , requireall = False , allof = None , anyof = None , name = None ) : \"\"\"\"\"\" super ( Bag , self ) . __init__ ( elements , name ) self . sep_expr = rcompile ( sep , re . IGNORECASE ) self . onceper = onceper self . requireall = requireall self . allof = allof self . anyof = anyof def parse ( self , text , dt , pos = , debug = - ) : first = True d = adatetime ( ) seen = [ False ] * len ( self . elements ) while True : newpos = pos print_debug ( debug , \"\" , self . name , text [ pos : ] ) if not first : print_debug ( debug , \"\" , self . name ) m = self . sep_expr . match ( text , pos ) if m : newpos = m . end ( ) else : print_debug ( debug , \"\" , self . name ) break for i , e in enumerate ( self . elements ) : print_debug ( debug , \"\" , self . name , e ) try : at , xpos = e . parse ( text , dt , newpos , debug + ) except TimeError : at , xpos = None , None print_debug ( debug , \"\" , self . name , at ) if at : if self . onceper and seen [ i ] : return ( None , None ) d = fill_in ( d , at ) newpos = xpos seen [ i ] = True break else : break pos = newpos if self . onceper and all ( seen ) : break first = False if ( not any ( seen ) or ( self . allof and not all ( seen [ pos ] for pos in self . allof ) ) or ( self . anyof and not any ( seen [ pos ] for pos in self . anyof ) ) or ( self . requireall and not all ( seen ) ) ) : return ( None , None ) print_debug ( debug , \"\" , self . name , d ) return ( d , pos ) class Optional ( ParserBase ) : \"\"\"\"\"\" def __init__ ( self , element ) : self . element = self . to_parser ( element ) def __repr__ ( self ) : return \"\" % ( self . __class__ . __name__ , self . element ) def parse ( self , text , dt , pos = , debug = - ) : try : d , pos = self . element . parse ( text , dt , pos , debug + ) except TimeError : d , pos = None , None if d : return ( d , pos ) else : return ( adatetime ( ) , pos ) class ToEnd ( ParserBase ) : \"\"\"\"\"\" def __init__ ( self , element ) : self . element = element def __repr__ ( self ) : return \"\" % ( self . __class__ . __name__ , self . element ) def parse ( self , text , dt , pos = , debug = - ) : try : d , pos = self . element . parse ( text , dt , pos , debug + ) except TimeError : d , pos = None , None if d and pos == len ( text ) : return ( d , pos ) else : return ( None , None ) class Regex ( ParserBase ) : \"\"\"\"\"\" fn = None modify = None def __init__ ( self , pattern , fn = None , modify = None ) : self . pattern = pattern self . expr = rcompile ( pattern , re . IGNORECASE ) self . fn = fn self . modify = modify def __repr__ ( self ) : return \"\" % ( self . pattern , ) def parse ( self , text , dt , pos = , debug = - ) : m = self . expr . match ( text , pos ) if not m : return ( None , None ) props = self . extract ( m ) self . modify_props ( props ) try : d = self . props_to_date ( props , dt ) except TimeError : d = None if d : return ( d , m . end ( ) ) else : return ( None , None ) def extract ( self , match ) : d = match . groupdict ( ) for key , value in iteritems ( d ) : try : value = int ( value ) d [ key ] = value except ( ValueError , TypeError ) : pass return Props ( ** d ) def modify_props ( self , props ) : if self . modify : self . modify ( props ) def props_to_date ( self , props , dt ) : if self . fn : return self . fn ( props , dt ) else : args = { } for key in adatetime . units : args [ key ] = props . get ( key ) return adatetime ( ** args ) class Month ( Regex ) : def __init__ ( self , * patterns ) : self . patterns = patterns self . exprs = [ rcompile ( pat , re . IGNORECASE ) for pat in self . patterns ] self . pattern = ( \"\" + \"\" . join ( \"\" % pat for pat in self . patterns ) + \"\" ) self . expr = rcompile ( self . pattern , re . IGNORECASE ) def modify_props ( self , p ) : text = p . month for i , expr in enumerate ( self . exprs ) : m = expr . match ( text ) if m : p . month = i + break class PlusMinus ( Regex ) : def __init__ ( self , years , months , weeks , days , hours , minutes , seconds ) : rel_years = \"\" % years rel_months = \"\" % months rel_weeks = \"\" % weeks rel_days = \"\" % days rel_hours = \"\" % hours rel_mins = \"\" % minutes rel_secs = \"\" % seconds self . pattern = ( \"\" % ( rel_years , rel_months , rel_weeks , rel_days , rel_hours , rel_mins , rel_secs ) ) self . expr = rcompile ( self . pattern , re . IGNORECASE ) def props_to_date ( self , p , dt ) : if p . dir == \"\" : dir = - else : dir = delta = relativedelta ( years = ( p . get ( \"\" ) or ) * dir , months = ( p . get ( \"\" ) or ) * dir , weeks = ( p . get ( \"\" ) or ) * dir , days = ( p . get ( \"\" ) or ) * dir , hours = ( p . get ( \"\" ) or ) * dir , minutes = ( p . get ( \"\" ) or ) * dir , seconds = ( p . get ( \"\" ) or ) * dir ) return dt + delta class Daynames ( Regex ) : def __init__ ( self , next , last , daynames ) : self . next_pattern = next self . last_pattern = last self . _dayname_exprs = tuple ( rcompile ( pat , re . IGNORECASE ) for pat in daynames ) dn_pattern = \"\" . join ( daynames ) self . pattern = ( \"\" % ( next , last , dn_pattern ) ) self . expr = rcompile ( self . pattern , re . IGNORECASE ) def props_to_date ( self , p , dt ) : if re . match ( p . dir , self . last_pattern ) : dir = - else : dir = for daynum , expr in enumerate ( self . _dayname_exprs ) : m = expr . match ( p . day ) if m : break current_daynum = dt . weekday ( ) days_delta = relative_days ( current_daynum , daynum , dir ) d = dt . date ( ) + timedelta ( days = days_delta ) return adatetime ( year = d . year , month = d . month , day = d . day ) class Time12 ( Regex ) : def __init__ ( self ) : self . pattern = ( \"\" \"\" \"\" ) self . expr = rcompile ( self . pattern , re . IGNORECASE ) def props_to_date ( self , p , dt ) : isam = p . ampm . lower ( ) . startswith ( \"\" ) if p . hour == : if isam : hr = else : hr = else : hr = p . hour if not isam : hr += return adatetime ( hour = hr , minute = p . mins , second = p . secs , microsecond = p . usecs ) class DateParser ( object ) : \"\"\"\"\"\" day = Regex ( \"\" , lambda p , dt : adatetime ( day = p . day ) ) year = Regex ( \"\" , lambda p , dt : adatetime ( year = p . year ) ) time24 = Regex ( \"\" \"\" \"\" , lambda p , dt : adatetime ( hour = p . hour , minute = p . mins , second = p . secs , microsecond = p . usecs ) ) time12 = Time12 ( ) def __init__ ( self ) : simple_year = \"\" simple_month = \"\" simple_day = \"\" simple_hour = \"\" simple_minute = \"\" simple_second = \"\" simple_usec = \"\" tup = ( simple_year , simple_month , simple_day , simple_hour , simple_minute , simple_second , simple_usec ) simple_seq = Sequence ( tup , sep = \"\" , name = \"\" , progressive = True ) self . simple = Sequence ( ( simple_seq , \"\" ) , sep = '' ) self . setup ( ) def setup ( self ) : raise NotImplementedError def get_parser ( self ) : return self . all def parse ( self , text , dt , pos = , debug = - ) : parser = self . get_parser ( ) d , newpos = parser . parse ( text , dt , pos = pos , debug = debug ) if isinstance ( d , ( adatetime , timespan ) ) : d = d . disambiguated ( dt ) return ( d , newpos ) def date_from ( self , text , basedate = None , pos = , debug = - , toend = True ) : if basedate is None : basedate = datetime . utcnow ( ) parser = self . get_parser ( ) if toend : parser = ToEnd ( parser ) d = parser . date_from ( text , basedate , pos = pos , debug = debug ) if isinstance ( d , ( adatetime , timespan ) ) : d = d . disambiguated ( basedate ) return d class English ( DateParser ) : day = Regex ( \"\" , lambda p , dt : adatetime ( day = p . day ) ) def setup ( self ) : self . plusdate = PlusMinus ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) self . dayname = Daynames ( \"\" , \"\" , ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) ) midnight_l = lambda p , dt : adatetime ( hour = , minute = , second = , microsecond = ) midnight = Regex ( \"\" , midnight_l ) noon_l = lambda p , dt : adatetime ( hour = , minute = , second = , microsecond = ) noon = Regex ( \"\" , noon_l ) now = Regex ( \"\" , lambda p , dt : dt ) self . time = Choice ( ( self . time12 , self . time24 , midnight , noon , now ) , name = \"\" ) def tomorrow_to_date ( p , dt ) : d = dt . date ( ) + timedelta ( days = + ) return adatetime ( year = d . year , month = d . month , day = d . day ) tomorrow = Regex ( \"\" , tomorrow_to_date ) def yesterday_to_date ( p , dt ) : d = dt . date ( ) + timedelta ( days = - ) return adatetime ( year = d . year , month = d . month , day = d . day ) yesterday = Regex ( \"\" , yesterday_to_date ) thisyear = Regex ( \"\" , lambda p , dt : adatetime ( year = dt . year ) ) thismonth = Regex ( \"\" , lambda p , dt : adatetime ( year = dt . year , month = dt . month ) ) today = Regex ( \"\" , lambda p , dt : adatetime ( year = dt . year , month = dt . month , day = dt . day ) ) self . month = Month ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) self . dmy = Choice ( ( Sequence ( ( self . day , self . month , self . year ) , name = \"\" ) , Sequence ( ( self . month , self . day , self . year ) , name = \"\" ) , Sequence ( ( self . year , self . month , self . day ) , name = \"\" ) , Sequence ( ( self . year , self . day , self . month ) , name = \"\" ) , Sequence ( ( self . day , self . month ) , name = \"\" ) , Sequence ( ( self . month , self . day ) , name = \"\" ) , Sequence ( ( self . month , self . year ) , name = \"\" ) , self . month , self . year , self . dayname , tomorrow , yesterday , thisyear , thismonth , today , now , ) , name = \"\" ) self . datetime = Bag ( ( self . time , self . dmy ) , name = \"\" ) self . bundle = Choice ( ( self . plusdate , self . datetime , self . simple ) , name = \"\" ) self . torange = Combo ( ( self . bundle , \"\" , self . bundle ) , name = \"\" ) self . all = Choice ( ( self . torange , self . bundle ) , name = \"\" ) class DateParserPlugin ( plugins . Plugin ) : \"\"\"\"\"\" def __init__ ( self , basedate = None , dateparser = None , callback = None , free = False , free_expr = \"\" ) : \"\"\"\"\"\" self . basedate = basedate if dateparser is None : dateparser = English ( ) self . dateparser = dateparser self . callback = callback self . free = free self . freeexpr = free_expr def taggers ( self , parser ) : if self . free : return [ ( DateTagger ( self , self . freeexpr ) , - ) ] else : return ( ) def filters ( self , parser ) : return [ ( self . do_dates , ) ] def errorize ( self , message , node ) : if self . callback : self . callback ( message ) return syntax . ErrorNode ( message , node ) def text_to_dt ( self , node ) : text = node . text try : dt = self . dateparser . date_from ( text , self . basedate ) if dt is None : return self . errorize ( text , node ) else : n = DateTimeNode ( node . fieldname , dt , node . boost ) except DateParseError : e = sys . exc_info ( ) [ ] n = self . errorize ( e , node ) n . startchar = node . startchar n . endchar = node . endchar return n def range_to_dt ( self , node ) : start = end = None dp = self . dateparser . get_parser ( ) if node . start : start = dp . date_from ( node . start , self . basedate ) if start is None : return self . errorize ( node . start , node ) if node . end : end = dp . date_from ( node . end , self . basedate ) if end is None : return self . errorize ( node . end , node ) if start and end : ts = timespan ( start , end ) . disambiguated ( self . basedate ) start , end = ts . start , ts . end elif start : start = start . disambiguated ( self . basedate ) if isinstance ( start , timespan ) : start = start . start elif end : end = end . disambiguated ( self . basedate ) if isinstance ( end , timespan ) : end = end . end drn = DateRangeNode ( node . fieldname , start , end , boost = node . boost ) drn . startchar = node . startchar drn . endchar = node . endchar return drn def do_dates ( self , parser , group ) : schema = parser . schema if not schema : return group from whoosh . fields import DATETIME datefields = frozenset ( fieldname for fieldname , field in parser . schema . items ( ) if isinstance ( field , DATETIME ) ) for i , node in enumerate ( group ) : if node . has_fieldname : fname = node . fieldname or parser . fieldname else : fname = None if isinstance ( node , syntax . GroupNode ) : group [ i ] = self . do_dates ( parser , node ) elif fname in datefields : if node . has_text : group [ i ] = self . text_to_dt ( node ) elif isinstance ( node , syntax . RangeNode ) : group [ i ] = self . range_to_dt ( node ) return group class DateTimeNode ( syntax . SyntaxNode ) : has_fieldname = True has_boost = True def __init__ ( self , fieldname , dt , boost = ) : self . fieldname = fieldname self . dt = dt self . boost = def r ( self ) : return repr ( self . dt ) def query ( self , parser ) : from whoosh import query fieldname = self . fieldname or parser . fieldname field = parser . schema [ fieldname ] dt = self . dt if isinstance ( self . dt , datetime ) : return query . Term ( fieldname , field . to_text ( dt ) , boost = self . boost ) elif isinstance ( self . dt , timespan ) : ", "answer": "return query . DateRange ( fieldname , dt . start , dt . end ,"}, {"prompt": " from django . http import HttpResponse from django . views . generic import View class MockView ( View ) : ", "answer": "def get ( self , request , * args , ** kwargs ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import models from django . db . migrations . operations . base import Operation from django . db . migrations . state import ModelState from django . db . models . options import normalize_together from django . utils import six from django . utils . functional import cached_property from . fields import ( AddField , AlterField , FieldOperation , RemoveField , RenameField , ) def _check_for_duplicates ( arg_name , objs ) : used_vals = set ( ) for val in objs : if val in used_vals : raise ValueError ( \"\" % ( val , arg_name ) ) used_vals . add ( val ) class ModelOperation ( Operation ) : def __init__ ( self , name ) : self . name = name @ cached_property def name_lower ( self ) : return self . name . lower ( ) def references_model ( self , name , app_label = None ) : return name . lower ( ) == self . name_lower def reduce ( self , operation , in_between , app_label = None ) : return ( super ( ModelOperation , self ) . reduce ( operation , in_between , app_label = app_label ) or not operation . references_model ( self . name , app_label ) ) class CreateModel ( ModelOperation ) : \"\"\"\"\"\" serialization_expand_args = [ '' , '' , '' ] def __init__ ( self , name , fields , options = None , bases = None , managers = None ) : self . fields = fields self . options = options or { } self . bases = bases or ( models . Model , ) self . managers = managers or [ ] super ( CreateModel , self ) . __init__ ( name ) _check_for_duplicates ( '' , ( name for name , _ in self . fields ) ) _check_for_duplicates ( '' , ( base . _meta . label_lower if hasattr ( base , '' ) else base . lower ( ) if isinstance ( base , six . string_types ) else base for base in self . bases ) ) _check_for_duplicates ( '' , ( name for name , _ in self . managers ) ) def deconstruct ( self ) : kwargs = { '' : self . name , '' : self . fields , } if self . options : kwargs [ '' ] = self . options if self . bases and self . bases != ( models . Model , ) : kwargs [ '' ] = self . bases if self . managers and self . managers != [ ( '' , models . Manager ( ) ) ] : kwargs [ '' ] = self . managers return ( self . __class__ . __name__ , [ ] , kwargs ) def state_forwards ( self , app_label , state ) : state . add_model ( ModelState ( app_label , self . name , list ( self . fields ) , dict ( self . options ) , tuple ( self . bases ) , list ( self . managers ) , ) ) def database_forwards ( self , app_label , schema_editor , from_state , to_state ) : model = to_state . apps . get_model ( app_label , self . name ) if self . allow_migrate_model ( schema_editor . connection . alias , model ) : schema_editor . create_model ( model ) def database_backwards ( self , app_label , schema_editor , from_state , to_state ) : model = from_state . apps . get_model ( app_label , self . name ) if self . allow_migrate_model ( schema_editor . connection . alias , model ) : schema_editor . delete_model ( model ) def describe ( self ) : return \"\" % ( \"\" if self . options . get ( \"\" , False ) else \"\" , self . name ) def references_model ( self , name , app_label = None ) : strings_to_check = [ self . name ] for base in self . bases : if isinstance ( base , six . string_types ) : strings_to_check . append ( base . split ( \"\" ) [ - ] ) for fname , field in self . fields : if field . remote_field : if isinstance ( field . remote_field . model , six . string_types ) : strings_to_check . append ( field . remote_field . model . split ( \"\" ) [ - ] ) for string in strings_to_check : if string . lower ( ) == name . lower ( ) : return True return False def model_to_key ( self , model ) : \"\"\"\"\"\" if isinstance ( model , six . string_types ) : return model . split ( \"\" , ) else : return model . _meta . app_label , model . _meta . object_name def reduce ( self , operation , in_between , app_label = None ) : if ( isinstance ( operation , DeleteModel ) and self . name_lower == operation . name_lower and not self . options . get ( \"\" , False ) ) : return [ ] elif isinstance ( operation , RenameModel ) and self . name_lower == operation . old_name_lower : return [ CreateModel ( operation . new_name , fields = self . fields , options = self . options , bases = self . bases , managers = self . managers , ) , ] elif isinstance ( operation , FieldOperation ) and self . name_lower == operation . model_name_lower : if isinstance ( operation , AddField ) : if hasattr ( operation . field , \"\" ) and operation . field . remote_field : for between in in_between : app_label , object_name = self . model_to_key ( operation . field . remote_field . model ) if between . references_model ( object_name , app_label ) : return False if getattr ( operation . field . remote_field , \"\" , None ) : app_label , object_name = self . model_to_key ( operation . field . remote_field . through ) if between . references_model ( object_name , app_label ) : return False return [ CreateModel ( self . name , fields = self . fields + [ ( operation . name , operation . field ) ] , options = self . options , bases = self . bases , managers = self . managers , ) , ] elif isinstance ( operation , AlterField ) : return [ CreateModel ( self . name , fields = [ ( n , operation . field if n == operation . name else v ) for n , v in self . fields ] , options = self . options , bases = self . bases , managers = self . managers , ) , ] elif isinstance ( operation , RemoveField ) : return [ CreateModel ( self . name , fields = [ ( n , v ) for n , v in self . fields if n . lower ( ) != operation . name_lower ] , options = self . options , bases = self . bases , managers = self . managers , ) , ] elif isinstance ( operation , RenameField ) : return [ CreateModel ( self . name , fields = [ ( operation . new_name if n == operation . old_name else n , v ) for n , v in self . fields ] , options = self . options , bases = self . bases , managers = self . managers , ) , ] return super ( CreateModel , self ) . reduce ( operation , in_between , app_label = app_label ) class DeleteModel ( ModelOperation ) : \"\"\"\"\"\" def deconstruct ( self ) : kwargs = { '' : self . name , } return ( self . __class__ . __name__ , [ ] , kwargs ) def state_forwards ( self , app_label , state ) : state . remove_model ( app_label , self . name_lower ) def database_forwards ( self , app_label , schema_editor , from_state , to_state ) : model = from_state . apps . get_model ( app_label , self . name ) if self . allow_migrate_model ( schema_editor . connection . alias , model ) : schema_editor . delete_model ( model ) def database_backwards ( self , app_label , schema_editor , from_state , to_state ) : model = to_state . apps . get_model ( app_label , self . name ) if self . allow_migrate_model ( schema_editor . connection . alias , model ) : schema_editor . create_model ( model ) def describe ( self ) : return \"\" % ( self . name , ) class RenameModel ( ModelOperation ) : \"\"\"\"\"\" def __init__ ( self , old_name , new_name ) : self . old_name = old_name self . new_name = new_name super ( RenameModel , self ) . __init__ ( old_name ) @ cached_property def old_name_lower ( self ) : return self . old_name . lower ( ) @ cached_property def new_name_lower ( self ) : return self . new_name . lower ( ) def deconstruct ( self ) : kwargs = { '' : self . old_name , '' : self . new_name , } return ( self . __class__ . __name__ , [ ] , kwargs ) def state_forwards ( self , app_label , state ) : apps = state . apps model = apps . get_model ( app_label , self . old_name ) model . _meta . apps = apps all_related_objects = ( f for f in model . _meta . get_fields ( include_hidden = True ) if f . auto_created and not f . concrete and ( not f . hidden or f . many_to_many ) ) state . models [ app_label , self . new_name_lower ] = state . models [ app_label , self . old_name_lower ] state . models [ app_label , self . new_name_lower ] . name = self . new_name state . remove_model ( app_label , self . old_name_lower ) for related_object in all_related_objects : if related_object . model is not model : continue if related_object . related_model == model : related_key = ( app_label , self . new_name_lower ) else : related_key = ( related_object . related_model . _meta . app_label , related_object . related_model . _meta . model_name , ) new_fields = [ ] for name , field in state . models [ related_key ] . fields : if name == related_object . field . name : field = field . clone ( ) field . remote_field . model = \"\" % ( app_label , self . new_name ) new_fields . append ( ( name , field ) ) state . models [ related_key ] . fields = new_fields state . reload_model ( * related_key ) state . reload_model ( app_label , self . new_name_lower ) def database_forwards ( self , app_label , schema_editor , from_state , to_state ) : new_model = to_state . apps . get_model ( app_label , self . new_name ) if self . allow_migrate_model ( schema_editor . connection . alias , new_model ) : old_model = from_state . apps . get_model ( app_label , self . old_name ) ", "answer": "schema_editor . alter_db_table ("}, {"prompt": " import logbook from . utils import capturing_stderr_context , make_fake_mail_handler def test_custom_logger ( activation_strategy , logger ) : client_ip = '' class CustomLogger ( logbook . Logger ) : def process_record ( self , record ) : record . extra [ '' ] = client_ip custom_log = CustomLogger ( '' ) fmt = ( '' '' ) handler = logbook . TestHandler ( format_string = fmt ) assert handler . format_string == fmt with activation_strategy ( handler ) : custom_log . warn ( '' ) ", "answer": "logger . warn ( '' )"}, {"prompt": " from twisted . internet import defer , error , reactor from twisted . protocols import loopback from twisted . python import failure from twisted . trial import unittest from twirrdy import protocol from twirrdy . unittests import DummyCacheProtocol , DummyCacheServer class ProtocolTestCase ( unittest . TestCase ) : def setUp ( self ) : self . server = DummyCacheProtocol ( ) self . client = protocol . RRDCacheProtocol ( ) self . client . factory = self loopback . loopbackAsync ( self . server , self . client ) def tearDown ( self ) : def check ( result ) : self . assertIsInstance ( result , failure . Failure ) self . assertIsInstance ( result . value , error . ConnectionDone ) d = self . client . sendLine ( \"\" ) d . addBoth ( check ) return d def clientConnectionMade ( self , p ) : pass def testSimpleCommand ( self ) : d = self . client . sendLine ( \"\" ) d . addBoth ( lambda x : self . assertEquals ( x , \"\" ) ) return d def testStatCommand ( self ) : def check ( result ) : lines = result . split ( '' ) self . assertEquals ( lines [ ] , \"\" ) self . assertEquals ( len ( lines ) , ) d = self . client . sendLine ( \"\" ) d . addBoth ( check ) return d def testManyCommands ( self ) : dlist = [ ] for x in xrange ( ) : d = self . client . sendLine ( \"\" ) d . addBoth ( lambda x : self . assertEquals ( x , \"\" ) ) dlist . append ( d ) return defer . DeferredList ( dlist ) def testUnknownCommand ( self ) : def check ( result ) : self . assertIsInstance ( result , failure . Failure ) self . assertIsInstance ( result . value , protocol . RRDCacheError ) d = self . client . sendLine ( \"\" ) d . addBoth ( check ) return d def testManyUnknownCommands ( self ) : def check ( result ) : self . assertIsInstance ( result , failure . Failure ) self . assertIsInstance ( result . value , protocol . RRDCacheError ) dlist = [ ] for x in xrange ( ) : d = self . client . sendLine ( \"\" ) d . addBoth ( check ) dlist . append ( d ) return defer . DeferredList ( dlist ) class FactoryTestCase ( unittest . TestCase ) : def setUp ( self ) : ", "answer": "sock = self . mktemp ( )"}, {"prompt": " import transitfeed import agency ", "answer": "import fareattribute"}, {"prompt": " from django . conf . urls import patterns , url from testproject import views urlpatterns = patterns ( '' , ", "answer": "url ( r'' , views . test_view ) ,"}, {"prompt": " 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 = '' , callback = self . handle ) def _raise ( self , code , message ) : if self . log : self . log . error ( '' , code , message ) raise bottle . HTTPError ( code , message ) ", "answer": "def require_auth ( fn ) :"}, {"prompt": " import sys , re ", "answer": "import os"}, {"prompt": " from __future__ import unicode_literals from django . db . models import Sum from django . utils . functional import cached_property from django . utils . translation import ugettext_lazy as _ from django_fsm import transition from shop . models . delivery import DeliveryModel class PartialDeliveryWorkflowMixin ( object ) : \"\"\"\"\"\" TRANSITION_TARGETS = { '' : _ ( \"\" ) , '' : _ ( \"\" ) , ", "answer": "'' : _ ( \"\" ) ,"}, {"prompt": " \"\"\"\"\"\" import sys import webbrowser import argparse import duckduckgo def main ( ) : \"\"\"\"\"\" '' parser = argparse . ArgumentParser ( description = '' ) parser . add_argument ( '' , nargs = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , help = '' ) args = parser . parse_args ( ) '' if args . query : queries = [ '' . join ( args . query ) ] elif not sys . stdin . isatty ( ) : queries = sys . stdin . read ( ) . splitlines ( ) else : parser . print_help ( ) return '' prefix = '' if args . search else '' if args . bang else '' '' for query in queries : '' query = prefix + query '' results = duckduckgo . search ( query ) '' if not results : continue '' if args . json : print_result ( results . json ) continue '' ", "answer": "results_priority = get_results_priority ( args )"}, {"prompt": " import argparse from tornado . ioloop import IOLoop from tornado . wsgi import WSGIContainer from tornado . httpserver import HTTPServer from werkzeug . serving import run_simple from osrc import create_app if __name__ == \"\" : parser = argparse . ArgumentParser ( ) parser . add_argument ( \"\" , \"\" , default = , type = int , help = \"\" ) parser . add_argument ( \"\" , \"\" , action = \"\" , help = \"\" ) parser . add_argument ( \"\" , \"\" , default = None , ", "answer": "help = \"\" )"}, {"prompt": " import re import uuid import collections try : from urllib . parse import unquote except ImportError : from urllib import unquote try : import asyncio from asyncio . queues import Queue except ImportError : import trollius as asyncio from trollius . queues import Queue try : from configparser import ConfigParser except ImportError : from ConfigParser import ConfigParser EOL = '' re_code = re . compile ( r'' ) re_kv = re . compile ( r'' ) def parse_agi_result ( line ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import os import logging import logging . config import yaml from helion_configurationprocessor . cp . model . v2_0 . HlmPaths import HlmPaths from helion_configurationprocessor . cp . model . v2_0 . CloudModel import CloudModel from helion_configurationprocessor . cp . model . v2_0 import ServerState from helion_configurationprocessor . cp . model . BuilderPlugin import BuilderPlugin from helion_configurationprocessor . cp . model . BuilderPlugin import ArtifactMode from helion_configurationprocessor . cp . model . CPLogging import CPLogging as KenLog LOG = logging . getLogger ( __name__ ) class ServerInfoBuilder ( BuilderPlugin ) : def __init__ ( self , instructions , models , controllers ) : super ( ServerInfoBuilder , self ) . __init__ ( , instructions , models , controllers , '' ) LOG . info ( '' % KenLog . fcn ( ) ) self . cloud_desc = self . _models [ '' ] [ '' ] self . _file_path = HlmPaths . get_output_path ( self . _instructions , self . cloud_desc ) self . _cloud_model = self . _models [ '' ] self . _cloud_version = CloudModel . version ( self . _cloud_model , self . _version ) self . _cloud_internal = CloudModel . internal ( self . _cloud_model ) HlmPaths . make_path ( self . _file_path ) def build ( self ) : LOG . info ( '' % KenLog . fcn ( ) ) servers = CloudModel . get ( self . _cloud_internal , '' ) server_info = { } for server in servers : server_info [ server [ '' ] ] = { } data = server_info [ server [ '' ] ] data [ '' ] = server [ '' ] if server [ '' ] == ServerState . ALLOCATED : data [ '' ] = server [ '' ] data [ '' ] = server [ '' ] net_info = { } for if_name , if_data in server [ '' ] . iteritems ( ) : net_info [ if_name ] = { } for net_name , net_data in if_data [ '' ] . iteritems ( ) : net_info [ if_name ] [ net_name ] = { '' : net_data . get ( '' ) , '' : net_data . get ( '' ) , '' : net_data . get ( '' , True ) } data [ '' ] = net_info ", "answer": "filename = \"\" % ("}, {"prompt": " import os import atexit import subprocess process = subprocess . Popen ( ", "answer": "args = ( '' , os . path . join ( os . path . dirname ( __file__ ) , '' ) , ) ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Creature ( )"}, {"prompt": " from uuid import uuid4 from urllib import quote from changes . constants import Cause , Result from changes . testutils import APITestCase class ProjectBuildListTest ( APITestCase ) : def test_simple ( self ) : fake_project_id = uuid4 ( ) project = self . create_project ( ) self . create_build ( project ) project1 = self . create_project ( ) build1 = self . create_build ( project1 , label = '' , target = '' , result = Result . passed ) project2 = self . create_project ( ) build2 = self . create_build ( project2 , label = '' , target = '' , tags = [ '' ] , result = Result . failed ) path = '' . format ( fake_project_id . hex ) resp = self . client . get ( path ) assert resp . status_code == path = '' . format ( project1 . id . hex ) resp = self . client . get ( path ) assert resp . status_code == data = self . unserialize ( resp ) assert len ( data ) == assert data [ ] [ '' ] == build1 . id . hex resp = self . client . get ( path + '' ) assert resp . status_code == data = self . unserialize ( resp ) assert len ( data ) == assert data [ ] [ '' ] == build1 . id . hex resp = self . client . get ( path + '' ) assert resp . status_code == data = self . unserialize ( resp ) assert len ( data ) == assert data [ ] [ '' ] == build1 . id . hex resp = self . client . get ( path + '' ) assert resp . status_code == data = self . unserialize ( resp ) assert len ( data ) == assert data [ ] [ '' ] == build1 . id . hex resp = self . client . get ( path + '' ) assert resp . status_code == data = self . unserialize ( resp ) assert len ( data ) == resp = self . client . get ( path ) assert resp . status_code == data = self . unserialize ( resp ) assert len ( data ) == assert data [ ] [ '' ] == build1 . id . hex path = '' . format ( project2 . id . hex ) resp = self . client . get ( path + '' ) assert resp . status_code == data = self . unserialize ( resp ) assert len ( data ) == assert data [ ] [ '' ] == build2 . id . hex resp = self . client . get ( path + '' ) assert resp . status_code == data = self . unserialize ( resp ) assert len ( data ) == build3 = self . create_build ( project2 , label = '' , target = '' , tags = [ '' ] , result = Result . failed ) resp = self . client . get ( path + '' ) assert resp . status_code == data = self . unserialize ( resp ) assert len ( data ) == assert data [ ] [ '' ] == build2 . id . hex resp = self . client . get ( path + '' ) ", "answer": "assert resp . status_code == "}, {"prompt": " import unittest from . mock import MagicMock , Mock from . util import TrelloElementMock , CommandMock , OperationMock from operations import * class BaseOperationTests ( unittest . TestCase ) : def setUp ( self ) : self . base_operation , self . trello_element = OperationMock . create ( BaseOperation ) self . class_mock , self . instance_mock = OperationMock . instance ( self . base_operation ) self . collection = TrelloElementMock . collection ( ) self . base_operation . collection = TrelloCollection ( self . collection ) def test_items_sets_the_collection ( self ) : self . base_operation . set_collection = MagicMock ( ) self . base_operation . items ( ) ", "answer": "self . base_operation . set_collection . assert_called_with ( )"}, {"prompt": " import datetime import cassiopeia . riotapi import cassiopeia . dto . matchlistapi ", "answer": "import cassiopeia . core . requests"}, {"prompt": " from __future__ import absolute_import __version__ = \"\" try : from __builtin__ import basestring except ImportError : basestring = str class _ArrayType ( object ) : is_array = True subtypes = [ '' ] def __init__ ( self , dtype , ndim , is_c_contig = False , is_f_contig = False , inner_contig = False , broadcasting = None ) : self . dtype = dtype self . ndim = ndim self . is_c_contig = is_c_contig self . is_f_contig = is_f_contig self . inner_contig = inner_contig or is_c_contig or is_f_contig self . broadcasting = broadcasting def __repr__ ( self ) : axes = [ \"\" ] * self . ndim if self . is_c_contig : axes [ - ] = \"\" elif self . is_f_contig : axes [ ] = \"\" return \"\" % ( self . dtype , \"\" . join ( axes ) ) def index_type ( base_type , item ) : \"\"\"\"\"\" class InvalidTypeSpecification ( Exception ) : pass def verify_slice ( s ) : if s . start or s . stop or s . step not in ( None , ) : raise InvalidTypeSpecification ( \"\" \"\" ) if isinstance ( item , tuple ) : step_idx = None for idx , s in enumerate ( item ) : verify_slice ( s ) if s . step and ( step_idx or idx not in ( , len ( item ) - ) ) : raise InvalidTypeSpecification ( \"\" \"\" ) if s . step == : step_idx = idx return _ArrayType ( base_type , len ( item ) , is_c_contig = step_idx == len ( item ) - , is_f_contig = step_idx == ) elif isinstance ( item , slice ) : verify_slice ( item ) return _ArrayType ( base_type , , is_c_contig = bool ( item . step ) ) else : assert int ( item ) == item array ( base_type , item ) compiled = False _Unspecified = object ( ) def _empty_decorator ( x ) : return x def locals ( ** arg_types ) : return _empty_decorator def test_assert_path_exists ( * paths ) : return _empty_decorator def test_fail_if_path_exists ( * paths ) : return _empty_decorator class _EmptyDecoratorAndManager ( object ) : def __call__ ( self , x ) : return x def __enter__ ( self ) : pass def __exit__ ( self , exc_type , exc_value , traceback ) : pass class _Optimization ( object ) : pass cclass = ccall = cfunc = _EmptyDecoratorAndManager ( ) returns = wraparound = boundscheck = initializedcheck = nonecheck = overflowcheck = embedsignature = cdivision = cdivision_warnings = always_allows_keywords = profile = linetrace = infer_type = unraisable_tracebacks = freelist = lambda arg : _EmptyDecoratorAndManager ( ) optimization = _Optimization ( ) overflowcheck . fold = optimization . use_switch = optimization . unpack_method_calls = lambda arg : _EmptyDecoratorAndManager ( ) final = internal = type_version_tag = no_gc_clear = _empty_decorator def inline ( f , * args , ** kwds ) : if isinstance ( f , basestring ) : from Cython . Build . Inline import cython_inline return cython_inline ( f , * args , ** kwds ) else : assert len ( args ) == len ( kwds ) == return f def compile ( f ) : from Cython . Build . Inline import RuntimeCompiledFunction return RuntimeCompiledFunction ( f ) def cdiv ( a , b ) : q = a / b if q < : q += def cmod ( a , b ) : r = a % b if ( a * b ) < : r -= b return r def cast ( type , * args , ** kwargs ) : kwargs . pop ( '' , None ) assert not kwargs if hasattr ( type , '' ) : return type ( * args ) else : return args [ ] def sizeof ( arg ) : return def typeof ( arg ) : return arg . __class__ . __name__ def address ( arg ) : return pointer ( type ( arg ) ) ( [ arg ] ) ", "answer": "def declare ( type = None , value = _Unspecified , ** kwds ) :"}, {"prompt": " from robot . libraries import BuiltIn from keywordgroup import KeywordGroup BUILTIN = BuiltIn . BuiltIn ( ) class RunOnFailure ( KeywordGroup ) : def __init__ ( self ) : self . _run_on_failure_keyword = None self . _running_on_failure_routine = False def register_keyword_to_run_on_failure ( self , keyword ) : \"\"\"\"\"\" print keyword old_keyword = self . _run_on_failure_keyword old_keyword_text = old_keyword if old_keyword is not None else \"\" new_keyword = keyword if keyword . strip ( ) . lower ( ) != \"\" else None new_keyword_text = new_keyword if new_keyword is not None else \"\" self . _run_on_failure_keyword = new_keyword self . _info ( '' % new_keyword_text ) return old_keyword_text ", "answer": "def _run_on_failure ( self ) :"}, {"prompt": " \"\"\"\"\"\" import base64 from cafe . drivers . unittest . decorators import tags from cloudcafe . common . tools . datagen import rand_name from cloudcafe . compute . common . types import NovaServerStatusTypes ", "answer": "from cloudroast . compute . fixtures import ComputeFixture"}, {"prompt": " import django . dispatch ", "answer": "confirm_sanity_check = django . dispatch . Signal ( )"}, {"prompt": " from collections import namedtuple import datetime import os import sys import xlrd def banner_str ( s ) : return ( \"\" % s ) . center ( BANNER_PADDING , '' ) BANNER_PADDING = PROFILE_OUTPUT_FILE_HEADER_MAGIC = '' % ( '' * BANNER_PADDING , banner_str ( '' ) , '' * BANNER_PADDING , ) PROFILE_OUTPUT_FILE_HEADER_FMT = '''''' % PROFILE_OUTPUT_FILE_HEADER_MAGIC Field = namedtuple ( '' , ( '' , '' , '' , '' , '' ) ) DynamicField = namedtuple ( '' , ( '' , '' , '' , '' , '' , '' ) ) Type = namedtuple ( '' , ( '' , '' , '' ) ) TypeValue = namedtuple ( '' , ( '' , '' ) ) SpecialFunctionType = namedtuple ( '' , ( '' , '' , '' ) ) FIELD_BASE_TYPES = { '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , } SPECIAL_TYPES = { '' : SpecialFunctionType ( '' , '' , None ) , '' : SpecialFunctionType ( '' , '' , None ) , } SPECIAL_TYPES_IN_TYPES_SPREADSHEET = { '' : SpecialFunctionType ( '' , '' , None ) , '' : SpecialFunctionType ( '' , '' , None ) , '' : SpecialFunctionType ( '' , '' , None ) , '' : SpecialFunctionType ( '' , '' , None ) , } SPECIAL_TYPES_ALL = dict ( SPECIAL_TYPES . items ( ) + SPECIAL_TYPES_IN_TYPES_SPREADSHEET . items ( ) ) if len ( sys . argv ) <= or not os . path . exists ( sys . argv [ ] ) : print \"\" % os . path . basename ( sys . argv [ ] ) sys . exit ( ) profile_xls_filename = sys . argv [ ] workbook = xlrd . open_workbook ( profile_xls_filename ) write_buffer = \"\" def write ( s ) : global write_buffer write_buffer += str ( s ) def writeln ( s = '' ) : write ( str ( s ) + \"\" ) def parse_types ( ) : types_sheet = workbook . sheet_by_name ( '' ) types = { } for row in range ( , types_sheet . nrows ) : row_values = [ str ( v ) . strip ( ) if isinstance ( v , ( str , unicode ) ) else v for v in types_sheet . row_values ( row , end_colx = ) ] if not any ( row_values ) : continue possible_type_name , possible_base_type , name , value = row_values if possible_type_name : type_name = possible_type_name base_type = possible_base_type if possible_type_name : types [ type_name ] = Type ( type_name , base_type , { } ) elif name : if '' in base_type or base_type == '' : if type ( value ) == float and value % == : value = int ( value ) types [ type_name ] . values [ value ] = TypeValue ( name , value ) types . update ( SPECIAL_TYPES ) for value in [ v . value for v in types [ '' ] . values . copy ( ) . itervalues ( ) if v . name in ( '' , '' ) ] : del types [ '' ] . values [ value ] return types def parse_fields ( ) : messages_sheet = workbook . sheet_by_name ( '' ) fields = { } last_field = None last_f_def_num = None for row in range ( , messages_sheet . nrows ) : row_values = [ str ( v ) . strip ( ) if isinstance ( v , ( str , unicode ) ) else v for v in messages_sheet . row_values ( row , end_colx = ) ] if not any ( row_values ) : continue if not any ( row_values [ : ] ) and row_values [ ] : continue possible_message_name , f_def_num , f_name , f_type = row_values if possible_message_name : message_name = possible_message_name fields [ message_name ] = { } else : if not ( message_name and f_name and f_type ) : pass else : is_dynamic_field = False try : f_def_num = int ( f_def_num ) except ValueError : is_dynamic_field = True if not isinstance ( last_field , DynamicField ) : last_field = DynamicField ( * ( tuple ( last_field ) + ( { } , ) ) ) fields [ message_name ] [ last_f_def_num ] = last_field ref_field_names = [ str ( n ) . strip ( ) for n in messages_sheet . row_values ( row ) [ ] . split ( '' ) ] ref_field_values = [ str ( n ) . strip ( ) for n in messages_sheet . row_values ( row ) [ ] . split ( '' ) ] if len ( ref_field_names ) != len ( ref_field_values ) : raise Exception ( \"\" % f_name ) try : f_scale = int ( messages_sheet . row_values ( row ) [ ] ) if f_scale == : raise ValueError except ValueError : f_scale = None try : f_offset = int ( messages_sheet . row_values ( row ) [ ] ) except ValueError : f_offset = None f_units = str ( messages_sheet . row_values ( row ) [ ] ) . strip ( ) if not f_units : f_units = None field = Field ( f_name , f_type , f_scale , f_units , f_offset ) if is_dynamic_field : for i in range ( len ( ref_field_names ) ) : last_field . possibilities . setdefault ( ref_field_names [ i ] , { } ) [ ref_field_values [ i ] ] = field else : fields [ message_name ] [ f_def_num ] = field last_field = field last_f_def_num = f_def_num event = fields [ '' ] for k , v in event . iteritems ( ) : if v . name == '' : data_num = k elif v . name == '' : data16_num = k try : event [ data16_num ] = DynamicField ( * tuple ( event [ data16_num ] + ( event [ data_num ] . possibilities . copy ( ) , ) ) ) except NameError : raise Exception ( \"\" ) return fields def autogen_python ( types , fields ) : global write_buffer functions = { } writeln ( \"\" % banner_str ( '' ) ) for _ , type in sorted ( types . iteritems ( ) ) : write ( \"\" % ( repr ( type . name ) , FIELD_BASE_TYPES [ type . base_type ] ) ) if type . name in SPECIAL_TYPES_ALL : special_type = SPECIAL_TYPES_ALL [ type . name ] if type . base_type != special_type . base_type : raise Exception ( \"\" % type . name ) func_name = special_type . func_name ", "answer": "if not special_type . func_name :"}, {"prompt": " import json import pytest import requests from datetime import datetime , timedelta from . fixtures import tornado_server , tornado_app , sample_data1_server from . util import ( assert_error , assert_success , assert_created , assert_deleted , Client ) def test_malformed ( sample_data1_server ) : client = sample_data1_server assert_error ( client . post ( \"\" , data = \"\" ) , ) def test_creation ( sample_data1_server ) : client = sample_data1_server assert_success ( client . get ( \"\" ) , { \"\" : , \"\" : , \"\" : } , strip = [ \"\" , \"\" ] ) assert_success ( client . get ( \"\" ) , { \"\" : , \"\" : , \"\" : , \"\" : [ ] } ) assert_success ( client . get ( \"\" ) , { \"\" : , \"\" : , \"\" : , \"\" : [ ] } ) target_time = datetime . utcnow ( ) + timedelta ( days = ) assert_created ( client . create ( \"\" , creator = \"\" , fateId = , targetTime = str ( target_time ) , description = \"\" , hostnames = [ \"\" , \"\" , \"\" ] ) , \"\" ) assert_success ( client . get ( \"\" ) , { \"\" : , \"\" : , \"\" : , \"\" : [ { \"\" : None , \"\" : None , \"\" : , \"\" : None , \"\" : None , \"\" : , \"\" : str ( target_time ) , \"\" : , \"\" : True , \"\" : False , \"\" : , \"\" : None , \"\" : } , { \"\" : None , \"\" : None , \"\" : None , \"\" : , \"\" : str ( target_time ) , \"\" : , \"\" : True , \"\" : False , \"\" : , \"\" : None , \"\" : , \"\" : None , \"\" : } , { \"\" : None , \"\" : None , \"\" : None , \"\" : , \"\" : str ( target_time ) , \"\" : , \"\" : True , \"\" : False , \"\" : , \"\" : None , \"\" : , \"\" : None , \"\" : } ] , } , strip = [ \"\" , \"\" ] ) def test_update ( sample_data1_server ) : client = sample_data1_server assert_created ( client . create ( \"\" , creator = \"\" , fateId = , description = \"\" , hostnames = [ \"\" , \"\" , \"\" ] ) , \"\" ) assert_success ( client . get ( \"\" ) , { \"\" : , \"\" : , \"\" : } , strip = [ \"\" , \"\" ] ) assert_created ( client . create ( \"\" , hostname = \"\" , user = \"\" , eventTypeId = , note = \"\" ) , \"\" ) assert_success ( client . get ( \"\" ) , { \"\" : None , \"\" : None , \"\" : None , \"\" : None , \"\" : , \"\" : , \"\" : True , \"\" : False , \"\" : , \"\" : None , \"\" : , \"\" : None , \"\" : None } , strip = [ \"\" ] ) response = client . update ( \"\" , ackUser = \"\" , questId = ) assert_success ( response , { \"\" : \"\" , \"\" : None , \"\" : None , \"\" : , \"\" : None , \"\" : , \"\" : , \"\" : None , \"\" : True , \"\" : False , \"\" : , \"\" : None , \"\" : } , strip = [ \"\" , \"\" ] ) assert response . json ( ) [ '' ] is not None def test_labor_filter_by_eventttype ( sample_data1_server ) : client = sample_data1_server assert_success ( client . get ( \"\" ) , { \"\" : , \"\" : , \"\" : , \"\" : [ ] } ) ", "answer": "assert_created ("}, {"prompt": " import re from datetime import datetime import os import time import subprocess from ajenti . api import * from ajenti . plugins . main . api import SectionPlugin from ajenti . plugins . services . api import ServiceMultiplexor from ajenti . ui import on from ajenti . ui . binder import Binder from ajenti . util import platform_select from reconfigure . configs . base import Reconfig from reconfigure . parsers import SSVParser from reconfigure . builders import BoundBuilder from reconfigure . nodes import Node , PropertyNode from reconfigure . items . bound import BoundData open_ntpd_conf = '' ntpd_conf = '' def isopenntpd ( ) : return not ServiceMultiplexor . get ( ) . get_one ( '' ) is None class NTPDData ( BoundData ) : pass class ServerData ( BoundData ) : def template ( self ) : return Node ( '' , Node ( '' , PropertyNode ( '' , '' ) ) , Node ( '' , PropertyNode ( '' , '' ) ) , ) NTPDData . bind_collection ( '' , selector = lambda x : x . children [ ] . get ( '' ) . value == '' , item_class = ServerData ) ServerData . bind_property ( '' , '' , path = lambda x : x . children [ ] ) class NTPDConfig ( Reconfig ) : def __init__ ( self , ** kwargs ) : k = { '' : SSVParser ( ) , '' : BoundBuilder ( NTPDData ) , } k . update ( kwargs ) Reconfig . __init__ ( self , ** k ) @ plugin class NTPDPlugin ( SectionPlugin ) : def get_tz_debian ( self ) : return open ( '' ) . read ( ) . strip ( ) def get_tz_nondebian ( self ) : return os . path . realpath ( '' ) [ len ( '' ) : ] if os . path . islink ( '' ) else '' def set_tz_debian ( self , timezone ) : open ( '' , '' ) . write ( timezone + '' ) def set_tz_nondebian ( self , timezone ) : tz = os . path . join ( '' , timezone ) if os . path . exists ( '' ) : os . unlink ( '' ) os . symlink ( tz , '' ) openntpd = isopenntpd ( ) service_name = platform_select ( default = '' if openntpd else '' , centos = '' if openntpd else '' , mageia = '' , ) get_tz = platform_select ( debian = get_tz_debian , default = get_tz_nondebian , ) set_tz = platform_select ( debian = set_tz_debian , default = set_tz_nondebian , ) def init ( self ) : self . title = _ ( '' ) self . icon = '' self . category = _ ( '' ) self . append ( self . ui . inflate ( '' ) ) self . find ( '' ) . name = self . service_name self . find ( '' ) . reload ( ) self . config = NTPDConfig ( path = platform_select ( default = open_ntpd_conf if self . openntpd else ntpd_conf , centos = '' if self . openntpd else ntpd_conf , freebsd = '' if self . openntpd else ntpd_conf , ) ) self . binder = Binder ( None , self ) self . available_zones = [ ] for d , dirs , files in os . walk ( '' , followlinks = False ) : for f in files : if f != '' : self . available_zones . append ( os . path . join ( d , f ) ) self . available_zones = [ x [ len ( '' ) : ] for x in self . available_zones ] self . available_zones . sort ( ) self . find ( '' ) . new_item = lambda c : ServerData ( ) def on_page_load ( self ) : self . refresh ( ) def refresh ( self ) : self . config . load ( ) self . now = int ( time . time ( ) ) self . timezone = self . get_tz ( ) self . binder . setup ( self ) . populate ( ) @ on ( '' , '' ) def on_set ( self ) : ", "answer": "self . binder . update ( )"}, {"prompt": " from __future__ import print_function import argparse import signal import sys from thrift . protocol . TBinaryProtocol import TBinaryProtocol from thrift . protocol . TCompactProtocol import TCompactProtocol from thrift . protocol . TJSONProtocol import TJSONProtocol from . message_sniffer import MessageSnifferOptions , MessageSniffer from . printer import FormatOptions , LatencyPrinter , PairedPrinter , Printer VALID_PROTOCOLS = '' def get_flags ( ) : p = argparse . ArgumentParser ( formatter_class = argparse . ArgumentDefaultsHelpFormatter ) p . add_argument ( '' , type = str , default = '' , metavar = '' , help = '' ) p . add_argument ( '' , type = int , default = , metavar = '' , help = '' ) p . add_argument ( '' , type = int , default = * , metavar = '' , help = '' ) p . add_argument ( '' , type = int , default = * , help = '' ) p . add_argument ( '' , type = str , nargs = '' , help = '' ) p . add_argument ( '' , default = False , action = '' , help = '' '' ) p . add_argument ( '' , type = str , default = '' , help = '' ) p . add_argument ( '' , default = False , action = '' , help = '' ) p . add_argument ( '' , type = str , default = '' , help = '' % VALID_PROTOCOLS ) cmds = p . add_subparsers ( dest = '' ) dump = cmds . add_parser ( '' ) dump . add_argument ( '' , default = False , action = '' , ", "answer": "help = '' )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import re from pysb import * import pysb . bng import pysb . examples . earm_1_0 Model ( base = pysb . examples . earm_1_0 . model ) Annotation ( model , '' , '' ) Bcl2c . rename ( '' ) Bcl2c_0 . rename ( '' ) inhibit_tBid_by_Bcl2c . rename ( '' ) Parameter ( '' , ) Rule ( '' , DISC ( b = None ) >> L ( b = None ) + pR ( b = None ) , kf31 ) pR_0 . value = flip_0 . value = pC8_0 . value = Bid_0 . value = Bax_0 . value = Bcl2_0 . value = v = kr1 . value = kc1 . value = kf3 . value = kf6 . value = kf7 . value = kr9 . value = kc9 . value = kr13 . value = kf14 . value = / v kf15 . value = * / v kf16 . value = / v kf17 . value = * / v kf18 . value = / v kf19 . value = / v kf20 . value = / v kf21 . value = / v kf22 . value = kf26 . value = pysb . bng . generate_equations ( model ) all_species = list ( model . species ) model . reset_equations ( ) def synthesize ( name , species , ks ) : \"\"\"\"\"\" ", "answer": "Rule ( name , None >> species , ks )"}, {"prompt": " from . . excel_comparsion_test import ExcelComparisonTest from ... workbook import Workbook class TestCompareXLSXFiles ( ExcelComparisonTest ) : \"\"\"\"\"\" def setUp ( self ) : self . maxDiff = None filename = '' test_dir = '' self . got_filename = test_dir + '' + filename self . exp_filename = test_dir + '' + filename self . ignore_files = [ ] ", "answer": "self . ignore_elements = { }"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from rally import consts class Credential ( object ) : def __init__ ( self , auth_url , username , password , tenant_name = None , permission = consts . EndpointPermission . USER , region_name = None , endpoint_type = consts . EndpointType . PUBLIC , domain_name = None , endpoint = None , user_domain_name = \"\" , admin_domain_name = \"\" , project_domain_name = \"\" , https_insecure = False , https_cacert = None ) : self . auth_url = auth_url self . username = username self . password = password self . tenant_name = tenant_name self . permission = permission self . region_name = region_name self . endpoint_type = endpoint_type self . domain_name = domain_name self . user_domain_name = user_domain_name self . admin_domain_name = admin_domain_name self . project_domain_name = project_domain_name self . endpoint = endpoint self . insecure = https_insecure ", "answer": "self . cacert = https_cacert"}, {"prompt": " from django . contrib import admin ", "answer": "from emaillist . models import EmailAddress"}, {"prompt": " import os import sys from distutils . util import convert_path try : from setuptools import setup except ImportError : from distutils . core import setup sys . path . append ( os . getcwd ( ) ) main_ = { } ver_path = convert_path ( '' ) with open ( ver_path ) as f : for line in f : if line . startswith ( '' ) : exec ( line , main_ ) setup ( name = '' , description = '' , version = main_ [ '' ] , classifiers = [ '' , '' , '' , '' , '' ] , packages = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] , install_requires = [ '' , '' , '' , '' , '' ] , ", "answer": "author = '' ,"}, {"prompt": " from lib . action import TravisCI class ListHooksAction ( TravisCI ) : def run ( self ) : \"\"\"\"\"\" path = '' response = self . _perform_request ( path , method = '' , requires_auth = True ) data = response . json ( ) hooks = { } for hook in data [ '' ] : ", "answer": "hooks [ hook [ '' ] ] = [ hook [ '' ] , hook [ '' ] ]"}, {"prompt": " \"\"\"\"\"\" import subprocess import shlex RUN_TAGGER_CMD = \"\" def _split_results ( rows ) : \"\"\"\"\"\" for line in rows : line = line . strip ( ) if len ( line ) > : if line . count ( '' ) == : parts = line . split ( '' ) tokens = parts [ ] tags = parts [ ] confidence = float ( parts [ ] ) yield tokens , tags , confidence def _call_runtagger ( tweets , run_tagger_cmd = RUN_TAGGER_CMD ) : \"\"\"\"\"\" tweets_cleaned = [ tw . replace ( '' , '' ) for tw in tweets ] message = \"\" . join ( tweets_cleaned ) message = message . encode ( '' ) args = shlex . split ( run_tagger_cmd ) args . append ( '' ) args . append ( '' ) po = subprocess . Popen ( args , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) ", "answer": "result = po . communicate ( message )"}, {"prompt": " from __future__ import absolute_import , print_function , division import errno import os import sys from theano . compat import PY3 from theano . gof . compilelock import get_lock , release_lock from theano import config from . import cmodule if os . path . exists ( os . path . join ( config . compiledir , '' ) ) : os . remove ( os . path . join ( config . compiledir , '' ) ) def compile_cutils_code ( ) : types = [ '' + t for t in [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ] complex_types = [ '' + t for t in [ '' , '' , '' , '' , '' , '' ] ] inplace_map_template = \"\"\"\"\"\" floatadd = ( \"\" \"\" \"\" ) complexadd = \"\"\"\"\"\" fns = '' . join ( [ inplace_map_template % { '' : t , '' : t . upper ( ) , '' : floatadd % { '' : t } } for t in types ] + [ inplace_map_template % { '' : t , '' : t . upper ( ) , '' : complexadd % { '' : t } } for t in complex_types ] ) def gen_binop ( type , typen ) : return \"\"\"\"\"\" % dict ( type = type , typen = typen ) fn_array = ( \"\" + '' . join ( [ gen_binop ( type = t , typen = t . upper ( ) ) for t in types + complex_types ] ) + \"\" ) ", "answer": "def gen_num ( typen ) :"}, {"prompt": " from django . contrib . contenttypes . fields import ( GenericForeignKey , GenericRelation , ) from django . contrib . contenttypes . models import ContentType from django . db import models from django . utils . encoding import python_2_unicode_compatible ", "answer": "@ python_2_unicode_compatible"}, {"prompt": " from __future__ import absolute_import , print_function , division import numpy from six . moves import xrange import theano import scipy . sparse from theano import gof , tensor from theano . tensor . opt import register_specialize from theano . sparse . basic import ( as_sparse_variable , SparseType , add_s_s , neg , mul_s_s , mul_s_d , dot , CSMProperties , CSM , _is_sparse_variable , _is_dense_variable , CSC , CSR , csm_properties , csm_data , csm_indices , csm_indptr , csm_shape , _is_sparse , Remove0 , remove0 , Cast , bcast , wcast , icast , lcast , fcast , dcast , ccast , zcast , HStack , hstack , VStack , vstack , AddSSData , add_s_s_data , MulSV , mul_s_v , structured_monoid , structured_sigmoid , structured_exp , structured_log , structured_pow , structured_minimum , structured_maximum , structured_add , StructuredAddSV , structured_add_s_v , SamplingDot , sampling_dot ) from theano . sparse . opt import ( MulSDCSC , mul_s_d_csc , MulSDCSR , mul_s_d_csr , MulSVCSR , mul_s_v_csr , StructuredAddSVCSR , structured_add_s_v_csr , SamplingDotCSR , sampling_dot_csr , local_mul_s_d , local_mul_s_v , local_structured_add_s_v , local_sampling_dot_csr ) EliminateZeros = Remove0 eliminate_zeros = remove0 class Poisson ( gof . op . Op ) : \"\"\"\"\"\" __props__ = ( ) def make_node ( self , x ) : x = as_sparse_variable ( x ) return gof . Apply ( self , [ x ] , [ x . type ( ) ] ) def perform ( self , node , inputs , outputs ) : ( x , ) = inputs ( out , ) = outputs assert _is_sparse ( x ) assert x . format in [ \"\" , \"\" ] out [ ] = x . copy ( ) out [ ] . data = numpy . asarray ( numpy . random . poisson ( out [ ] . data ) , dtype = x . dtype ) out [ ] . eliminate_zeros ( ) def grad ( self , inputs , outputs_gradients ) : comment = \"\" return [ theano . gradient . grad_undefined ( op = self , x_pos = , x = inputs [ ] , comment = comment ) ] def infer_shape ( self , node , ins_shapes ) : return ins_shapes poisson = Poisson ( ) class Binomial ( gof . op . Op ) : \"\"\"\"\"\" __props__ = ( \"\" , \"\" ) def __init__ ( self , format , dtype ) : self . format = format self . dtype = dtype def make_node ( self , n , p , shape ) : n = tensor . as_tensor_variable ( n ) p = tensor . as_tensor_variable ( p ) ", "answer": "shape = tensor . as_tensor_variable ( shape )"}, {"prompt": " import os from setuptools import setup setup ( name = \"\" , version = \"\" , author = \"\" , author_email = \"\" , description = ( \"\" ) , license = \"\" , keywords = \"\" , url = \"\" , packages = [ '' , ] , scripts = [ '' ] , classifiers = [ \"\" , \"\" , ", "answer": "\"\" ,"}, {"prompt": " \"\"\"\"\"\" import os from pybuilder . core import task , init , depends , dependents , optional , after , use_plugin from pybuilder . errors import BuildFailedException from pybuilder . utils import assert_can_execute , execute_command __author__ = \"\" use_plugin ( \"\" ) @ init def pdoc_init ( project ) : project . plugin_depends_on ( \"\" ) project . set_property_if_unset ( \"\" , [ \"\" , \"\" , \"\" , \"\" ] ) project . set_property_if_unset ( \"\" , \"\" ) project . set_property_if_unset ( \"\" , \"\" ) project . set_property_if_unset ( \"\" , None ) @ after ( \"\" ) def pdoc_prepare ( project , logger ) : \"\"\"\"\"\" logger . debug ( \"\" ) assert_can_execute ( command_and_arguments = [ \"\" , \"\" ] , prerequisite = \"\" , caller = \"\" ) pdoc_output_dir = project . expand_path ( \"\" ) if not os . path . exists ( pdoc_output_dir ) : os . mkdir ( pdoc_output_dir ) @ task ( \"\" , \"\" ) @ depends ( \"\" , \"\" ) @ dependents ( optional ( \"\" ) ) def pdoc_compile_docs ( project , logger ) : logger . info ( \"\" ) if not project . get_property ( \"\" ) : raise BuildFailedException ( \"\" ) pdoc_command_args = project . get_property ( \"\" , [ ] ) pdoc_output_dir = project . expand_path ( \"\" ) command_and_arguments = [ \"\" ] + pdoc_command_args if \"\" in pdoc_command_args : command_and_arguments += [ \"\" , pdoc_output_dir ] command_and_arguments += [ project . get_property ( \"\" ) ] ", "answer": "source_directory = project . expand_path ( \"\" )"}, {"prompt": " '''''' ", "answer": "import os"}, {"prompt": " import os import sublime class HierarchyView ( object ) : def __init__ ( self , name , window = None ) : self . name = name self . window = window if window else sublime . active_window ( ) self . file_lines = dict ( ) self . set_view ( ) def set_content ( self , content ) : self . view . set_read_only ( False ) edit = self . view . begin_edit ( ) self . view . insert ( edit , , content ) self . view . end_edit ( edit ) self . fold_files ( content ) self . view . set_scratch ( True ) self . view . set_read_only ( True ) def empty_view ( self ) : self . view . set_read_only ( False ) e = self . view . begin_edit ( ) self . view . erase ( e , sublime . Region ( , self . view . size ( ) ) ) self . view . end_edit ( e ) self . view . set_read_only ( True ) def set_view ( self ) : for view in self . window . views ( ) : if view . name ( ) == self . name : self . view = view self . empty_view ( ) self . window . focus_view ( self . view ) return self . view = self . window . new_file ( ) self . view . set_name ( self . name ) self . view . set_syntax_file ( '' ) def fold_files ( self , content ) : \"\"\"\"\"\" current_class = None for line_number , line in enumerate ( content . split ( \"\" ) ) : line = line . strip ( ) if not line . startswith ( \"\" ) : self . file_lines [ line_number ] = [ ] current_class = self . file_lines [ line_number ] else : current_class . append ( line_number ) for class_line in self . file_lines . keys ( ) : self . toggle_class_file_lines ( class_line ) def get_file_region ( self , row ) : file_lines = None try : file_lines = self . file_lines [ row ] except KeyError : for lines in self . file_lines . values ( ) : if row in lines : file_lines = lines break if len ( file_lines ) == : return None region_from = self . view . text_point ( min ( file_lines ) , ) - region_to = self . view . text_point ( max ( file_lines ) + , ) - ", "answer": "if region_to + == self . view . size ( ) :"}, {"prompt": " from coro . ssh . util import debug from coro . ssh . util import packet as ssh_packet from coro . ssh . transport import transport as ssh_transport from coro . ssh . keys import key_storage from coro . ssh . transport . constants import * from coro . ssh . auth import userauth from coro import write_stderr as W class SSH_Server_Transport ( ssh_transport . SSH_Transport ) : def __init__ ( self , server_key , client_transport = None , server_transport = None , debug = None ) : ssh_transport . SSH_Transport . __init__ ( self , client_transport , server_transport , debug ) self . self2remote = self . s2c self . remote2self = self . c2s self . is_server = True self . s2c . supported_server_keys = [ server_key ] def connect ( self , transport , authenticator ) : \"\"\"\"\"\" try : self . _connect ( transport , authenticator ) except : self . disconnect ( ) raise def _connect ( self , transport , authenticator ) : self . transport = transport if self . s2c . comments : comments = '' + self . s2c . comments else : comments = '' self . s2c . version_string = '' + self . s2c . protocol_version + '' + self . s2c . software_version + comments transport . write ( self . s2c . version_string + '' ) while : line = transport . read_line ( ) if line . startswith ( '' ) : self . c2s . version_string = line i = line . find ( '' ) if i != - : self . c2s . comments = line [ i + : ] line = line [ : i ] parts = line . split ( '' ) if len ( parts ) != : self . send_disconnect ( ssh_transport . SSH_DISCONNECT_PROTOCOL_ERROR , '' % line ) self . c2s . protocol_version = parts [ ] self . c2s . software_version = parts [ ] if self . c2s . protocol_version not in ( '' , '' ) : self . send_disconnect ( ssh_transport . SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED , '' % self . c2s . protocol_version ) break self . send_kexinit ( ) self . s2c . set_preferred ( '' ) self . s2c . set_preferred ( '' ) if self . self2remote . proactive_kex : self . s2c . set_preferred ( '' ) self . s2c . set_preferred ( '' ) self . set_key_exchange ( ) self . debug . write ( debug . DEBUG_3 , '' ) packet = self . c2s . key_exchange . get_initial_server_kex_packet ( ) self . send_packet ( packet ) ", "answer": "self . start_receive_thread ( )"}, {"prompt": " from __future__ import unicode_literals ", "answer": "from django . db import migrations , models"}, {"prompt": " import urllib2 ", "answer": "import urllib"}, {"prompt": " import six import sys import os import errno from gevent import select , socket import greentest import unittest class TestSelect ( greentest . GenericWaitTestCase ) : def wait ( self , timeout ) : select . select ( [ ] , [ ] , [ ] , timeout ) if sys . platform != '' : class TestSelectRead ( greentest . GenericWaitTestCase ) : def wait ( self , timeout ) : r , w = os . pipe ( ) try : select . select ( [ r ] , [ ] , [ ] , timeout ) finally : os . close ( r ) os . close ( w ) @ unittest . skipIf ( sys . platform . startswith ( '' ) , '' ) def test_errno ( self ) : with open ( __file__ , '' ) as fp : fd = fp . fileno ( ) fp . close ( ) try : select . select ( [ fd ] , [ ] , [ ] , ) except OSError as err : self . assertEqual ( err . errno , errno . EBADF ) except select . error as err : self . assertEqual ( err . args [ ] , errno . EBADF ) else : self . fail ( \"\" ) if hasattr ( select , '' ) : class TestPollRead ( greentest . GenericWaitTestCase ) : def wait ( self , timeout ) : ", "answer": "r , w = os . pipe ( )"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( unique = True , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( unique = True , max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( blank = True ) ) , ( '' , self . gf ( '' ) ( blank = True ) ) , ( '' , self . gf ( '' ) ( blank = True ) ) , ( '' , self . gf ( '' ) ( blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( unique = True , max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( unique = True , max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , max_digits = , decimal_places = , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( ) ) , ( '' , self . gf ( '' ) ( ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( u'' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , unique = True ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( max_length = , null = True , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) def backwards ( self , orm ) : db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) db . delete_table ( u'' ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : \"\" } ) ,"}, {"prompt": " from aliyunsdkcore . request import RpcRequest ", "answer": "class BindIpRangeRequest ( RpcRequest ) :"}, {"prompt": " from django . conf . urls . defaults import patterns , include , handler500 from django . conf import settings from django . contrib import admin admin . autodiscover ( ) handler500 = '' ", "answer": "handler404 = ''"}, {"prompt": " from scrapy . contrib . spiders import CrawlSpider , Rule from scrapy . contrib . linkextractors . sgml import SgmlLinkExtractor ", "answer": "from scrapy . selector import HtmlXPathSelector"}, {"prompt": " import os , os . path import subprocess from play . utils import * import time if os . name == '' : import win32pdh , string , win32api COMMANDS = [ '' , '' , '' , '' , '' ] HELP = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } def execute ( ** kargs ) : command = kargs . get ( \"\" ) app = kargs . get ( \"\" ) args = kargs . get ( \"\" ) play_env = kargs . get ( \"\" ) if command == '' : start ( app , args ) if command == '' : stop ( app ) if command == '' : restart ( app , args ) if command == '' : pid ( app ) if command == '' : out ( app ) def start ( app , args ) : app . check ( ) if os . path . exists ( app . pid_path ( ) ) : pid = open ( app . pid_path ( ) ) . readline ( ) . strip ( ) if process_running ( pid ) : print \"\" % ( os . path . normpath ( app . path ) , pid , os . path . normpath ( app . pid_path ( ) ) ) print \"\" sys . exit ( ) else : print \"\" % ( os . path . normpath ( app . pid_path ( ) ) , pid ) os . remove ( app . pid_path ( ) ) sysout = app . readConf ( '' ) sysout = sysout != '' and sysout != '' if not sysout : sout = None else : sout = open ( os . path . join ( app . log_path ( ) , '' ) , '' ) try : pid = subprocess . Popen ( app . java_cmd ( args ) , stdout = sout , env = os . environ ) . pid except OSError : print \"\" sys . exit ( - ) print \"\" % os . path . normpath ( app . path ) if sysout : print \"\" % os . path . normpath ( os . path . join ( app . log_path ( ) , '' ) ) pid_file = open ( app . pid_path ( ) , '' ) pid_file . write ( str ( pid ) ) print \"\" % pid print \"\" def stop ( app ) : app . check ( ) if not os . path . exists ( app . pid_path ( ) ) : print \"\" % os . path . normpath ( app . path ) print \"\" sys . exit ( - ) pid = open ( app . pid_path ( ) ) . readline ( ) . strip ( ) kill ( pid ) os . remove ( app . pid_path ( ) ) print \"\" % app . path print \"\" def restart ( app , args ) : app . check ( ) if not os . path . exists ( app . pid_path ( ) ) : print \"\" % os . path . normpath ( app . path ) print \"\" else : pid = open ( app . pid_path ( ) ) . readline ( ) . strip ( ) os . remove ( app . pid_path ( ) ) kill ( pid ) sysout = app . readConf ( '' ) sysout = sysout != '' and sysout != '' java_cmd = app . java_cmd ( args ) if not sysout : sout = None else : sout = open ( os . path . join ( app . log_path ( ) , '' ) , '' ) try : pid = subprocess . Popen ( java_cmd , stdout = sout , env = os . environ ) . pid except OSError : print \"\" sys . exit ( - ) print \"\" % os . path . normpath ( app . path ) if sysout : print \"\" % os . path . normpath ( os . path . join ( app . log_path ( ) , '' ) ) pid_file = open ( app . pid_path ( ) , '' ) pid_file . write ( str ( pid ) ) print \"\" % pid print \"\" sys . exit ( ) def pid ( app ) : app . check ( ) if not os . path . exists ( app . pid_path ( ) ) : print \"\" % os . path . normpath ( app . path ) print \"\" sys . exit ( - ) pid = open ( app . pid_path ( ) ) . readline ( ) . strip ( ) print \"\" % pid print \"\" def out ( app ) : app . check ( ) if not os . path . exists ( os . path . join ( app . log_path ( ) , '' ) ) : print \"\" % os . path . normpath ( os . path . join ( app . log_path ( ) , '' ) ) print \"\" sys . exit ( - ) sout = open ( os . path . join ( app . log_path ( ) , '' ) , '' ) try : sout . seek ( - , os . SEEK_END ) except IOError : sout . seek ( ) while True : where = sout . tell ( ) line = sout . readline ( ) . strip ( ) if not line : time . sleep ( ) sout . seek ( where ) else : print line def kill ( pid ) : if os . name == '' : import ctypes handle = ctypes . windll . kernel32 . OpenProcess ( , False , int ( pid ) ) if not ctypes . windll . kernel32 . TerminateProcess ( handle , ) : print \"\" % ( pid , ctypes . windll . kernel32 . GetLastError ( ) ) print \"\" sys . exit ( - ) else : try : os . kill ( int ( pid ) , ) except OSError : print \"\" % pid print \"\" sys . exit ( - ) def process_running ( pid ) : if os . name == '' : return process_running_nt ( pid ) else : try : os . kill ( int ( pid ) , ) return True except OSError : return False def process_list_nt ( ) : ", "answer": "junk , instances = win32pdh . EnumObjectItems ( None , None , '' , win32pdh . PERF_DETAIL_WIZARD )"}, {"prompt": " from cloudferry . lib . base . action import action from cloudferry . lib . utils . ssh_util import SshUtil class RemoteExecution ( action . Action ) : def __init__ ( self , cloud , host = None , int_host = None , config_migrate = None ) : self . cloud = cloud self . host = host self . int_host = int_host self . config_migrate = config_migrate ", "answer": "self . remote_exec_obj = SshUtil ( self . cloud ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import warnings import functools from . registry import class_name_dict , class_id_dict from . exceptions import ( ClosedNodeError , NodeError , UndoRedoWarning , PerformanceWarning ) from . path import join_path , split_path , isvisiblepath from . utils import lazyattr from . undoredo import move_to_shadow from . attributeset import AttributeSet , NotLoggedAttributeSet import six __docformat__ = '' \"\"\"\"\"\" def _closedrepr ( oldmethod ) : \"\"\"\"\"\" @ functools . wraps ( oldmethod ) def newmethod ( self ) : if not self . _v_isopen : cmod = self . __class__ . __module__ cname = self . __class__ . __name__ addr = hex ( id ( self ) ) return '' % ( cmod , cname , addr ) return oldmethod ( self ) return newmethod class MetaNode ( type ) : \"\"\"\"\"\" def __new__ ( class_ , name , bases , dict_ ) : for mname in [ '' , '' ] : if mname in dict_ : dict_ [ mname ] = _closedrepr ( dict_ [ mname ] ) return type . __new__ ( class_ , name , bases , dict_ ) def __init__ ( class_ , name , bases , dict_ ) : super ( MetaNode , class_ ) . __init__ ( name , bases , dict_ ) class_name_dict [ class_ . __name__ ] = class_ cid = getattr ( class_ , '' , None ) if cid is not None : for base in bases : pcid = getattr ( base , '' , None ) if pcid == cid : break else : class_id_dict [ cid ] = class_ class Node ( six . with_metaclass ( MetaNode , object ) ) : \"\"\"\"\"\" _AttributeSet = AttributeSet def _g_getparent ( self ) : \"\" ( parentpath , nodename ) = split_path ( self . _v_pathname ) return self . _v_file . _get_node ( parentpath ) _v_parent = property ( _g_getparent ) @ lazyattr def _v_attrs ( self ) : \"\"\"\"\"\" return self . _AttributeSet ( self ) def _g_gettitle ( self ) : \"\" if hasattr ( self . _v_attrs , '' ) : return self . _v_attrs . TITLE else : return '' def _g_settitle ( self , title ) : self . _v_attrs . TITLE = title _v_title = property ( _g_gettitle , _g_settitle ) _v_isopen = False \"\"\"\"\"\" def __init__ ( self , parentnode , name , _log = True ) : if isinstance ( parentnode , class_name_dict [ '' ] ) : parentnode = parentnode . dereference ( ) self . _v_file = None \"\"\"\"\"\" self . _v_isopen = False \"\"\"\"\"\" self . _v_pathname = None \"\"\"\"\"\" self . _v_name = None \"\"\"\"\"\" self . _v_depth = None \"\"\"\"\"\" self . _v_maxtreedepth = parentnode . _v_file . params [ '' ] \"\"\"\"\"\" self . _v__deleting = False \"\"\"\"\"\" self . _v_objectid = None \"\"\"\"\"\" validate = new = self . _v_new self . _g_check_group ( parentnode ) parentnode . _g_check_open ( ) file_ = parentnode . _v_file if new : file_ . _check_writable ( ) if new : parentnode . _g_refnode ( self , name , validate ) self . _g_set_location ( parentnode , name ) ", "answer": "try :"}, {"prompt": " from . mp import Modpath ", "answer": "from . mpbas import ModpathBas"}, {"prompt": " import re import textutils from htmlutils import htmlify re_tag = re . compile ( \"\" ) re_decimal_entity = re . compile ( \"\" ) class Tag : def __init__ ( self , value ) : self . value = value def __str__ ( self ) : return self . value def __nonzero__ ( self ) : return False def __repr__ ( self ) : return \"\" % self . value def splitTags ( line ) : def process ( token ) : if token [ ] == '' : return Tag ( token ) else : def replace_decimal ( match ) : return unichr ( int ( match . group ( ) ) ) token = textutils . decode ( token ) token = re_decimal_entity . sub ( replace_decimal , token ) token = token . encode ( \"\" ) return token . replace ( \"\" , \"\" ) . replace ( \"\" , \">\" ) . replace ( \"\" , \"\" ) return map ( process , filter ( None , re_tag . split ( line ) ) ) def joinTags ( tags ) : def process ( token ) : if token : return htmlify ( token ) else : return str ( token ) return \"\" . join ( map ( process , tags ) ) def insertTag ( tags , offset , newTag ) : newTag = Tag ( newTag ) index = while index < len ( tags ) : tag = tags [ index ] if tag : ", "answer": "if len ( tag ) < offset : offset -= len ( tag )"}, {"prompt": " from . . excel_comparsion_test import ExcelComparisonTest from ... workbook import Workbook class TestCompareXLSXFiles ( ExcelComparisonTest ) : \"\"\"\"\"\" def setUp ( self ) : self . maxDiff = None filename = '' test_dir = '' self . got_filename = test_dir + '' + filename self . exp_filename = test_dir + '' + filename self . ignore_files = [ ] self . ignore_elements = { } def test_create_file ( self ) : \"\"\"\"\"\" workbook = Workbook ( self . got_filename ) worksheet = workbook . add_worksheet ( ) chart = workbook . add_chart ( { '' : '' } ) chart . axis_ids = [ , ] data = [ [ , , , , ] , [ , , , , ] , [ , , , , ] , ] worksheet . write_column ( '' , data [ ] ) worksheet . write_column ( '' , data [ ] ) worksheet . write_column ( '' , data [ ] ) chart . add_series ( { '' : '' } ) ", "answer": "chart . add_series ( { '' : '' } )"}, {"prompt": " import os import platform import socket import time ", "answer": "import json"}, {"prompt": " import numpy as np from numpy . testing import assert_array_equal from nose . tools import assert_raises , assert_equals , assert_almost_equals from ... . models . classes import MatrixPreferenceDataModel , MatrixBooleanPrefDataModel from . . item_strategies import ItemsNeighborhoodStrategy , AllPossibleItemsStrategy from . . neighborhood_strategies import AllNeighborsStrategy , NearestNeighborsStrategy from ... . similarities . basic_similarities import ItemSimilarity , UserSimilarity from . . classes import ItemBasedRecommender , UserBasedRecommender from ... . models . utils import ItemNotFoundError , UserNotFoundError from ... . metrics . pairwise import euclidean_distances , jaccard_coefficient , pearson_correlation movies = { '' : { '' : , '' : , '' : , '' : , '' : , '' : } , '' : { '' : , '' : , '' : , '' : , '' : , '' : } , '' : { '' : , '' : , '' : , '' : } , '' : { '' : , '' : , '' : , '' : , '' : } , '' : { '' : , '' : , '' : , '' : , '' : , '' : } , '' : { '' : , '' : , '' : , '' : , '' : } , '' : { '' : , '' : , '' : } , '' : { } } matrix_model = MatrixPreferenceDataModel ( movies ) boolean_matrix_model = MatrixBooleanPrefDataModel ( movies ) def test_create_ItemBasedRecommender ( ) : items_strategy = AllPossibleItemsStrategy ( ) similarity = ItemSimilarity ( matrix_model , euclidean_distances ) recsys = ItemBasedRecommender ( matrix_model , similarity , items_strategy ) assert_equals ( recsys . similarity , similarity ) assert_equals ( recsys . items_selection_strategy , items_strategy ) assert_equals ( recsys . model , matrix_model ) assert_equals ( recsys . capper , True ) def test_create_UserBasedRecommender ( ) : nhood_strategy = AllNeighborsStrategy ( ) similarity = UserSimilarity ( matrix_model , euclidean_distances ) recsys = UserBasedRecommender ( matrix_model , similarity , nhood_strategy ) assert_equals ( recsys . similarity , similarity ) ", "answer": "assert_equals ( recsys . neighborhood_strategy , nhood_strategy )"}, {"prompt": " \"\"\"\"\"\" class PeerObjectProxy ( object ) : \"\"\"\"\"\" def __init__ ( self , name , conn ) : self . _name = name self . _conn = conn def notify ( self , * args ) : self . _conn . sendNotify ( self . _name , args ) def __call__ ( self , * args ) : evt = self . _conn . sendRequest ( self . _name , args ) return evt . waitForResponse ( ) def __getattr__ ( self , name ) : return PeerObjectProxy ( self . _name + \"\" + name , self . _conn ) class PeerProxy : def __init__ ( self , connectionHandler ) : self . _connectionHandler = connectionHandler def __getattr__ ( self , name ) : return PeerObjectProxy ( name , self . _connectionHandler ) import re class ServiceProxy ( PeerProxy ) : def __init__ ( self , url , localService = None , messageDelimiter = \"\" ) : m = re . match ( r\"\" , url ) if m : from jsonrpc . socketserver import SocketServiceHandler import socket from threading import Thread ( host , port ) = m . groups ( ) ", "answer": "port = int ( port )"}, {"prompt": " class MethodRedef ( object ) : \"\"\"\"\"\" def a ( self , i ) : return i + def a ( self , i ) : ", "answer": "return i + "}, {"prompt": " \"\"\"\"\"\" ", "answer": "import sys"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Installation ( )"}, {"prompt": " import collections import copy from . Utils import _write_complex_object class ExceptionDetails ( object ) : \"\"\"\"\"\" _defaults = collections . OrderedDict ( [ ( '' , None ) , ( '' , None ) , ( '' , None ) , ( '' , None ) , ( '' , True ) , ( '' , None ) , ( '' , [ ] ) ] ) def __init__ ( self ) : \"\"\"\"\"\" self . _values = { '' : None , '' : None , '' : True , } self . _initialize ( ) @ property def id ( self ) : \"\"\"\"\"\" if '' in self . _values : return self . _values [ '' ] return self . _defaults [ '' ] @ id . setter def id ( self , value ) : \"\"\"\"\"\" if value == self . _defaults [ '' ] and '' in self . _values : del self . _values [ '' ] else : self . _values [ '' ] = value @ property def outer_id ( self ) : \"\"\"\"\"\" if '' in self . _values : return self . _values [ '' ] return self . _defaults [ '' ] @ outer_id . setter def outer_id ( self , value ) : \"\"\"\"\"\" if value == self . _defaults [ '' ] and '' in self . _values : del self . _values [ '' ] else : self . _values [ '' ] = value @ property def type_name ( self ) : \"\"\"\"\"\" return self . _values [ '' ] @ type_name . setter def type_name ( self , value ) : \"\"\"\"\"\" self . _values [ '' ] = value @ property def message ( self ) : \"\"\"\"\"\" return self . _values [ '' ] @ message . setter def message ( self , value ) : \"\"\"\"\"\" self . _values [ '' ] = value @ property def has_full_stack ( self ) : \"\"\"\"\"\" if '' in self . _values : return self . _values [ '' ] return self . _defaults [ '' ] @ has_full_stack . setter def has_full_stack ( self , value ) : \"\"\"\"\"\" if value == self . _defaults [ '' ] and '' in self . _values : del self . _values [ '' ] else : self . _values [ '' ] = value @ property def stack ( self ) : \"\"\"\"\"\" if '' in self . _values : return self . _values [ '' ] return self . _defaults [ '' ] @ stack . setter def stack ( self , value ) : \"\"\"\"\"\" if value == self . _defaults [ '' ] and '' in self . _values : del self . _values [ '' ] else : self . _values [ '' ] = value ", "answer": "@ property"}, {"prompt": " import sys m = sys . modules [ \"\" ] ", "answer": "setattr ( m , \"\" , )"}, {"prompt": " import pytest import tempfile from calliope . utils import AttrDict from . import common from . common import assert_almost_equal , solver , _add_test_path def create_and_run_model ( override , iterative_warmstart = False , demand_file = '' ) : locations = \"\"\"\"\"\" config_run = \"\"\"\"\"\" override = AttrDict . from_yaml_string ( override ) override . set_key ( '' , solver ) with tempfile . NamedTemporaryFile ( ) as f : f . write ( locations . format ( demand_file = demand_file ) . encode ( '' ) ) f . read ( ) model = common . simple_model ( config_run = config_run , config_locations = f . name , override = override , path = _add_test_path ( '' ) ) model . run ( iterative_warmstart ) return model class TestModel : def test_model_fixed_costs_op ( self ) : override = \"\"\"\"\"\" model1 = create_and_run_model ( override . format ( ) ) cost1 = model1 . solution [ '' ] . loc [ dict ( k = '' , x = '' , y = '' ) ] lcoe1 = model1 . solution [ '' ] . loc [ dict ( techs = '' , cols_summary = '' ) ] model2 = create_and_run_model ( override . format ( ) ) cost2 = model2 . solution [ '' ] . loc [ dict ( k = '' , x = '' , y = '' ) ] lcoe2 = model2 . solution [ '' ] . loc [ dict ( techs = '' , cols_summary = '' ) ] assert_almost_equal ( lcoe1 , lcoe2 , tolerance = ) assert_almost_equal ( * cost1 , cost2 , tolerance = ) def test_model_var_costs_op ( self ) : override = \"\"\"\"\"\" model1 = create_and_run_model ( override . format ( ) ) cost1 = model1 . solution [ '' ] . loc [ dict ( k = '' , x = '' , y = '' ) ] lcoe1 = model1 . solution [ '' ] . loc [ dict ( techs = '' , cols_summary = '' ) ] model2 = create_and_run_model ( override . format ( ) ) cost2 = model2 . solution [ '' ] . loc [ dict ( k = '' , x = '' , y = '' ) ] lcoe2 = model2 . solution [ '' ] . loc [ dict ( techs = '' , cols_summary = '' ) ] assert_almost_equal ( lcoe1 , lcoe2 , tolerance = ) assert_almost_equal ( * cost1 , cost2 , tolerance = ) def test_model_fixed_costs_op_with_varying_demand ( self ) : override = \"\"\"\"\"\" demand = '' model1 = create_and_run_model ( override . format ( ) , demand_file = demand ) cost1 = model1 . solution [ '' ] . loc [ dict ( k = '' , x = '' , y = '' ) ] lcoe1 = model1 . solution [ '' ] . loc [ dict ( techs = '' , cols_summary = '' ) ] model2 = create_and_run_model ( override . format ( ) , demand_file = demand ) cost2 = model2 . solution [ '' ] . loc [ dict ( k = '' , x = '' , y = '' ) ] lcoe2 = model2 . solution [ '' ] . loc [ dict ( techs = '' , cols_summary = '' ) ] assert lcoe1 > lcoe2 assert_almost_equal ( * cost1 , cost2 , tolerance = ) def test_model_var_costs_op_with_varying_demand ( self ) : ", "answer": "override = \"\"\"\"\"\""}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Tangible ( )"}, {"prompt": " import os , sys sys . path . insert ( , os . path . normpath ( os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , \"\" ) ) ) from test_common import ( my_print , setup , createSearchMode , compareWithCPython , withPythonPathChange ) python_version = setup ( needs_io_encoding = True ) search_mode = createSearchMode ( ) extra_options = os . environ . get ( \"\" , \"\" ) for filename in sorted ( os . listdir ( '' ) ) : if not os . path . isdir ( filename ) or filename . endswith ( \"\" ) or filename . endswith ( \"\" ) : continue filename = os . path . relpath ( filename ) expected_errors = [ \"\" , \"\" , \"\" , \"\" ] if python_version < \"\" : expected_errors . append ( \"\" ) if filename not in expected_errors : extra_flags = [ \"\" ] else : extra_flags = [ \"\" ] if filename in ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) : extra_flags . append ( \"\" ) extra_flags . append ( \"\" ) extra_flags . append ( \"\" ) extra_flags . append ( \"\" ) if filename != \"\" : extra_flags . append ( \"\" ) else : extra_flags . append ( \"\" ) if filename == \"\" : os . environ [ \"\" ] = extra_options + \"\" % ( os . path . abspath ( filename ) ) elif filename == \"\" : if python_version < '' : os . environ [ \"\" ] = extra_options + \"\" % ( os . path . abspath ( filename ) ) else : os . environ [ \"\" ] = extra_options + \"\" % ( os . path . abspath ( filename ) ) extra_flags . append ( \"\" ) else : os . environ [ \"\" ] = extra_options active = search_mode . consider ( dirname = None , filename = filename ) if active : my_print ( \"\" , filename ) for filename_main in os . listdir ( filename ) : if filename_main . endswith ( \"\" ) : break if filename_main . endswith ( \"\" ) : break else : sys . exit ( \"\"\"\"\"\" % ( filename ) ) extra_python_path = [ ", "answer": "os . path . abspath ( os . path . join ( filename , entry ) )"}, {"prompt": " \"\"\"\"\"\" import json from django . forms . models import model_to_dict from django . test import TestCase from django . utils . timezone import timedelta from mixer . backend . django import mixer from . . constants import FREQUENCIES , OCCURRENCE_DECISIONS from . . forms import OccurrenceForm from . . models import Event , Occurrence from . . utils import now class OccurrenceFormTestCase ( TestCase ) : \"\"\"\"\"\" longMessage = True def setUp ( self ) : self . event = mixer . blend ( '' , rule = None , end_recurring_period = None ) self . event_occurrence = next ( self . event . get_occurrences ( self . event . start ) ) self . rule = mixer . blend ( '' , name = '' , frequency = FREQUENCIES [ '' ] , params = json . dumps ( { '' : } ) ) self . rec_event = mixer . blend ( '' , rule = self . rule , start = now ( ) , end_recurring_period = now ( ) + timedelta ( days = ) , ) self . rec_occurrence_list = [ occ for occ in self . rec_event . get_occurrences ( self . rec_event . start , self . rec_event . end_recurring_period ) ] self . rec_occurrence = self . rec_occurrence_list [ ] def test_form ( self ) : \"\"\"\"\"\" data = model_to_dict ( self . event_occurrence ) initial = data . copy ( ) data . update ( { '' : OCCURRENCE_DECISIONS [ '' ] , '' : '' } ) form = OccurrenceForm ( data = data , initial = initial ) self . assertTrue ( form . is_valid ( ) , msg = ( '' ) ) form . save ( ) event = Event . objects . get ( pk = self . event . pk ) self . assertEqual ( event . title , '' , msg = ( '' ) ) data = model_to_dict ( self . rec_occurrence ) initial = data . copy ( ) data . update ( { '' : OCCURRENCE_DECISIONS [ '' ] , '' : '' } ) form = OccurrenceForm ( data = data , initial = initial ) self . assertTrue ( form . is_valid ( ) , msg = ( '' ) ) form . save ( ) self . assertEqual ( Occurrence . objects . all ( ) . count ( ) , , msg = ( '' '' ) ) occ = Occurrence . objects . get ( ) self . assertEqual ( occ . title , '' , msg = ( '' '' ) ) occ_to_use = self . rec_occurrence_list [ ] data = model_to_dict ( occ_to_use ) initial = data . copy ( ) new_start = occ_to_use . start + timedelta ( hours = ) data . update ( { '' : OCCURRENCE_DECISIONS [ '' ] , '' : '' , '' : new_start } ) form = OccurrenceForm ( data = data , initial = initial ) self . assertTrue ( form . is_valid ( ) , msg = ( '' ) ) form . save ( ) self . assertEqual ( Occurrence . objects . all ( ) . count ( ) , , msg = ( '' '' ) ) occ = Occurrence . objects . get ( ) self . assertEqual ( occ . title , '' , msg = ( '' '' ) ) self . assertEqual ( occ . description , '' , msg = ( '' '' ) ) self . assertEqual ( occ . start , self . rec_occurrence . start + timedelta ( hours = ) , msg = ( '' '' ) ) occ_to_use = self . rec_occurrence_list [ ] data = model_to_dict ( occ_to_use ) initial = data . copy ( ) new_start = occ_to_use . start - timedelta ( days = ) data . update ( { '' : OCCURRENCE_DECISIONS [ '' ] , '' : new_start } ) form = OccurrenceForm ( data = data , initial = initial ) self . assertTrue ( form . is_valid ( ) , msg = ( '' ) ) form . save ( ) self . assertEqual ( Event . objects . all ( ) . count ( ) , , msg = ( '' '' ) ) event1 = Event . objects . get ( pk = self . rec_event . pk ) event2 = Event . objects . exclude ( pk__in = [ self . rec_event . pk , self . event . pk ] ) . get ( ) self . assertEqual ( event1 . end_recurring_period , event2 . start - timedelta ( days = ) , msg = ( ", "answer": "''"}, {"prompt": " import pytest import datetime as dt from mock import MagicMock from gitfs . utils . strptime import TimeParser from gitfs . utils import strptime class TestDateTimeUtils ( object ) : def test_strptime ( self ) : date = dt . date ( , , ) datetime = dt . datetime ( , , , , , ) assert strptime ( \"\" , \"\" ) == date assert strptime ( \"\" , \"\" , to_datetime = True ) == datetime date = dt . date ( , , ) datetime = dt . datetime ( , , , , , ) ", "answer": "assert strptime ( \"\" , \"\" ) == date"}, {"prompt": " from aliyunsdkcore . request import RpcRequest class AlterTableRequest ( RpcRequest ) : def __init__ ( self ) : RpcRequest . __init__ ( self , '' , '' , '' ) def get_DrdsInstanceId ( self ) : return self . get_query_params ( ) . get ( '' ) def set_DrdsInstanceId ( self , DrdsInstanceId ) : self . add_query_param ( '' , DrdsInstanceId ) def get_DbName ( self ) : return self . get_query_params ( ) . get ( '' ) def set_DbName ( self , DbName ) : ", "answer": "self . add_query_param ( '' , DbName )"}, {"prompt": " '''''' import pika connection = pika . BlockingConnection ( pika . ConnectionParameters ( host = \"\" ) ) channel = connection . channel ( ) channel . queue_purge ( queue = '' ) channel . queue_declare ( queue = '' , durable = True ) channel . basic_publish ( exchange = '' , routing_key = '' , body = \"\" , properties = pika . BasicProperties ( delivery_mode = , ) ) ", "answer": "connection . close ( ) "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , print_function import click from sentry . runner . decorators import configuration @ click . group ( ) def queues ( ) : \"\" @ queues . command ( ) @ click . option ( '' , '' , default = False , is_flag = True , help = '' ) @ click . option ( '' , '' , default = False , is_flag = True , help = '' ) @ configuration def list ( sort_size , reverse ) : \"\" from django . conf import settings from sentry . monitoring . queues import backend if backend is None : raise click . ClickException ( '' ) queues = backend . bulk_get_sizes ( [ q . name for q in settings . CELERY_QUEUES ] ) if sort_size : queues = sorted ( queues , key = lambda q : ( - q [ ] , q [ ] ) , reverse = reverse ) else : queues = sorted ( queues , reverse = reverse ) for queue in queues : click . echo ( '' % queue ) @ queues . command ( ) @ click . option ( '' , '' , default = False , is_flag = True , help = '' ) @ click . argument ( '' ) @ configuration def purge ( force , queue ) : \"\" from sentry . monitoring . queues import get_queue_by_name , backend if get_queue_by_name ( queue ) is None : ", "answer": "raise click . ClickException ( '' % queue )"}, {"prompt": " \"\"\"\"\"\" import math ", "answer": "import unittest"}, {"prompt": " \"\"\"\"\"\" from collections import Counter , defaultdict import hashlib import random import re import math import nltk import numpy as np import pandas as pd from . . common import smart_open , DocIDError from . . common_abc import SaveLoad from . import nlp from . import streaming_filters class BaseTokenizer ( SaveLoad ) : \"\"\"\"\"\" def text_to_counter ( self , text ) : \"\"\"\"\"\" return Counter ( self . text_to_token_list ( text ) ) class MakeTokenizer ( BaseTokenizer ) : \"\"\"\"\"\" def __init__ ( self , tokenizer_func ) : \"\"\"\"\"\" self . text_to_token_list = tokenizer_func class TokenizerBasic ( BaseTokenizer ) : \"\"\"\"\"\" def text_to_token_list ( self , text ) : \"\"\"\"\"\" tokens = nlp . word_tokenize ( text , L = , numeric = False ) return [ word . lower ( ) for word in tokens if not nlp . is_stopword ( word ) ] class TokenizerPOSFilter ( BaseTokenizer ) : \"\"\"\"\"\" def __init__ ( self , pos_types = [ ] , sent_tokenizer = nltk . sent_tokenize , word_tokenizer = TokenizerBasic ( ) , word_tokenizer_func = None , pos_tagger = nltk . pos_tag ) : \"\"\"\"\"\" self . pos_types = set ( pos_types ) self . sent_tokenizer = sent_tokenizer self . pos_tagger = pos_tagger if not word_tokenizer : self . word_tokenizer = MakeTokenizer ( word_tokenizer_func ) else : self . word_tokenizer = word_tokenizer def text_to_token_list ( self , text ) : \"\"\"\"\"\" sentences = self . sent_tokenizer ( text ) func = self . word_tokenizer . text_to_token_list tokenized_sentences = [ func ( sent ) for sent in sentences ] tagged_sentences = [ self . pos_tagger ( sent ) for sent in tokenized_sentences ] token_list = sum ( [ self . _sent_filter ( sent ) for sent in tagged_sentences ] , [ ] ) return token_list def _sent_filter ( self , tokenized_sent ) : return [ word for ( word , pos ) in tokenized_sent if pos in self . pos_types ] class SparseFormatter ( object ) : \"\"\"\"\"\" def _parse_feature_str ( self , feature_str ) : \"\"\"\"\"\" assert feature_str [ ] == '' feature_str = feature_str [ : ] fv_list = re . findall ( r'' , feature_str ) feature_values = { f : self . _string_to_number ( v , empty_sub = ) for ( f , v ) in fv_list } return feature_values def sstr_to_dict ( self , sstr ) : \"\"\"\"\"\" sstr = sstr . rstrip ( '' ) . rstrip ( '' ) idx = sstr . index ( self . preamble_char ) preamble , feature_str = sstr [ : idx ] , sstr [ idx + : ] record_dict = self . _parse_preamble ( preamble ) record_dict [ '' ] = self . _parse_feature_str ( feature_str ) return record_dict def sstr_to_info ( self , sstr ) : \"\"\"\"\"\" info = self . sstr_to_dict ( sstr ) info [ '' ] = self . _dict_to_tokens ( info ) return info def _dict_to_tokens ( self , record_dict ) : token_list = [ ] if '' in record_dict : for feature , value in record_dict [ '' ] . iteritems ( ) : int_value = int ( value ) assert int_value == value token_list += [ feature ] * int_value return token_list def sstr_to_token_list ( self , sstr ) : \"\"\"\"\"\" record_dict = self . sstr_to_dict ( sstr ) return self . _dict_to_tokens ( record_dict ) def sfile_to_token_iter ( self , filepath_or_buffer , limit = None ) : \"\"\"\"\"\" with smart_open ( filepath_or_buffer ) as open_file : for index , line in enumerate ( open_file ) : if index == limit : raise StopIteration yield self . sstr_to_token_list ( line ) def _string_to_number ( self , string , empty_sub = None ) : \"\"\"\"\"\" try : return int ( string ) except ValueError : pass try : return float ( string ) except ValueError : if ( string == '' ) and ( empty_sub is not None ) : return empty_sub else : raise class VWFormatter ( SparseFormatter ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals import contextlib import hashlib import random try : from urllib . parse import quote , quote_plus except ImportError : from urllib import quote , quote_plus import requests from requests_oauthlib import OAuth1 from . exceptions import LinkedInError from . models import AccessToken , LinkedInInvitation , LinkedInMessage from . utils import enum , to_utf8 , raise_for_error , json , StringIO __all__ = [ '' , '' , '' ] PERMISSIONS = enum ( '' , COMPANY_ADMIN = '' , BASIC_PROFILE = '' , FULL_PROFILE = '' , EMAIL_ADDRESS = '' , NETWORK = '' , CONTACT_INFO = '' , NETWORK_UPDATES = '' , GROUPS = '' , MESSAGES = '' ) ENDPOINTS = enum ( '' , PEOPLE = '' , PEOPLE_SEARCH = '' , GROUPS = '' , POSTS = '' , COMPANIES = '' , COMPANY_SEARCH = '' , JOBS = '' , JOB_SEARCH = '' ) NETWORK_UPDATES = enum ( '' , APPLICATION = '' , COMPANY = '' , CONNECTION = '' , JOB = '' , GROUP = '' , PICTURE = '' , EXTENDED_PROFILE = '' , CHANGED_PROFILE = '' , SHARED = '' , VIRAL = '' ) class LinkedInDeveloperAuthentication ( object ) : \"\"\"\"\"\" def __init__ ( self , consumer_key , consumer_secret , user_token , user_secret , redirect_uri , permissions = [ ] ) : self . consumer_key = consumer_key self . consumer_secret = consumer_secret self . user_token = user_token self . user_secret = user_secret self . redirect_uri = redirect_uri self . permissions = permissions class LinkedInAuthentication ( object ) : \"\"\"\"\"\" AUTHORIZATION_URL = '' ACCESS_TOKEN_URL = '' def __init__ ( self , key , secret , redirect_uri , permissions = None ) : self . key = key self . secret = secret self . redirect_uri = redirect_uri self . permissions = permissions or [ ] self . state = None self . authorization_code = None self . token = None self . _error = None @ property def authorization_url ( self ) : qd = { '' : '' , '' : self . key , '' : ( '' . join ( self . permissions ) ) . strip ( ) , '' : self . state or self . _make_new_state ( ) , '' : self . redirect_uri } qsl = [ '' % ( quote ( k ) , quote ( v ) ) for k , v in qd . items ( ) ] return '' % ( self . AUTHORIZATION_URL , '' . join ( qsl ) ) @ property def last_error ( self ) : return self . _error def _make_new_state ( self ) : return hashlib . md5 ( '' . format ( random . randrange ( , ** ) , self . secret ) . encode ( \"\" ) ) . hexdigest ( ) def get_access_token ( self , timeout = ) : assert self . authorization_code , '' qd = { '' : '' , '' : self . authorization_code , '' : self . redirect_uri , '' : self . key , '' : self . secret } response = requests . post ( self . ACCESS_TOKEN_URL , data = qd , timeout = timeout ) raise_for_error ( response ) response = response . json ( ) self . token = AccessToken ( response [ '' ] , response [ '' ] ) return self . token class LinkedInSelector ( object ) : @ classmethod def parse ( cls , selector ) : with contextlib . closing ( StringIO ( ) ) as result : if type ( selector ) == dict : for k , v in selector . items ( ) : result . write ( '' % ( to_utf8 ( k ) , cls . parse ( v ) ) ) elif type ( selector ) in ( list , tuple ) : result . write ( '' . join ( map ( cls . parse , selector ) ) ) else : result . write ( to_utf8 ( selector ) ) return result . getvalue ( ) class LinkedInApplication ( object ) : BASE_URL = '' def __init__ ( self , authentication = None , token = None ) : assert authentication or token , '' self . authentication = authentication if not self . authentication : self . authentication = LinkedInAuthentication ( '' , '' , '' ) self . authentication . token = AccessToken ( token , None ) def make_request ( self , method , url , data = None , params = None , headers = None , timeout = ) : if headers is None : headers = { '' : '' , '' : '' } else : headers . update ( { '' : '' , '' : '' } ) if params is None : params = { } kw = dict ( data = data , params = params , headers = headers , timeout = timeout ) if isinstance ( self . authentication , LinkedInDeveloperAuthentication ) : auth = OAuth1 ( self . authentication . consumer_key , self . authentication . consumer_secret , self . authentication . user_token , self . authentication . user_secret ) kw . update ( { '' : auth } ) else : params . update ( { '' : self . authentication . token . access_token } ) return requests . request ( method . upper ( ) , url , ** kw ) def get_profile ( self , member_id = None , member_url = None , selectors = None , params = None , headers = None ) : if member_id : if type ( member_id ) is list : url = '' % ( ENDPOINTS . PEOPLE , '' . join ( member_id ) ) else : url = '' % ( ENDPOINTS . PEOPLE , str ( member_id ) ) elif member_url : url = '' % ( ENDPOINTS . PEOPLE , quote_plus ( member_url ) ) else : url = '' % ENDPOINTS . PEOPLE ", "answer": "if selectors :"}, {"prompt": " import os import sys import struct import colorama from awscli . compat import six def determine_terminal_width ( default_width = ) : try : from termios import TIOCGWINSZ from fcntl import ioctl except ImportError : return default_width try : height , width = struct . unpack ( '' , ioctl ( sys . stdout , TIOCGWINSZ , '' * ) ) [ : ] except Exception : return default_width else : return width def is_a_tty ( ) : try : return os . isatty ( sys . stdout . fileno ( ) ) except Exception : return False def center_text ( text , length = , left_edge = '' , right_edge = '' , text_length = None ) : \"\"\"\"\"\" if text_length is None : text_length = len ( text ) output = [ ] char_start = ( length // ) - ( text_length // ) - output . append ( left_edge + '' * char_start + text ) length_so_far = len ( left_edge ) + char_start + text_length right_side_spaces = length - len ( right_edge ) - length_so_far output . append ( '' * right_side_spaces ) output . append ( right_edge ) final = '' . join ( output ) return final def align_left ( text , length , left_edge = '' , right_edge = '' , text_length = None , left_padding = ) : \"\"\"\"\"\" if text_length is None : text_length = len ( text ) computed_length = ( text_length + left_padding + len ( left_edge ) + len ( right_edge ) ) if length - computed_length >= : padding = left_padding else : padding = output = [ ] length_so_far = output . append ( left_edge ) length_so_far += len ( left_edge ) output . append ( '' * padding ) length_so_far += padding output . append ( text ) length_so_far += text_length output . append ( '' * ( length - length_so_far - len ( right_edge ) ) ) output . append ( right_edge ) return '' . join ( output ) def convert_to_vertical_table ( sections ) : for i , section in enumerate ( sections ) : if len ( section . rows ) == and section . headers : headers = section . headers new_section = Section ( ) new_section . title = section . title new_section . indent_level = section . indent_level for header , element in zip ( headers , section . rows [ ] ) : new_section . add_row ( [ header , element ] ) sections [ i ] = new_section class IndentedStream ( object ) : def __init__ ( self , stream , indent_level , left_indent_char = '' , right_indent_char = '' ) : self . _stream = stream self . _indent_level = indent_level self . _left_indent_char = left_indent_char self . _right_indent_char = right_indent_char def write ( self , text ) : self . _stream . write ( self . _left_indent_char * self . _indent_level ) if text . endswith ( '' ) : self . _stream . write ( text [ : - ] ) self . _stream . write ( self . _right_indent_char * self . _indent_level ) self . _stream . write ( '' ) else : self . _stream . write ( text ) def __getattr__ ( self , attr ) : return getattr ( self . _stream , attr ) class Styler ( object ) : def style_title ( self , text ) : return text def style_header_column ( self , text ) : return text def style_row_element ( self , text ) : return text def style_indentation_char ( self , text ) : return text class ColorizedStyler ( Styler ) : def __init__ ( self ) : colorama . init ( autoreset = True ) def style_title ( self , text ) : return text def style_header_column ( self , text ) : return text def style_row_element ( self , text ) : return ( colorama . Style . BRIGHT + colorama . Fore . BLUE + text + colorama . Style . RESET_ALL ) def style_indentation_char ( self , text ) : return ( colorama . Style . DIM + colorama . Fore . YELLOW + text + colorama . Style . RESET_ALL ) class MultiTable ( object ) : def __init__ ( self , terminal_width = None , initial_section = True , column_separator = '' , terminal = None , styler = None , auto_reformat = True ) : self . _auto_reformat = auto_reformat if initial_section : self . _current_section = Section ( ) self . _sections = [ self . _current_section ] else : self . _current_section = None self . _sections = [ ] if styler is None : if is_a_tty ( ) : self . _styler = ColorizedStyler ( ) else : self . _styler = Styler ( ) else : self . _styler = styler self . _rendering_index = self . _column_separator = column_separator if terminal_width is None : self . _terminal_width = determine_terminal_width ( ) def add_title ( self , title ) : self . _current_section . add_title ( title ) def add_row_header ( self , headers ) : self . _current_section . add_header ( headers ) def add_row ( self , row_elements ) : self . _current_section . add_row ( row_elements ) def new_section ( self , title , indent_level = ) : self . _current_section = Section ( ) self . _sections . append ( self . _current_section ) self . _current_section . add_title ( title ) self . _current_section . indent_level = indent_level def render ( self , stream ) : max_width = self . _calculate_max_width ( ) should_convert_table = self . _determine_conversion_needed ( max_width ) if should_convert_table : convert_to_vertical_table ( self . _sections ) max_width = self . _calculate_max_width ( ) stream . write ( '' * max_width + '' ) for section in self . _sections : self . _render_section ( section , max_width , stream ) def _determine_conversion_needed ( self , max_width ) : if max_width > self . _terminal_width : return self . _auto_reformat def _calculate_max_width ( self ) : max_width = max ( s . total_width ( padding = , with_border = True , outer_padding = s . indent_level ) for s in self . _sections ) return max_width def _render_section ( self , section , max_width , stream ) : stream = IndentedStream ( stream , section . indent_level , self . _styler . style_indentation_char ( '' ) , self . _styler . style_indentation_char ( '' ) ) max_width -= ( section . indent_level * ) self . _render_title ( section , max_width , stream ) self . _render_column_titles ( section , max_width , stream ) self . _render_rows ( section , max_width , stream ) def _render_title ( self , section , max_width , stream ) : if section . title : title = self . _styler . style_title ( section . title ) stream . write ( center_text ( title , max_width , '' , '' , len ( section . title ) ) + '' ) if not section . headers and not section . rows : stream . write ( '' % ( '' * ( max_width - ) ) + '' ) def _render_column_titles ( self , section , max_width , stream ) : if not section . headers : return widths = section . calculate_column_widths ( padding = , max_width = max_width ) current = '' length_so_far = first = True for width , header in zip ( widths , section . headers ) : stylized_header = self . _styler . style_header_column ( header ) if first : left_edge = '' first = False else : left_edge = '' current += center_text ( text = stylized_header , length = width , left_edge = left_edge , right_edge = '' , text_length = len ( header ) ) length_so_far += width self . _write_line_break ( stream , widths ) stream . write ( current + '' ) def _write_line_break ( self , stream , widths ) : parts = [ ] first = True for width in widths : if first : parts . append ( '' % ( '' * ( width - ) ) ) first = False else : parts . append ( '' % ( '' * ( width - ) ) ) parts . append ( '' ) stream . write ( '' . join ( parts ) ) def _render_rows ( self , section , max_width , stream ) : if not section . rows : return ", "answer": "widths = section . calculate_column_widths ( padding = ,"}, {"prompt": " from django . shortcuts import get_object_or_404 from cab . models import Language from cab . utils import month_object_list , object_list def language_list ( request ) : return object_list ( request , queryset = Language . objects . all ( ) , paginate_by = , ) def language_detail ( request , slug ) : ", "answer": "language = get_object_or_404 ( Language , slug = slug )"}, {"prompt": " import graphene from graphene . core . schema import Schema my_id = class Query ( graphene . ObjectType ) : base = graphene . String ( ) class ChangeNumber ( graphene . Mutation ) : '''''' class Input : to = graphene . Int ( ) result = graphene . String ( ) @ classmethod def mutate ( cls , instance , args , info ) : global my_id my_id = args . get ( '' , my_id + ) return ChangeNumber ( result = my_id ) class MyResultMutation ( graphene . ObjectType ) : change_number = graphene . Field ( ChangeNumber ) schema = Schema ( query = Query , mutation = MyResultMutation ) def test_mutation_input ( ) : assert list ( schema . T ( ChangeNumber . arguments ) . keys ( ) ) == [ '' ] def test_execute_mutations ( ) : query = '''''' expected = { '' : { '' : '' , } , ", "answer": "'' : {"}, {"prompt": " from __future__ import division __author__ = \"\" __copyright__ = \"\" __credits__ = [ \"\" , \"\" , \"\" , \"\" , \"\" ] __license__ = \"\" __version__ = \"\" __maintainer__ = \"\" __email__ = \"\" __status__ = \"\" def format_mapping_file ( headers , mapping_data , comments = None ) : \"\"\"\"\"\" result = [ ] result . append ( '' + '' . join ( headers ) ) ", "answer": "if comments != None :"}, {"prompt": " from collections import namedtuple from Vintageous . tests import ViewTest from Vintageous . vi . utils import modes test_data = namedtuple ( '' , '' ) NORMAL_CASES = ( test_data ( '' , ( , ) , '' , modes . NORMAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . NORMAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . NORMAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . NORMAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . NORMAL , ( , ) , '' ) , ) INTERNAL_NORMAL_CASES = ( test_data ( '' , ( , ) , '' , modes . INTERNAL_NORMAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . INTERNAL_NORMAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . INTERNAL_NORMAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . INTERNAL_NORMAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . INTERNAL_NORMAL , ( , ) , '' ) , ) VISUAL_MULTI_CHAR_CASES = ( test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , ) VISUAL_ONE_CHAR_CASES = ( test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , ) VISUAL_MULTI_MATCHES_CASES = ( test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , ) VISUAL_MULTI_LINE_CASES = ( test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , test_data ( '' , ( , ) , '' , modes . VISUAL , ( , ) , '' ) , ) SKIP_CASES = ( ", "answer": "test_data ( '' , ( , ) , '' , modes . NORMAL , ( , ) , '' ) ,"}, {"prompt": " import sys import os import zipfile from botocore . compat import six advance_iterator = six . advance_iterator PY3 = six . PY3 queue = six . moves . queue shlex_quote = six . moves . shlex_quote StringIO = six . StringIO urlopen = six . moves . urllib . request . urlopen try : import zlib ZIP_COMPRESSION_MODE = zipfile . ZIP_DEFLATED except ImportError : ZIP_COMPRESSION_MODE = zipfile . ZIP_STORED class BinaryStdout ( object ) : def __enter__ ( self ) : if sys . platform == \"\" : import msvcrt self . previous_mode = msvcrt . setmode ( sys . stdout . fileno ( ) , ", "answer": "os . O_BINARY )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Tangible ( )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ] operations = [ migrations . CreateModel ( name = '' , fields = [ ", "answer": "( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) ,"}, {"prompt": " from datetime import datetime from django . utils . timezone import make_aware from recurrence import choices from recurrence . models import Date , Recurrence , Rule import pytest import pytz import recurrence def aware ( dt ) : return make_aware ( dt , pytz . utc ) @ pytest . mark . django_db ", "answer": "def test_recurrence_to_recurrence_object ( ) :"}, {"prompt": " import numpy as np import theano import theano . tensor as T import lasagne as nn import data import load import nn_plankton import dihedral import tmp_dnn import tta patch_sizes = [ ( , ) , ( , ) ] augmentation_params = { '' : ( / , ) , '' : ( , ) , '' : ( - , ) , '' : ( - , ) , '' : True , '' : , } batch_size = // chunk_size = // num_chunks_train = momentum = learning_rate_schedule = { : , : , : , } validate_every = save_every = def estimate_scale ( img ) : return np . maximum ( img . shape [ ] , img . shape [ ] ) / scale_factors = [ estimate_scale , ] augmentation_transforms_test = tta . build_quasirandom_transforms ( , ** { '' : ( / , ) , '' : ( , ) , '' : ( - , ) , '' : ( - , ) , '' : True , '' : , } ) data_loader = load . ZmuvMultiscaleDataLoader ( scale_factors = scale_factors , num_chunks_train = num_chunks_train , patch_sizes = patch_sizes , chunk_size = chunk_size , augmentation_params = augmentation_params , augmentation_transforms_test = augmentation_transforms_test ) Conv2DLayer = tmp_dnn . Conv2DDNNLayer MaxPool2DLayer = tmp_dnn . MaxPool2DDNNLayer def build_model ( ) : l0_variable = nn . layers . InputLayer ( ( batch_size , , patch_sizes [ ] [ ] , patch_sizes [ ] [ ] ) ) l0c = dihedral . CyclicSliceLayer ( l0_variable ) l1a = Conv2DLayer ( l0c , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l1b = Conv2DLayer ( l1a , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l1 = MaxPool2DLayer ( l1b , ds = ( , ) , strides = ( , ) ) l2a = Conv2DLayer ( l1 , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l2b = Conv2DLayer ( l2a , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l2 = MaxPool2DLayer ( l2b , ds = ( , ) , strides = ( , ) ) l3a = Conv2DLayer ( l2 , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l3b = Conv2DLayer ( l3a , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l3c = Conv2DLayer ( l3b , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l3 = MaxPool2DLayer ( l3c , ds = ( , ) , strides = ( , ) ) l4a = Conv2DLayer ( l3 , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l4b = Conv2DLayer ( l4a , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l4c = Conv2DLayer ( l4b , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l4 = MaxPool2DLayer ( l4c , ds = ( , ) , strides = ( , ) ) l4f = nn . layers . flatten ( l4 ) l5 = nn . layers . DenseLayer ( nn . layers . dropout ( l4f , p = ) , num_units = , W = nn_plankton . Orthogonal ( ) , b = nn . init . Constant ( ) ) l5r = dihedral . CyclicRollLayer ( l5 ) l6 = nn . layers . DenseLayer ( nn . layers . dropout ( l5r , p = ) , num_units = , W = nn_plankton . Orthogonal ( ) , b = nn . init . Constant ( ) ) l_variable = dihedral . CyclicPoolLayer ( l6 , pool_function = nn_plankton . rms ) l0_fixed = nn . layers . InputLayer ( ( batch_size , , patch_sizes [ ] [ ] , patch_sizes [ ] [ ] ) ) l0c = dihedral . CyclicSliceLayer ( l0_fixed ) l1a = Conv2DLayer ( l0c , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l1b = Conv2DLayer ( l1a , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l1 = MaxPool2DLayer ( l1b , ds = ( , ) , strides = ( , ) ) l2a = Conv2DLayer ( l1 , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l2b = Conv2DLayer ( l2a , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l2 = MaxPool2DLayer ( l2b , ds = ( , ) , strides = ( , ) ) l3a = Conv2DLayer ( l2 , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l3b = Conv2DLayer ( l3a , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l3c = Conv2DLayer ( l3b , num_filters = , filter_size = ( , ) , border_mode = \"\" , W = nn_plankton . Conv2DOrthogonal ( ) , b = nn . init . Constant ( ) ) l3 = MaxPool2DLayer ( l3c , ds = ( , ) , strides = ( , ) ) ", "answer": "l3f = nn . layers . flatten ( l3 )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " import importlib PLUGINS = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , ", "answer": "\"\" : \"\" ,"}, {"prompt": " import os , sys , subprocess , hashlib , urllib , tempfile , shutil from locale import normalize sys . path . append ( os . path . dirname ( os . path . dirname ( __file__ ) ) ) import timesavers , xxdg . DesktopEntry , xxdg . BaseDirectory def get_appimages_in_dir ( directory ) : \"\" list = [ ] files = timesavers . run_shell_command ( \"\" + directory + \"\" ) for file in files : AI = AppImage ( file ) if AI . check_whether_is_appimage ( ) == True : list . append ( AI ) return list class AppImage : def __init__ ( self , path ) : self . path = os . path . normpath ( os . path . abspath ( path ) ) self . path_md5 = hashlib . md5 ( '' + urllib . quote ( self . path ) ) . hexdigest ( ) self . is_appimage = False self . iconfile_path = os . path . expanduser ( '' ) + self . path_md5 + '' desktopfiles_location = xxdg . BaseDirectory . xdg_data_home + \"\" self . desktopfile_path = desktopfiles_location + self . path_md5 + \"\" def check_whether_is_appimage ( self ) : \"\" type = timesavers . run_shell_command ( \"\" + os . path . realpath ( self . path ) + \"\" ) if type != None : self . is_appimage = True return True else : return False def get_file ( self , filepath , destination = None ) : \"\" command = \"\" + self . path + \"\" + filepath + \"\" result = timesavers . run_shell_command ( command , False ) if result != \"\" : return result else : return None def get_desktop_filename ( self , destination = None ) : command = \"\" + self . path + \"\" toplevel_files = timesavers . run_shell_command ( command ) for toplevel_file in toplevel_files : if \"\" in toplevel_file : return toplevel_file def get_icon_filename ( self , destination = None ) : return \"\" def get_file_list ( self ) : command = \"\" + self . path + \"\" return timesavers . run_shell_command ( command ) def install_desktop_integration ( self , parentifthreaded = None ) : if not os . path . exists ( self . iconfile_path ) : try : os . makedirs ( os . path . dirname ( self . iconfile_path ) ) except : pass print \"\" % ( self . iconfile_path ) f = open ( self . iconfile_path , \"\" ) f . write ( self . get_file ( \"\" ) ) f . close ( ) if not os . path . exists ( self . desktopfile_path ) : try : os . makedirs ( os . path . dirname ( self . desktopfile_path ) ) except : pass print \"\" % ( self . desktopfile_path ) f = tempfile . NamedTemporaryFile ( delete = False ) f . write ( self . get_file ( self . get_desktop_filename ( ) ) ) f . close ( ) desktop = xxdg . DesktopEntry . DesktopEntry ( ) desktop . parse ( f . name ) desktop . set ( \"\" , desktop . get ( \"\" ) ) desktop . set ( \"\" , desktop . get ( \"\" ) ) try : if desktop . get ( \"\" ) : desktop . set ( \"\" , desktop . get ( \"\" ) ) desktop . set ( \"\" , self . path ) except : pass desktop . set ( \"\" , self . iconfile_path ) desktop . set ( \"\" , self . path ) desktop . set ( \"\" , \"\" ) desktop . set ( \"\" , '' + self . path + '' ) desktop . write ( f . name ) os . chmod ( f . name , ) print self . desktopfile_path shutil . move ( f . name , self . desktopfile_path ) if os . env ( \"\" ) == \"\" : timesavers . run_shell_command ( \"\" ) def uninstall_desktop_integration ( self ) : if os . path . isfile ( self . desktopfile_path ) : try : os . unlink ( self . desktopfile_path ) print \"\" % ( self . desktopfile_path ) except : print \"\" % ( self . desktopfile_path ) if os . path . isfile ( self . iconfile_path ) : try : ", "answer": "os . unlink ( self . iconfile_path )"}, {"prompt": " from _GafferImageUI import * import DisplayUI from FormatPlugValueWidget import FormatPlugValueWidget from ChannelMaskPlugValueWidget import ChannelMaskPlugValueWidget import OpenImageIOReaderUI import ImageReaderUI import ImageViewToolbar import ImageTransformUI import ConstantUI import ImageSwitchUI import ColorSpaceUI import ImageContextVariablesUI import ImageStatsUI import DeleteChannelsUI import ObjectToImageUI import ClampUI import ImageWriterUI import GradeUI import ImageTimeWarpUI import ImageSamplerUI import MergeUI import ImageNodeUI import ChannelDataProcessorUI import ImageProcessorUI import ImageMetadataUI import DeleteImageMetadataUI ", "answer": "import CopyImageMetadataUI"}, {"prompt": " from __future__ import absolute_import ", "answer": "from . . import __version__ as version"}, {"prompt": " from cement . core . foundation import CementApp from cement . core . controller import CementBaseController , expose from cement . core import handler class MyBaseController ( CementBaseController ) : class Meta : label = '' class MySecondController ( CementBaseController ) : class Meta : label = '' stacked_type = '' stacked_on = '' description = '' arguments = [ ( [ '' , '' ] , dict ( help = '' , action = '' ) ) , ( [ '' ] , ", "answer": "dict ( action = '' , nargs = '' ) ) ,"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from social . backends . oauth import BaseOAuth1"}, {"prompt": " from datetime import datetime , timedelta from nose . tools import eq_ from kitsune . announcements . models import Announcement from kitsune . announcements . tests import AnnouncementFactory from kitsune . sumo . tests import TestCase from kitsune . users . tests import UserFactory , GroupFactory from kitsune . wiki . tests import LocaleFactory class AnnouncementModelTests ( TestCase ) : def setUp ( self ) : super ( AnnouncementModelTests , self ) . setUp ( ) self . creator = UserFactory ( ) self . group = GroupFactory ( ) self . locale = LocaleFactory ( locale = '' ) self . creator . groups . add ( self . group ) def test_active ( self ) : \"\"\"\"\"\" AnnouncementFactory ( show_after = datetime . now ( ) - timedelta ( days = ) , show_until = datetime . now ( ) + timedelta ( days = ) ) eq_ ( , Announcement . get_site_wide ( ) . count ( ) ) def test_always_visible ( self ) : \"\"\"\"\"\" AnnouncementFactory ( show_after = datetime . now ( ) + timedelta ( days = ) ) AnnouncementFactory ( show_after = datetime . now ( ) - timedelta ( days = ) , content = '' ) ", "answer": "site_wide = Announcement . get_site_wide ( )"}, {"prompt": " from django . test import TestCase from wall . forms import WallItemForm class TestWallItemForm ( TestCase ) : def setUp ( self ) : self . form = WallItemForm ( ) def tearDown ( self ) : ", "answer": "pass"}, {"prompt": " import sys , os , re from setuptools import setup , find_packages ", "answer": "DEPS = [ '' , '' ]"}, {"prompt": " from atom . api import Typed , ForwardTyped , Enum , Range , observe from enaml . core . declarative import d_ ", "answer": "from . toolkit_object import ToolkitObject , ProxyToolkitObject"}, {"prompt": " \"\"\"\"\"\" import os import yaml ", "answer": "import cloudferry_devlab . tests . config as config"}, {"prompt": " import click import os import requests import sys import json from soccer import leagueids from soccer . exceptions import IncorrectParametersException , APIErrorException from soccer . writers import get_writer BASE_URL = '' LIVE_URL = '' LEAGUE_IDS = leagueids . LEAGUE_IDS def load_json ( file ) : \"\"\"\"\"\" here = os . path . dirname ( os . path . abspath ( __file__ ) ) with open ( os . path . join ( here , file ) ) as jfile : data = json . load ( jfile ) return data TEAM_DATA = load_json ( \"\" ) [ \"\" ] TEAM_NAMES = { team [ \"\" ] : team [ \"\" ] for team in TEAM_DATA } def get_input_key ( ) : \"\"\"\"\"\" click . secho ( \"\" , fg = \"\" , bold = True ) click . secho ( \"\" . format ( BASE_URL ) , fg = \"\" , bold = True ) while True : confkey = click . prompt ( click . style ( \"\" , fg = \"\" , bold = True ) ) if len ( confkey ) == : try : int ( confkey , ) except ValueError : click . secho ( \"\" , fg = \"\" , bold = True ) else : break else : click . secho ( \"\" , fg = \"\" , bold = True ) return confkey def load_config_key ( ) : \"\"\"\"\"\" global api_token try : api_token = os . environ [ '' ] except KeyError : home = os . path . expanduser ( \"\" ) config = os . path . join ( home , \"\" ) if not os . path . exists ( config ) : with open ( config , \"\" ) as cfile : key = get_input_key ( ) cfile . write ( key ) else : with open ( config , \"\" ) as cfile : key = cfile . read ( ) if key : api_token = key else : os . remove ( config ) click . secho ( '' '' '' '' . format ( BASE_URL ) , fg = \"\" , bold = True ) sys . exit ( ) return api_token def _get ( url ) : \"\"\"\"\"\" req = requests . get ( BASE_URL + url , headers = headers ) if req . status_code == requests . codes . ok : return req if req . status_code == requests . codes . bad : raise APIErrorException ( '' ) if req . status_code == requests . codes . forbidden : raise APIErrorException ( '' ) if req . status_code == requests . codes . not_found : raise APIErrorException ( '' ) if req . status_codes == requests . codes . too_many_requests : raise APIErrorException ( '' ) def get_live_scores ( writer , use_12_hour_format ) : \"\"\"\"\"\" req = requests . get ( LIVE_URL ) if req . status_code == requests . codes . ok : scores = req . json ( ) if len ( scores [ \"\" ] ) == : click . secho ( \"\" , fg = \"\" , bold = True ) return writer . live_scores ( scores , use_12_hour_format ) else : click . secho ( \"\" , fg = \"\" , bold = True ) def get_team_scores ( team , time , writer , show_upcoming , use_12_hour_format ) : \"\"\"\"\"\" team_id = TEAM_NAMES . get ( team , None ) time_frame = '' if show_upcoming else '' if team_id : try : req = _get ( '' . format ( team_id = team_id , time_frame = time_frame , time = time ) ) team_scores = req . json ( ) if len ( team_scores [ \"\" ] ) == : click . secho ( \"\" \"\" , fg = \"\" , bold = True ) else : writer . team_scores ( team_scores , time , show_upcoming , use_12_hour_format ) except APIErrorException as e : click . secho ( e . args [ ] , fg = \"\" , bold = True ) else : click . secho ( \"\" , fg = \"\" , bold = True ) def get_standings ( league , writer ) : \"\"\"\"\"\" league_id = LEAGUE_IDS [ league ] try : req = _get ( '' . format ( id = league_id ) ) writer . standings ( req . json ( ) , league ) except APIErrorException : click . secho ( \"\" . format ( league = league ) , fg = \"\" , bold = True ) def get_league_scores ( league , time , writer , show_upcoming , use_12_hour_format ) : \"\"\"\"\"\" time_frame = '' if show_upcoming else '' if league : try : league_id = LEAGUE_IDS [ league ] req = _get ( '' . format ( id = league_id , time_frame = time_frame , time = str ( time ) ) ) fixtures_results = req . json ( ) if len ( fixtures_results [ \"\" ] ) == : click . secho ( \"\" . format ( league = league ) , fg = \"\" , bold = True ) return writer . league_scores ( fixtures_results , time , show_upcoming , use_12_hour_format ) except APIErrorException : click . secho ( \"\" , fg = \"\" , bold = True ) else : try : req = _get ( '' . format ( time_frame = time_frame , time = str ( time ) ) ) fixtures_results = req . json ( ) writer . league_scores ( fixtures_results , time , show_upcoming , use_12_hour_format ) except APIErrorException : click . secho ( \"\" , fg = \"\" , bold = True ) def get_team_players ( team , writer ) : \"\"\"\"\"\" team_id = TEAM_NAMES . get ( team , None ) try : req = _get ( '' . format ( team_id = team_id ) ) team_players = req . json ( ) if int ( team_players [ \"\" ] ) == : click . secho ( \"\" , fg = \"\" , bold = True ) else : writer . team_players ( team_players ) except APIErrorException : click . secho ( \"\" , fg = \"\" , bold = True ) def map_team_id ( code ) : \"\"\"\"\"\" for team in TEAM_DATA : if team [ \"\" ] == code : click . secho ( team [ \"\" ] , fg = \"\" ) break else : click . secho ( \"\" , fg = \"\" , bold = True ) def list_team_codes ( ) : \"\"\"\"\"\" cleanlist = sorted ( TEAM_DATA , key = lambda k : ( k [ \"\" ] [ \"\" ] , k [ \"\" ] ) ) leaguenames = sorted ( list ( set ( [ team [ \"\" ] [ \"\" ] for team in cleanlist ] ) ) ) for league in leaguenames : teams = [ team for team in cleanlist if team [ \"\" ] [ \"\" ] == league ] click . secho ( league , fg = \"\" , bold = True ) for team in teams : if team [ \"\" ] != \"\" : click . secho ( u\"\" . format ( team [ \"\" ] , team [ \"\" ] ) , fg = \"\" ) click . secho ( \"\" ) @ click . command ( ) @ click . option ( '' , default = load_config_key , help = \"\" ) @ click . option ( '' , '' , is_flag = True , help = \"\" ) @ click . option ( '' , is_flag = True , help = \"\" ) @ click . option ( '' , is_flag = True , default = False , help = \"\" ) @ click . option ( '' , is_flag = True , help = \"\" ) @ click . option ( '' , '' , type = click . Choice ( LEAGUE_IDS . keys ( ) ) , help = ( \"\" \"\" ) ) @ click . option ( '' , is_flag = True , help = \"\" ) @ click . option ( '' , type = click . Choice ( TEAM_NAMES . keys ( ) ) , help = ( \"\" \"\" ) ) @ click . option ( '' , is_flag = True , help = \"\" ) @ click . option ( '' , default = , help = \"\" ) @ click . option ( '' , is_flag = True , default = False , help = \"\" ) @ click . option ( '' , '' , flag_value = '' , default = True , help = \"\" ) @ click . option ( '' , '' , flag_value = '' , help = '' ) @ click . option ( '' , '' , flag_value = '' , help = '' ) @ click . option ( '' , '' , default = None , help = \"\" ) def main ( league , time , standings , team , live , use12hour , players , output_format , output_file , upcoming , lookup , listcodes , apikey ) : \"\"\"\"\"\" global headers headers = { '' : apikey } try : if output_format == '' and output_file : raise IncorrectParametersException ( '' '' ) writer = get_writer ( output_format , output_file ) if listcodes : list_team_codes ( ) return if live : get_live_scores ( writer , use12hour ) return if standings : if not league : raise IncorrectParametersException ( '' '' ) get_standings ( league , writer ) return if team : if lookup : map_team_id ( team ) return if players : get_team_players ( team , writer ) return ", "answer": "else :"}, {"prompt": " import os import tempfile from twisted . python import filepath from twisted . trial import unittest from piped import conf , exceptions class ConfigurationManagerTest ( unittest . TestCase ) : def setUp ( self ) : self . cm = conf . ConfigurationManager ( ) def test_get_with_path ( self ) : config = dict ( foo = , bar = dict ( baz = '' ) ) self . cm . _config = config self . assertEquals ( self . cm . get ( '' ) , ) self . assertEquals ( self . cm . get ( '' ) , dict ( baz = '' ) ) self . assertEquals ( self . cm . get ( '' ) , '' ) self . assertEquals ( self . cm . get ( '' , '' ) , '' ) self . assertEquals ( self . cm . get ( ( '' , '' ) , '' ) , '' ) def test_set_with_path ( self ) : config = dict ( foo = , bar = dict ( baz = '' ) ) self . cm . _config = config self . cm . set ( '' , ) self . assertEquals ( self . cm . get ( '' ) , ) self . cm . set ( '' , '' ) self . assertEquals ( self . cm . get ( '' ) , dict ( baz = '' ) ) self . assertEquals ( self . cm . get ( '' ) , '' ) self . cm . set ( '' , '' ) self . assertEquals ( self . cm . get ( '' ) , dict ( b = '' ) ) self . assertEquals ( self . cm . get ( '' ) , '' ) self . assertEquals ( self . cm . get ( '' ) , dict ( foo = , bar = dict ( baz = '' ) , a = dict ( b = '' ) ) ) self . assertEquals ( self . cm . setdefault ( '' , '' ) , '' ) self . assertEquals ( self . cm . setdefault ( '' , '' ) , '' ) def test_loading_nonexistent ( self ) : nonexistent_file = filepath . FilePath ( __file__ ) . sibling ( '' ) self . assertRaises ( exceptions . ConfigurationError , self . cm . load_from_file , nonexistent_file ) def test_loading ( self ) : test_config_file = filepath . FilePath ( __file__ ) . parent ( ) . preauthChild ( os . path . join ( '' , '' ) ) self . cm . load_from_file ( test_config_file ) self . assertEquals ( self . cm . get ( '' ) , { '' : { '' : { '' : '' , '' : } } } ) def test_loading_invalid ( self ) : ", "answer": "test_invalid_config_file = filepath . FilePath ( __file__ ) . parent ( ) . preauthChild ( os . path . join ( '' , '' ) )"}, {"prompt": " \"\"\"\"\"\" import argparse import sys from oauth2client import client DEFAULT_CLIENT_ID = None DEFAULT_CLIENT_SECRET = None SCOPE = u'' parser = argparse . ArgumentParser ( description = '' '' ) parser . add_argument ( '' , default = DEFAULT_CLIENT_ID , help = '' ) parser . add_argument ( '' , default = DEFAULT_CLIENT_SECRET , help = '' '' ) parser . add_argument ( '' , default = None , help = '' '' ) def main ( client_id , client_secret , scopes ) : \"\"\"\"\"\" flow = client . OAuth2WebServerFlow ( client_id = client_id , client_secret = client_secret , scope = scopes , user_agent = '' , redirect_uri = '' ) authorize_url = flow . step1_get_authorize_url ( ) print ( '' '' % ( authorize_url ) ) print '' code = raw_input ( '' ) . strip ( ) try : credential = flow . step2_exchange ( code ) except client . FlowExchangeError , e : print '' % e sys . exit ( ) else : print ( '' '' % ( credential . access_token , credential . refresh_token ) ) if __name__ == '' : args = parser . parse_args ( ) configured_scopes = [ SCOPE ] if not ( any ( [ args . client_id , DEFAULT_CLIENT_ID ] ) and any ( [ args . client_secret , DEFAULT_CLIENT_SECRET ] ) ) : raise AttributeError ( '' ) if args . additional_scopes : configured_scopes . extend ( args . additional_scopes . replace ( '' , '' ) . split ( '' ) ) ", "answer": "main ( args . client_id , args . client_secret , configured_scopes ) "}, {"prompt": " from __future__ import unicode_literals import warnings import django from django . db import models class FilteredQuerysetManager ( models . Manager ) : def __init__ ( self , * args , ** kwargs ) : self . args = args ", "answer": "self . kwargs = kwargs"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " \"\"\"\"\"\" import os from pkgutil import walk_packages import socket import sys import tempfile import traceback import time from pip import commands from pip . log import logger from pip . baseparser import parser , ConfigOptionParser , UpdatingDefaultsHelpFormatter from pip . download import urlopen from pip . exceptions import ( BadCommand , InstallationError , UninstallationError , CommandError ) from pip . backwardcompat import StringIO from pip . status_codes import SUCCESS , ERROR , UNKNOWN_ERROR , VIRTUALENV_NOT_FOUND from pip . util import get_prog __all__ = [ '' , '' , '' , '' , '' ] command_dict = { } get_proxy = urlopen . get_proxy class Command ( object ) : name = None usage = None hidden = False def __init__ ( self ) : assert self . name self . parser = ConfigOptionParser ( usage = self . usage , prog = '' % ( get_prog ( ) , self . name ) , version = parser . version , formatter = UpdatingDefaultsHelpFormatter ( ) , name = self . name ) for option in parser . option_list : if not option . dest or option . dest == '' : continue self . parser . add_option ( option ) command_dict [ self . name ] = self def merge_options ( self , initial_options , options ) : for attr in [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] : setattr ( options , attr , getattr ( initial_options , attr ) or getattr ( options , attr ) ) options . quiet += initial_options . quiet options . verbose += initial_options . verbose def setup_logging ( self ) : pass def main ( self , args , initial_options ) : options , args = self . parser . parse_args ( args ) self . merge_options ( initial_options , options ) level = level += options . verbose level -= options . quiet level = logger . level_for_integer ( - level ) complete_log = [ ] logger . consumers . extend ( [ ( level , sys . stdout ) , ( logger . DEBUG , complete_log . append ) ] ) if options . log_explicit_levels : logger . explicit_levels = True self . setup_logging ( ) if options . no_input : os . environ [ '' ] = '' if options . exists_action : os . environ [ '' ] = '' . join ( options . exists_action ) if options . require_venv : if not os . environ . get ( '' ) : logger . fatal ( '' ) sys . exit ( VIRTUALENV_NOT_FOUND ) if options . log : log_fp = open_logfile ( options . log , '' ) logger . consumers . append ( ( logger . DEBUG , log_fp ) ) else : log_fp = None socket . setdefaulttimeout ( options . timeout or None ) urlopen . setup ( proxystr = options . proxy , prompting = not options . no_input ) exit = SUCCESS store_log = False try : status = self . run ( options , args ) if isinstance ( status , int ) : exit = status except ( InstallationError , UninstallationError ) : ", "answer": "e = sys . exc_info ( ) [ ]"}, {"prompt": " from parakeet import jit @ jit def avg ( x , y , z ) : \"\"\"\"\"\" return ( x + y + z ) / import numpy as np N = x = np . random . randn ( N ) y = np . random . randn ( N ) ", "answer": "z = np . random . randn ( N )"}, {"prompt": " import sys from mock import patch from . . utils import is_interactive from nose . tools import assert_false , assert_true def test_is_interactive_crippled_stdout ( ) : class mocked_out ( object ) : \"\"\"\"\"\" def write ( self , * args , ** kwargs ) : pass class mocked_isatty ( mocked_out ) : def isatty ( self ) : return True for inout in ( '' , '' , '' ) : with patch ( '' % inout , mocked_out ( ) ) : assert_false ( is_interactive ( ) ) ", "answer": "with patch ( '' , mocked_isatty ( ) ) , patch ( '' , mocked_isatty ( ) ) , patch ( '' , mocked_isatty ( ) ) :"}, {"prompt": " '''''' from __future__ import absolute_import , division , print_function import re import os ", "answer": "import sys"}, {"prompt": " from getpass import getpass try : input = raw_input except NameError : pass from ... gafferd . util import confirm from ... httpclient . base import GafferConflict from ... httpclient . users import Users from . base import Command class UserAdd ( Command ) : \"\"\"\"\"\" name = \"\" short_descr = \"\" def run ( self , config , args ) : server = config . get ( '' ) username = args [ '' ] password = args [ '' ] api_key = args [ '' ] user_type = args [ \"\" ] try : if username is None : while True : username = input ( \"\" ) if username and username is not None : break print ( \"\" ) if password is None : while True : password = getpass ( \"\" ) if password and password is not None : break print ( \"\" ) while True : confirm_password = getpass ( \"\" ) if confirm_password == password : break print ( \"\" ) if api_key is None : api_key = input ( \"\" ) if not api_key : api_key = None if user_type is None or not user_type . isdigit ( ) : while True : user_type = input ( \"\" ) if user_type . isdigit ( ) or not user_type : break print ( \"\" ) except KeyboardInterrupt : ", "answer": "return"}, {"prompt": " import pytest @ pytest . fixture def context ( ) : \"\"\"\"\"\" return { u'' : { ", "answer": "u'' : u'' ,"}, {"prompt": " from django . conf . urls . defaults import * from modernizr import test_views urlpatterns = patterns ( '' , url ( r'' , test_views . test_view ) , url ( r'' , test_views . test_view_with_content_length ) , ", "answer": "url ( r'' , test_views . test_view_with_charset ) ,"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os from collections import defaultdict from contextlib import contextmanager from pants . goal . products import MultipleRootedProducts , Products ", "answer": "from pants . util . contextutil import temporary_dir"}, {"prompt": " import abc import logging import math from collections import defaultdict from fn import _ from fn . iters import map , filter from . manipulator import Parameter from . metatechniques import RecyclingMetaTechnique from . technique import SequentialSearchTechnique , register log = logging . getLogger ( __name__ ) class SimplexTechnique ( SequentialSearchTechnique ) : \"\"\"\"\"\" def __init__ ( self , seed_cfg = None , * args , ** kwargs ) : super ( SimplexTechnique , self ) . __init__ ( * args , ** kwargs ) self . centroid = None self . last_simplex_points = None self . seed_cfg = seed_cfg self . simplex_points = [ ] def calculate_centroid ( self ) : \"\"\"\"\"\" sums = defaultdict ( float ) counts = defaultdict ( int ) for config in self . simplex_points : cfg = config . data for param in self . manipulator . parameters ( cfg ) : if param . is_primitive ( ) : sums [ param . name ] += param . get_unit_value ( cfg ) counts [ param . name ] += centroid = self . manipulator . copy ( self . simplex_points [ ] . data ) for param in self . manipulator . parameters ( centroid ) : if param . is_primitive ( ) : param . set_unit_value ( centroid , sums [ param . name ] / float ( counts [ param . name ] ) ) return centroid def cfg_to_str ( self , cfg ) : params = list ( filter ( Parameter . is_primitive , self . manipulator . parameters ( cfg ) ) ) params . sort ( key = _ . name ) return str ( tuple ( map ( lambda x : x . get_unit_value ( cfg ) , params ) ) ) def debug_log ( self ) : for i , config in enumerate ( self . simplex_points ) : log . debug ( \"\" , i , self . cfg_to_str ( config . data ) ) if self . centroid : log . debug ( \"\" , self . cfg_to_str ( self . centroid ) ) def linear_point ( self , p1 , p2 , scale ) : \"\"\"\"\"\" return self . manipulator . linear_config ( , p1 , scale , p1 , - scale , p2 ) def convergence_criterea ( self ) : \"\"\"\"\"\" if self . rounds_since_novel_request > * len ( self . simplex_points ) + : return True if self . last_simplex_points == self . simplex_points : return True self . last_simplex_points = list ( self . simplex_points ) return False def initial_simplex_seed ( self ) : \"\"\"\"\"\" if self . seed_cfg is not None : return self . seed_cfg return self . manipulator . random ( ) @ abc . abstractmethod def initial_simplex ( self ) : \"\"\"\"\"\" return [ ] class RandomInitialMixin ( object ) : \"\"\"\"\"\" def initial_simplex ( self ) : cfg0 = self . initial_simplex_seed ( ) params = self . manipulator . parameters ( cfg0 ) return [ cfg0 ] + [ self . manipulator . random ( ) for p in params if p . is_primitive ( ) ] class RightInitialMixin ( object ) : \"\"\"\"\"\" def __init__ ( self , initial_unit_edge_length = , * args , ** kwargs ) : assert initial_unit_edge_length <= self . initial_unit_edge_length = initial_unit_edge_length super ( RightInitialMixin , self ) . __init__ ( * args , ** kwargs ) def initial_simplex ( self ) : cfg0 = self . initial_simplex_seed ( ) simplex = [ cfg0 ] params = self . manipulator . parameters ( cfg0 ) params = filter ( lambda x : x . is_primitive ( ) , params ) for p in params : simplex . append ( self . manipulator . copy ( cfg0 ) ) v = p . get_unit_value ( simplex [ - ] ) if v <= : v += self . initial_unit_edge_length else : v -= self . initial_unit_edge_length p . set_unit_value ( simplex [ - ] , v ) return simplex class RegularInitialMixin ( object ) : \"\"\"\"\"\" def __init__ ( self , initial_unit_edge_length = , * args , ** kwargs ) : assert initial_unit_edge_length <= self . initial_unit_edge_length = initial_unit_edge_length super ( RegularInitialMixin , self ) . __init__ ( * args , ** kwargs ) def initial_simplex ( self ) : cfg0 = self . initial_simplex_seed ( ) simplex = [ cfg0 ] params = self . manipulator . parameters ( cfg0 ) params = list ( filter ( lambda x : x . is_primitive ( ) , params ) ) if len ( params ) == : return simplex q = ( ( ( math . sqrt ( len ( params ) + ) - ) / ( len ( params ) * math . sqrt ( ) ) ) * self . initial_unit_edge_length ) p = q + ( ( / math . sqrt ( ) ) * self . initial_unit_edge_length ) base = [ x . get_unit_value ( cfg0 ) for x in params ] for j in xrange ( len ( base ) ) : if max ( p , q ) + base [ j ] > : base [ j ] *= - for i in xrange ( len ( params ) ) : simplex . append ( self . manipulator . copy ( cfg0 ) ) params [ i ] . set_unit_value ( simplex [ - ] , abs ( base [ i ] + p ) ) for j in xrange ( i + , len ( params ) ) : params [ j ] . set_unit_value ( simplex [ - ] , abs ( base [ i ] + q ) ) return simplex class NelderMead ( SimplexTechnique ) : \"\"\"\"\"\" def __init__ ( self , alpha = , gamma = , beta = , sigma = , * args , ** kwargs ) : self . alpha = alpha self . gamma = gamma self . beta = beta self . sigma = sigma super ( NelderMead , self ) . __init__ ( * args , ** kwargs ) @ classmethod def get_hyper_parameters ( cls ) : return [ '' , '' , '' , '' ] def main_generator ( self ) : objective = self . objective driver = self . driver self . simplex_points = list ( map ( driver . get_configuration , self . initial_simplex ( ) ) ) if len ( self . simplex_points ) <= : log . warning ( \"\" , self . name ) return log . debug ( \"\" ) for p in self . simplex_points : self . yield_nonblocking ( p ) yield None while not self . convergence_criterea ( ) : self . simplex_points . sort ( cmp = objective . compare ) self . limit = objective . limit_from_config ( self . simplex_points [ - ] ) self . centroid = self . calculate_centroid ( ) if log . isEnabledFor ( logging . DEBUG ) : self . debug_log ( ) reflection = self . reflection_point ( ) yield reflection if objective . lt ( reflection , self . simplex_points [ ] ) : expansion = self . expansion_point ( reflection ) yield expansion if objective . lt ( expansion , reflection ) : log . debug ( \"\" ) self . simplex_points [ - ] = expansion else : log . debug ( \"\" ) self . simplex_points [ - ] = reflection elif objective . lt ( reflection , self . simplex_points [ ] ) : log . debug ( \"\" ) self . simplex_points [ - ] = reflection else : if objective . lte ( reflection , self . simplex_points [ - ] ) : contract_base = reflection else : contract_base = self . simplex_points [ - ] contraction = self . contraction_point ( contract_base ) yield contraction if objective . lte ( contraction , contract_base ) : log . debug ( \"\" ) self . simplex_points [ - ] = contraction else : log . debug ( \"\" ) self . perform_shrink_reduction ( ) for p in self . simplex_points : self . yield_nonblocking ( p ) yield None def reflection_point ( self ) : \"\"\"\"\"\" return self . driver . get_configuration ( self . linear_point ( self . centroid , self . simplex_points [ - ] . data , self . alpha ) ) def expansion_point ( self , reflection ) : \"\"\"\"\"\" return self . driver . get_configuration ( self . linear_point ( self . centroid , reflection . data , - self . gamma ) ) def contraction_point ( self , contract_base ) : \"\"\"\"\"\" return self . driver . get_configuration ( self . linear_point ( self . centroid , contract_base . data , - self . beta ) ) def perform_shrink_reduction ( self ) : \"\"\"\"\"\" for i in xrange ( , len ( self . simplex_points ) ) : self . simplex_points [ i ] = self . driver . get_configuration ( self . linear_point ( self . simplex_points [ ] . data , self . simplex_points [ i ] . data , - self . sigma ) ) class Torczon ( SimplexTechnique ) : \"\"\"\"\"\" def __init__ ( self , alpha = , gamma = , beta = , * args , ** kwargs ) : self . alpha = alpha self . gamma = gamma self . beta = beta super ( Torczon , self ) . __init__ ( * args , ** kwargs ) @ classmethod def get_hyper_parameters ( cls ) : return [ '' , '' , '' ] def main_generator ( self ) : objective = self . objective driver = self . driver self . simplex_points = list ( map ( driver . get_configuration , self . initial_simplex ( ) ) ) if len ( self . simplex_points ) <= : log . warning ( \"\" , self . name ) return log . debug ( \"\" ) for p in self . simplex_points : self . yield_nonblocking ( p ) yield None self . simplex_points . sort ( cmp = objective . compare ) while not self . convergence_criterea ( ) : self . limit = objective . limit_from_config ( self . simplex_points [ - ] ) if log . isEnabledFor ( logging . DEBUG ) : self . debug_log ( ) reflected = self . reflected_simplex ( ) yield None reflected . sort ( cmp = objective . compare ) if reflected [ ] is not self . simplex_points [ ] : expanded = self . expanded_simplex ( ) yield None expanded . sort ( cmp = objective . compare ) if objective . lt ( expanded [ ] , reflected [ ] ) : log . debug ( \"\" ) self . simplex_points = expanded else : log . debug ( \"\" ) self . simplex_points = reflected else : contracted = self . contracted_simplex ( ) yield None contracted . sort ( cmp = objective . compare ) log . debug ( \"\" ) self . simplex_points = contracted def scaled_simplex ( self , scale ) : \"\"\"\"\"\" simplex = list ( self . simplex_points ) for i in xrange ( , len ( simplex ) ) : simplex [ i ] = self . driver . get_configuration ( self . linear_point ( simplex [ ] . data , simplex [ i ] . data , scale ) ) self . yield_nonblocking ( simplex [ i ] ) return simplex def reflected_simplex ( self ) : return self . scaled_simplex ( self . alpha ) def expanded_simplex ( self ) : return self . scaled_simplex ( self . gamma ) def contracted_simplex ( self ) : return self . scaled_simplex ( - self . beta ) class RandomNelderMead ( RandomInitialMixin , NelderMead ) : pass class RightNelderMead ( RightInitialMixin , NelderMead ) : pass class RegularNelderMead ( RegularInitialMixin , NelderMead ) : pass class RandomTorczon ( RandomInitialMixin , Torczon ) : pass class RightTorczon ( RightInitialMixin , Torczon ) : pass class RegularTorczon ( RegularInitialMixin , Torczon ) : pass class MultiNelderMead ( RecyclingMetaTechnique ) : def __init__ ( self ) : super ( MultiNelderMead , self ) . __init__ ( [ RightNelderMead , RandomNelderMead , RegularNelderMead ] ) class MultiTorczon ( RecyclingMetaTechnique ) : def __init__ ( self ) : super ( MultiTorczon , self ) . __init__ ( [ RightTorczon , RandomTorczon , RegularTorczon ] ) register ( RandomNelderMead ( ) ) register ( RegularNelderMead ( ) ) register ( RightNelderMead ( ) ) register ( MultiNelderMead ( ) ) register ( RandomTorczon ( ) ) ", "answer": "register ( RegularTorczon ( ) )"}, {"prompt": " from django . shortcuts import render_to_response , get_object_or_404 from django . template import RequestContext from dnd . menu import menu_item , submenu_item from dnd . mobile . dnd_paginator import DndMobilePaginator from dnd . filters import DeityFilter from dnd . models import Deity @ menu_item ( \"\" ) def deity_list_mobile ( request ) : f = DeityFilter ( request . GET , queryset = Deity . objects . all ( ) ) form_submitted = if '' in request . GET else paginator = DndMobilePaginator ( f . qs , request ) return render_to_response ( '' , { '' : request , '' : paginator . items ( ) , '' : paginator , '' : f , '' : form_submitted , } , context_instance = RequestContext ( request ) , ) @ menu_item ( \"\" ) def deity_detail_mobile ( request , deity_slug ) : deity = get_object_or_404 ( Deity . objects . select_related ( '' , '' ) , slug = deity_slug ) return render_to_response ( '' , { ", "answer": "'' : deity ,"}, {"prompt": " import pprint from flask import Flask , current_app from flaskext . script import Manager , prompt_choices , Server def create_app ( config = None ) : app = Flask ( __name__ ) app . debug = False print \"\" , config app . config . from_envvar ( '' , silent = True ) @ app . route ( \"\" ) def index ( ) : assert False , \"\" return app manager = Manager ( create_app ) @ manager . command def dumpconfig ( ) : \"\" pprint . pprint ( current_app . config ) @ manager . command def output ( name ) : \"\" print name print type ( name ) @ manager . command def outputplus ( name , url = None ) : \"\" print name , url @ manager . command def getrolesimple ( ) : choices = ( \"\" , \"\" , \"\" ) role = prompt_choices ( \"\" , choices = choices , default = \"\" ) print \"\" , role @ manager . command def getrole ( ) : ", "answer": "choices = ("}, {"prompt": " from __future__ import division import copy from vistrails . db . versions . v0_9_4 . domain import DBVistrail , DBAction , DBTag , DBModule , DBConnection , DBPortSpec , DBFunction , DBParameter , DBLocation , DBAdd , DBChange , DBDelete , DBAnnotation , DBPort , DBGroup , DBWorkflow , DBLog , DBAbstraction def update_workflow ( old_obj , translate_dict ) : return DBWorkflow . update_version ( old_obj . db_workflow , translate_dict , DBWorkflow ( ) ) def update_modules ( old_obj , trans_dict ) : new_modules = [ ] for obj in old_obj . db_modules : if obj . vtType == '' : new_modules . append ( DBModule . update_version ( obj , trans_dict ) ) elif obj . vtType == '' : new_modules . append ( DBAbstraction . update_version ( obj , trans_dict ) ) elif obj . vtType == '' : new_modules . append ( DBGroup . update_version ( obj , trans_dict ) ) return new_modules def translateVistrail ( _vistrail ) : def update_operations ( old_obj , trans_dict ) : def update_abstractionRef ( old_obj , trans_dict ) : def get_internal_version ( old_obj , trans_dict ) : return str ( old_obj . db_version ) def get_version ( old_obj , trans_dict ) : return '' new_dict = { '' : { '' : get_internal_version , '' : get_version } } new_dict . update ( trans_dict ) return DBAbstraction . update_version ( old_obj . db_data , new_dict ) new_ops = [ ] for obj in old_obj . db_operations : if obj . vtType == '' : if obj . db_what == '' : trans_dict [ '' ] = { '' : update_abstractionRef } new_op = DBAdd . update_version ( obj , trans_dict ) new_op . db_what = '' new_ops . append ( new_op ) del trans_dict [ '' ] ", "answer": "else :"}, {"prompt": " import tokenize import warnings from django import template from django_assets import Bundle from django_assets . env import get_env from webassets import six from webassets . exceptions import ImminentDeprecationWarning def parse_debug_value ( value ) : \"\"\"\"\"\" if isinstance ( value , bool ) : return value try : from webassets . env import parse_debug_value return parse_debug_value ( value ) except ValueError : raise template . TemplateSyntaxError ( '' '' % value ) class AssetsNode ( template . Node ) : BundleClass = Bundle def __init__ ( self , filters , depends , output , debug , files , childnodes ) : self . childnodes = childnodes self . output = output self . files = files self . depends = depends self . filters = filters self . debug = debug def resolve ( self , context = { } ) : \"\"\"\"\"\" def resolve_var ( x ) : if x is None : return None else : try : return template . Variable ( x ) . resolve ( context ) except template . VariableDoesNotExist : raise def resolve_depends ( x ) : value = resolve_var ( x ) if isinstance ( value , six . text_type ) : value = value . split ( '' ) return value def resolve_bundle ( name ) : try : return get_env ( ) [ name ] except KeyError : return name return self . BundleClass ( * [ resolve_bundle ( resolve_var ( f ) ) for f in self . files ] , ** { '' : resolve_var ( self . output ) , '' : resolve_var ( self . filters ) , '' : resolve_depends ( self . depends ) , '' : parse_debug_value ( resolve_var ( self . debug ) ) } ) def render ( self , context ) : bundle = self . resolve ( context ) result = u\"\" with bundle . bind ( get_env ( ) ) : for url in bundle . urls ( ) : context . update ( { '' : url , '' : bundle . extra } ) try : result += self . childnodes . render ( context ) finally : context . pop ( ) ", "answer": "return result"}, {"prompt": " \"\"\"\"\"\" __author__ = \"\" from . import support import os import sys import logging from . . import pytree import pgen2 from pgen2 import driver logging . basicConfig ( ) def main ( ) : gr = driver . load_grammar ( \"\" ) dr = driver . Driver ( gr , convert = pytree . convert ) fn = \"\" tree = dr . parse_file ( fn , debug = True ) if not diff ( fn , tree ) : print \"\" if not sys . argv [ : ] : return problems = [ ] for name in sys . modules : mod = sys . modules [ name ] if mod is None or not hasattr ( mod , \"\" ) : continue fn = mod . __file__ if fn . endswith ( \"\" ) : fn = fn [ : - ] if not fn . endswith ( \"\" ) : continue print >> sys . stderr , \"\" , fn tree = dr . parse_file ( fn , debug = True ) if diff ( fn , tree ) : problems . append ( fn ) ", "answer": "for dir in sys . path :"}, {"prompt": " '''''' from __future__ import absolute_import from __future__ import with_statement import logging import threading from . import os_helper if os_helper . isJython ( ) : from com . ziclix . python . sql import zxJDBC else : from . . site_packages import pypyodbc from . import conf threadVar = threading . local ( ) def closeConnection_jdbc ( ) : logger = logging . getLogger ( __name__ ) try : _ = threadVar . connection except : threadVar . connection = None if ( threadVar . connection is not None ) and ( threadVar . connection . closed == False ) : threadVar . connection . close ( ) logger . info ( \"\" ) threadVar . connection = None def closeConnection_odbc ( ) : logger = logging . getLogger ( __name__ ) try : _ = threadVar . connection except : threadVar . connection = None if ( threadVar . connection is not None ) and ( threadVar . connection . connected ) : threadVar . connection . close ( ) logger . info ( \"\" ) threadVar . connection = None def openConnection_jdbc ( ) : logger = logging . getLogger ( __name__ ) try : _ = threadVar . connection except : threadVar . connection = None if threadVar . connection is None : logger . info ( '' ) threadVar . connection = zxJDBC . connect ( conf . tera_url_jdbc , conf . tera_uid_jdbc , conf . tera_pwd_jdbc , conf . tera_driver_jdbc ) logger . info ( '' , ( threadVar . connection , ) ) ", "answer": "return threadVar . connection"}, {"prompt": " '''''' from kivy . app import App from kivy . lang import Builder kv = '''''' ", "answer": "class CircleApp ( App ) :"}, {"prompt": " import json import os import datetime from south . db import db from south . v2 import DataMigration from django . db import models class Migration ( DataMigration ) : def forwards ( self , orm ) : from django . core . management import call_command jf = os . path . join ( os . path . abspath ( os . path . dirname ( __file__ ) ) , \"\" , \"\" , \"\" ) with open ( jf ) as json_fd : data = json_fd . read ( ) groups = json . loads ( data ) for entry in groups : group = orm . bsdGroups ( pk = entry [ '' ] ) for field in entry [ '' ] : mfield = orm . bsdGroups . _meta . get_field ( field ) setattr ( group , field , entry [ '' ] . get ( field ) ) group . save ( ) jf = os . path . join ( os . path . abspath ( os . path . dirname ( __file__ ) ) , \"\" , \"\" , \"\" ) with open ( jf ) as json_fd : data = json_fd . read ( ) users = json . loads ( data ) for entry in users : user = orm . bsdUsers ( pk = entry [ '' ] ) for field in entry [ '' ] : mfield = orm . bsdUsers . _meta . get_field ( field ) if mfield . rel != None : inst = mfield . rel . to . objects . get ( pk = entry [ '' ] . get ( field ) ) setattr ( user , field , inst ) else : setattr ( user , field , entry [ '' ] . get ( field ) ) user . save ( ) def backwards ( self , orm ) : \"\" models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) ", "answer": "} ,"}, {"prompt": " import unittest import threading import time from brewery import ds import brewery . metadata from sqlalchemy import Table , Column , Integer , String , Text from sqlalchemy import create_engine , MetaData class SQLStreamsTestCase ( unittest . TestCase ) : def setUp ( self ) : self . engine = create_engine ( \"\" ) self . metadata = MetaData ( ) self . fields = brewery . metadata . FieldList ( [ ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) ] ) self . example_row = [ \"\" , \"\" , \"\" , \"\" , \"\" , , ] def test_table_fields ( self ) : table = Table ( '' , self . metadata , Column ( '' , Integer , primary_key = True ) , Column ( '' , String ( ) ) , Column ( '' , String ( ) ) , Column ( '' , Text ) ", "answer": ")"}, {"prompt": " from threading import Thread , Event class PeriodicTask ( Thread ) : def __init__ ( self , interval = , target = None ) : super ( PeriodicTask , self ) . __init__ ( ) self . status = Event ( ) self . interval = interval self . target = target self . daemon = True def stop ( self ) : self . status . set ( ) @ property def stopped ( self ) : return self . status . isSet ( ) def run ( self ) : while True : if self . stopped : return self . status . wait ( self . interval ) ", "answer": "self . task ( )"}, {"prompt": " import os . path import unittest2 def get_tests ( ) : ", "answer": "start_dir = os . path . dirname ( __file__ )"}, {"prompt": " import six from six . moves . urllib . parse import urlencode from uuid import uuid4 from struct import unpack def url_concat ( url , args , fragments = None ) : \"\"\"\"\"\" if not args and not fragments : return url while url [ - ] == '' : url = url [ : - ] ", "answer": "fragment_tail = ''"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import sys from gevent . hub import get_hub , getcurrent , _NONE from gevent . _compat import reraise from gevent . hub import InvalidSwitchError from gevent . timeout import Timeout from gevent . _tblib import dump_traceback , load_traceback __all__ = [ '' , '' ] class _AbstractLinkable ( object ) : _notifier = None def __init__ ( self ) : self . _links = set ( ) self . hub = get_hub ( ) def ready ( self ) : raise NotImplementedError ( ) def _check_and_notify ( self ) : if self . ready ( ) : if self . _links and not self . _notifier : self . _notifier = self . hub . loop . run_callback ( self . _notify_links ) def rawlink ( self , callback ) : \"\"\"\"\"\" if not callable ( callback ) : raise TypeError ( '' % ( callback , ) ) self . _links . add ( callback ) self . _check_and_notify ( ) def unlink ( self , callback ) : \"\"\"\"\"\" try : self . _links . remove ( callback ) except KeyError : pass def _notify_links ( self ) : todo = set ( self . _links ) for link in todo : if link in self . _links : try : link ( self ) except : self . hub . handle_error ( ( link , self ) , * sys . exc_info ( ) ) if getattr ( link , '' , None ) : self . unlink ( link ) del todo del self . _notifier def _wait_core ( self , timeout , catch = Timeout ) : switch = getcurrent ( ) . switch self . rawlink ( switch ) try : timer = Timeout . _start_new_or_dummy ( timeout ) try : try : result = self . hub . switch ( ) if result is not self : raise InvalidSwitchError ( '' % ( result , ) ) return True except catch as ex : if ex is not timer : raise return False finally : timer . cancel ( ) finally : self . unlink ( switch ) def _wait_return_value ( self , waited , wait_success ) : return None def _wait ( self , timeout = None ) : if self . ready ( ) : return self . _wait_return_value ( False , False ) gotit = self . _wait_core ( timeout ) return self . _wait_return_value ( True , gotit ) class Event ( _AbstractLinkable ) : \"\"\"\"\"\" _flag = False def __str__ ( self ) : return '' % ( self . __class__ . __name__ , ( self . _flag and '' ) or '' , len ( self . _links ) ) def is_set ( self ) : \"\"\"\"\"\" return self . _flag isSet = is_set ready = is_set def set ( self ) : \"\"\"\"\"\" self . _flag = True self . _check_and_notify ( ) def clear ( self ) : \"\"\"\"\"\" self . _flag = False def _wait_return_value ( self , waited , gotit ) : if not waited : flag = self . _flag assert flag , \"\" return flag return gotit def wait ( self , timeout = None ) : \"\"\"\"\"\" return self . _wait ( timeout ) def _reset_internal_locks ( self ) : pass class AsyncResult ( _AbstractLinkable ) : \"\"\"\"\"\" _value = _NONE _exc_info = ( ) _notifier = None @ property def _exception ( self ) : return self . _exc_info [ ] if self . _exc_info else _NONE @ property def value ( self ) : \"\"\"\"\"\" return self . _value if self . _value is not _NONE else None @ property def exc_info ( self ) : \"\"\"\"\"\" if self . _exc_info : return ( self . _exc_info [ ] , self . _exc_info [ ] , load_traceback ( self . _exc_info [ ] ) ) return ( ) def __str__ ( self ) : result = '' % ( self . __class__ . __name__ , ) if self . value is not None or self . _exception is not _NONE : result += '' % self . value if self . _exception is not None and self . _exception is not _NONE : result += '' % self . _exception if self . _exception is _NONE : result += '' return result + '' % len ( self . _links ) def ready ( self ) : \"\"\"\"\"\" return self . _exc_info or self . _value is not _NONE def successful ( self ) : \"\"\"\"\"\" return self . _value is not _NONE @ property def exception ( self ) : \"\"\"\"\"\" if self . _exc_info : return self . _exc_info [ ] def set ( self , value = None ) : \"\"\"\"\"\" self . _value = value ", "answer": "self . _check_and_notify ( )"}, {"prompt": " from eucaops import Eucaops import re import time import httplib from xml . etree import ElementTree import sys from eutester . eutestcase import EutesterTestCase from eutester . sshconnection import SshCbReturn from eutester . machine import Machine from conversiontask import ConversionTask class ImageUtils ( EutesterTestCase ) : gig = mb = kb = def __init__ ( self , tester = None , config_file = None , password = \"\" , credpath = None , destpath = None , time_per_gig = , eof = True , worker_hostname = None , worker_keypath = None , worker_username = '' , worker_password = None , worker_machine = None ) : self . setuptestcase ( ) if not tester or not isinstance ( tester , Eucaops ) : self . debug ( '' '' . format ( config_file , password , credpath ) ) self . tester = Eucaops ( config_file = config_file , password = password , credpath = credpath ) else : self . tester = tester self . tester . exit_on_fail = eof self . debugmethod = self . tester . debug self . worker_keypath = worker_keypath or self . tester . keypath self . worker_username = worker_username self . worker_password = worker_password or self . tester . password self . worker_machine = self . _get_worker_machine ( worker_machine ) if destpath is not None : self . destpath = str ( destpath ) else : self . destpath = \"\" self . time_per_gig = time_per_gig self . credpath = credpath or self . tester . credpath def _get_worker_machine ( self , worker ) : '''''' worker = worker or self . tester . clc self . debug ( '' ) if isinstance ( worker , Machine ) : return worker else : self . debug ( '' + str ( worker ) + \"\" ) new_machine = Machine ( hostname = worker , username = self . worker_username , password = self . worker_password , keypath = self . worker_keypath ) return new_machine def getHttpRemoteImageSize ( self , url , unit = None , maxredirect = ) : return ImageUtils . _getHttpRemoteImageSize ( url , unit = unit , maxredirect = maxredirect ) @ staticmethod def _getHttpRemoteImageSize ( url , unit = None , maxredirect = , debug = None ) : '''''' unit = unit or if debug is None : def printdebug ( msg ) : print msg debug = printdebug def get_location ( url , depth , maxdepth ) : if depth > maxdepth : raise ValueError ( '' . format ( depth , maxdepth ) ) conn = None try : url = url . replace ( '' , '' ) host = url . split ( '' ) [ ] path = url . replace ( host , '' ) debug ( \"\" + host + \"\" + path + \"\" ) conn = httplib . HTTPConnection ( host ) conn . request ( \"\" , path ) res = conn . getresponse ( ) location = res . getheader ( '' ) if location and location != url : depth += debug ( '' . format ( depth , location ) ) return get_location ( location , depth = depth , maxdepth = maxdepth ) else : content_length = res . getheader ( '' ) if content_length is None : raise ValueError ( '' . format ( url ) ) fbytes = int ( content_length ) return fbytes except Exception as HE : debug ( '' . format ( url ) ) raise HE finally : if conn : conn . close ( ) try : fbytes = get_location ( url , depth = , maxdepth = maxredirect ) debug ( \"\" + str ( fbytes ) ) if fbytes == : rfsize = else : rfsize = ( ( ( fbytes / unit ) + ) or ) debug ( \"\" + str ( rfsize ) + \"\" ) except Exception , e : debug ( \"\" ) raise e return rfsize def wget_image ( self , url , destpath = None , dest_file_name = None , machine = None , user = None , password = None , retryconn = True , time_per_gig = ) : '''''' machine = machine or self . worker_machine if destpath is None and self . destpath is not None : destpath = self . destpath size = self . getHttpRemoteImageSize ( url ) if ( size < machine . get_available ( destpath , unit = self . __class__ . gig ) ) : raise Exception ( \"\" + str ( destpath ) + \"\" + str ( url ) ) timeout = size * time_per_gig self . debug ( '' + str ( url ) + '' + str ( destpath ) + '' + str ( machine . hostname ) ) saved_location = machine . wget_remote_image ( url , path = destpath , dest_file_name = dest_file_name , user = user , password = password , retryconn = retryconn , timeout = timeout ) return ( size , saved_location ) def get_manifest_obj ( self , path , machine = None , local = False , timeout = ) : '''''' cmd = '' + str ( path ) if not local : machine = machine or self . worker_machine out = machine . cmd ( cmd , timeout = timeout , verbose = False ) if out [ '' ] != : raise Exception ( '' + str ( out [ '' ] ) ) output = out [ '' ] else : output = self . tester . sys ( cmd , timeout = timeout , listformat = False , code = ) xml = ElementTree . fromstring ( output ) return xml def get_manifest_part_count ( self , path , machine = None , local = False , timeout = ) : '''''' manifest_xml = self . get_manifest_obj ( path = path , machine = machine , local = local , timeout = timeout ) image = manifest_xml . find ( '' ) parts = image . find ( '' ) part_count = parts . get ( '' ) self . debug ( '' + str ( path ) + '' + str ( part_count ) ) return int ( part_count ) def get_manifest_image_name ( self , path , machine = None , local = False , timeout = ) : '''''' manifest_xml = self . get_manifest_obj ( path = path , machine = machine , local = local , timeout = timeout ) image = manifest_xml . find ( '' ) name_elem = image . find ( '' ) return name_elem . text def euca2ools_bundle_image ( self , path , machine = None , machine_credpath = None , prefix = None , kernel = None , ramdisk = None , block_device_mapping = None , destination = '' , arch = '' , debug = False , interbundle_timeout = , time_per_gig = None ) : '''''' self . status ( '' . format ( path ) ) time_per_gig = time_per_gig or self . time_per_gig credpath = machine_credpath or self . credpath machine = machine or self . worker_machine image_size = machine . get_file_size ( path ) / self . gig or timeout = time_per_gig * image_size cbargs = [ timeout , interbundle_timeout , time . time ( ) , , True ] if destination is None : destination = machine . sys ( '' ) [ ] freesize = machine . get_available ( str ( destination ) , ( self . gig / self . kb ) ) if ( freesize < image_size ) : raise Exception ( \"\" + str ( destination ) ) cmdargs = \"\" if prefix : cmdargs = cmdargs + \"\" + str ( prefix ) if kernel : cmdargs = cmdargs + \"\" + str ( kernel ) if ramdisk : cmdargs = cmdargs + \"\" + str ( ramdisk ) if block_device_mapping : cmdargs = cmdargs + \"\" + str ( block_device_mapping ) if destination : cmdargs = cmdargs + \"\" + str ( destination ) if arch : cmdargs = cmdargs + \"\" + str ( arch ) if debug : cmdargs = cmdargs + \"\" cmdargs = cmdargs + \"\" + str ( path ) if credpath is not None : cmd = '' + str ( credpath ) + '' + str ( cmdargs ) else : skey = self . tester . get_secret_key ( ) akey = self . tester . get_access_key ( ) cmd = '' + str ( akey ) + '' + str ( skey ) + str ( cmdargs ) out = machine . cmd ( cmd , timeout = timeout , listformat = True , cb = self . _bundle_status_cb , cbargs = cbargs ) if out [ '' ] != : raise Exception ( '' + str ( path ) + '' + str ( out [ '' ] ) ) manifest = None for line in out [ '' ] : line = str ( line ) if re . search ( \"\" , line ) : manifest = line . split ( ) [ ] break if manifest is None : raise Exception ( '' + str ( path ) ) self . debug ( '' + str ( path ) + '' + str ( manifest ) ) return manifest def euca2ools_upload_bundle ( self , manifest , machine = None , bucketname = None , machine_credpath = None , debug = False , interbundle_timeout = , timeout = , image_check_timeout = , uniquebucket = True ) : '''''' self . status ( '' . format ( manifest ) ) machine = machine or self . worker_machine credpath = machine_credpath or self . credpath cbargs = [ timeout , interbundle_timeout , time . time ( ) , , True ] bname = '' cmdargs = \"\" manifest = str ( manifest ) upmanifest = None part_count = - try : part_count = self . get_manifest_part_count ( manifest , machine = machine ) except : pass self . debug ( '' + str ( manifest ) + \"\" + str ( bucketname ) + \"\" + str ( part_count ) ) if bucketname : bname = bucketname if uniquebucket : bname = self . _get_unique_bucket_name ( bname ) else : bname = self . _generate_unique_bucket_name_from_manifest ( manifest , unique = uniquebucket ) self . debug ( '' + str ( bname ) ) cmdargs = cmdargs + \"\" + str ( bname ) if debug : cmdargs = cmdargs + \"\" cmdargs = cmdargs + \"\" + str ( bname ) + \"\" + str ( manifest ) if credpath is not None : cmd = '' + str ( credpath ) + '' + str ( cmdargs ) else : skey = self . tester . get_secret_key ( ) akey = self . tester . get_access_key ( ) cmd = '' + str ( akey ) + '' + str ( skey ) + str ( cmdargs ) out = machine . cmd ( cmd , timeout = image_check_timeout , listformat = True , cb = self . _bundle_status_cb , cbargs = cbargs ) if out [ '' ] != : raise Exception ( '' + str ( manifest ) + '' + str ( out [ '' ] ) ) for line in out [ '' ] : line = str ( line ) if re . search ( '' , line ) and re . search ( '' , line ) : upmanifest = line . split ( ) . pop ( ) break if upmanifest is None : raise Exception ( '' '' ) self . debug ( '' + str ( manifest ) + '' + str ( upmanifest ) ) return upmanifest def euca2ools_bundle_and_upload ( self , file , arch , bucket , prefix = None , directory = None , kernel = None , ramdisk = None , block_device_map = [ ] , product_codes = None , acl = None , location = None , ) : raise NotImplemented ( '' '' ) def euca2ools_register ( self , manifest , name , description = None , arch = None , kernel = None , ramdisk = None , root_device_name = None , snapshot_id = None , block_dev_map = [ ] , virtualization_type = None , platform = None , machine = None , machine_credpath = None ) : self . status ( '' . format ( manifest , kernel , ramdisk ) ) machine = machine or self . worker_machine credpath = machine_credpath or self . credpath cmdargs = str ( manifest ) + \"\" + str ( name ) emi = None if description : cmdargs += '' + str ( description ) if arch : cmdargs += '' + str ( arch ) if kernel : cmdargs += '' + str ( kernel ) if ramdisk : cmdargs += '' + str ( ramdisk ) if root_device_name : cmdargs += '' + str ( root_device_name ) if snapshot_id : cmdargs += '' + str ( snapshot_id ) for dev in block_dev_map : cmdargs += '' + str ( dev ) if virtualization_type : cmdargs += '' + str ( virtualization_type ) if platform : cmdargs += '' + str ( platform ) if credpath is not None : cmd = '' + str ( credpath ) + '' + str ( cmdargs ) else : skey = self . tester . get_secret_key ( ) akey = self . tester . get_access_key ( ) cmd = ( '' + str ( akey ) + '' + str ( skey ) + str ( cmdargs ) ) out = machine . sys ( cmd = cmd , code = ) for line in out : if re . search ( '' , line ) : emi = line . split ( ) . pop ( ) . strip ( ) assert emi , '' + str ( emi ) + '' self . tester . test_resources [ \"\" ] . append ( self . tester . ec2 . get_all_images ( [ emi ] ) [ ] ) return emi def euca2ools_download_bundle ( self , bucket , manifest = None , prefix = None , directory = None , image_name = None , machine = None , machine_credpath = None , ) : machine = machine or self . worker_machine credpath = machine_credpath or self . credpath cmdargs = \"\" + str ( bucket ) if manifest : cmdargs += \"\" + str ( manifest ) if prefix : cmdargs += \"\" + str ( prefix ) if directory : cmdargs += \"\" + str ( directory ) if credpath is not None : cmd = '' + str ( credpath ) + '' + str ( cmdargs ) else : skey = self . tester . get_secret_key ( ) akey = self . tester . get_access_key ( ) cmd = ( '' + str ( akey ) + '' + str ( skey ) + str ( cmdargs ) ) out = machine . sys ( cmd = cmd , code = ) raise NotImplemented ( '' '' ) def euca2ools_download_and_unbundle ( self , bucket , manifest = None , prefix = None , directory = None , maxbytes = None , ) : raise NotImplemented ( '' '' ) def euca2ools_import_volume ( self , import_file , bucket , zone , format , size = None , presigned_manifest_url = None , ", "answer": "prefix = None ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " from setuptools import setup setup_data = { '' : '' , '' : '' , '' : \"\" , '' : open ( '' , '' ) . read ( ) , '' : '' , '' : [ '' , '' , ] , '' : \"\" , '' : [ '' , '' , '' , '' , '' , '' , '' , ] , '' : { '' : [ '' , ] , ", "answer": "} ,"}, {"prompt": " import fnmatch import os ", "answer": "import os . path"}, {"prompt": " \"\"\"\"\"\" ", "answer": "__version__ = '' "}, {"prompt": " import mock import webob from nova . api . openstack . compute . legacy_v2 . contrib import multinic as multinic_v2 from nova . api . openstack . compute import multinic as multinic_v21 from nova import compute from nova import exception from nova import objects from nova import test from nova . tests . unit . api . openstack import fakes UUID = '' last_add_fixed_ip = ( None , None ) last_remove_fixed_ip = ( None , None ) def compute_api_add_fixed_ip ( self , context , instance , network_id ) : global last_add_fixed_ip last_add_fixed_ip = ( instance [ '' ] , network_id ) def compute_api_remove_fixed_ip ( self , context , instance , address ) : global last_remove_fixed_ip last_remove_fixed_ip = ( instance [ '' ] , address ) def compute_api_get ( self , context , instance_id , want_objects = False , expected_attrs = None ) : instance = objects . Instance ( ) instance . uuid = instance_id instance . id = instance . vm_state = '' instance . task_state = '' instance . obj_reset_changes ( ) return instance class FixedIpTestV21 ( test . NoDBTestCase ) : controller_class = multinic_v21 validation_error = exception . ValidationError def setUp ( self ) : super ( FixedIpTestV21 , self ) . setUp ( ) fakes . stub_out_networking ( self ) fakes . stub_out_rate_limiting ( self . stubs ) self . stub_out ( '' , compute_api_add_fixed_ip ) self . stub_out ( '' , compute_api_remove_fixed_ip ) self . stub_out ( '' , compute_api_get ) self . controller = self . controller_class . MultinicController ( ) self . fake_req = fakes . HTTPRequest . blank ( '' ) def test_add_fixed_ip ( self ) : global last_add_fixed_ip last_add_fixed_ip = ( None , None ) body = dict ( addFixedIp = dict ( networkId = '' ) ) resp = self . controller . _add_fixed_ip ( self . fake_req , UUID , body = body ) if isinstance ( self . controller , multinic_v21 . MultinicController ) : status_int = self . controller . _add_fixed_ip . wsgi_code else : status_int = resp . status_int self . assertEqual ( status_int , ) self . assertEqual ( last_add_fixed_ip , ( UUID , '' ) ) def _test_add_fixed_ip_bad_request ( self , body ) : self . assertRaises ( self . validation_error , self . controller . _add_fixed_ip , self . fake_req , UUID , body = body ) def test_add_fixed_ip_empty_network_id ( self ) : body = { '' : { '' : '' } } self . _test_add_fixed_ip_bad_request ( body ) ", "answer": "def test_add_fixed_ip_network_id_bigger_than_36 ( self ) :"}, {"prompt": " from flask import Blueprint , make_response , request , redirect , url_for , session , render_template , current_app , send_from_directory , flash import json import sys import os import gzip import requests from uuid import uuid4 from werkzeug import secure_filename from csvkit import convert from csvkit . unicsv import UnicodeCSVReader from csvkit . cleanup import RowChecker from cStringIO import StringIO from geomancer . helpers import import_class , get_geo_types , get_data_sources , guess_geotype , check_combos , SENSICAL_TYPES from geomancer . app_config import ALLOWED_EXTENSIONS , MAX_CONTENT_LENGTH from werkzeug . exceptions import RequestEntityTooLarge views = Blueprint ( '' , __name__ ) def allowed_file ( filename ) : return '' in filename and filename . rsplit ( '' , ) [ ] in ALLOWED_EXTENSIONS @ views . route ( '' , methods = [ '' , '' ] ) def index ( ) : return render_template ( '' ) @ views . route ( '' , methods = [ '' , '' ] ) def about ( ) : return render_template ( '' ) @ views . route ( '' , methods = [ '' , '' ] ) def upload_formats ( ) : return render_template ( '' ) @ views . route ( '' , methods = [ '' , '' ] ) def contribute_data ( ) : return render_template ( '' ) @ views . route ( '' , methods = [ '' , '' ] ) def geographies ( ) : geographies , errors = get_geo_types ( ) for error in errors : flash ( error ) return render_template ( '' , geographies = geographies ) @ views . route ( '' , methods = [ '' , '' ] ) def data_sources ( ) : data_sources , errors = get_data_sources ( ) for error in errors : flash ( error ) return render_template ( '' , data_sources = data_sources ) @ views . route ( '' , methods = [ '' , '' ] ) def upload ( ) : context = { } if request . method == '' : big_file = False try : files = request . files except RequestEntityTooLarge , e : files = None big_file = True current_app . logger . info ( e ) if files : f = files [ '' ] if allowed_file ( f . filename ) : inp = StringIO ( f . read ( ) ) file_format = convert . guess_format ( f . filename ) try : converted = convert . convert ( inp , file_format ) except UnicodeDecodeError : context [ '' ] = [ '' ] converted = None f . seek ( ) if converted : outp = StringIO ( converted ) reader = UnicodeCSVReader ( outp ) session [ '' ] = reader . next ( ) rows = [ ] columns = [ [ ] for c in session [ '' ] ] column_ids = range ( len ( session [ '' ] ) ) for row in range ( ) : try : rows . append ( reader . next ( ) ) except StopIteration : break for i , row in enumerate ( rows ) : for j , d in enumerate ( row ) : columns [ j ] . append ( row [ column_ids [ j ] ] ) sample_data = [ ] guesses = { } for index , header_val in enumerate ( session [ '' ] ) : guesses [ index ] = guess_geotype ( header_val , columns [ index ] ) sample_data . append ( ( index , header_val , columns [ index ] ) ) session [ '' ] = sample_data session [ '' ] = json . dumps ( guesses ) outp . seek ( ) session [ '' ] = outp . getvalue ( ) session [ '' ] = f . filename return redirect ( url_for ( '' ) ) else : context [ '' ] = [ '' ] else : context [ '' ] = [ '' ] if big_file : context [ '' ] = [ '' ] return render_template ( '' , ** context ) @ views . route ( '' , methods = [ '' , '' ] ) def select_geo ( ) : if not session . get ( '' ) : return redirect ( url_for ( '' ) ) context = { } if request . method == '' : inp = StringIO ( session [ '' ] ) reader = UnicodeCSVReader ( inp ) header = reader . next ( ) fields = { } valid = True geotype_val = None if not request . form : valid = False context [ '' ] = [ '' ] else : geotypes = [ ] indexes = [ ] for k , v in request . form . items ( ) : if k . startswith ( \"\" ) : geotypes . append ( v ) indexes . append ( k . split ( '' ) [ ] ) if len ( indexes ) > : valid = False context [ '' ] = [ '' ] else : fields_key = '' . join ( [ header [ int ( i ) ] for i in indexes ] ) geotype_val = '' . join ( [ g for g in geotypes ] ) if not check_combos ( geotype_val ) : valid = False types = [ t . title ( ) for t in geotype_val . split ( '' ) ] context [ '' ] = [ '' . format ( * types ) ] else : fields [ fields_key ] = { '' : geotype_val , '' : '' . join ( indexes ) } if valid : try : geo_type = SENSICAL_TYPES [ geotype_val ] except KeyError : geo_type = geotype_val mancer_data , errors = get_data_sources ( geo_type = geo_type ) session [ '' ] = fields session [ '' ] = mancer_data for error in errors : flash ( error ) return redirect ( url_for ( '' ) ) return render_template ( '' , ** context ) @ views . route ( '' , methods = [ '' , '' ] ) def select_tables ( ) : if not session . get ( '' ) : return redirect ( url_for ( '' ) ) ", "answer": "context = { }"}, {"prompt": " import shelve from twisted . internet . defer import inlineCallbacks from autobahn import wamp from autobahn . twisted . wamp import ApplicationSession class KeyValueStore ( ApplicationSession ) : \"\"\"\"\"\" @ inlineCallbacks def onJoin ( self , details ) : self . store = shelve . open ( \"\" , flag = '' , writeback = False ) yield self . register ( self ) print ( \"\" ) @ wamp . register ( u\"\" ) def set ( self , key = None , value = None ) : if key is not None : k = str ( key ) if value is not None : ", "answer": "self . store [ k ] = value"}, {"prompt": " import requests import ssl import datetime import utils import ConfigParser import os from django . conf import settings from pyVmomi import vim from ConfigParser import SafeConfigParser from pyVim . connect import SmartConnect class PluginManager : property_file_path = settings . HERE + '' resurce_folder_path = settings . HERE + '' def create_event_keyvalue_pairs ( self ) : try : eri_list = [ ] for file in os . listdir ( self . resurce_folder_path ) : file = open ( self . resurce_folder_path + '' + file ) eri = vim . Extension . ResourceInfo ( ) eri . module = '' for line in file : if len ( line ) > and '' in line : if '' in line : eri . locale = line . split ( '' ) [ ] . lstrip ( ) . rstrip ( ) else : prop = line . split ( '' ) key_val = vim . KeyValue ( ) key_val . key = prop [ ] . lstrip ( ) . rstrip ( ) key_val . value = prop [ ] . lstrip ( ) . rstrip ( ) eri . data . append ( key_val ) file . close ( ) eri_list . append ( eri ) return eri_list except Exception as ex : return '' + str ( ex ) def get_extensionKey ( self ) : cp = SafeConfigParser ( ) cp . read ( self . property_file_path ) key = cp . get ( '' , '' ) return key def get_extension ( self , vcp_url , thumb_print ) : try : cp = SafeConfigParser ( ) cp . read ( self . property_file_path ) company = cp . get ( '' , '' ) descr = cp . get ( '' , '' ) key = cp . get ( '' , '' ) events = cp . get ( '' , '' ) . split ( \"\" ) tasks = cp . get ( '' , '' ) . split ( \"\" ) version = utils . get_plugin_version ( ) if '' in version : return version label = cp . get ( '' , '' ) sys_guiprotocol = vcp_url . split ( '' ) [ ] description = vim . Description ( ) description . label = label description . summary = descr ext = vim . Extension ( ) ext . company = company ext . version = version ext . key = key ext . description = description ext . lastHeartbeatTime = datetime . datetime . now ( ) server_info = vim . Extension . ServerInfo ( ) server_info . serverThumbprint = thumb_print server_info . type = sys_guiprotocol . upper ( ) server_info . url = vcp_url server_info . description = description server_info . company = company server_info . adminEmail = [ '' ] ext . server = [ server_info ] client = vim . Extension . ClientInfo ( ) client . url = vcp_url client . company = company client . version = version client . description = description client . type = \"\" ext . client = [ client ] event_info = [ ] for e in events : ext_event_type_info = vim . Extension . EventTypeInfo ( ) ext_event_type_info . eventID = e event_info . append ( ext_event_type_info ) task_info = [ ] for t in tasks : ext_type_info = vim . Extension . TaskTypeInfo ( ) ext_type_info . taskID = t task_info . append ( ext_type_info ) ext . taskList = task_info ext . eventList = event_info resource_list = self . create_event_keyvalue_pairs ( ) if isinstance ( resource_list , str ) : return resource_list ext . resourceList = resource_list return ext except ConfigParser . NoOptionError as ex : return '' + str ( ex ) except Exception as ex : return str ( ex ) . replace ( \"\" , \"\" ) . replace ( \"\" , \"\" ) . replace ( \">\" , \"\" ) def install_vCenter_plugin ( self , vc_ip , usernName , password , port , vcp_url , thumb_print ) : try : try : ssl . _create_default_https_context = ssl . _create_unverified_context except AttributeError : print '' si = SmartConnect ( \"\" , vc_ip , int ( port ) , usernName , password ) ext = self . get_extension ( vcp_url , thumb_print ) if isinstance ( ext , vim . Extension ) : si . RetrieveServiceContent ( ) . extensionManager . RegisterExtension ( ext ) return True else : return ext except vim . fault . NoPermission as ex : return '' except Exception as ex : return str ( ex ) . replace ( \"\" , \"\" ) . replace ( \"\" , \"\" ) . replace ( \">\" , \"\" ) def uninstall_vCenter_plugin ( self , vc_ip , usernName , password , port ) : try : try : ssl . _create_default_https_context = ssl . _create_unverified_context except AttributeError : print '' si = SmartConnect ( \"\" , vc_ip , int ( port ) , usernName , password ) extkey = self . get_extensionKey ( ) si . RetrieveServiceContent ( ) . extensionManager . UnregisterExtension ( extkey ) return True except vim . fault . NoPermission as ex : return '' ", "answer": "except Exception as ex :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " from django . conf import settings import django __all__ = [ '' , '' ] AUTH_USER_MODEL = getattr ( settings , '' , '' ) if django . VERSION >= ( , ) : from django . contrib . auth import get_user_model User = get_user_model ( ) ", "answer": "username_field = User . USERNAME_FIELD"}, {"prompt": " __version__ = '' __build__ = '' ", "answer": "__release__ = __version__ + __build__ "}, {"prompt": " from wand . image import Image import os import re MANIFEST = ( ( '' , ) , ( '' , ) , ( '' , ) ) if __name__ == \"\" : files = os . listdir ( \"\" ) files = filter ( lambda x : re . match ( r\"\" , x ) is not None , files ) for filename in files : with Image ( filename = \"\" % filename ) as img : print ( \"\" % filename ) ", "answer": "width , height = img . size"}, {"prompt": " \"\"\"\"\"\" import os from io import open import shutil import errno import re import yaml from drupan . entity import Entity class Reader ( object ) : \"\"\"\"\"\" def __init__ ( self , site , config ) : \"\"\"\"\"\" self . site = site self . config = config self . content = config . get_option ( \"\" , \"\" , optional = True ) self . extension = config . get_option ( \"\" , \"\" ) self . template = config . get_option ( \"\" , \"\" , optional = True ) if self . content is None : self . content = config . get_option ( \"\" , \"\" ) print ( \"\" ) if self . template is None : self . template = config . get_option ( \"\" , \"\" ) print ( \"\" ) if not self . extension . startswith ( \"\" ) : self . extension = \"\" . format ( self . extension ) def run ( self ) : \"\"\"\"\"\" self . read_content ( ) self . read_template ( ) self . read_images ( ) def read_content ( self ) : \"\"\"\"\"\" for current in os . listdir ( self . content ) : if not os . path . splitext ( current ) [ ] == self . extension : continue fqp = os . path . join ( self . content , current ) with open ( fqp , '' , encoding = '' ) as infile : self . parse_file ( infile . read ( ) ) def parse_file ( self , raw ) : \"\"\"\"\"\" ( header , separator , content ) = raw . partition ( \"\" ) meta = yaml . load ( header ) entity = Entity ( self . config ) entity . meta = meta entity . raw = content . strip ( ) self . site . entities . append ( entity ) def read_template ( self ) : \"\"\"\"\"\" template_extensions = ( \"\" , \"\" , \"\" , \"\" ) for file_names , dir_name in dir_walker ( self . template ) : for name in file_names : if name . startswith ( \"\" ) : continue store = self . site . templates mode = \"\" if not name . endswith ( template_extensions ) : store = self . site . assets mode = \"\" stripped = re . sub ( self . template , \"\" , dir_name ) if stripped . startswith ( os . path . sep ) : stripped = stripped [ : ] fqp = os . path . join ( dir_name , name ) key = os . path . join ( stripped , name ) with open ( fqp , mode ) as infile : store [ key ] = infile . read ( ) def read_images ( self ) : \"\"\"\"\"\" path = os . path . join ( self . content , \"\" ) for file_names , dir_name in dir_walker ( path ) : for name in file_names : if name . startswith ( \"\" ) : continue with open ( os . path . join ( dir_name , name ) , \"\" ) as infile : self . site . images [ name ] = infile . read ( ) class Writer ( object ) : \"\"\"\"\"\" def __init__ ( self , site , config ) : \"\"\"\"\"\" self . site = site self . config = config self . base_path = config . get_option ( \"\" , \"\" ) def run ( self ) : \"\"\"\"\"\" self . clean_dir ( ) self . write_entities ( ) self . write_assets ( ) self . write_templates ( ) def write_entities ( self ) : \"\"\"\"\"\" for entity in self . site . entities : if entity . path is None : continue path = os . path . join ( self . base_path , entity . path ) create_path ( path ) path = os . path . join ( path , \"\" ) write ( entity . rendered , path ) self . write_images ( entity ) def write_assets ( self ) : \"\"\"\"\"\" for name , content in self . site . assets . items ( ) : path = os . path . join ( self . base_path , os . path . dirname ( name ) ) create_path ( path ) path = os . path . join ( self . base_path , name ) write ( content , path , binary = True ) def write_templates ( self ) : \"\"\"\"\"\" for name , content in self . site . templates . items ( ) : if name . startswith ( \"\" ) : continue path = os . path . join ( self . base_path , os . path . dirname ( name ) ) create_path ( path ) path = os . path . join ( self . base_path , name ) write ( content , path ) def write_images ( self , entity ) : \"\"\"\"\"\" path = os . path . join ( self . base_path , entity . path ) for name in entity . images : image = self . site . images [ name ] output = os . path . join ( path , name ) write ( image , output , binary = True ) def clean_dir ( self ) : \"\"\"\"\"\" try : shutil . rmtree ( self . base_path ) except : pass def dir_walker ( path ) : \"\"\"\"\"\" for dir_name , dir_names , file_names in os . walk ( path ) : skip = False for name in dir_name . split ( os . path . sep ) : if name . startswith ( \"\" ) : skip = True if skip is True : continue yield ( file_names , dir_name ) def create_path ( path ) : \"\"\"\"\"\" if path == \"\" : return if os . path . exists ( path ) : return try : os . makedirs ( path ) except OSError : if OSError . errno == errno . EEXIST : pass else : raise def write ( content , path , binary = False ) : \"\"\"\"\"\" if binary : ", "answer": "with open ( path , \"\" ) as output :"}, {"prompt": " from cms . app_base import CMSApp ", "answer": "from cms . apphook_pool import apphook_pool"}, {"prompt": " from django . test . client import Client , FakePayload from django . conf import global_settings from django . conf import settings from django . core . handlers . wsgi import WSGIRequest from django . core . handlers . wsgi import WSGIHandler from djangobench . utils import run_comparison_benchmark class RequestFactory ( Client ) : \"\"\"\"\"\" def request ( self , ** request ) : \"\"\"\"\"\" environ = { '' : self . cookies . output ( header = '' , sep = '' ) , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : , '' : '' , '' : FakePayload ( '' ) , } environ . update ( self . defaults ) environ . update ( request ) return WSGIRequest ( environ ) ", "answer": "def setup ( ) :"}, {"prompt": " from __future__ import print_function from copy import deepcopy from math import sqrt , ceil import numpy as np from scipy import linalg from . mxne_debiasing import compute_bias from . . utils import logger , verbose , sum_squared , warn from . . time_frequency . stft import stft_norm2 , stft , istft from . . externals . six . moves import xrange as range def groups_norm2 ( A , n_orient ) : \"\"\"\"\"\" n_positions = A . shape [ ] // n_orient return np . sum ( np . power ( A , , A ) . reshape ( n_positions , - ) , axis = ) def norm_l2inf ( A , n_orient , copy = True ) : \"\"\"\"\"\" if A . size == : return if copy : A = A . copy ( ) return sqrt ( np . max ( groups_norm2 ( A , n_orient ) ) ) def norm_l21 ( A , n_orient , copy = True ) : \"\"\"\"\"\" if A . size == : return if copy : A = A . copy ( ) return np . sum ( np . sqrt ( groups_norm2 ( A , n_orient ) ) ) def prox_l21 ( Y , alpha , n_orient , shape = None , is_stft = False ) : \"\"\"\"\"\" if len ( Y ) == : return np . zeros_like ( Y ) , np . zeros ( ( , ) , dtype = np . bool ) if shape is not None : shape_init = Y . shape Y = Y . reshape ( * shape ) n_positions = Y . shape [ ] // n_orient if is_stft : rows_norm = np . sqrt ( stft_norm2 ( Y ) . reshape ( n_positions , - ) . sum ( axis = ) ) else : rows_norm = np . sqrt ( ( Y * Y . conj ( ) ) . real . reshape ( n_positions , - ) . sum ( axis = ) ) shrink = np . maximum ( - alpha / np . maximum ( rows_norm , alpha ) , ) active_set = shrink > if n_orient > : active_set = np . tile ( active_set [ : , None ] , [ , n_orient ] ) . ravel ( ) shrink = np . tile ( shrink [ : , None ] , [ , n_orient ] ) . ravel ( ) Y = Y [ active_set ] if shape is None : Y *= shrink [ active_set ] [ : , np . newaxis ] else : Y *= shrink [ active_set ] [ : , np . newaxis , np . newaxis ] Y = Y . reshape ( - , * shape_init [ : ] ) return Y , active_set def prox_l1 ( Y , alpha , n_orient ) : \"\"\"\"\"\" n_positions = Y . shape [ ] // n_orient norms = np . sqrt ( ( Y * Y . conj ( ) ) . real . T . reshape ( - , n_orient ) . sum ( axis = ) ) shrink = np . maximum ( - alpha / np . maximum ( norms , alpha ) , ) shrink = shrink . reshape ( - , n_positions ) . T active_set = np . any ( shrink > , axis = ) shrink = shrink [ active_set ] if n_orient > : active_set = np . tile ( active_set [ : , None ] , [ , n_orient ] ) . ravel ( ) Y = Y [ active_set ] if len ( Y ) > : for o in range ( n_orient ) : Y [ o : : n_orient ] *= shrink return Y , active_set def dgap_l21 ( M , G , X , active_set , alpha , n_orient ) : \"\"\"\"\"\" GX = np . dot ( G [ : , active_set ] , X ) R = M - GX penalty = norm_l21 ( X , n_orient , copy = True ) nR2 = sum_squared ( R ) pobj = * nR2 + alpha * penalty dual_norm = norm_l2inf ( np . dot ( G . T , R ) , n_orient , copy = False ) scaling = alpha / dual_norm scaling = min ( scaling , ) dobj = * ( scaling ** ) * nR2 + scaling * np . sum ( R * GX ) gap = pobj - dobj return gap , pobj , dobj , R @ verbose def _mixed_norm_solver_prox ( M , G , alpha , lipschitz_constant , maxit = , tol = , verbose = None , init = None , n_orient = ) : \"\"\"\"\"\" n_sensors , n_times = M . shape n_sensors , n_sources = G . shape if n_sources < n_sensors : gram = np . dot ( G . T , G ) GTM = np . dot ( G . T , M ) else : gram = None if init is None : X = R = M . copy ( ) if gram is not None : R = np . dot ( G . T , R ) else : X = init if gram is None : R = M - np . dot ( G , X ) else : R = GTM - np . dot ( gram , X ) t = Y = np . zeros ( ( n_sources , n_times ) ) E = [ ] active_set = np . ones ( n_sources , dtype = np . bool ) for i in range ( maxit ) : X0 , active_set_0 = X , active_set if gram is None : Y += np . dot ( G . T , R ) / lipschitz_constant else : Y += R / lipschitz_constant X , active_set = prox_l21 ( Y , alpha / lipschitz_constant , n_orient ) t0 = t t = * ( + sqrt ( + * t ** ) ) Y . fill ( ) dt = ( ( t0 - ) / t ) Y [ active_set ] = ( + dt ) * X Y [ active_set_0 ] -= dt * X0 Y_as = active_set_0 | active_set if gram is None : R = M - np . dot ( G [ : , Y_as ] , Y [ Y_as ] ) else : R = GTM - np . dot ( gram [ : , Y_as ] , Y [ Y_as ] ) gap , pobj , dobj , _ = dgap_l21 ( M , G , X , active_set , alpha , n_orient ) E . append ( pobj ) logger . debug ( \"\" % ( pobj , gap ) ) if gap < tol : logger . debug ( '' % ( gap , tol ) ) break return X , active_set , E @ verbose def _mixed_norm_solver_cd ( M , G , alpha , lipschitz_constant , maxit = , tol = , verbose = None , init = None , n_orient = ) : \"\"\"\"\"\" from sklearn . linear_model . coordinate_descent import MultiTaskLasso n_sensors , n_times = M . shape n_sensors , n_sources = G . shape if init is not None : init = init . T clf = MultiTaskLasso ( alpha = alpha / len ( M ) , tol = tol , normalize = False , fit_intercept = False , max_iter = maxit , warm_start = True ) clf . coef_ = init clf . fit ( G , M ) X = clf . coef_ . T active_set = np . any ( X , axis = ) X = X [ active_set ] gap , pobj , dobj , _ = dgap_l21 ( M , G , X , active_set , alpha , n_orient ) return X , active_set , pobj @ verbose def _mixed_norm_solver_bcd ( M , G , alpha , lipschitz_constant , maxit = , tol = , verbose = None , init = None , n_orient = ) : \"\"\"\"\"\" G = np . asfortranarray ( G ) n_sensors , n_times = M . shape n_sensors , n_sources = G . shape n_positions = n_sources // n_orient if init is None : X = np . zeros ( ( n_sources , n_times ) ) R = M . copy ( ) else : X = init R = M - np . dot ( G , X ) E = [ ] active_set = np . zeros ( n_sources , dtype = np . bool ) alpha_lc = alpha / lipschitz_constant for i in range ( maxit ) : for j in range ( n_positions ) : idx = slice ( j * n_orient , ( j + ) * n_orient ) G_j = G [ : , idx ] X_j = X [ idx ] X_j_new = np . dot ( G_j . T , R ) / lipschitz_constant [ j ] was_non_zero = np . any ( X_j ) if was_non_zero : R += np . dot ( G_j , X_j ) X_j_new += X_j block_norm = linalg . norm ( X_j_new , '' ) if block_norm <= alpha_lc [ j ] : X_j . fill ( ) active_set [ idx ] = False else : shrink = np . maximum ( - alpha_lc [ j ] / block_norm , ) X_j_new *= shrink R -= np . dot ( G_j , X_j_new ) X_j [ : ] = X_j_new active_set [ idx ] = True gap , pobj , dobj , _ = dgap_l21 ( M , G , X [ active_set ] , active_set , alpha , n_orient ) E . append ( pobj ) logger . debug ( \"\" % ( i + , pobj , gap , np . sum ( active_set ) / n_orient ) ) if gap < tol : logger . debug ( '' % ( gap , tol ) ) break X = X [ active_set ] return X , active_set , E @ verbose def mixed_norm_solver ( M , G , alpha , maxit = , tol = , verbose = None , active_set_size = , debias = True , n_orient = , solver = '' ) : \"\"\"\"\"\" n_dipoles = G . shape [ ] n_positions = n_dipoles // n_orient n_sensors , n_times = M . shape alpha_max = norm_l2inf ( np . dot ( G . T , M ) , n_orient , copy = False ) logger . info ( \"\" % alpha_max ) alpha = float ( alpha ) has_sklearn = True try : from sklearn . linear_model . coordinate_descent import MultiTaskLasso except ImportError : has_sklearn = False if solver == '' : if has_sklearn and ( n_orient == ) : solver = '' else : solver = '' if solver == '' : if n_orient == and not has_sklearn : warn ( '' '' ) solver = '' if n_orient > : warn ( '' '' '' ) solver = '' if solver == '' : logger . info ( \"\" ) l21_solver = _mixed_norm_solver_cd lc = None elif solver == '' : logger . info ( \"\" ) l21_solver = _mixed_norm_solver_bcd G = np . asfortranarray ( G ) if n_orient == : lc = np . sum ( G * G , axis = ) else : lc = np . empty ( n_positions ) for j in range ( n_positions ) : G_tmp = G [ : , ( j * n_orient ) : ( ( j + ) * n_orient ) ] lc [ j ] = linalg . norm ( np . dot ( G_tmp . T , G_tmp ) , ord = ) else : logger . info ( \"\" ) l21_solver = _mixed_norm_solver_prox lc = * linalg . norm ( G , ord = ) ** if active_set_size is not None : E = list ( ) X_init = None active_set = np . zeros ( n_dipoles , dtype = np . bool ) idx_large_corr = np . argsort ( groups_norm2 ( np . dot ( G . T , M ) , n_orient ) ) new_active_idx = idx_large_corr [ - active_set_size : ] if n_orient > : new_active_idx = ( n_orient * new_active_idx [ : , None ] + np . arange ( n_orient ) [ None , : ] ) . ravel ( ) active_set [ new_active_idx ] = True as_size = np . sum ( active_set ) for k in range ( maxit ) : if solver == '' : lc_tmp = lc [ active_set [ : : n_orient ] ] elif solver == '' : lc_tmp = None else : lc_tmp = * linalg . norm ( G [ : , active_set ] , ord = ) ** X , as_ , _ = l21_solver ( M , G [ : , active_set ] , alpha , lc_tmp , maxit = maxit , tol = tol , init = X_init , n_orient = n_orient ) active_set [ active_set ] = as_ . copy ( ) idx_old_active_set = np . where ( active_set ) [ ] gap , pobj , dobj , R = dgap_l21 ( M , G , X , active_set , alpha , n_orient ) E . append ( pobj ) logger . info ( \"\" \"\" % ( k + , pobj , gap , as_size // n_orient , np . sum ( active_set ) // n_orient ) ) if gap < tol : logger . info ( '' % ( gap , tol ) ) break if k < ( maxit - ) : idx_large_corr = np . argsort ( groups_norm2 ( np . dot ( G . T , R ) , n_orient ) ) new_active_idx = idx_large_corr [ - active_set_size : ] if n_orient > : new_active_idx = ( n_orient * new_active_idx [ : , None ] + np . arange ( n_orient ) [ None , : ] ) new_active_idx = new_active_idx . ravel ( ) active_set [ new_active_idx ] = True idx_active_set = np . where ( active_set ) [ ] as_size = np . sum ( active_set ) X_init = np . zeros ( ( as_size , n_times ) , dtype = X . dtype ) idx = np . searchsorted ( idx_active_set , idx_old_active_set ) X_init [ idx ] = X else : warn ( '' % ( gap , tol ) ) else : X , active_set , E = l21_solver ( M , G , alpha , lc , maxit = maxit , tol = tol , n_orient = n_orient , init = None ) if np . any ( active_set ) and debias : bias = compute_bias ( M , G [ : , active_set ] , X , n_orient = n_orient ) X *= bias [ : , np . newaxis ] logger . info ( '' % ( np . sum ( active_set ) // n_orient ) ) return X , active_set , E @ verbose def iterative_mixed_norm_solver ( M , G , alpha , n_mxne_iter , maxit = , tol = , verbose = None , active_set_size = , debias = True , n_orient = , solver = '' ) : \"\"\"\"\"\" def g ( w ) : return np . sqrt ( np . sqrt ( groups_norm2 ( w . copy ( ) , n_orient ) ) ) def gprime ( w ) : return * np . repeat ( g ( w ) , n_orient ) . ravel ( ) E = list ( ) active_set = np . ones ( G . shape [ ] , dtype = np . bool ) weights = np . ones ( G . shape [ ] ) X = np . zeros ( ( G . shape [ ] , M . shape [ ] ) ) for k in range ( n_mxne_iter ) : X0 = X . copy ( ) active_set_0 = active_set . copy ( ) G_tmp = G [ : , active_set ] * weights [ np . newaxis , : ] if active_set_size is not None : if np . sum ( active_set ) > ( active_set_size * n_orient ) : X , _active_set , _ = mixed_norm_solver ( M , G_tmp , alpha , debias = False , n_orient = n_orient , maxit = maxit , tol = tol , active_set_size = active_set_size , solver = solver , verbose = verbose ) else : X , _active_set , _ = mixed_norm_solver ( M , G_tmp , alpha , debias = False , n_orient = n_orient , maxit = maxit , tol = tol , active_set_size = None , solver = solver , verbose = verbose ) else : X , _active_set , _ = mixed_norm_solver ( M , G_tmp , alpha , debias = False , n_orient = n_orient , maxit = maxit , tol = tol , active_set_size = None , solver = solver , verbose = verbose ) logger . info ( '' % ( _active_set . sum ( ) / n_orient ) ) if _active_set . sum ( ) > : active_set [ active_set ] = _active_set X *= weights [ _active_set ] [ : , np . newaxis ] weights = gprime ( X ) p_obj = * linalg . norm ( M - np . dot ( G [ : , active_set ] , X ) , '' ) ** + alpha * np . sum ( g ( X ) ) E . append ( p_obj ) if ( ( k >= ) and np . all ( active_set == active_set_0 ) and np . all ( np . abs ( X - X0 ) < tol ) ) : print ( '' % k ) break else : active_set = np . zeros_like ( active_set ) p_obj = * linalg . norm ( M ) ** E . append ( p_obj ) break if np . any ( active_set ) and debias : bias = compute_bias ( M , G [ : , active_set ] , X , n_orient = n_orient ) X *= bias [ : , np . newaxis ] return X , active_set , E @ verbose def tf_lipschitz_constant ( M , G , phi , phiT , tol = , verbose = None ) : \"\"\"\"\"\" n_times = M . shape [ ] n_points = G . shape [ ] iv = np . ones ( ( n_points , n_times ) , dtype = np . float ) v = phi ( iv ) L = for it in range ( ) : L_old = L logger . info ( '' % it ) iv = np . real ( phiT ( v ) ) Gv = np . dot ( G , iv ) GtGv = np . dot ( G . T , Gv ) w = phi ( GtGv ) L = np . max ( np . abs ( w ) ) v = w / L if abs ( ( L - L_old ) / L_old ) < tol : break return L def safe_max_abs ( A , ia ) : \"\"\"\"\"\" if np . sum ( ia ) : return np . max ( np . abs ( A [ ia ] ) ) else : return def safe_max_abs_diff ( A , ia , B , ib ) : \"\"\"\"\"\" A = A [ ia ] if np . sum ( ia ) else B = B [ ib ] if np . sum ( ia ) else return np . max ( np . abs ( A - B ) ) class _Phi ( object ) : \"\"\"\"\"\" def __init__ ( self , wsize , tstep , n_coefs ) : self . wsize = wsize self . tstep = tstep self . n_coefs = n_coefs def __call__ ( self , x ) : return stft ( x , self . wsize , self . tstep , verbose = False ) . reshape ( - , self . n_coefs ) class _PhiT ( object ) : \"\"\"\"\"\" def __init__ ( self , tstep , n_freq , n_step , n_times ) : self . tstep = tstep self . n_freq = n_freq self . n_step = n_step self . n_times = n_times def __call__ ( self , z ) : return istft ( z . reshape ( - , self . n_freq , self . n_step ) , self . tstep , self . n_times ) def norm_l21_tf ( Z , shape , n_orient ) : if Z . shape [ ] : Z2 = Z . reshape ( * shape ) l21_norm = np . sqrt ( stft_norm2 ( Z2 ) . reshape ( - , n_orient ) . sum ( axis = ) ) l21_norm = l21_norm . sum ( ) else : l21_norm = return l21_norm def norm_l1_tf ( Z , shape , n_orient ) : if Z . shape [ ] : n_positions = Z . shape [ ] // n_orient Z_ = np . sqrt ( np . sum ( ( np . abs ( Z ) ** ) . reshape ( ( n_orient , - ) , order = '' ) , axis = ) ) Z_ = Z_ . reshape ( ( n_positions , - ) , order = '' ) . reshape ( * shape ) l1_norm = ( * Z_ . sum ( axis = ) . sum ( axis = ) - np . sum ( Z_ [ : , , : ] , axis = ) - np . sum ( Z_ [ : , - , : ] , axis = ) ) l1_norm = l1_norm . sum ( ) else : l1_norm = return l1_norm @ verbose def _tf_mixed_norm_solver_bcd_ ( M , G , Z , active_set , alpha_space , alpha_time , lipschitz_constant , phi , phiT , wsize = , tstep = , n_orient = , maxit = , tol = , log_objective = True , perc = None , verbose = None ) : G = np . asfortranarray ( G ) n_sensors , n_times = M . shape n_sources = G . shape [ ] n_positions = n_sources // n_orient n_step = int ( ceil ( n_times / float ( tstep ) ) ) n_freq = wsize // + shape = ( - , n_freq , n_step ) G = dict ( zip ( np . arange ( n_positions ) , np . hsplit ( G , n_positions ) ) ) R = M . copy ( ) active = np . where ( active_set ) [ ] [ : : n_orient ] // n_orient for idx in active : R -= np . dot ( G [ idx ] , phiT ( Z [ idx ] ) ) E = [ ] alpha_time_lc = alpha_time / lipschitz_constant alpha_space_lc = alpha_space / lipschitz_constant converged = False for i in range ( maxit ) : val_norm_l21_tf = val_norm_l1_tf = max_diff = active_set_0 = active_set . copy ( ) for j in range ( n_positions ) : ids = j * n_orient ide = ids + n_orient G_j = G [ j ] Z_j = Z [ j ] active_set_j = active_set [ ids : ide ] Z0 = deepcopy ( Z_j ) was_active = np . any ( active_set_j ) GTR = np . dot ( G_j . T , R ) / lipschitz_constant [ j ] X_j_new = GTR . copy ( ) if was_active : X_j = phiT ( Z_j ) R += np . dot ( G_j , X_j ) X_j_new += X_j rows_norm = linalg . norm ( X_j_new , '' ) if rows_norm <= alpha_space_lc [ j ] : if was_active : Z [ j ] = active_set_j [ : ] = False else : if was_active : Z_j_new = Z_j + phi ( GTR ) else : Z_j_new = phi ( GTR ) col_norm = np . sqrt ( np . sum ( np . abs ( Z_j_new ) ** , axis = ) ) if np . all ( col_norm <= alpha_time_lc [ j ] ) : Z [ j ] = active_set_j [ : ] = False else : shrink = np . maximum ( - alpha_time_lc [ j ] / np . maximum ( col_norm , alpha_time_lc [ j ] ) , ) Z_j_new *= shrink [ np . newaxis , : ] shape_init = Z_j_new . shape Z_j_new = Z_j_new . reshape ( * shape ) row_norm = np . sqrt ( stft_norm2 ( Z_j_new ) . sum ( ) ) if row_norm <= alpha_space_lc [ j ] : Z [ j ] = active_set_j [ : ] = False else : shrink = np . maximum ( - alpha_space_lc [ j ] / np . maximum ( row_norm , alpha_space_lc [ j ] ) , ) Z_j_new *= shrink Z [ j ] = Z_j_new . reshape ( - , * shape_init [ : ] ) . copy ( ) active_set_j [ : ] = True R -= np . dot ( G_j , phiT ( Z [ j ] ) ) if log_objective : val_norm_l21_tf += norm_l21_tf ( Z [ j ] , shape , n_orient ) val_norm_l1_tf += norm_l1_tf ( Z [ j ] , shape , n_orient ) max_diff = np . maximum ( max_diff , np . max ( np . abs ( Z [ j ] - Z0 ) ) ) if log_objective : pobj = ( * ( R ** ) . sum ( ) + alpha_space * val_norm_l21_tf + alpha_time * val_norm_l1_tf ) E . append ( pobj ) logger . info ( \"\" % ( i + , pobj , np . sum ( active_set ) / n_orient ) ) else : logger . info ( \"\" % ( i + ) ) if perc is not None : if np . sum ( active_set ) / float ( n_orient ) <= perc * n_positions : break if np . array_equal ( active_set , active_set_0 ) : if max_diff < tol : logger . info ( \"\" ) converged = True break return Z , active_set , E , converged @ verbose def _tf_mixed_norm_solver_bcd_active_set ( M , G , alpha_space , alpha_time , lipschitz_constant , phi , phiT , Z_init = None , wsize = , tstep = , n_orient = , maxit = , tol = , log_objective = True , perc = None , verbose = None ) : \"\"\"\"\"\" n_sources = G . shape [ ] n_positions = n_sources // n_orient if Z_init is None : Z = dict . fromkeys ( range ( n_positions ) , ) active_set = np . zeros ( n_sources , dtype = np . bool ) else : active_set = np . zeros ( n_sources , dtype = np . bool ) active = list ( ) for i in range ( n_positions ) : if np . any ( Z_init [ i * n_orient : ( i + ) * n_orient ] ) : active_set [ i * n_orient : ( i + ) * n_orient ] = True active . append ( i ) Z = dict . fromkeys ( range ( n_positions ) , ) if len ( active ) : Z . update ( dict ( zip ( active , np . vsplit ( Z_init [ active_set ] , len ( active ) ) ) ) ) Z , active_set , E , _ = _tf_mixed_norm_solver_bcd_ ( M , G , Z , active_set , alpha_space , alpha_time , lipschitz_constant , phi , phiT , wsize = wsize , tstep = tstep , n_orient = n_orient , maxit = , tol = tol , log_objective = log_objective , perc = None , verbose = verbose ) while active_set . sum ( ) : active = np . where ( active_set ) [ ] [ : : n_orient ] // n_orient Z_init = dict ( zip ( range ( len ( active ) ) , [ Z [ idx ] for idx in active ] ) ) Z , as_ , E_tmp , converged = _tf_mixed_norm_solver_bcd_ ( M , G [ : , active_set ] , Z_init , np . ones ( len ( active ) * n_orient , dtype = np . bool ) , alpha_space , alpha_time , lipschitz_constant [ active_set [ : : n_orient ] ] , phi , phiT , wsize = wsize , tstep = tstep , n_orient = n_orient , maxit = maxit , tol = tol , log_objective = log_objective , perc = , verbose = verbose ) E += E_tmp active = np . where ( active_set ) [ ] [ : : n_orient ] // n_orient Z_init = dict . fromkeys ( range ( n_positions ) , ) Z_init . update ( dict ( zip ( active , Z . values ( ) ) ) ) active_set [ active_set ] = as_ active_set_0 = active_set . copy ( ) Z , active_set , E_tmp , _ = _tf_mixed_norm_solver_bcd_ ( M , G , Z_init , active_set , alpha_space , alpha_time , lipschitz_constant , phi , phiT , wsize = wsize , tstep = tstep , n_orient = n_orient , maxit = , tol = tol , log_objective = log_objective , perc = None , verbose = verbose ) E += E_tmp if converged : if np . array_equal ( active_set_0 , active_set ) : break if active_set . sum ( ) : Z = np . vstack ( [ Z_ for Z_ in list ( Z . values ( ) ) if np . any ( Z_ ) ] ) X = phiT ( Z ) else : n_sensors , n_times = M . shape ", "answer": "n_step = int ( ceil ( n_times / float ( tstep ) ) )"}, {"prompt": " class NF : def __init__ ( self , fmt ) : self . fmt = fmt ", "answer": "def format ( self , num ) :"}, {"prompt": " from datetime import datetime import json from bson import ObjectId from flask . ext . pymongo import MongoClient import eve from eve . auth import BasicAuth from eve . tests import TestBase from eve . tests . test_settings import MONGO1_PASSWORD , MONGO1_USERNAME , MONGO1_DBNAME , MONGO_DBNAME class TestMultiMongo ( TestBase ) : def setUp ( self ) : super ( TestMultiMongo , self ) . setUp ( ) self . setupDB2 ( ) schema = { '' : { '' : '' } , '' : { '' : '' } , } settings = { '' : schema , '' : '' } ", "answer": "self . app . register_resource ( '' , settings )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AlterField ( model_name = '' , name = '' , field = models . SlugField ( max_length = , verbose_name = '' ) , preserve_default = True , ) , ", "answer": "] "}, {"prompt": " from __future__ import absolute_import import os from celery import Celery from django . conf import settings os . environ . setdefault ( '' , '' ) app = Celery ( '' ) ", "answer": "app . config_from_object ( '' )"}, {"prompt": " from functools import wraps def _create_method_wrapper ( fn ) : @ wraps ( fn ) def wrapper ( self , * args , ** kwargs ) : return fn ( * args , ** kwargs ) return wrapper def callable_setting ( fn = None , takes_self = True ) : def decorator ( fn ) : if not takes_self : fn = _create_method_wrapper ( fn ) fn . is_callable_setting = True ", "answer": "return fn"}, {"prompt": " \"\"\"\"\"\" import re from xml . sax . saxutils import quoteattr from jinja2 import Markup from . helpers import local , to_unicode , url_for __all__ = ( '' , '' , ) def dumb_plural ( num , plural = '' , singular = '' ) : \"\"\"\"\"\" return plural if num != else singular def html_attrs ( classes = None , ** kwargs ) : \"\"\"\"\"\" attrs = [ ] props = [ ] classes = classes . strip ( ) if classes : classes = to_unicode ( quoteattr ( classes ) ) attrs . append ( '' % classes ) for key , value in kwargs . iteritems ( ) : key = key . replace ( '' , '' ) key = to_unicode ( key ) if isinstance ( value , bool ) : if value is True : props . append ( key ) else : value = quoteattr ( to_unicode ( value ) ) attrs . append ( u'' % ( key , value ) ) attrs . sort ( ) props . sort ( ) attrs . extend ( props ) return u'' . join ( attrs ) URL_RE = ur '' def link_to ( text = '' , endpoint = '' , classes = '' , wrapper = None , partial = False , ** kwargs ) : \"\"\"\"\"\" request = local . request path = request . path . rstrip ( '' ) patterns = endpoint if isinstance ( endpoint , ( list , tuple ) ) else [ endpoint ] patterns = [ p if p . startswith ( '' ) or re . match ( URL_RE , p ) else url_for ( p ) for p in patterns ] for url in patterns : url = url . rstrip ( '' ) if path == url or ( partial and path . startswith ( url ) ) : ", "answer": "classes += ''"}, {"prompt": " from hazelcast . serialization . bits import * from hazelcast . protocol . client_message import ClientMessage ", "answer": "from hazelcast . protocol . custom_codec import *"}, {"prompt": " import math from skbio . util . _misc import chunk_str from skbio . metadata . _repr import _MetadataReprBuilder class _SequenceReprBuilder ( _MetadataReprBuilder ) : \"\"\"\"\"\" def __init__ ( self , seq , width , indent , chunk_size ) : super ( _SequenceReprBuilder , self ) . __init__ ( seq , width , indent ) self . _chunk_size = chunk_size def _process_header ( self ) : cls_name = self . _obj . __class__ . __name__ self . _lines . add_line ( cls_name ) self . _lines . add_separator ( ) def _process_data ( self ) : num_lines , num_chars , column_width = self . _find_optimal_seq_chunking ( ) if num_lines <= : self . _lines . add_lines ( self . _format_chunked_seq ( range ( num_lines ) , num_chars , column_width ) ) else : self . _lines . add_lines ( self . _format_chunked_seq ( range ( ) , num_chars , column_width ) ) self . _lines . add_line ( '' ) self . _lines . add_lines ( self . _format_chunked_seq ( range ( num_lines - , num_lines ) , num_chars , column_width ) ) ", "answer": "def _find_optimal_seq_chunking ( self ) :"}, {"prompt": " import unittest from Vintageous . ex . parser . parser import parse_command_line from Vintageous . ex . parser . scanner import Scanner from Vintageous . ex . parser . tokens import TokenDot from Vintageous . ex . parser . tokens import TokenSearchForward from Vintageous . ex . parser . tokens import TokenSearchBackward from Vintageous . ex . parser . tokens import TokenDollar from Vintageous . ex . parser . tokens import TokenDigits from Vintageous . ex . parser . tokens import TokenPercent from Vintageous . ex . parser . tokens import TokenMark from Vintageous . ex . parser . tokens import TokenOffset from Vintageous . ex . parser . tokens import TokenComma from Vintageous . ex . parser . tokens import TokenSemicolon class parse_line_ref_Tests ( unittest . TestCase ) : def test_CanParseEmpty ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range , None ) self . assertEqual ( parsed . command , None ) def test_CanParseDotAsStartLine ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDot ( ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_CanParseDotWithOffset ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDot ( ) , TokenOffset ( [ ] ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_CanParseLoneOffset ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenOffset ( [ ] ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_FailsIfDotAfterOffset ( self ) : self . assertRaises ( ValueError , parse_command_line , '' ) def test_CanParseMultipleOffsets ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenOffset ( [ , ] ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_CanParseSearchForward ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenSearchForward ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_SearchForwardClearsPreviousReferences ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDot ( ) , TokenSearchForward ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_SearchForwardClearsPreviousReferencesWithOffsets ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDot ( ) , TokenOffset ( [ ] ) , TokenSearchForward ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_CanParseSearchBackward ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenSearchBackward ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_SearchBackwardClearsPreviousReferences ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDot ( ) , TokenSearchBackward ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_SearchBackwardClearsPreviousReferencesWithOffsets ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDot ( ) , TokenOffset ( [ ] ) , TokenSearchBackward ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_CanParseSearchForwardWithOffset ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenSearchForward ( '' ) , TokenOffset ( [ ] ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_CanParseSearchForwardWithOffsets ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenSearchForward ( '' ) , TokenOffset ( [ , , ] ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_CanParseSearchBacwardWithOffset ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenSearchBackward ( '' ) , TokenOffset ( [ ] ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_CanParseSearchBacwardWithOffsets ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenSearchBackward ( '' ) , TokenOffset ( [ , , ] ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) def test_CanParseDollarOnItsOwn ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDollar ( ) ] ) def test_CanParseDollarWithCompany ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDigits ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ TokenDollar ( ) ] ) def test_FailsIfDollarOffset ( self ) : self . assertRaises ( ValueError , parse_command_line , '' ) def test_FailsIfPrecededByAnything ( self ) : self . assertRaises ( ValueError , parse_command_line , '' ) self . assertRaises ( ValueError , parse_command_line , '' ) self . assertRaises ( ValueError , parse_command_line , '' ) def test_CanParseLoneComma ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . separator , TokenComma ( ) ) def test_CanParseDotComma ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDot ( ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) self . assertEqual ( parsed . line_range . separator , TokenComma ( ) ) def test_CanParseCommaDot ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . separator , TokenComma ( ) ) self . assertEqual ( parsed . line_range . start , [ ] ) self . assertEqual ( parsed . line_range . end , [ TokenDot ( ) ] ) def test_CanParseLoneSmicolon ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . separator , TokenSemicolon ( ) ) def test_CanParseDotSmicolon ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDot ( ) ] ) self . assertEqual ( parsed . line_range . end , [ ] ) self . assertEqual ( parsed . line_range . separator , TokenSemicolon ( ) ) def test_CanParseSmicolonDot ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ ] ) self . assertEqual ( parsed . line_range . end , [ TokenDot ( ) ] ) self . assertEqual ( parsed . line_range . separator , TokenSemicolon ( ) ) def test_CanParseCommaOffset ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . separator , TokenComma ( ) ) self . assertEqual ( parsed . line_range . start , [ ] ) self . assertEqual ( parsed . line_range . end , [ TokenOffset ( [ ] ) ] ) def test_CanParseSemicolonOffset ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . separator , TokenComma ( ) ) self . assertEqual ( parsed . line_range . start , [ ] ) self . assertEqual ( parsed . line_range . end , [ ] ) self . assertEqual ( parsed . line_range . end_offset , [ ] ) def test_CanParseOffsetCommaOffset ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . separator , TokenComma ( ) ) self . assertEqual ( parsed . line_range . start , [ TokenOffset ( [ ] ) ] ) self . assertEqual ( parsed . line_range . end , [ TokenOffset ( [ ] ) ] ) def test_CanParseSemicolonOffset ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenOffset ( [ ] ) ] ) self . assertEqual ( parsed . line_range . end , [ TokenOffset ( [ ] ) ] ) self . assertEqual ( parsed . line_range . separator , TokenSemicolon ( ) ) def test_CanParseNumber ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDigits ( '' ) ] ) def test_CanParseNumberRightHandSide ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ ] ) self . assertEqual ( parsed . line_range . end , [ TokenDigits ( '' ) ] ) def test_FailsIfDotDigits ( self ) : self . assertRaises ( ValueError , parse_command_line , '' ) class parse_line_ref_TokenComma_Tests ( unittest . TestCase ) : def test_CanParseLongSequence ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDigits ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ TokenDigits ( '' ) ] ) class parse_line_ref_ParseSubstituteCommand ( unittest . TestCase ) : def test_CanParseItOnItsOwn ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . command . content , '' ) def test_CanParseAlias ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . command . content , '' ) def test_CanParseWithSimpleRange ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDigits ( '' ) ] ) self . assertEqual ( parsed . command . content , '' ) def test_CanParseWithStartAndEndLines ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDigits ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ TokenDigits ( '' ) ] ) self . assertEqual ( parsed . command . content , '' ) def test_CanParseWithSearchForward ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenSearchForward ( '' ) ] ) self . assertEqual ( parsed . command . content , '' ) def test_CanParseWithSearchBackward ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenSearchBackward ( '' ) ] ) self . assertEqual ( parsed . command . content , '' ) def test_CanParseWithSearchBackwardAndSearchForward ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenSearchBackward ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ TokenSearchForward ( '' ) ] ) self . assertEqual ( parsed . command . content , '' ) def test_CanParseWithZeroAndDollar ( self ) : parsed = parse_command_line ( '' ) self . assertEqual ( parsed . line_range . start , [ TokenDigits ( '' ) ] ) self . assertEqual ( parsed . line_range . end , [ TokenDollar ( ) ] ) self . assertEqual ( parsed . command . content , '' ) class parse_line_ref_Percent ( unittest . TestCase ) : def test_CanParsePercent ( self ) : parsed = parse_command_line ( \"\" ) self . assertEqual ( parsed . line_range . start , [ TokenPercent ( ) ] ) class parse_line_ref_SetLineRangeSeparator ( unittest . TestCase ) : def test_CanSetComma ( self ) : parsed = parse_command_line ( \"\" ) self . assertEqual ( parsed . line_range . separator , TokenComma ( ) ) def test_CanSetSemicolon ( self ) : parsed = parse_command_line ( \"\" ) self . assertEqual ( parsed . line_range . separator , TokenSemicolon ( ) ) def test_CanSetCommaMultipleTimes ( self ) : parsed = parse_command_line ( \"\" ) self . assertEqual ( parsed . line_range . separator , TokenComma ( ) ) def test_CanSetSemicolonMultipleTimes ( self ) : parsed = parse_command_line ( \"\" ) self . assertEqual ( parsed . line_range . separator , TokenSemicolon ( ) ) def test_CanSetMultipleTimesSemicolonLast ( self ) : parsed = parse_command_line ( \"\" ) self . assertEqual ( parsed . line_range . separator , TokenSemicolon ( ) ) def test_CanSetMultipleTimesCommaLast ( self ) : parsed = parse_command_line ( \"\" ) self . assertEqual ( parsed . line_range . separator , TokenComma ( ) ) class parse_line_ref_ParseMarks ( unittest . TestCase ) : def test_CanParseItOnItsOwn ( self ) : parsed = parse_command_line ( \"\" ) self . assertEqual ( parsed . line_range . start , [ TokenMark ( '' ) ] ) ", "answer": "def test_CanParseOnTwoSides ( self ) :"}, {"prompt": " __author__ = '' from aktos_dcs import * class TestEsp ( SerialPortReader ) : def on_connect ( self ) : print \"\" print \"\" % self . ser . baudrate print \"\" if self . ser . baudrate != : self . send_cmd ( \"\" ) sleep ( ) self . ser . baudrate = self . ser . close ( ) else : print \"\" print self . ser ", "answer": "def on_disconnect ( self ) :"}, {"prompt": " from esrally . track import track GEO_NAMES_INDEX_NAME = \"\" GEO_NAMES_TYPE_NAME = \"\" class DefaultQuery ( track . Query ) : def __init__ ( self ) : track . Query . __init__ ( self , \"\" ) def run ( self , es ) : return es . search ( index = GEO_NAMES_INDEX_NAME ) class TermQuery ( track . Query ) : def __init__ ( self ) : track . Query . __init__ ( self , \"\" ) def run ( self , es ) : return es . search ( index = GEO_NAMES_INDEX_NAME , doc_type = GEO_NAMES_TYPE_NAME , q = \"\" ) class PhraseQuery ( track . Query ) : def __init__ ( self ) : track . Query . __init__ ( self , \"\" ) def run ( self , es ) : return es . search ( index = GEO_NAMES_INDEX_NAME , doc_type = GEO_NAMES_TYPE_NAME , body = '''''' ) class CountryAggQuery ( track . Query ) : def __init__ ( self , suffix = \"\" , use_request_cache = True ) : track . Query . __init__ ( self , \"\" + suffix ) self . use_request_cache = use_request_cache def run ( self , es ) : return es . search ( index = GEO_NAMES_INDEX_NAME , doc_type = GEO_NAMES_TYPE_NAME , request_cache = self . use_request_cache , body = '''''' ) class ScrollQuery ( track . Query ) : PAGES = ITEMS_PER_PAGE = ", "answer": "def __init__ ( self ) :"}, {"prompt": " import binascii import struct from django . forms import ValidationError from . const import ( GDAL_TO_POSTGIS , GDAL_TO_STRUCT , POSTGIS_HEADER_STRUCTURE , POSTGIS_TO_GDAL , STRUCT_SIZE , ) def pack ( structure , data ) : \"\"\"\"\"\" return binascii . hexlify ( struct . pack ( '' + structure , * data ) ) . upper ( ) def unpack ( structure , data ) : \"\"\"\"\"\" return struct . unpack ( '' + structure , binascii . unhexlify ( data ) ) def chunk ( data , index ) : \"\"\"\"\"\" return data [ : index ] , data [ index : ] def get_pgraster_srid ( data ) : \"\"\"\"\"\" if data is None : return return unpack ( '' , data [ : ] ) [ ] def from_pgraster ( data ) : \"\"\"\"\"\" if data is None : return header , data = chunk ( data , ) header = unpack ( POSTGIS_HEADER_STRUCTURE , header ) bands = [ ] pixeltypes = [ ] while data : pixeltype , data = chunk ( data , ) pixeltype = unpack ( '' , pixeltype ) [ ] has_nodata = pixeltype >= if has_nodata : pixeltype -= pixeltype = POSTGIS_TO_GDAL [ pixeltype ] pack_type = GDAL_TO_STRUCT [ pixeltype ] pack_size = * STRUCT_SIZE [ pack_type ] nodata , data = chunk ( data , pack_size ) nodata = unpack ( pack_type , nodata ) [ ] ", "answer": "band , data = chunk ( data , pack_size * header [ ] * header [ ] )"}, {"prompt": " from kaa import bot from urllib import quote import json ", "answer": "import requests"}, {"prompt": " from django import forms from django . contrib import messages from django . core . exceptions import ValidationError from django . db . models import ObjectDoesNotExist from django . shortcuts import get_object_or_404 , redirect , render_to_response from django . template import RequestContext from django . utils . translation import ugettext as _ from django . views import generic from plata . contact . models import Contact from plata . discount . models import Discount from plata . shop . views import Shop from plata . shop . models import Order from staggered . models import Product shop = Shop ( Contact , Order , Discount ) product_list = generic . ListView . as_view ( queryset = Product . objects . filter ( is_active = True ) , template_name = '' , ) class OrderItemForm ( forms . Form ) : quantity = forms . IntegerField ( label = _ ( '' ) , initial = , ", "answer": "min_value = , max_value = )"}, {"prompt": " from . main import Lightning from . session import Session from . visualization import Visualization , VisualizationLocal from . types . plots import * from . types . images import * from . types . streaming import * from . types . three import * ", "answer": "__version__ = \"\" "}, {"prompt": " from openstack_dashboard import api from openstack_dashboard . test import helpers as test from neutronclient . v2_0 import client neutronclient = client . Client class VPNaasApiTests ( test . APITestCase ) : @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_vpnservice_create ( self ) : vpnservice1 = self . api_vpnservices . first ( ) form_data = { '' : vpnservice1 [ '' ] , '' : vpnservice1 [ '' ] , '' : vpnservice1 [ '' ] , '' : vpnservice1 [ '' ] , '' : vpnservice1 [ '' ] } vpnservice = { '' : self . api_vpnservices . first ( ) } neutronclient . create_vpnservice ( { '' : form_data } ) . AndReturn ( vpnservice ) self . mox . ReplayAll ( ) ret_val = api . vpn . vpnservice_create ( self . request , ** form_data ) self . assertIsInstance ( ret_val , api . vpn . VPNService ) @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_vpnservices_get ( self ) : vpnservices = { '' : self . vpnservices . list ( ) } vpnservices_dict = { '' : self . api_vpnservices . list ( ) } neutronclient . list_vpnservices ( ) . AndReturn ( vpnservices_dict ) self . mox . ReplayAll ( ) ret_val = api . vpn . vpnservices_get ( self . request ) for ( v , d ) in zip ( ret_val , vpnservices [ '' ] ) : self . assertIsInstance ( v , api . vpn . VPNService ) self . assertTrue ( v . name , d . name ) self . assertTrue ( v . id ) @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_vpnservice_get ( self ) : vpnservice1 = self . api_vpnservices . first ( ) vpnservice = { '' : vpnservice1 } neutronclient . show_vpnservice ( vpnservice [ '' ] [ '' ] ) . AndReturn ( vpnservice ) self . mox . ReplayAll ( ) ret_val = api . vpn . vpnservice_get ( self . request , vpnservice [ '' ] [ '' ] ) self . assertIsInstance ( ret_val , api . vpn . VPNService ) @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_ikepolicy_create ( self ) : ikepolicy1 = self . api_ikepolicies . first ( ) form_data = { '' : ikepolicy1 [ '' ] , '' : ikepolicy1 [ '' ] , '' : ikepolicy1 [ '' ] , '' : ikepolicy1 [ '' ] , '' : ikepolicy1 [ '' ] , '' : ikepolicy1 [ '' ] , '' : ikepolicy1 [ '' ] , '' : ikepolicy1 [ '' ] } ikepolicy = { '' : self . api_ikepolicies . first ( ) } neutronclient . create_ikepolicy ( { '' : form_data } ) . AndReturn ( ikepolicy ) self . mox . ReplayAll ( ) ret_val = api . vpn . ikepolicy_create ( self . request , ** form_data ) self . assertIsInstance ( ret_val , api . vpn . IKEPolicy ) @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_ikepolicies_get ( self ) : ikepolicies = { '' : self . ikepolicies . list ( ) } ikepolicies_dict = { '' : self . api_ikepolicies . list ( ) } neutronclient . list_ikepolicies ( ) . AndReturn ( ikepolicies_dict ) self . mox . ReplayAll ( ) ret_val = api . vpn . ikepolicies_get ( self . request ) for ( v , d ) in zip ( ret_val , ikepolicies [ '' ] ) : self . assertIsInstance ( v , api . vpn . IKEPolicy ) self . assertTrue ( v . name , d . name ) self . assertTrue ( v . id ) @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_ikepolicy_get ( self ) : ikepolicy1 = self . api_ikepolicies . first ( ) ikepolicy = { '' : ikepolicy1 } neutronclient . show_ikepolicy ( ikepolicy [ '' ] [ '' ] ) . AndReturn ( ikepolicy ) self . mox . ReplayAll ( ) ret_val = api . vpn . ikepolicy_get ( self . request , ikepolicy [ '' ] [ '' ] ) self . assertIsInstance ( ret_val , api . vpn . IKEPolicy ) @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_ipsecpolicy_create ( self ) : ipsecpolicy1 = self . api_ipsecpolicies . first ( ) form_data = { '' : ipsecpolicy1 [ '' ] , '' : ipsecpolicy1 [ '' ] , '' : ipsecpolicy1 [ '' ] , '' : ipsecpolicy1 [ '' ] , '' : ipsecpolicy1 [ '' ] , '' : ipsecpolicy1 [ '' ] , '' : ipsecpolicy1 [ '' ] , '' : ipsecpolicy1 [ '' ] } ipsecpolicy = { '' : self . api_ipsecpolicies . first ( ) } neutronclient . create_ipsecpolicy ( { '' : form_data } ) . AndReturn ( ipsecpolicy ) self . mox . ReplayAll ( ) ret_val = api . vpn . ipsecpolicy_create ( self . request , ** form_data ) self . assertIsInstance ( ret_val , api . vpn . IPSecPolicy ) @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_ipsecpolicies_get ( self ) : ipsecpolicies = { '' : self . ipsecpolicies . list ( ) } ipsecpolicies_dict = { '' : self . api_ipsecpolicies . list ( ) } neutronclient . list_ipsecpolicies ( ) . AndReturn ( ipsecpolicies_dict ) self . mox . ReplayAll ( ) ret_val = api . vpn . ipsecpolicies_get ( self . request ) for ( v , d ) in zip ( ret_val , ipsecpolicies [ '' ] ) : self . assertIsInstance ( v , api . vpn . IPSecPolicy ) self . assertTrue ( v . name , d . name ) self . assertTrue ( v . id ) @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_ipsecpolicy_get ( self ) : ipsecpolicy1 = self . api_ipsecpolicies . first ( ) ipsecpolicy = { '' : ipsecpolicy1 } neutronclient . show_ipsecpolicy ( ipsecpolicy [ '' ] [ '' ] ) . AndReturn ( ipsecpolicy ) self . mox . ReplayAll ( ) ret_val = api . vpn . ipsecpolicy_get ( self . request , ipsecpolicy [ '' ] [ '' ] ) self . assertIsInstance ( ret_val , api . vpn . IPSecPolicy ) @ test . create_stubs ( { neutronclient : ( '' , ) } ) def test_ipsecsiteconnection_create ( self ) : ipsecsiteconnection1 = self . api_ipsecsiteconnections . first ( ) form_data = { '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , '' : ipsecsiteconnection1 [ '' ] , ", "answer": "'' : ipsecsiteconnection1 [ '' ]"}, {"prompt": " import abc class AbstractMetricsReporter ( object ) : \"\"\"\"\"\" __metaclass__ = abc . ABCMeta @ abc . abstractmethod def init ( self , metrics ) : \"\"\"\"\"\" raise NotImplementedError @ abc . abstractmethod def metric_change ( self , metric ) : \"\"\"\"\"\" raise NotImplementedError @ abc . abstractmethod def metric_removal ( self , metric ) : \"\"\"\"\"\" raise NotImplementedError @ abc . abstractmethod def configure ( self , configs ) : \"\"\"\"\"\" raise NotImplementedError @ abc . abstractmethod ", "answer": "def close ( self ) :"}, {"prompt": " from django import forms ", "answer": "from django . conf import settings as site_settings"}, {"prompt": " import re from time import time , gmtime from calendar import timegm from webtest import TestApp from google . appengine . ext import webapp from google . appengine . ext . webapp import util import sys , os sys . path . append ( os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '' ) ) ) from signedcookie import SignedCookie , SIG_LEN from session import RequestHandler , SECRET_KEY , SESSION_TTL , SID_TTL class User : def __init__ ( self , nickname ) : self . nickname = nickname class Login ( RequestHandler ) : def post ( self ) : nickname = self . request . get ( '' ) self . session . start ( User ( nickname ) ) class Regen ( RequestHandler ) : def post ( self ) : self . session . regen ( ) class Touch ( RequestHandler ) : def get ( self ) : pass class Logout ( RequestHandler ) : def get ( self ) : self . session . end ( ) def application ( ) : return webapp . WSGIApplication ( [ ( '' , Login ) , ( '' , Regen ) , ( '' , Touch ) , ( '' , Logout ) ] , debug = True ) def test_login ( ) : app = TestApp ( application ( ) ) app = TestApp ( application ( ) ) response = app . post ( '' , { '' : '' } ) res = str ( response ) assert '' in res assert '' in res assert '' in res def test_logout ( ) : app = TestApp ( application ( ) ) SID = '' c = SignedCookie ( SECRET_KEY + SID ) c [ '' ] = SID c [ '' ] = '' c [ '' ] = timegm ( gmtime ( ) ) s = '' + '' . join ( m . output ( ) [ : ] for m in c . values ( ) ) response = app . get ( '' , extra_environ = { '' : s } ) res = str ( response ) assert re . search ( '' , res ) assert re . search ( '' , res ) assert re . search ( '' , res ) def test_regen ( ) : app = TestApp ( application ( ) ) SID = '' c = SignedCookie ( SECRET_KEY + SID ) c [ '' ] = SID c [ '' ] = '' c [ '' ] = timegm ( gmtime ( ) ) s = '' + '' . join ( m . output ( ) [ : ] for m in c . values ( ) ) response = app . post ( '' , extra_environ = { '' : s } ) res = str ( response ) new_SID = re . search ( '' , res ) . group ( ) new_user = re . search ( '' , res ) . group ( ) assert new_SID [ : - SIG_LEN ] != c [ '' ] . value assert new_user [ : - SIG_LEN ] == c [ '' ] . value assert new_user != c [ '' ] . coded_value ", "answer": "def test_autoregen ( ) :"}, {"prompt": " \"\"\"\"\"\" import weakref from eventlet import corolocal class WeakLocal ( corolocal . local ) : def __getattribute__ ( self , attr ) : rval = corolocal . local . __getattribute__ ( self , attr ) if rval : rval = rval ( ) ", "answer": "return rval"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Tangible ( )"}, {"prompt": " from ctypes import BigEndianStructure , Union , c_uint8 , c_uint16 , c_uint32 from io import BytesIO from . compat import * from . error import * from . packet import * from . types import * from . util import * class Box ( Packet ) : exception = F4VError def __init__ ( self , type , payload , extended_size = False ) : self . type = type self . payload = payload self . extended_size = extended_size @ property def size ( self ) : size = size += self . payload . size if size > or self . extended_size : size += return size @ classmethod def _deserialize ( cls , io , strict = False , raw_payload = False ) : size = U32BE . read ( io ) type_ = FourCC . read ( io ) header_size = extended_size = False if size == : size = U64BE . read ( io ) header_size += extended_size = True if size == : data = io . read ( ) else : data = chunked_read ( io , size - header_size , exception = F4VError ) if type_ in PayloadTypes and not raw_payload : payloadcls = PayloadTypes [ type_ ] payloadio = BytesIO ( data ) payload = payloadcls . deserialize ( payloadio ) else : payload = RawPayload ( data ) box = cls ( type_ , payload , extended_size ) if strict and box . size != size : raise F4VError ( \"\" ) return box def _serialize ( self , packet ) : size = self . payload . size if size > or self . extended_size : packet += U32BE ( ) else : packet += U32BE ( size + ) packet += FourCC ( self . type ) if size > or self . extended_size : packet += U64BE ( size + ) if isinstance ( self . payload , BoxPayload ) : self . payload . serialize ( packet ) else : packetwrite ( self . payload ) class BoxPayload ( Packet ) : exception = F4VError @ property def size ( self ) : return @ classmethod def box ( cls , * args , ** kw ) : type_ = None for name , kls in PayloadTypes . items ( ) : if kls == cls : type_ = name break payload = cls ( * args , ** kw ) return Box ( type_ , , payload ) class BoxContainer ( BoxPayload ) : def __init__ ( self , boxes ) : self . boxes = boxes @ property def size ( self ) : size = for box in self . boxes : size += box . size return size def _serialize ( self , packet ) : for box in self . boxes : box . serialize ( packet ) @ classmethod def _deserialize ( cls , io ) : boxes = [ ] while True : try : box = Box . deserialize ( io ) except IOError : break boxes . append ( box ) return cls ( boxes ) class BoxContainerSingle ( BoxPayload ) : def __init__ ( self , box ) : self . box = box @ property def size ( self ) : return self . box . size def _serialize ( self , packet ) : self . box . serialize ( packet ) @ classmethod def _deserialize ( cls , io ) : box = Box . deserialize ( io ) return cls ( box ) class RawPayload ( BoxPayload ) : def __init__ ( self , data ) : self . data = data def __repr__ ( self ) : return \"\" . format ( self . size ) @ property def size ( self ) : return len ( self . data ) @ classmethod def _deserialize ( cls , io ) : data = io . read ( ) return cls ( data ) def _serialize ( self , packet ) : packet += self . data class BoxPayloadFTYP ( BoxPayload ) : def __init__ ( self , major_brand = \"\" , minor_version = , compatible_brands = [ \"\" , \"\" , \"\" ] ) : self . major_brand = major_brand self . minor_version = minor_version self . compatible_brands = compatible_brands @ property def size ( self ) : return + + ( len ( self . compatible_brands ) * ) def _serialize ( self , packet ) : packet += FourCC ( self . major_brand ) packet += U32BE ( self . minor_version ) for brand in self . compatible_brands : packet += FourCC ( brand ) @ classmethod def _deserialize ( cls , io ) : major_brand = FourCC . read ( io ) minor_version = U32BE . read ( io ) compatible_brands = [ ] while True : try : brand = FourCC . read ( io ) except IOError : break compatible_brands . append ( brand ) return cls ( major_brand , minor_version , compatible_brands ) class BoxPayloadMVHD ( BoxPayload ) : def __init__ ( self , version = , creation_time = , modification_time = , time_scale = , duration = , rate = , volume = , matrix = [ , , , , , , , , ] , next_track_id = ) : self . version = version self . creation_time = creation_time self . modification_time = modification_time self . time_scale = time_scale self . duration = duration self . rate = rate self . volume = volume self . matrix = matrix self . next_track_id = next_track_id @ property def size ( self ) : size = + + + + + + + + ( * ) + ( * ) + if self . version == : size += * else : size += * return size def _serialize ( self , packet ) : packet += U8 ( self . version ) packet += U24BE ( ) packet += U3264 ( self . creation_time , self . version ) packet += U3264 ( self . modification_time , self . version ) packet += U32BE ( self . time_scale ) packet += U3264 ( self . duration , self . version ) packet += S16BE_16 ( self . rate ) packet += S8_8BE ( self . volume ) packet += U16BE ( ) packet += U32BE ( ) packet += U32BE ( ) for m in self . matrix : packet += U32BE ( m ) for i in range ( ) : packet += U32BE ( ) packet += U32BE ( self . next_track_id ) @ classmethod def _deserialize ( cls , io ) : version = U8 . read ( io ) U24BE . read ( io ) creation_time = U3264 . read ( io , version ) modification_time = U3264 . read ( io , version ) time_scale = U32BE . read ( io ) duration = U3264 . read ( io , version ) rate = S16_16 . read ( io ) volume = S8_8BE . read ( io ) U16BE . read ( io ) U32BE . read ( io ) U32BE . read ( io ) matrix = [ ] for i in range ( ) : matrix . append ( U32BE . read ( io ) ) for i in range ( ) : U32BE . read ( io ) next_track_id = U32BE . read ( io ) return cls ( version , creation_time , modification_time , time_scale , duration , rate , volume , matrix , next_track_id ) class SampleFlags ( BoxPayload ) : class Flags ( Union ) : class Bits ( BigEndianStructure ) : _fields_ = [ ( \"\" , c_uint8 , ) , ( \"\" , c_uint8 , ) , ( \"\" , c_uint8 , ) , ( \"\" , c_uint8 , ) , ( \"\" , c_uint8 , ) , ( \"\" , c_uint8 , ) , ( \"\" , c_uint16 , ) ] _fields_ = [ ( \"\" , Bits ) , ( \"\" , c_uint32 ) ] def __init__ ( self , sample_depends_on , sample_is_depended_on , sample_has_redundancy , sample_padding_value , sample_is_difference_sample , sample_degradation_priority ) : self . flags = self . Flags ( ) self . flags . bit . reserved = self . flags . bit . sample_depends_on = sample_depends_on self . flags . bit . sample_is_depended_on = sample_is_depended_on self . flags . bit . sample_has_redundancy = sample_has_redundancy self . flags . bit . sample_padding_value = sample_padding_value self . flags . bit . sample_is_difference_sample = sample_is_difference_sample self . flags . bit . sample_degradation_priority = sample_degradation_priority @ property def size ( self ) : return def _serialize ( self , packet ) : packet += U32BE ( self . flags . byte ) @ classmethod def _deserialize ( cls , io ) : flags = cls . Flags ( ) flags . byte = U32BE . read ( io ) return cls ( flags . bit . sample_depends_on , flags . bit . sample_is_depended_on , flags . bit . sample_has_redundancy , flags . bit . sample_padding_value , flags . bit . sample_is_difference_sample , flags . bit . sample_degradation_priority ) class BoxPayloadTREX ( BoxPayload ) : def __init__ ( self , version , track_id , default_sample_description_index , default_sample_duration , default_sample_size , default_sample_flags ) : self . version = version self . track_id = track_id self . default_sample_description_index = default_sample_description_index self . default_sample_duration = default_sample_duration self . default_sample_size = default_sample_size self . default_sample_flags = default_sample_flags @ property def size ( self ) : return + + + + + + self . default_sample_flags . size def _serialize ( self , packet ) : packet += U8 ( self . version ) packet += U24BE ( ) packet += U32BE ( self . track_id ) packet += U32BE ( self . default_sample_description_index ) packet += U32BE ( self . default_sample_duration ) packet += U32BE ( self . default_sample_size ) self . default_sample_flags . serialize ( packet ) @ classmethod def _deserialize ( cls , io ) : version = U8 . read ( io ) flags = U24BE . read ( io ) track_id = U32BE . read ( io ) default_sample_description_index = U32BE . read ( io ) default_sample_duration = U32BE . read ( io ) default_sample_size = U32BE . read ( io ) default_sample_flags = SampleFlags . deserialize ( io ) return cls ( version , track_id , default_sample_description_index , default_sample_duration , default_sample_size , default_sample_flags ) class BoxPayloadTKHD ( BoxPayload ) : def __init__ ( self , version = , flags = , creation_time = , modification_time = , track_id = , duration = , layer = , alternate_group = , volume = , transform_matrix = [ , , , , , , , , ] , width = , height = ) : self . version = version self . flags = flags self . creation_time = creation_time self . modification_time = modification_time self . track_id = track_id self . duration = duration self . layer = layer self . alternate_group = alternate_group self . volume = volume self . transform_matrix = transform_matrix self . width = width self . height = height @ property def size ( self ) : size = + + + + + + + ( * ) + + + + + ( * ) + + if self . version == : size += * return size def _serialize ( self , packet ) : packet += U8 ( self . version ) packet += U24BE ( self . flags ) packet += U3264 ( self . creation_time , self . version ) packet += U3264 ( self . modification_time , self . version ) packet += U32BE ( self . track_id ) packet += U32BE ( ) packet += U3264 ( self . duration , self . version ) for i in range ( ) : packet += U32BE ( ) packet += S16BE ( self . layer ) packet += S16BE ( self . alternate_group ) packet += S8_8BE ( self . volume ) packet += U16BE ( ) for i in range ( ) : packet += U32BE ( self . transform_matrix [ i ] ) packet += S16BE_16 ( self . width ) packet += S16BE_16 ( self . height ) @ classmethod def _deserialize ( cls , io ) : version = U8 . read ( io ) flags = U24BE . read ( io ) creation_time = U3264 . read ( io , version ) modification_time = U3264 . read ( io , version ) track_id = U32BE . read ( io ) U32BE . read ( io ) duration = U3264 . read ( io , version ) for i in range ( ) : U32BE . read ( io ) layer = S16BE . read ( io ) alternate_group = S16BE . read ( io ) volume = S8_8BE . read ( io ) U16BE . read ( io ) transform_matrix = [ ] for i in range ( ) : transform_matrix . append ( S32BE . read ( io ) ) width = S16_16 . read ( io ) height = S16_16 . read ( io ) return cls ( version , flags , creation_time , modification_time , track_id , duration , layer , alternate_group , volume , transform_matrix , width , height ) class BoxPayloadMDHD ( BoxPayload ) : def __init__ ( self , version = , creation_time = , modification_time = , time_scale = , duration = , language = \"\" ) : self . version = version self . creation_time = creation_time self . modification_time = modification_time self . time_scale = time_scale self . duration = duration self . language = language @ property def size ( self ) : size = + + + + + + + if self . version == : size += * return size def _serialize ( self , packet ) : packet += U8 ( self . version ) packet += U24BE ( ) packet += U3264 ( self . creation_time , self . version ) packet += U3264 ( self . modification_time , self . version ) packet += U32BE ( self . time_scale ) packet += U3264 ( self . duration , self . version ) packet += S16BE ( iso639_to_lang ( self . language ) ) packet += U16BE ( ) @ classmethod def _deserialize ( cls , io ) : version = U8 . read ( io ) U24BE . read ( io ) creation_time = U3264 . read ( io , version ) modification_time = U3264 . read ( io , version ) time_scale = U32BE . read ( io ) duration = U3264 . read ( io , version ) language = lang_to_iso639 ( U16BE . read ( io ) ) U16BE . read ( io ) return cls ( version , creation_time , modification_time , time_scale , duration , language ) class BoxPayloadHDLR ( BoxPayload ) : def __init__ ( self , version = , predefined = , handler_type = \"\" , name = \"\" ) : self . version = version self . predefined = predefined self . handler_type = handler_type self . name = name @ property def size ( self ) : size = + + + + ( * ) size += len ( self . name ) return size def _serialize ( self , packet ) : packet += U8 ( self . version ) packet += U24BE ( ) packet += U32BE ( self . predefined ) packet += FourCC ( self . handler_type ) for i in range ( ) : packet += U32BE ( ) packet += CString ( self . name ) @ classmethod def _deserialize ( cls , io ) : version = U8 . read ( io ) flags = U24BE . read ( io ) predefined = U32BE . read ( io ) handler_type = FourCC . read ( io ) for i in range ( ) : U32BE . read ( io ) name = CString . read ( io ) return cls ( version , predefined , handler_type , name ) class BoxPayloadVMHD ( BoxPayload ) : def __init__ ( self , version = , flags = , graphics_mode = , op_color = [ , , ] ) : self . version = version self . flags = flags self . graphics_mode = graphics_mode self . op_color = op_color @ property def size ( self ) : return + + + ( * ) def _serialize ( self , packet ) : packet += U8 ( self . version ) packet += U24BE ( self . flags ) packet += U16BE ( self . graphics_mode ) for i in range ( ) : packet += U16BE ( self . op_color [ i ] ) @ classmethod def _deserialize ( cls , io ) : version = U8 . read ( io ) flags = U24BE . read ( io ) graphics_mode = U16BE . read ( io ) op_color = [ ] for i in range ( ) : op_color . append ( U16BE . read ( io ) ) return cls ( version , flags , graphics_mode , op_color ) class BoxPayloadDREF ( BoxContainer ) : def __init__ ( self , version = , boxes = [ ] ) : self . version = version self . boxes = boxes @ property def size ( self ) : size = + + for box in self . boxes : size += box . size return size def _serialize ( self , packet ) : packet += U8 ( self . version ) packet += U24BE ( ) packet += U32BE ( len ( self . boxes ) ) for box in self . boxes : box . serialize ( packet ) @ classmethod ", "answer": "def _deserialize ( cls , io ) :"}, {"prompt": " from . . excel_comparsion_test import ExcelComparisonTest from ... workbook import Workbook class TestCompareXLSXFiles ( ExcelComparisonTest ) : \"\"\"\"\"\" def setUp ( self ) : self . maxDiff = None filename = '' test_dir = '' self . got_filename = test_dir + '' + filename self . exp_filename = test_dir + '' + filename ", "answer": "self . ignore_files = [ ]"}, {"prompt": " from south . utils import datetime_utils as datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = ) , keep_default = False ) db . add_column ( '' , '' , ", "answer": "self . gf ( '' ) ( auto_now_add = True , default = datetime . datetime ( , , , , ) , blank = True ) ,"}, {"prompt": " from __future__ import unicode_literals from . . baseapi import BaseApi class Report ( BaseApi ) : def __init__ ( self , * args , ** kwargs ) : super ( Report , self ) . __init__ ( * args , ** kwargs ) self . endpoint = '' def all ( self , ** kwargs ) : \"\"\"\"\"\" ", "answer": "return self . _mc_client . _get ( url = self . endpoint , ** kwargs )"}, {"prompt": " import random from lightsocket . server import Resource , Response , Router class ExampleProxy ( Resource ) : def __init__ ( self ) : self . router = Router ( self ) self . method_map = dict ( yep = self . yep ) def handle_request ( self , request ) : method = self . get_method ( request ) return method ( request ) def yep ( self , request ) : data = \"\" + str ( random . random ( ) ) return Response ( , data ) class Example ( Resource ) : ", "answer": "def __init__ ( self ) :"}, {"prompt": " VERSION = ( , , , '' , ) __version__ = '' . join ( map ( str , VERSION ) ) ", "answer": "def get_version ( ) :"}, {"prompt": " from django . core . urlresolvers import reverse from sky_visitor import views as sky_visitor_views ", "answer": "class CustomLogoutView ( sky_visitor_views . LogoutView ) :"}, {"prompt": " from datetime import datetime from django . core . urlresolvers import reverse from django . http import HttpResponse , Http404 from django . shortcuts import render_to_response , get_object_or_404 from django . template import RequestContext from django . template . loader import render_to_string from django . utils import simplejson as json from django . core . paginator import Paginator , EmptyPage , InvalidPage from django . contrib . sites . models import Site from biblion . exceptions import InvalidSection from biblion . models import Post , FeedHit from biblion . settings import ALL_SECTION_NAME from threadedcomments . forms import RichCommentForm def blog_list ( request , section = None ) : posts = Post . objects . current ( ) section_name = None if section : try : section_name = dict ( Post . SECTION_CHOICES ) [ Post . section_idx ( section ) ] except KeyError : raise Http404 ( ) try : posts = Post . objects . section ( section ) except InvalidSection : raise Http404 ( ) return render_to_response ( \"\" , { \"\" : section , \"\" : section_name , \"\" : posts , } , context_instance = RequestContext ( request ) ) def blog_post_detail ( request , ** kwargs ) : if \"\" in kwargs : if request . user . is_authenticated ( ) and request . user . is_staff : queryset = Post . objects . all ( ) post = get_object_or_404 ( queryset , pk = kwargs [ \"\" ] ) else : raise Http404 ( ) else : queryset = Post . objects . current ( ) queryset = queryset . filter ( published__year = int ( kwargs [ \"\" ] ) , published__month = int ( kwargs [ \"\" ] ) , published__day = int ( kwargs [ \"\" ] ) , ) post = get_object_or_404 ( queryset , slug = kwargs [ \"\" ] ) post . inc_views ( ) comment_form = RichCommentForm ( auto_id = '' ) return render_to_response ( \"\" , { \"\" : post , \"\" : comment_form , } , context_instance = RequestContext ( request ) ) def serialize_request ( request ) : data = { \"\" : request . path , \"\" : { \"\" : request . META . get ( \"\" ) , \"\" : request . META . get ( \"\" ) , } } for key in request . META : if key . startswith ( \"\" ) : data [ \"\" ] [ key ] = request . META [ key ] return json . dumps ( data ) def blog_feed ( request , section = None ) : try : posts = Post . objects . section ( section ) except InvalidSection : raise Http404 ( ) if section is None : section = ALL_SECTION_NAME current_site = Site . objects . get_current ( ) feed_title = \"\" % ( current_site . name , section [ ] . upper ( ) + section [ : ] ) blog_url = \"\" % ( current_site . domain , reverse ( \"\" ) ) url_name , kwargs = \"\" , { \"\" : section } feed_url = \"\" % ( current_site . domain , reverse ( url_name , kwargs = kwargs ) ) if posts : feed_updated = posts [ ] . published else : feed_updated = datetime ( , , , , , ) hit = FeedHit ( ) hit . request_data = serialize_request ( request ) hit . save ( ) atom = render_to_string ( \"\" , { \"\" : feed_url , \"\" : feed_title , \"\" : blog_url , \"\" : feed_url , \"\" : feed_updated , \"\" : posts , ", "answer": "\"\" : current_site ,"}, {"prompt": " import netaddr import six import webob . exc from nova . api . openstack . compute . schemas import floating_ips_bulk from nova . api . openstack import extensions from nova . api . openstack import wsgi from nova . api import validation import nova . conf from nova import exception from nova . i18n import _ from nova import objects CONF = nova . conf . CONF CONF . import_opt ( '' , '' ) ALIAS = '' authorize = extensions . os_compute_authorizer ( ALIAS ) class FloatingIPBulkController ( wsgi . Controller ) : @ extensions . expected_errors ( ) def index ( self , req ) : \"\"\"\"\"\" context = req . environ [ '' ] authorize ( context ) return self . _get_floating_ip_info ( context ) @ extensions . expected_errors ( ) def show ( self , req , id ) : \"\"\"\"\"\" context = req . environ [ '' ] authorize ( context ) return self . _get_floating_ip_info ( context , id ) def _get_floating_ip_info ( self , context , host = None ) : ", "answer": "floating_ip_info = { \"\" : [ ] }"}, {"prompt": " from __future__ import absolute_import , print_function \"\"\"\"\"\" from cryptography . fernet import Fernet from nsot . util . commands import NsotCommand ", "answer": "class Command ( NsotCommand ) :"}, {"prompt": " PANEL = '' ", "answer": "PANEL_DASHBOARD = ''"}, {"prompt": " from __future__ import division from vistrails . db . domain import DBWorkflow , DBAdd , DBDelete , DBAction , DBAbstraction , DBModule , DBConnection , DBPort , DBFunction , DBParameter , DBGroup from vistrails . db . services . action_chain import getActionChain , getCurrentOperationDict , getCurrentOperations , simplify_ops from vistrails . db import VistrailsDBException import copy import datetime import getpass import unittest import vistrails . core . system from itertools import chain def update_id_scope ( vistrail ) : if hasattr ( vistrail , '' ) : vistrail . update_id_scope ( ) else : for action in vistrail . db_actions : vistrail . idScope . updateBeginId ( '' , action . db_id + ) if action . db_session is not None : vistrail . idScope . updateBeginId ( '' , action . db_session + ) for operation in action . db_operations : vistrail . idScope . updateBeginId ( '' , operation . db_id + ) if operation . vtType == '' or operation . vtType == '' : vistrail . idScope . updateBeginId ( operation . db_what , getNewObjId ( operation ) + ) if operation . db_data is None : if operation . vtType == '' : operation . db_objectId = operation . db_oldObjId vistrail . db_add_object ( operation . db_data ) for annotation in action . db_annotations : vistrail . idScope . updateBeginId ( '' , annotation . db_id + ) def materializeWorkflow ( vistrail , version ) : if vistrail . db_has_action_with_id ( version ) : workflow = DBWorkflow ( ) performActions ( getActionChain ( vistrail , version ) , workflow ) workflow . db_id = version workflow . db_vistrailId = vistrail . db_id return workflow elif version == : return DBWorkflow ( ) else : raise VistrailsDBException ( \"\" % version ) def performAction ( action , workflow ) : if action . actionType == '' : for operation in action . db_operations : workflow . db_add_object ( operation . db_data , operation . db_parentObjType , operation . db_parentObjId ) elif action . actionType == '' : for operation in action . db_operations : workflow . db_change_object ( operation . db_data , operation . db_parentObjType , operation . db_parentObjId ) elif action . actionType == '' : for operation in action . operations : workflow . db_delete_object ( operation . db_objectId , operation . db_what , operation . db_parentObjType , operation . db_parentObjId ) else : msg = \"\" % action . db_actionType raise TypeError ( msg ) def performDeletes ( deleteOps , workflow ) : for operation in deleteOps : workflow . db_delete_object ( getOldObjId ( operation ) , operation . db_what , operation . db_parentObjType , operation . db_parentObjId ) def performAdds ( addOps , workflow ) : for operation in addOps : workflow . db_add_object ( operation . db_data , operation . db_parentObjType , operation . db_parentObjId ) def performActions ( actions , workflow ) : performAdds ( getCurrentOperations ( actions ) , workflow ) def synchronize ( old_vistrail , new_vistrail , current_action_id ) : id_remap = { } for action in new_vistrail . db_actions : if action . is_new : new_action = action . do_copy ( True , old_vistrail . idScope , id_remap ) old_vistrail . db_add_action ( new_action ) else : old_action = old_vistrail . db_actions_id_index [ action . db_id ] for annotation in action . db_deleted_annotations : if old_action . db_has_annotation_with_id ( annotation . db_id ) : old_action . db_delete_annotation ( annotation ) else : if old_action . db_has_annotation_with_key ( '' ) : old_annotation = old_action . db_get_annotation_by_key ( '' ) old_action . db_delete_annotation ( old_annotation ) else : pass for annotation in action . db_annotations : if annotation . is_new : new_annotation = annotation . do_copy ( True , old_vistrail . idScope , id_remap ) old_action . db_add_annotation ( new_annotation ) for tag in new_vistrail . db_deleted_tags : if old_vistrail . db_has_tag_with_id ( tag . db_id ) : old_vistrail . db_delete_tag ( tag ) else : pass for tag in new_vistrail . db_tags : if tag . is_new : new_tag = tag . do_copy ( False ) try : new_tag . db_id = id_remap [ ( DBAction . vtType , new_tag . db_id ) ] except KeyError : pass try : old_tag = old_vistrail . db_tags_name_index [ new_tag . db_name ] except KeyError : old_vistrail . db_delete_tag ( old_tag ) try : old_tag = old_vistrail . db_tags_id_index [ new_tag . db_id ] except KeyError : old_vistrail . db_delete_tag ( old_tag ) old_vistrail . db_add_tag ( new_tag ) new_action_id = id_remap . get ( ( DBAction . vtType , current_action_id ) , current_action_id ) old_vistrail . db_currentVersion = new_action_id return new_action_id def merge ( sb , next_sb , app = '' , interactive = False , tmp_dir = '' , next_tmp_dir = '' ) : \"\"\"\"\"\" vt = sb . vistrail next_vt = next_sb . vistrail merge_gui = interactive MergeGUI = merge_gui . MergeGUI if merge_gui else False skip = sb . mashups = list ( next_sb . mashups ) sb . abstractions = list ( next_sb . abstractions ) id_remap = { } checkout_key = \"\" action_key = checkout_key + app annotation_key = action_key + '' action_annotation_key = action_key + '' checkinId = if len ( app ) and next_vt . db_has_annotation_with_key ( action_key ) : co = next_vt . db_get_annotation_by_key ( action_key ) checkinId = int ( co . _db_value ) else : actions = [ ] actionDict = { } for action in vt . db_actions : unique = action . _db_user + str ( action . _db_date ) copy_no = while ( unique + str ( copy_no ) ) in actionDict : copy_no += unique = unique + str ( copy_no ) actions . append ( unique ) actionDict [ unique ] = action actionNexts = [ ] actionDictNext = { } for action in next_vt . db_actions : unique = action . _db_user + str ( action . _db_date ) copy_no = while ( unique + str ( copy_no ) ) in actionDictNext : copy_no += unique = unique + str ( copy_no ) actionNexts . append ( unique ) actionDictNext [ unique ] = action while checkinId < len ( actions ) and checkinId < len ( actionNexts ) and actions [ checkinId ] == actionNexts [ checkinId ] : checkinId += if checkinId > : checkinId = actionDict [ actions [ checkinId - ] ] . db_id deletekeys = [ action_key , annotation_key , action_annotation_key ] for key in deletekeys : while vt . db_has_annotation_with_key ( key ) : a = vt . db_get_annotation_by_key ( key ) vt . db_delete_annotation ( a ) mergeAnnotations = True if len ( app ) and next_vt . db_has_annotation_with_key ( annotation_key ) : co = next_vt . db_get_annotation_by_key ( annotation_key ) old_hash = co . _db_value mergeAnnotations = ( old_hash != vt . hashAnnotations ( ) ) mergeActionAnnotations = True if len ( app ) and next_vt . db_has_annotation_with_key ( action_annotation_key ) : co = next_vt . db_get_annotation_by_key ( action_annotation_key ) old_hash = co . _db_value mergeActionAnnotations = ( old_hash != vt . hashActionAnnotations ( ) ) for action in next_vt . db_actions : if action . _db_id > checkinId : new_action = action . do_copy ( True , vt . idScope , id_remap ) vt . db_add_action ( new_action ) if not mergeAnnotations : for annotation in [ a for a in vt . db_annotations ] : if not next_vt . db_has_annotation_with_id ( annotation . db_id ) : vt . db_delete_annotation ( annotation ) for annotation in next_vt . db_annotations : if not vt . db_has_annotation_with_id ( annotation . db_id ) : new_annotation = annotation . do_copy ( True , vt . idScope , id_remap ) vt . db_add_annotation ( new_annotation ) else : old_annotation = vt . db_get_annotation_by_id ( annotation . db_id ) if old_annotation . db_key != annotation . db_key : old_annotation . db_key = annotation . db_key if old_annotation . db_value != annotation . db_value : old_annotation . db_value = annotation . db_value else : annotations = { } for annotation in vt . db_annotations : if annotation . db_key not in annotations : annotations [ annotation . db_key ] = [ ] if annotation . db_value not in annotations [ annotation . db_key ] : annotations [ annotation . db_key ] . append ( annotation . db_value ) for annotation in next_vt . db_annotations : if annotation . db_key not in annotations or annotation . db_value not in annotations [ annotation . db_key ] : new_annotation = annotation . do_copy ( True , vt . idScope , id_remap ) vt . db_add_annotation ( new_annotation ) if not mergeActionAnnotations : for annotation in [ a for a in vt . db_actionAnnotations ] : if not next_vt . db_has_actionAnnotation_with_id ( annotation . db_id ) : vt . db_delete_actionAnnotation ( annotation ) if annotation . db_key == '' and len ( sb . thumbnails ) > : thumb = '' . join ( sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + annotation . db_value if thumb in sb . thumbnails : sb . thumbnails . remove ( thumb ) for annotation in next_vt . db_actionAnnotations : if not vt . db_has_actionAnnotation_with_id ( annotation . db_id ) : annotation = annotation . do_copy ( True , vt . idScope , id_remap ) vt . db_add_actionAnnotation ( annotation ) if annotation . db_key == '' and len ( next_sb . thumbnails ) > : thumb = '' . join ( next_sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + annotation . db_value if thumb not in sb . thumbnails : sb . thumbnails . append ( thumb ) else : old_annotation = vt . db_get_actionAnnotation_by_id ( annotation . db_id ) if old_annotation . db_value != annotation . db_value : if annotation . db_key == '' and len ( sb . thumbnails ) > : thumb = '' . join ( sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + old_annotation . db_value if thumb in sb . thumbnails : sb . thumbnails . remove ( thumb ) if annotation . db_key == '' and len ( next_sb . thumbnails ) > : thumb = '' . join ( next_sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + annotation . db_value if thumb not in sb . thumbnails : sb . thumbnails . append ( thumb ) old_annotation . db_value = annotation . db_value old_annotation . db_date = annotation . db_date old_annotation . db_user = annotation . db_user else : oas = { } for a in vt . db_actionAnnotations : if not a . db_action_id in oas : oas [ a . db_action_id ] = { } if not a . db_key in oas [ a . db_action_id ] : oas [ a . db_action_id ] [ a . db_key ] = [ ] oas [ a . db_action_id ] [ a . db_key ] . append ( a ) for new_annotation in next_vt . db_actionAnnotations : if new_annotation . db_key == '' : value = int ( new_annotation . db_value ) if ( '' , value ) in id_remap : new_annotation . db_value = str ( id_remap [ ( '' , value ) ] ) annotation = new_annotation . do_copy ( True , vt . idScope , id_remap ) vt . db_add_actionAnnotation ( annotation ) elif new_annotation . db_action_id <= checkinId and new_annotation . db_key in oas [ new_annotation . db_action_id ] : old_action = oas [ new_annotation . db_action_id ] if new_annotation . db_key == '' : old_annotation = old_action [ new_annotation . db_key ] [ ] if old_annotation . db_value != new_annotation . db_value : value = old_annotation . db_value + \"\" + new_annotation . db_value if interactive : if skip == : pass elif skip == : old_annotation . db_value = new_annotation . db_value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user else : v , value = MergeGUI . resolveTags ( old_annotation , new_annotation , value ) if v == merge_gui . CHOICE_OTHER_ALL : skip = elif v == merge_gui . CHOICE_OTHER : pass elif v == merge_gui . CHOICE_RESOLVED : old_annotation . db_value = value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user pass elif v == merge_gui . CHOICE_OWN : old_annotation . db_value = new_annotation . db_value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user elif v == merge_gui . CHOICE_OWN_ALL : old_annotation . db_value = new_annotation . db_value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user skip = else : old_annotation . db_value = value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user elif new_annotation . db_key == '' : old_annotation = old_action [ new_annotation . db_key ] [ ] if new_annotation . db_value != old_annotation . db_value : value = ( \"\" + \"\" + \"\" ) % ( str ( old_annotation . db_date ) , old_annotation . db_user , old_annotation . db_value , str ( new_annotation . db_date ) , new_annotation . db_user , new_annotation . db_value ) if interactive : if skip == : pass elif skip == : old_annotation . db_value = new_annotation . db_value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user else : v , value = MergeGUI . resolveNotes ( old_annotation , new_annotation , value ) if v == merge_gui . CHOICE_OTHER_ALL : skip = elif v == merge_gui . CHOICE_OTHER : pass elif v == merge_gui . CHOICE_RESOLVED : old_annotation . db_value = value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user pass elif v == merge_gui . CHOICE_OWN : old_annotation . db_value = new_annotation . db_value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user elif v == merge_gui . CHOICE_OWN_ALL : old_annotation . db_value = new_annotation . db_value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user skip = else : old_annotation . db_value = value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user elif new_annotation . db_key == '' : old_annotation = old_action [ new_annotation . db_key ] [ ] if new_annotation . db_value != old_annotation . db_value : if interactive : if skip == : pass elif skip == : thumb = '' . join ( sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + old_annotation . db_value if thumb in sb . thumbnails : sb . thumbnails . remove ( thumb ) old_annotation . db_value = new_annotation . db_value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user thumb = '' . join ( next_sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + new_annotation . db_value if thumb not in sb . thumbnails : sb . thumbnails . append ( thumb ) else : v = MergeGUI . resolveThumbs ( old_annotation , new_annotation , tmp_dir , next_tmp_dir ) if v == merge_gui . CHOICE_OTHER_ALL : skip = elif v == merge_gui . CHOICE_OTHER : pass elif v in ( merge_gui . CHOICE_OWN , merge_gui . CHOICE_OWN_ALL ) : thumb = '' . join ( sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + old_annotation . db_value if thumb in sb . thumbnails : sb . thumbnails . remove ( thumb ) old_annotation . db_value = new_annotation . db_value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user thumb = '' . join ( next_sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + new_annotation . db_value if thumb not in sb . thumbnails : sb . thumbnails . append ( thumb ) if v == merge_gui . CHOICE_OWN_ALL : skip = else : thumb = '' . join ( sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + old_annotation . db_value if thumb in sb . thumbnails : sb . thumbnails . remove ( thumb ) old_annotation . db_value = new_annotation . db_value old_annotation . db_date = new_annotation . db_date old_annotation . db_user = new_annotation . db_user thumb = '' . join ( next_sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + new_annotation . db_value if thumb not in sb . thumbnails : sb . thumbnails . append ( thumb ) elif new_annotation . db_key == '' : pass else : values = [ ] for old_annotation in old_action [ new_annotation . db_key ] : values . append ( old_annotation . db_value ) if new_annotation . db_value not in values : annotation = new_annotation . do_copy ( True , vt . idScope , id_remap ) vt . db_add_actionAnnotation ( annotation ) else : annotation = new_annotation . do_copy ( True , vt . idScope , id_remap ) vt . db_add_actionAnnotation ( annotation ) if annotation . db_key == '' : thumb = '' . join ( next_sb . thumbnails [ ] . split ( '' ) [ : - ] ) + '' + annotation . db_value if thumb not in sb . thumbnails : sb . thumbnails . append ( thumb ) if len ( app ) : vt . update_checkout_version ( app ) def find_data ( what , id , op_dict ) : try : return op_dict [ ( what , id ) ] . db_data except KeyError : msg = '' % ( what , id ) raise KeyError ( msg ) def invertOperations ( op_dict , adds , deletes , do_copy = False ) : inverse_ops = [ ] deletes . reverse ( ) for op in deletes : data = find_data ( op . db_what , getOldObjId ( op ) , op_dict ) if do_copy : data = copy . copy ( data ) inv_op = DBAdd ( id = - , what = op . db_what , objectId = getOldObjId ( op ) , parentObjId = op . db_parentObjId , parentObjType = op . db_parentObjType , data = data ) inverse_ops . append ( inv_op ) adds . reverse ( ) for op in adds : inv_op = DBDelete ( id = - , what = op . db_what , objectId = getNewObjId ( op ) , parentObjId = op . db_parentObjId , parentObjType = op . db_parentObjType , ) inverse_ops . append ( inv_op ) return inverse_ops def normalOperations ( adds , deletes , do_copy = False ) : new_ops = [ ] for op in deletes : new_op = DBDelete ( id = - , what = op . db_what , objectId = getOldObjId ( op ) , parentObjId = op . db_parentObjId , parentObjType = op . db_parentObjType , ) new_ops . append ( new_op ) for op in adds : data = op . db_data if do_copy : data = copy . copy ( op . db_data ) new_op = DBAdd ( id = - , what = op . db_what , objectId = getNewObjId ( op ) , parentObjId = op . db_parentObjId , parentObjType = op . db_parentObjType , data = data ) new_ops . append ( new_op ) return new_ops def getPathAsAction ( vistrail , v1 , v2 , do_copy = False ) : sharedRoot = getSharedRoot ( vistrail , [ v1 , v2 ] ) sharedActionChain = getActionChain ( vistrail , sharedRoot ) sharedOperationDict = getCurrentOperationDict ( sharedActionChain ) v1Actions = getActionChain ( vistrail , v1 , sharedRoot ) v2Actions = getActionChain ( vistrail , v2 , sharedRoot ) ( v1AddDict , v1DeleteDict ) = getOperationDiff ( v1Actions , sharedOperationDict ) ( v2AddDict , v2DeleteDict ) = getOperationDiff ( v2Actions , sharedOperationDict ) v1Adds = v1AddDict . values ( ) v1Adds . sort ( key = lambda x : x . db_id ) v1Deletes = v1DeleteDict . values ( ) v1Deletes . sort ( key = lambda x : x . db_id ) v1InverseOps = invertOperations ( sharedOperationDict , v1Adds , v1Deletes , do_copy ) v2Adds = v2AddDict . values ( ) v2Adds . sort ( key = lambda x : x . db_id ) v2Deletes = v2DeleteDict . values ( ) v2Deletes . sort ( key = lambda x : x . db_id ) v2Ops = normalOperations ( v2Adds , v2Deletes , do_copy ) allOps = v1InverseOps + v2Ops simplifiedOps = simplify_ops ( allOps ) return DBAction ( id = - , operations = simplifiedOps , ) def addAndFixActions ( startDict , actions ) : curDict = copy . copy ( startDict ) for action in actions : new_ops = [ ] for op in action . db_operations : if op . vtType == '' : if op . db_parentObjId is None or curDict . has_key ( ( op . db_parentObjType , op . db_parentObjId ) ) : curDict [ ( op . db_what , op . db_objectId ) ] = op new_ops . append ( op ) elif op . vtType == '' : if curDict . has_key ( ( op . db_what , op . db_oldObjId ) ) and ( op . db_parentObjId is None or curDict . has_key ( ( op . db_parentObjType , op . db_parentObjId ) ) ) : del curDict [ ( op . db_what , op . db_oldObjId ) ] curDict [ ( op . db_what , op . db_newObjId ) ] = op new_ops . append ( op ) elif op . vtType == '' : if ( op . db_parentObjId is None or curDict . has_key ( ( op . db_parentObjType , op . db_parentObjId ) ) ) and curDict . has_key ( ( op . db_what , op . db_objectId ) ) : del curDict [ ( op . db_what , op . db_objectId ) ] new_ops . append ( op ) action . db_operations = new_ops return curDict def fixActions ( vistrail , v , actions ) : startingChain = getActionChain ( vistrail , v ) startingDict = getCurrentOperationDict ( startingChain ) addAndFixActions ( startingDict , actions ) def getSharedRoot ( vistrail , versions ) : current = copy . copy ( versions ) while not in current : maxId = max ( current ) if current . count ( maxId ) == len ( current ) : return maxId else : newId = vistrail . db_get_action_by_id ( maxId ) . db_prevId for i , v in enumerate ( current ) : if v == maxId : current [ i ] = newId return def getOperationDiff ( actions , operationDict ) : addDict = { } deleteDict = { } for action in actions : for operation in action . db_operations : if operation . vtType == '' : addDict [ ( operation . db_what , operation . db_objectId ) ] = operation elif operation . vtType == '' : if operationDict . has_key ( ( operation . db_what , operation . db_objectId ) ) : deleteDict [ ( operation . db_what , operation . db_objectId ) ] = operation elif addDict . has_key ( ( operation . db_what , operation . db_objectId ) ) : del addDict [ ( operation . db_what , operation . db_objectId ) ] else : pass elif operation . vtType == '' : if operationDict . has_key ( ( operation . db_what , operation . db_oldObjId ) ) : deleteDict [ ( operation . db_what , operation . db_oldObjId ) ] = operation elif addDict . has_key ( ( operation . db_what , operation . db_oldObjId ) ) : del addDict [ ( operation . db_what , operation . db_oldObjId ) ] addDict [ ( operation . db_what , operation . db_newObjId ) ] = operation else : msg = \"\" % operation . vtType raise TypeError ( msg ) return ( addDict , deleteDict ) def updateOperationDict ( operationDict , deleteOps , addOps ) : for operation in deleteOps : if operationDict . has_key ( ( operation . db_what , getOldObjId ( operation ) ) ) : del operationDict [ ( operation . db_what , getOldObjId ( operation ) ) ] else : msg = \"\" + operation for operation in addOps : operationDict [ ( operation . db_what , getNewObjId ( operation ) ) ] = operation return operationDict def getObjects ( actions ) : objects = { } for action in actions : for operation in action . db_operations : if not objects . has_key ( operation . db_what ) : objects [ operation . db_what ] = [ ] object = copy . copy ( operation . db_data ) objects [ operation . db_what ] . append ( object ) return objects def getVersionDifferences ( vistrail , versions ) : sharedRoot = getSharedRoot ( vistrail , versions ) sharedActionChain = getActionChain ( vistrail , sharedRoot ) sharedOperationDict = getCurrentOperationDict ( sharedActionChain ) vOnlySorted = [ ] for v in versions : vActions = getActionChain ( vistrail , v , sharedRoot ) ( vAddDict , vDeleteDict ) = getOperationDiff ( vActions , sharedOperationDict ) ", "answer": "vOnlyAdds = vAddDict . values ( )"}, {"prompt": " \"\"\"\"\"\" from collections import Iterable from numbers import Integral import string from future . utils import istext , isbytes , PY3 , with_metaclass from future . types import no , issubset from future . types . newobject import newobject _builtin_bytes = bytes if PY3 : unicode = str class BaseNewBytes ( type ) : def __instancecheck__ ( cls , instance ) : if cls == newbytes : return isinstance ( instance , _builtin_bytes ) else : return issubclass ( instance . __class__ , cls ) class newbytes ( with_metaclass ( BaseNewBytes , _builtin_bytes ) ) : \"\"\"\"\"\" def __new__ ( cls , * args , ** kwargs ) : \"\"\"\"\"\" encoding = None errors = None if len ( args ) == : return super ( newbytes , cls ) . __new__ ( cls ) elif len ( args ) >= : args = list ( args ) if len ( args ) == : errors = args . pop ( ) encoding = args . pop ( ) if type ( args [ ] ) == newbytes : return args [ ] elif isinstance ( args [ ] , _builtin_bytes ) : value = args [ ] elif isinstance ( args [ ] , unicode ) : try : if '' in kwargs : assert encoding is None encoding = kwargs [ '' ] if '' in kwargs : assert errors is None errors = kwargs [ '' ] except AssertionError : raise TypeError ( '' ) if encoding is None : raise TypeError ( '' ) newargs = [ encoding ] if errors is not None : newargs . append ( errors ) value = args [ ] . encode ( * newargs ) elif isinstance ( args [ ] , Iterable ) : if len ( args [ ] ) == : value = b'' else : try : values = [ chr ( x ) for x in args [ ] ] value = b'' . join ( values ) except : raise ValueError ( '' ) elif isinstance ( args [ ] , Integral ) : if args [ ] < : raise ValueError ( '' ) value = b'' * args [ ] else : value = args [ ] return super ( newbytes , cls ) . __new__ ( cls , value ) def __repr__ ( self ) : return '' + super ( newbytes , self ) . __repr__ ( ) def __str__ ( self ) : return '' + \"\" . format ( super ( newbytes , self ) . __str__ ( ) ) def __getitem__ ( self , y ) : value = super ( newbytes , self ) . __getitem__ ( y ) if isinstance ( y , Integral ) : return ord ( value ) else : return newbytes ( value ) def __getslice__ ( self , * args ) : return self . __getitem__ ( slice ( * args ) ) def __contains__ ( self , key ) : ", "answer": "if isinstance ( key , int ) :"}, {"prompt": " schools = { \"\" : { \"\" : [ - , ] , \"\" : \"\" ", "answer": "} ,"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( blank = True ) ) , ( '' , self . gf ( '' ) ( default = False ) ) , ( '' , self . gf ( '' ) ( db_index = True , max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( default = '' , unique = True , max_length = , db_index = True ) ) , ( '' , self . gf ( '' ) ( db_index = True , max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( auto_now_add = True , blank = True ) ) , ( '' , self . gf ( '' ) ( auto_now = True , blank = True ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . add_column ( '' , '' , self . gf ( '' ) ( default = True ) , keep_default = False ) def backwards ( self , orm ) : db . delete_table ( '' ) db . delete_column ( '' , '' ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) ", "answer": "} ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " from setuptools import setup , find_packages kwargs = { '' : find_packages ( exclude = [ '' , '' , '' , '' ] ) , '' : True , '' : [ '' , ] , '' : '' , '' : '' , '' : __import__ ( '' ) . get_version ( ) , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : [ '' , '' , '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " from twisted . internet . protocol import DatagramProtocol from twisted . internet import reactor class MulticastPingPong ( DatagramProtocol ) : def startProtocol ( self ) : \"\"\"\"\"\" self . transport . setTTL ( ) ", "answer": "self . transport . joinGroup ( \"\" )"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " import itertools import numpy as np import scipy . linalg as linalg import scipy . sparse as sp from bayespy . utils import misc as utils from . import node as EF from . import CovarianceFunctions as CF class CovarianceMatrix : def cholesky ( self ) : pass def multiply ( A , B ) : return np . multiply ( A , B ) def gp_posterior_moment_function ( m , k , x , y , k_sparse = None , pseudoinputs = None , noise = None ) : mu = m ( x ) [ ] K_noise = None if noise != None : if K_noise is None : K_noise = noise else : K_noise += noise if k_sparse != None : if K_noise is None : K_noise = k_sparse ( x , x ) [ ] else : K_noise += k_sparse ( x , x ) [ ] if pseudoinputs != None : p = pseudoinputs K_pp = k ( p , p ) [ ] K_xp = k ( x , p ) [ ] U = utils . chol ( K_noise ) Lambda = K_pp + np . dot ( K_xp . T , utils . chol_solve ( U , K_xp ) ) U_lambda = utils . chol ( Lambda ) z = utils . chol_solve ( U_lambda , np . dot ( K_xp . T , utils . chol_solve ( U , y - mu ) ) ) U = utils . chol ( K_pp ) x = p else : K = K_noise if K is None : K = k ( x , x ) [ ] else : try : K += k ( x , x ) [ ] except : K = K + k ( x , x ) [ ] N = len ( y ) U = None z = None if N > : U = utils . chol ( K ) z = utils . chol_solve ( U , y - mu ) def get_moments ( h , covariance = , mean = True ) : K_xh = k ( x , h ) [ ] if k_sparse != None : try : K_xh += k_sparse ( x , h ) [ ] except : K_xh = K_xh + k_sparse ( x , h ) [ ] if not sp . issparse ( K_xh ) : K_xh = np . asarray ( K_xh ) if mean : m_h = m ( h ) [ ] if z != None : m_h += K_xh . T . dot ( z ) else : m_h = None if covariance : if covariance == : k_h = k ( h ) [ ] if k_sparse != None : k_h += k_sparse ( h ) [ ] if U != None : if isinstance ( K_xh , np . ndarray ) : k_h -= np . einsum ( '' , K_xh , utils . chol_solve ( U , K_xh ) ) else : k_h -= np . asarray ( K_xh . multiply ( utils . chol_solve ( U , K_xh ) ) ) . sum ( axis = ) if pseudoinputs != None : if isinstance ( K_xh , np . ndarray ) : k_h += np . einsum ( '' , K_xh , utils . chol_solve ( U_lambda , K_xh ) ) else : k_h += np . asarray ( K_xh . multiply ( utils . chol_solve ( U_lambda , K_xh ) ) ) . sum ( axis = ) k_h [ k_h < ] = return ( m_h , k_h ) elif covariance == : K_hh = k ( h , h ) [ ] if k_sparse != None : K_hh += k_sparse ( h ) [ ] if U != None : K_hh -= K_xh . T . dot ( utils . chol_solve ( U , K_xh ) ) if pseudoinputs != None : K_hh += K_xh . T . dot ( utils . chol_solve ( U_lambda , K_xh ) ) return ( m_h , K_hh ) else : return ( m_h , None ) return get_moments class Constant ( EF . Node ) : def __init__ ( self , f , ** kwargs ) : self . f = f EF . Node . __init__ ( self , dims = [ ( np . inf , ) ] , ** kwargs ) def message_to_child ( self , gradient = False ) : def func ( x , gradient = False ) : if gradient : return ( [ self . f ( x ) , None ] , [ ] ) else : return [ self . f ( x ) , None ] return func class Multiple ( EF . Node ) : def __init__ ( self , GPs , ** kwargs ) : EF . NodeVariable . __init__ ( self , * GPs , plates = ( ) , dims = [ ( np . inf , ) , ( np . inf , np . inf ) ] , ** kwargs ) def message_to_parent ( self , index ) : raise Exception ( \"\" ) def message_to_child ( self , gradient = False ) : u = [ parent . message_to_child ( ) for parent in self . parents ] def get_moments ( xh , ** kwargs ) : mh_all = [ ] khh_all = [ ] for i in range ( len ( self . parents ) ) : xi = np . array ( xh [ i ] ) if gradient : ( ( mh , khh ) , dm ) = u [ i ] ( xi , ** kwargs ) else : ( mh , khh ) = u [ i ] ( xi , ** kwargs ) mh_all = np . concatenate ( [ mh_all , mh ] ) if khh != None : print ( khh ) raise Exception ( '' ) if gradient : return ( [ mh_all , khh_all ] , [ ] ) else : return [ mh_all , khh_all ] return get_moments class GaussianProcess ( EF . Node ) : def __init__ ( self , m , k , k_sparse = None , pseudoinputs = None , ** kwargs ) : self . x = np . array ( [ ] ) self . f = np . array ( [ ] ) if pseudoinputs != None : pseudoinputs = EF . NodeConstant ( [ pseudoinputs ] , dims = [ np . shape ( pseudoinputs ) ] ) self . m = None self . k = None if isinstance ( k , list ) and isinstance ( m , list ) : if len ( k ) != len ( m ) : raise Exception ( '' ) k = CF . Multiple ( k ) m = Multiple ( m ) elif isinstance ( k , list ) : D = len ( k ) k = CF . Multiple ( k ) m = Multiple ( D * [ m ] ) elif isinstance ( m , list ) : D = len ( m ) k = CF . Multiple ( D * [ k ] ) m = Multiple ( m ) EF . NodeVariable . __init__ ( self , m , k , k_sparse , pseudoinputs , plates = ( ) , dims = [ ( np . inf , ) , ( np . inf , np . inf ) ] , ** kwargs ) def __call__ ( self , x , covariance = None ) : if not covariance : return self . u ( x , covariance = False ) [ ] elif covariance . lower ( ) == '' : return self . u ( x , covariance = ) elif covariance . lower ( ) == '' : return self . u ( x , covariance = ) else : raise Exception ( \"\" ) def message_to_parent ( self , index ) : ", "answer": "if index == :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations from corehq . form_processor . models import CaseTransaction , XFormInstanceSQL , CommCareCaseIndexSQL , XFormOperationSQL from corehq . sql_db . operations import RawSQLMigration , HqRunSQL migrator = RawSQLMigration ( ( '' , '' , '' ) , { } ) class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ ", "answer": "migrator . get_migration ( '' ) ,"}, {"prompt": " from cerberusclient . common import base from cerberusclient . v1 import base as v1_base class SecurityAlarm ( base . Resource ) : ", "answer": "def __repr__ ( self ) :"}, {"prompt": " from facebookads . adobjects . abstractobject import AbstractObject from facebookads . adobjects . abstractcrudobject import AbstractCrudObject from facebookads . adobjects . objectparser import ObjectParser from facebookads . api import FacebookRequest from facebookads . typechecker import TypeChecker from facebookads . mixins import HasAdLabels \"\"\"\"\"\" class Ad ( AbstractCrudObject , HasAdLabels , ) : def __init__ ( self , fbid = None , parent_id = None , api = None ) : self . _isAd = True super ( Ad , self ) . __init__ ( fbid , parent_id , api ) class Field ( AbstractObject . Field ) : account_id = '' ad_review_feedback = '' adlabels = '' adset = '' adset_id = '' bid_amount = '' bid_info = '' bid_type = '' campaign = '' campaign_id = '' configured_status = '' conversion_specs = '' created_time = '' creative = '' effective_status = '' id = '' last_updated_by_app_id = '' name = '' recommendations = '' status = '' tracking_specs = '' updated_time = '' date_format = '' display_sequence = '' execution_options = '' redownload = '' filename = '' class BidType : cpc = '' cpm = '' multi_premium = '' absolute_ocpm = '' ", "answer": "cpa = ''"}, {"prompt": " from ionyweb . administration . views import IsSuperAdminView from djangorestframework . response import Response , ErrorResponse from djangorestframework import status from django . conf import settings from django . template . loader import render_to_string from django . template import RequestContext from ionyweb . administration . utils import MESSAGES from ionyweb . file_manager . models import File , Directory from ionyweb . file_manager . views import ( render_quota_html , render_directories_list_html , render_files_list_html ) from ionyweb . file_manager . functions import get_path_or_create class FileManagerQuota ( IsSuperAdminView ) : def get ( self , request ) : quota = render_quota_html ( request ) response = Response ( status . HTTP_200_OK , { \"\" : quota } ) return self . render ( response ) class FileManagerPanel ( IsSuperAdminView ) : def get ( self , request ) : directory_list = render_directories_list_html ( request ) files_list = render_files_list_html ( request ) quota = render_quota_html ( request ) selector = False ", "answer": "if '' in request . GET :"}, {"prompt": " from time import * from constants import * def get_filename ( left_bound , right_bound ) : return str ( int ( left_bound ) ) + '' + str ( int ( right_bound ) ) + '' def get_filename_dict ( ID_bounds ) : filename_dict = { } for ( L , R ) in ID_bounds : for i in range ( int ( L ) , int ( R ) + ) : filename_dict [ i ] = get_filename ( L , R ) return filename_dict def get_ID_bounds ( halo_file , max_chunk_sz = None , chunk_dir = '' ) : halos = np . loadtxt ( halo_file ) if not max_chunk_sz : max_chunk_sz = halos [ ] [ N200a ] cur_sum = halos [ ] [ N200a ] left_bound = halos [ ] [ ID ] right_bound = halos [ ] [ ID ] ID_bounds = [ ] for h in halos : cur_id , num_p = h [ ID ] , h [ N200a ] ", "answer": "if cur_sum + num_p > max_chunk_sz :"}, {"prompt": " \"\"\"\"\"\" import copy import logging from pyparsing import alphanums from pyparsing import alphas from pyparsing import Combine from pyparsing import Literal from pyparsing import nums from pyparsing import Optional from pyparsing import Or from pyparsing import Suppress from pyparsing import Word from barf . core . reil . reil import ReilEmptyOperand from barf . core . reil . reil import ReilImmediateOperand from barf . core . reil . reil import ReilInstructionBuilder from barf . core . reil . reil import ReilMnemonic from barf . core . reil . reil import ReilRegisterOperand logger = logging . getLogger ( __name__ ) def parse_operand ( string , location , tokens ) : \"\"\"\"\"\" sizes = { \"\" : , \"\" : , \"\" : , \"\" : , \"\" : , \"\" : , \"\" : , \"\" : , } if \"\" in tokens : imm_str = \"\" . join ( tokens [ \"\" ] ) ", "answer": "base = if imm_str . startswith ( \"\" ) or imm_str . startswith ( \"\" ) else "}, {"prompt": " from __future__ import print_function import os import sys if sys . version_info >= ( , ) : import http . client else : import httplib import mimetypes import zipfile import time from dateutil . tz import * import iron_core try : import json except ImportError : import simplejson as json def file_exists ( file ) : \"\"\"\"\"\" if not os . path . exists ( file ) : return False try : open ( file ) . close ( ) except IOError : return False return True class Task : id = None project = None code_id = None code_history_id = None schedule_id = None status = None code_name = None code_rev = None created_at = None updated_at = None start_time = None end_time = None duration = None timeout = message = None delay = start_at = None end_at = None next_start = None last_run_time = None run_times = None run_count = None run_every = None percent = None payload = None priority = label = None cluster = None scheduled = False repeating = False __json_attrs = [ \"\" ] __rfc3339_attrs = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] __timestamp_attrs = [ \"\" , \"\" ] __schedule_attrs = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] __repeating_attrs = [ \"\" , \"\" , \"\" ] __aliases = { \"\" : \"\" , \"\" : \"\" } __ignore = [ \"\" ] def __str__ ( self ) : if self . id is not None and self . scheduled : return \"\" % self . id elif self . id is not None : return \"\" % self . id else : return \"\" def __repr__ ( self ) : return \"\" % str ( self ) def __set ( self , attr , value ) : if attr in self . __rfc3339_attrs : if sys . version_info >= ( , ) : if isinstance ( value , str ) : value = iron_core . IronClient . fromRfc3339 ( value ) else : if isinstance ( value , basestring ) : value = iron_core . IronClient . fromRfc3339 ( value ) if attr in self . __schedule_attrs : self . scheduled = True if attr in self . __repeating_attrs : self . repeating = True if attr in self . __json_attrs : try : if sys . version_info >= ( , ) : if isinstance ( value , str ) : value = json . loads ( value ) else : if isinstance ( value , basestring ) : value = json . loads ( value ) except : pass setattr ( self , attr , value ) def __init__ ( self , values = None , ** kwargs ) : if values is None : values = { } self . payload = { } attrs = [ x for x in vars ( self . __class__ ) . keys ( ) if not x . startswith ( \"\" ) ] for k in kwargs . keys ( ) : values [ k ] = kwargs [ k ] for prop in values . keys ( ) : if prop in attrs and prop not in self . __ignore : self . __set ( prop , values [ prop ] ) elif prop in self . __aliases : self . __set ( self . __aliases [ prop ] , values [ prop ] ) class CodePackage : id = None project = None name = None runtime = None latest_checksum = None revision = None latest_history_id = None latest_change = None files = None executable = None zip_path = None __rfc3339_attrs = [ \"\" ] __aliases = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } def __str__ ( self ) : if self . name is not None : return \"\" % self . name elif self . id is not None : return \"\" % self . id else : return \"\" def __repr__ ( self ) : return \"\" % str ( self ) def __set ( self , attr , value ) : if attr in self . __rfc3339_attrs : value = iron_core . IronClient . fromRfc3339 ( value ) setattr ( self , attr , value ) def __init__ ( self , values = None , ** kwargs ) : if values is None : values = { } self . files = { } for k in kwargs . keys ( ) : values [ k ] = kwargs [ k ] attrs = [ x for x in vars ( self . __class__ ) . keys ( ) if not x . startswith ( \"\" ) ] for prop in values . keys ( ) : if prop in attrs : self . __set ( prop , values [ prop ] ) elif prop in self . __aliases : self . __set ( self . __aliases [ prop ] , values [ prop ] ) def merge ( self , target , ignoreRootDir = False ) : if os . path . isfile ( target ) : self . files [ os . path . basename ( target ) ] = target elif os . path . isdir ( target ) : for dirname , dirnames , filenames in os . walk ( target ) : for filename in filenames : path = os . path . join ( dirname , filename ) if ignoreRootDir : ziploc = path . lstrip ( target ) . lstrip ( \"\" ) else : ziploc = path self . files [ ziploc ] = path else : raise ValueError ( \"\" % target ) if len ( self . files ) == : for dest , loc in self . files . items ( ) : self . executable = dest def merge_dependency ( self , dep ) : dependency = __import__ ( dep ) location = os . path . dirname ( dependency . __file__ ) sys . stdout . write ( str ( location ) ) parent = location . rstrip ( os . path . basename ( location ) ) sys . stdout . write ( str ( parent ) ) for dirname , dirnames , filenames in os . walk ( location ) : for filename in filenames : path = os . path . join ( dirname , filename ) if path . startswith ( parent ) : newpath = path [ len ( parent ) : ] else : newpath = path ziploc = newpath . lstrip ( \"\" ) self . files [ ziploc ] = path def zip ( self , destination = None , overwrite = True ) : if destination is None : if self . name is not None : destination = \"\" % self . name else : raise ValueError ( \"\" ) if file_exists ( destination ) and not overwrite : raise ValueError ( \"\" % destination ) filelist = self . files . copy ( ) for dest , loc in filelist . items ( ) : if not file_exists ( loc ) : del ( self . files [ dest ] ) if len ( self . files ) > : z = zipfile . ZipFile ( destination , \"\" ) for dest , loc in self . files . items ( ) : z . write ( loc , dest ) z . close ( ) self . zip_path = destination return file_exists ( destination ) class IronWorker : NAME = \"\" VERSION = \"\" isLoaded = False arguments = { '' : None , '' : None , '' : None , '' : None } def __init__ ( self , ** kwargs ) : \"\"\"\"\"\" self . client = iron_core . IronClient ( name = IronWorker . NAME , version = IronWorker . VERSION , product = \"\" , ** kwargs ) def codes ( self ) : packages = [ ] resp = self . client . get ( \"\" ) raw_packages = resp [ \"\" ] [ \"\" ] for package in raw_packages : packages . append ( CodePackage ( package ) ) return packages def code ( self , id ) : if isinstance ( id , CodePackage ) : id = id . id resp = self . client . get ( \"\" % id ) raw_package = resp [ \"\" ] return CodePackage ( raw_package ) def postCode ( self , code , zipFilename = None ) : zip_loc = code . zip_path if zipFilename is not None : zip_loc = zipFilename if zip_loc is None : raise ValueError ( \"\" ) if not file_exists ( zip_loc ) : raise ValueError ( \"\" % zip_loc ) if code . name is None : raise ValueError ( \"\" ) if code . executable is None : raise ValueError ( \"\" ) if code . runtime is None : code . runtime = \"\" file = open ( zip_loc , \"\" ) file_contents = file . read ( ) file . close ( ) data = [ ( \"\" , json . dumps ( { \"\" : code . name , \"\" : code . runtime , \"\" : code . executable } ) ) ] files = [ ( \"\" , zip_loc , file_contents ) ] content_type , body = IronWorker . encode_multipart_formdata ( data , files ) headers = { \"\" : content_type } resp = self . client . post ( url = \"\" , body = body , headers = headers ) return CodePackage ( resp [ \"\" ] ) def upload ( self , target , name = None , executable = None , overwrite = True ) : if isinstance ( target , CodePackage ) : ", "answer": "code = target"}, {"prompt": " from osgeo import ogr ds = ogr . Open ( r'' ) lyr = ds . GetLayerByName ( '' ) lyr . SetAttributeFilter ( \"\" ) row = next ( lyr ) all_areas = row . geometry ( ) . Clone ( ) common_areas = row . geometry ( ) . Clone ( ) for row in lyr : all_areas = all_areas . Union ( row . geometry ( ) ) common_areas = common_areas . Intersection ( row . geometry ( ) ) ", "answer": "percent = common_areas . GetArea ( ) / all_areas . GetArea ( ) * "}, {"prompt": " import json import logging from pygments import highlight from pygments . formatters import Terminal256Formatter from pygments . lexers . data import JsonLexer from datetime import datetime from pytz import utc try : bytes = bytes except : bytes = str str = unicode def utcnow ( ) : return datetime . utcnow ( ) . replace ( microsecond = , tzinfo = utc ) def D_ ( trn ) : if '' in trn : return trn [ '' ] return next ( trn . values ( ) ) def _ ( s ) : return s def L_ ( s ) : return s def annotate ( _obj = None , ** kw ) : def inner ( obj ) : for key in kw : ", "answer": "setattr ( obj , key , kw [ key ] )"}, {"prompt": " from twisted . internet import reactor , protocol class Echo ( protocol . Protocol ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import sys import os import re on_rtd = os . environ . get ( '' , None ) == '' if not on_rtd : import sphinx_rtd_theme html_theme = '' html_theme_path = [ sphinx_rtd_theme . get_html_theme_path ( ) ] extensions = [ '' , '' , '' , '' , ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' release = open ( '' ) . read ( ) . split ( ) [ ] . strip ( ) p = re . compile ( '' , re . IGNORECASE ) vers = p . search ( release ) version = vers . group ( ) exclude_patterns = [ '' ] pygments_style = '' html_favicon = '' html_static_path = [ '' ] htmlhelp_basename = '' latex_elements = { } latex_documents = [ ( '' , '' , u'' , u'' , '' ) , ] man_pages = [ ( '' , '' , u'' , [ u'' ] , ) ] texinfo_documents = [ ( '' , '' , u'' , u'' , '' , '' , ", "answer": "'' ) ,"}, {"prompt": " def bin ( num , sz = ) : b = [ ] while num : rem = int ( num % ) b . append ( rem ) num -= rem num /= ", "answer": "while len ( b ) % sz :"}, {"prompt": " from pandas import DataFrame df = DataFrame ( [ , , , ] , index = [ '' , '' , '' , '' ] , columns = [ '' ] ) df [ '' ] df . ix [ '' ] df . ix [ '' ] ", "answer": "df [ '' ] "}, {"prompt": " \"\"\"\"\"\" import datetime import optparse import sys import traceback import re from pybuilder import __version__ from pybuilder . core import Logger from pybuilder . errors import PyBuilderException from pybuilder . execution import ExecutionManager from pybuilder . reactor import Reactor from pybuilder . scaffolding import start_project , update_project from pybuilder . terminal import ( BOLD , BROWN , RED , GREEN , bold , styled_text , fg , italic , print_text , print_text_line , print_error , print_error_line , draw_line ) from pybuilder . utils import format_timestamp , get_dist_version_string PROPERTY_OVERRIDE_PATTERN = re . compile ( r'' ) class CommandLineUsageException ( PyBuilderException ) : def __init__ ( self , usage , message ) : super ( CommandLineUsageException , self ) . __init__ ( message ) self . usage = usage class StdOutLogger ( Logger ) : def _level_to_string ( self , level ) : if Logger . DEBUG == level : return \"\" if Logger . INFO == level : return \"\" if Logger . WARN == level : return \"\" return \"\" def _do_log ( self , level , message , * arguments ) : formatted_message = self . _format_message ( message , * arguments ) log_level = self . _level_to_string ( level ) print_text_line ( \"\" . format ( log_level , formatted_message ) ) class ColoredStdOutLogger ( StdOutLogger ) : def _level_to_string ( self , level ) : if Logger . DEBUG == level : return italic ( \"\" ) if Logger . INFO == level : return bold ( \"\" ) if Logger . WARN == level : return styled_text ( \"\" , BOLD , fg ( BROWN ) ) return styled_text ( \"\" , BOLD , fg ( RED ) ) def parse_options ( args ) : parser = optparse . OptionParser ( usage = \"\" , version = \"\" + __version__ ) def error ( msg ) : raise CommandLineUsageException ( parser . get_usage ( ) + parser . format_option_help ( ) , msg ) parser . error = error list_tasks_option = parser . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) list_plan_tasks_option = parser . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) start_project_option = parser . add_option ( \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) update_project_option = parser . add_option ( \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) parser . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) project_group = optparse . OptionGroup ( parser , \"\" , \"\" ) project_group . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" , metavar = \"\" , default = \"\" ) project_group . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" , metavar = \"\" , action = \"\" , default = [ ] ) project_group . add_option ( \"\" , action = \"\" , dest = \"\" , default = [ ] , metavar = \"\" , help = \"\" ) project_group . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , default = [ ] , metavar = \"\" , help = \"\" ) project_group . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) project_group . add_option ( \"\" , action = \"\" , dest = \"\" , default = [ ] , metavar = \"\" , help = \"\" \"\" ) parser . add_option_group ( project_group ) output_group = optparse . OptionGroup ( parser , \"\" , \"\" ) output_group . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) output_group . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) output_group . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) output_group . add_option ( \"\" , \"\" , action = \"\" , dest = \"\" , default = False , help = \"\" ) parser . add_option_group ( output_group ) options , arguments = parser . parse_args ( args = list ( args ) ) if options . list_tasks and options . list_plan_tasks : parser . error ( \"\" % ( list_tasks_option , list_plan_tasks_option ) ) if options . start_project and options . update_project : parser . error ( \"\" % ( start_project_option , update_project_option ) ) property_overrides = { } for pair in options . property_overrides : if not PROPERTY_OVERRIDE_PATTERN . match ( pair ) : parser . error ( \"\" % pair ) key , val = pair . split ( \"\" ) property_overrides [ key ] = val options . property_overrides = property_overrides if options . very_quiet : options . quiet = True return options , arguments def init_reactor ( logger ) : execution_manager = ExecutionManager ( logger ) reactor = Reactor ( logger , execution_manager ) return reactor def should_colorize ( options ) : return sys . stdout . isatty ( ) and not options . no_color def init_logger ( options ) : threshold = Logger . INFO if options . debug : threshold = Logger . DEBUG elif options . quiet : threshold = Logger . WARN if not should_colorize ( options ) : logger = StdOutLogger ( threshold ) else : logger = ColoredStdOutLogger ( threshold ) return logger def print_build_summary ( options , summary ) : print_text_line ( \"\" ) print_text_line ( \"\" % ( \"\" , summary . project . name ) ) print_text_line ( \"\" % ( \"\" , summary . project . version , get_dist_version_string ( summary . project ) ) ) print_text_line ( \"\" % ( \"\" , summary . project . basedir ) ) print_text_line ( \"\" % ( \"\" , \"\" . join ( options . environments ) ) ) task_summary = \"\" for task in summary . task_summaries : task_summary += \"\" % ( task . task , task . execution_time ) print_text_line ( \"\" % ( \"\" , task_summary ) ) def print_styled_text ( text , options , * style_attributes ) : if should_colorize ( options ) : text = styled_text ( text , * style_attributes ) print_text ( text ) def print_styled_text_line ( text , options , * style_attributes ) : print_styled_text ( text + \"\" , options , * style_attributes ) def print_build_status ( failure_message , options , successful ) : draw_line ( ) if successful : print_styled_text_line ( \"\" , options , BOLD , fg ( GREEN ) ) else : print_styled_text_line ( \"\" . format ( failure_message ) , options , BOLD , fg ( RED ) ) draw_line ( ) def print_elapsed_time_summary ( start , end ) : time_needed = end - start millis = ( ( time_needed . days * * * ) + time_needed . seconds ) * + time_needed . microseconds / print_text_line ( \"\" % format_timestamp ( end ) ) print_text_line ( \"\" % ( time_needed . seconds , millis ) ) def print_summary ( successful , summary , start , end , options , failure_message ) : print_build_status ( failure_message , options , successful ) if successful and summary : print_build_summary ( options , summary ) print_elapsed_time_summary ( start , end ) def length_of_longest_string ( list_of_strings ) : if len ( list_of_strings ) == : return result = for string in list_of_strings : length_of_string = len ( string ) if length_of_string > result : result = length_of_string return result def task_description ( task ) : return \"\" . join ( task . description ) or \"\" def print_task_list ( tasks , quiet = False ) : if quiet : print_text_line ( \"\" . join ( [ task . name + \"\" + task_description ( task ) for task in tasks ] ) ) return column_length = length_of_longest_string ( list ( map ( lambda task : task . name , tasks ) ) ) column_length += for task in tasks : task_name = task . name . rjust ( column_length ) print_text_line ( \"\" . format ( task_name , task_description ( task ) ) ) if task . dependencies : whitespace = ( column_length + ) * \"\" depends_on_message = \"\" % \"\" . join ( [ str ( dependency ) for dependency in task . dependencies ] ) print_text_line ( whitespace + depends_on_message ) def print_list_of_tasks ( reactor , quiet = False ) : tasks = reactor . get_tasks ( ) sorted_tasks = sorted ( tasks ) if not quiet : print_text_line ( '' % reactor . project . name ) print_task_list ( sorted_tasks , quiet ) def print_plan_list_of_tasks ( options , arguments , reactor , quiet = False ) : execution_plan = reactor . create_execution_plan ( arguments , options . environments ) if not quiet : print_text_line ( '' % reactor . project . name ) print_task_list ( execution_plan , quiet ) def main ( * args ) : if not args : args = sys . argv [ : ] try : options , arguments = parse_options ( args ) except CommandLineUsageException as e : print_error_line ( \"\" % e ) print_error ( e . usage ) return start = datetime . datetime . now ( ) ", "answer": "logger = init_logger ( options )"}, {"prompt": " from command import Command , AggregatedCommand , CommandException from utils . git_utils import get_repo , check_repo_is_clean from git import GitCommandError import feature def _pop ( ) : repo = get_repo ( ) check_repo_is_clean ( repo ) if repo . git . stash ( '' ) == '' : ", "answer": "raise CommandException ( '' )"}, {"prompt": " \"\"\"\"\"\" import memoized import requests from jut import defaults from jut . exceptions import JutException @ memoized . memoized def get_details ( app_url = defaults . APP_URL ) : \"\"\"\"\"\" url = '' % app_url response = requests . get ( url ) if response . status_code == : return response . json ( ) else : raise JutException ( '' % ( url , response . status_code , response . text ) ) ", "answer": "def get_auth_url ( app_url = defaults . APP_URL ) :"}, {"prompt": " \"\"\"\"\"\" import argparse import logging from collections import namedtuple from . import placeholder logger = logging . getLogger ( ) ShortenerSettings = namedtuple ( '' , [ '' , '' ] ) Settings = namedtuple ( '' , [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) def default_settings ( ) : return Settings ( verbose = False , strict = True , force = False , source = '' , destination = '' , templates = '' , images = '' , right_to_left = [ '' , '' ] , pattern = '' , shortener = { } , exclusive = None , default_locale = '' , workers_pool = , ", "answer": "local_images = '' ,"}, {"prompt": " from novaclient import extension from novaclient . tests . unit import utils from novaclient . tests . unit . v2 import fakes from novaclient . v2 . contrib import list_extensions class ListExtensionsTests ( utils . TestCase ) : def setUp ( self ) : super ( ListExtensionsTests , self ) . setUp ( ) extensions = [ extension . Extension ( list_extensions . __name__ . split ( \"\" ) [ - ] , list_extensions ) , ] self . cs = fakes . FakeClient ( extensions = extensions ) def test_list_extensions ( self ) : all_exts = self . cs . list_extensions . show_all ( ) self . assert_request_id ( all_exts , fakes . FAKE_REQUEST_ID_LIST ) self . cs . assert_called ( '' , '' ) ", "answer": "self . assertTrue ( len ( all_exts ) > )"}, {"prompt": " \"\"\"\"\"\" from django . core . management . base import BaseCommand , CommandError from optparse import make_option from datetime import datetime from django . conf import settings import os import sys import time try : from django . contrib . staticfiles . handlers import StaticFilesHandler USE_STATICFILES = '' in settings . INSTALLED_APPS except ImportError , e : USE_STATICFILES = False try : any except NameError : def any ( iterable ) : for element in iterable : if element : return True return False def label ( code ) : if isinstance ( code , str ) : return ( '' , , code ) else : return '' % ( code . co_name , code . co_filename , code . co_firstlineno ) class KCacheGrind ( object ) : def __init__ ( self , profiler ) : self . data = profiler . getstats ( ) self . out_file = None def output ( self , out_file ) : self . out_file = out_file print >> out_file , '' self . _print_summary ( ) for entry in self . data : self . _entry ( entry ) def _print_summary ( self ) : max_cost = for entry in self . data : totaltime = int ( entry . totaltime * ) max_cost = max ( max_cost , totaltime ) print >> self . out_file , '' % ( max_cost , ) def _entry ( self , entry ) : out_file = self . out_file code = entry . code if isinstance ( code , str ) : print >> out_file , '' else : print >> out_file , '' % ( code . co_filename , ) print >> out_file , '' % ( label ( code ) , ) inlinetime = int ( entry . inlinetime * ) if isinstance ( code , str ) : print >> out_file , '' , inlinetime else : ", "answer": "print >> out_file , '' % ( code . co_firstlineno , inlinetime )"}, {"prompt": " from __future__ import division from vistrails . db . domain import DBPluginData import unittest import copy import random from vistrails . db . domain import IdScope import vistrails . core class PluginData ( DBPluginData ) : def __init__ ( self , * args , ** kwargs ) : DBPluginData . __init__ ( self , * args , ** kwargs ) if self . id is None : self . id = - def __copy__ ( self ) : return PluginData . do_copy ( self ) def do_copy ( self , new_ids = False , id_scope = None , id_remap = None ) : cp = DBPluginData . do_copy ( self , new_ids , id_scope , id_remap ) cp . __class__ = PluginData return cp @ staticmethod def convert ( _plugin_data ) : _plugin_data . __class__ = PluginData id = DBPluginData . db_id data = DBPluginData . db_data def __eq__ ( self , other ) : ", "answer": "if type ( other ) != type ( self ) :"}, {"prompt": " \"\"\"\"\"\" import itertools as it import logging import homeassistant . core as ha from homeassistant . helpers . entity import split_entity_id from homeassistant . helpers . service import extract_entity_ids from homeassistant . loader import get_component from homeassistant . const import ( ATTR_ENTITY_ID , SERVICE_TURN_ON , SERVICE_TURN_OFF , SERVICE_TOGGLE ) _LOGGER = logging . getLogger ( __name__ ) def is_on ( hass , entity_id = None ) : \"\"\"\"\"\" if entity_id : group = get_component ( '' ) entity_ids = group . expand_entity_ids ( hass , [ entity_id ] ) else : entity_ids = hass . states . entity_ids ( ) for entity_id in entity_ids : domain = split_entity_id ( entity_id ) [ ] module = get_component ( domain ) try : if module . is_on ( hass , entity_id ) : return True except AttributeError : _LOGGER . exception ( \"\" , module , entity_id ) return False def turn_on ( hass , entity_id = None , ** service_data ) : \"\"\"\"\"\" if entity_id is not None : service_data [ ATTR_ENTITY_ID ] = entity_id hass . services . call ( ha . DOMAIN , SERVICE_TURN_ON , service_data ) def turn_off ( hass , entity_id = None , ** service_data ) : \"\"\"\"\"\" if entity_id is not None : service_data [ ATTR_ENTITY_ID ] = entity_id hass . services . call ( ha . DOMAIN , SERVICE_TURN_OFF , service_data ) def toggle ( hass , entity_id = None , ** service_data ) : \"\"\"\"\"\" if entity_id is not None : service_data [ ATTR_ENTITY_ID ] = entity_id hass . services . call ( ha . DOMAIN , SERVICE_TOGGLE , service_data ) def setup ( hass , config ) : \"\"\"\"\"\" def handle_turn_service ( service ) : \"\"\"\"\"\" ", "answer": "entity_ids = extract_entity_ids ( hass , service )"}, {"prompt": " \"\"\"\"\"\" import numpy as np import matplotlib . pyplot as plt from shapely . geometry import Point from geopandas import GeoSeries , GeoDataFrame np . random . seed ( ) DPI = boros = GeoDataFrame . from_file ( '' ) boros . set_index ( '' , inplace = True ) boros . sort ( ) boros . plot ( ) plt . xticks ( rotation = ) plt . savefig ( '' , dpi = DPI , bbox_inches = '' ) boros . geometry . convex_hull . plot ( ) plt . xticks ( rotation = ) plt . savefig ( '' , dpi = DPI , bbox_inches = '' ) N = R = xmin , xmax = plt . gca ( ) . get_xlim ( ) ymin , ymax = plt . gca ( ) . get_ylim ( ) xc = ( xmax - xmin ) * np . random . random ( N ) + xmin ", "answer": "yc = ( ymax - ymin ) * np . random . random ( N ) + ymin"}, {"prompt": " try : import pkg_resources pkg_resources . declare_namespace ( __name__ ) ", "answer": "except ImportError :"}, {"prompt": " \"\"\"\"\"\" import select import socket import sys import time import os from errno import EALREADY , EINPROGRESS , EWOULDBLOCK , ECONNRESET , ENOTCONN , ESHUTDOWN , EINTR , EISCONN , EBADF , ECONNABORTED , errorcode try : socket_map except NameError : socket_map = { } def _strerror ( err ) : res = os . strerror ( err ) if res == '' : res = errorcode [ err ] ", "answer": "return res"}, {"prompt": " import cStringIO ", "answer": "output = cStringIO . StringIO ( )"}, {"prompt": " from setuptools import setup from data import __version__ version_str = \"\" . join ( str ( n ) for n in __version__ ) setup ( name = \"\" , version = version_str , license = \"\" , description = \"\" , author = \"\" , author_email = \"\" , url = \"\" , packages = [ \"\" , \"\" , ] , package_data = { \"\" : [ \"\" , ] , } , zip_safe = False , install_requires = [ \"\" , \"\" , ] , classifiers = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ", "answer": "] ,"}, {"prompt": " \"\"\"\"\"\" from contextlib import contextmanager import abc import threading import traceback import warnings import pytest from injector import ( Binder , CallError , Injector , Scope , InstanceProvider , ClassProvider , inject , singleton , threadlocal , UnsatisfiedRequirement , CircularDependency , Module , provides , Key , SingletonScope , ScopeDecorator , with_injector , AssistedBuilder , BindingKey , SequenceKey , MappingKey , ProviderOf , ) def prepare_basic_injection ( ) : class B ( object ) : pass class A ( object ) : @ inject ( b = B ) def __init__ ( self , b ) : \"\"\"\"\"\" self . b = b return A , B def prepare_nested_injectors ( ) : def configure ( binder ) : binder . bind ( str , to = '' ) parent = Injector ( configure ) child = parent . create_child_injector ( ) return parent , child def check_exception_contains_stuff ( exception , stuff ) : stringified = str ( exception ) for thing in stuff : assert thing in stringified , ( '' % ( thing , stringified ) ) def test_child_injector_inherits_parent_bindings ( ) : parent , child = prepare_nested_injectors ( ) assert ( child . get ( str ) == parent . get ( str ) ) def test_child_injector_overrides_parent_bindings ( ) : parent , child = prepare_nested_injectors ( ) child . binder . bind ( str , to = '' ) assert ( ( parent . get ( str ) , child . get ( str ) ) == ( '' , '' ) ) def test_child_injector_rebinds_arguments_for_parent_scope ( ) : I = Key ( \"\" ) Cls = Key ( \"\" ) class A ( object ) : @ inject ( val = I ) def __init__ ( self , val ) : self . val = val def configure_parent ( binder ) : binder . bind ( Cls , to = A ) binder . bind ( I , to = \"\" ) def configure_child ( binder ) : binder . bind ( I , to = \"\" ) parent = Injector ( configure_parent ) assert ( parent . get ( Cls ) . val == \"\" ) child = parent . create_child_injector ( configure_child ) assert ( child . get ( Cls ) . val == \"\" ) def test_scopes_are_only_bound_to_root_injector ( ) : parent , child = prepare_nested_injectors ( ) class A ( object ) : pass parent . binder . bind ( A , to = A , scope = singleton ) assert ( parent . get ( A ) is child . get ( A ) ) def test_key_cannot_be_instantiated ( ) : Interface = Key ( '' ) with pytest . raises ( Exception ) : Interface ( ) with pytest . raises ( Exception ) : Injector ( ) . get ( Interface ) def test_get_default_injected_instances ( ) : A , B = prepare_basic_injection ( ) def configure ( binder ) : binder . bind ( A ) binder . bind ( B ) injector = Injector ( configure ) assert ( injector . get ( Injector ) is injector ) assert ( injector . get ( Binder ) is injector . binder ) def test_instantiate_injected_method ( ) : A , _ = prepare_basic_injection ( ) a = A ( '' ) assert ( a . b == '' ) def test_method_decorator_is_wrapped ( ) : A , _ = prepare_basic_injection ( ) assert ( A . __init__ . __doc__ == '' ) assert ( A . __init__ . __name__ == '' ) def test_decorator_works_for_function_with_no_args ( ) : @ inject ( s = str ) def wrapped ( * args , ** kwargs ) : pass def test_providers_arent_called_for_dependencies_that_are_already_provided ( ) : def configure ( binder ) : binder . bind ( int , to = lambda : / ) class A ( object ) : @ inject ( i = int ) def __init__ ( self , i ) : pass injector = Injector ( configure ) builder = injector . get ( AssistedBuilder ( A ) ) with pytest . raises ( ZeroDivisionError ) : builder . build ( ) builder . build ( i = ) def test_inject_direct ( ) : A , B = prepare_basic_injection ( ) def configure ( binder ) : binder . bind ( A ) binder . bind ( B ) injector = Injector ( configure ) a = injector . get ( A ) assert ( isinstance ( a , A ) ) assert ( isinstance ( a . b , B ) ) def test_configure_multiple_modules ( ) : A , B = prepare_basic_injection ( ) def configure_a ( binder ) : binder . bind ( A ) def configure_b ( binder ) : binder . bind ( B ) injector = Injector ( [ configure_a , configure_b ] ) a = injector . get ( A ) assert ( isinstance ( a , A ) ) assert ( isinstance ( a . b , B ) ) def test_inject_with_missing_dependency ( ) : A , _ = prepare_basic_injection ( ) def configure ( binder ) : binder . bind ( A ) injector = Injector ( configure , auto_bind = False ) with pytest . raises ( UnsatisfiedRequirement ) : injector . get ( A ) def test_inject_named_interface ( ) : class B ( object ) : pass class A ( object ) : @ inject ( b = B ) def __init__ ( self , b ) : self . b = b def configure ( binder ) : binder . bind ( A ) binder . bind ( B ) injector = Injector ( configure ) a = injector . get ( A ) assert ( isinstance ( a , A ) ) assert ( isinstance ( a . b , B ) ) def prepare_transitive_injection ( ) : class C ( object ) : pass class B ( object ) : @ inject ( c = C ) def __init__ ( self , c ) : self . c = c class A ( object ) : @ inject ( b = B ) def __init__ ( self , b ) : self . b = b return A , B , C def test_transitive_injection ( ) : A , B , C = prepare_transitive_injection ( ) def configure ( binder ) : binder . bind ( A ) binder . bind ( B ) binder . bind ( C ) injector = Injector ( configure ) a = injector . get ( A ) assert ( isinstance ( a , A ) ) assert ( isinstance ( a . b , B ) ) assert ( isinstance ( a . b . c , C ) ) def test_transitive_injection_with_missing_dependency ( ) : A , B , _ = prepare_transitive_injection ( ) def configure ( binder ) : binder . bind ( A ) binder . bind ( B ) injector = Injector ( configure , auto_bind = False ) with pytest . raises ( UnsatisfiedRequirement ) : injector . get ( A ) with pytest . raises ( UnsatisfiedRequirement ) : injector . get ( B ) def test_inject_singleton ( ) : class B ( object ) : pass class A ( object ) : @ inject ( b = B ) def __init__ ( self , b ) : self . b = b def configure ( binder ) : binder . bind ( A ) binder . bind ( B , scope = SingletonScope ) injector1 = Injector ( configure ) a1 = injector1 . get ( A ) a2 = injector1 . get ( A ) assert ( a1 . b is a2 . b ) def test_inject_decorated_singleton_class ( ) : @ singleton class B ( object ) : pass class A ( object ) : @ inject ( b = B ) def __init__ ( self , b ) : self . b = b def configure ( binder ) : binder . bind ( A ) binder . bind ( B ) injector1 = Injector ( configure ) a1 = injector1 . get ( A ) a2 = injector1 . get ( A ) assert ( a1 . b is a2 . b ) def test_threadlocal ( ) : @ threadlocal class A ( object ) : def __init__ ( self ) : pass def configure ( binder ) : binder . bind ( A ) injector = Injector ( configure ) a1 = injector . get ( A ) a2 = injector . get ( A ) assert ( a1 is a2 ) a3 = [ None ] ready = threading . Event ( ) def inject_a3 ( ) : a3 [ ] = injector . get ( A ) ready . set ( ) threading . Thread ( target = inject_a3 ) . start ( ) ready . wait ( ) assert ( a2 is not a3 [ ] and a3 [ ] is not None ) def test_injecting_interface_implementation ( ) : class Interface ( object ) : pass class Implementation ( object ) : pass class A ( object ) : @ inject ( i = Interface ) def __init__ ( self , i ) : self . i = i def configure ( binder ) : binder . bind ( A ) binder . bind ( Interface , to = Implementation ) injector = Injector ( configure ) a = injector . get ( A ) assert ( isinstance ( a . i , Implementation ) ) def test_cyclic_dependencies ( ) : class Interface ( object ) : pass class A ( object ) : @ inject ( i = Interface ) def __init__ ( self , i ) : self . i = i class B ( object ) : @ inject ( a = A ) def __init__ ( self , a ) : self . a = a def configure ( binder ) : binder . bind ( Interface , to = B ) binder . bind ( A ) injector = Injector ( configure ) with pytest . raises ( CircularDependency ) : injector . get ( A ) def test_avoid_circular_dependency_with_method_injection ( ) : class Interface ( object ) : pass class A ( object ) : @ inject ( i = Interface ) def __init__ ( self , i ) : self . i = i class B ( object ) : @ inject ( a = A ) def method ( self , a ) : self . a = a def configure ( binder ) : binder . bind ( Interface , to = B ) binder . bind ( A ) binder . bind ( B ) injector = Injector ( configure ) a = injector . get ( A ) assert ( isinstance ( a . i , B ) ) b = injector . get ( B ) b . method ( ) assert ( isinstance ( b . a , A ) ) def test_that_injection_is_lazy ( ) : class Interface ( object ) : constructed = False def __init__ ( self ) : Interface . constructed = True class A ( object ) : @ inject ( i = Interface ) def __init__ ( self , i ) : self . i = i def configure ( binder ) : binder . bind ( Interface ) binder . bind ( A ) injector = Injector ( configure ) assert not ( Interface . constructed ) injector . get ( A ) assert ( Interface . constructed ) def test_module_provides ( ) : class MyModule ( Module ) : @ provides ( str ) def provide_name ( self ) : return '' module = MyModule ( ) injector = Injector ( module ) assert injector . get ( str ) == '' def test_module_class_gets_instantiated ( ) : name = '' class MyModule ( Module ) : def configure ( self , binder ) : binder . bind ( str , to = name ) injector = Injector ( MyModule ) assert ( injector . get ( str ) == name ) def test_with_injector_works ( ) : name = '' def configure ( binder ) : binder . bind ( str , to = name ) class Aaa ( object ) : @ with_injector ( configure ) @ inject ( username = str ) def __init__ ( self , username ) : self . username = username aaa = Aaa ( ) assert ( aaa . username == name ) def test_bind_using_key ( ) : Name = Key ( '' ) Age = Key ( '' ) class MyModule ( Module ) : @ provides ( Name ) def provides_name ( self ) : return '' def configure ( self , binder ) : binder . bind ( Age , to = ) injector = Injector ( MyModule ( ) ) assert ( injector . get ( Age ) == ) assert ( injector . get ( Name ) == '' ) def test_inject_using_key ( ) : Name = Key ( '' ) Description = Key ( '' ) class MyModule ( Module ) : @ provides ( Name ) def provide_name ( self ) : return '' @ provides ( Description ) @ inject ( name = Name ) def provide_description ( self , name ) : return '' % name assert ( Injector ( MyModule ( ) ) . get ( Description ) == '' ) def test_inject_and_provide_coexist_happily ( ) : class MyModule ( Module ) : @ provides ( float ) def provide_weight ( self ) : return @ provides ( int ) def provide_age ( self ) : return @ provides ( str ) @ inject ( age = int , weight = float ) def provide_description ( self , age , weight ) : return '' % ( age , weight ) assert ( Injector ( MyModule ( ) ) . get ( str ) == '' ) def test_multibind ( ) : Names = Key ( '' ) def configure_one ( binder ) : binder . multibind ( Names , to = [ '' ] ) def configure_two ( binder ) : binder . multibind ( Names , to = [ '' ] ) assert ( Injector ( [ configure_one , configure_two ] ) . get ( Names ) == [ '' , '' ] ) def test_provides_sequence_decorator ( ) : Names = SequenceKey ( '' ) class MyModule ( Module ) : @ provides ( Names ) def bob ( self ) : return [ '' ] @ provides ( Names ) def tom ( self ) : return [ '' ] assert ( Injector ( MyModule ( ) ) . get ( Names ) == [ '' , '' ] ) def test_auto_bind ( ) : class A ( object ) : pass injector = Injector ( ) assert ( isinstance ( injector . get ( A ) , A ) ) def test_custom_scope ( ) : class RequestScope ( Scope ) : def configure ( self ) : self . context = None @ contextmanager def __call__ ( self , request ) : assert self . context is None self . context = { } binder = self . injector . get ( Binder ) binder . bind ( Request , to = request , scope = RequestScope ) yield self . context = None def get ( self , key , provider ) : if self . context is None : raise UnsatisfiedRequirement ( None , key ) try : return self . context [ key ] except KeyError : provider = InstanceProvider ( provider . get ( self . injector ) ) self . context [ key ] = provider return provider request = ScopeDecorator ( RequestScope ) class Request ( object ) : pass @ request class Handler ( object ) : def __init__ ( self , request ) : self . request = request class RequestModule ( Module ) : def configure ( self , binder ) : binder . bind_scope ( RequestScope ) @ provides ( Handler ) @ inject ( request = Request ) def handler ( self , request ) : return Handler ( request ) injector = Injector ( [ RequestModule ( ) ] , auto_bind = False ) with pytest . raises ( UnsatisfiedRequirement ) : injector . get ( Handler ) scope = injector . get ( RequestScope ) request = Request ( ) with scope ( request ) : handler = injector . get ( Handler ) assert ( handler . request is request ) with pytest . raises ( UnsatisfiedRequirement ) : injector . get ( Handler ) def test_bind_interface_of_list_of_types ( ) : def configure ( binder ) : binder . multibind ( [ int ] , to = [ , , ] ) binder . multibind ( [ int ] , to = [ , , ] ) injector = Injector ( configure ) assert ( injector . get ( [ int ] ) == [ , , , , , ] ) def test_provides_mapping ( ) : StrInt = MappingKey ( '' ) def configure ( binder ) : binder . multibind ( StrInt , to = { '' : } ) binder . multibind ( StrInt , to = { '' : } ) class MyModule ( Module ) : @ provides ( StrInt ) def provide_numbers ( self ) : return { '' : } @ provides ( StrInt ) def provide_more_numbers ( self ) : return { '' : } injector = Injector ( [ configure , MyModule ( ) ] ) assert ( injector . get ( StrInt ) == { '' : , '' : , '' : , '' : } ) def test_binder_install ( ) : class ModuleA ( Module ) : def configure ( self , binder ) : binder . bind ( str , to = '' ) class ModuleB ( Module ) : def configure ( self , binder ) : binder . install ( ModuleA ( ) ) injector = Injector ( [ ModuleB ( ) ] ) assert ( injector . get ( str ) == '' ) def test_binder_provider_for_method_with_explicit_provider ( ) : injector = Injector ( ) binder = injector . binder provider = binder . provider_for ( int , to = InstanceProvider ( ) ) assert ( type ( provider ) is InstanceProvider ) assert ( provider . get ( injector ) == ) def test_binder_provider_for_method_with_instance ( ) : injector = Injector ( ) binder = injector . binder provider = binder . provider_for ( int , to = ) assert ( type ( provider ) is InstanceProvider ) assert ( provider . get ( injector ) == ) def test_binder_provider_for_method_with_class ( ) : injector = Injector ( ) binder = injector . binder provider = binder . provider_for ( int ) assert ( type ( provider ) is ClassProvider ) assert ( provider . get ( injector ) == ) def test_binder_provider_for_method_with_class_to_specific_subclass ( ) : class A ( object ) : pass class B ( A ) : pass injector = Injector ( ) binder = injector . binder provider = binder . provider_for ( A , B ) assert ( type ( provider ) is ClassProvider ) assert ( isinstance ( provider . get ( injector ) , B ) ) def test_binder_provider_for_type_with_metaclass ( ) : A = abc . ABCMeta ( '' , ( object , ) , { } ) injector = Injector ( ) binder = injector . binder assert ( isinstance ( binder . provider_for ( A , None ) . get ( injector ) , A ) ) def test_injecting_undecorated_class_with_missing_dependencies_raises_the_right_error ( ) : class ClassA ( object ) : def __init__ ( self , parameter ) : pass class ClassB ( object ) : @ inject ( a = ClassA ) def __init__ ( self , a ) : pass injector = Injector ( ) try : injector . get ( ClassB ) except CallError as ce : check_exception_contains_stuff ( ce , ( '' , '' ) ) def test_call_to_method_with_legitimate_call_error_raises_type_error ( ) : class A ( object ) : def __init__ ( self ) : max ( ) injector = Injector ( ) with pytest . raises ( TypeError ) : injector . get ( A ) def test_call_to_method_containing_noninjectable_and_unsatisfied_dependencies_raises_the_right_error ( ) : class A ( object ) : @ inject ( something = str ) def fun ( self , something , something_different ) : pass injector = Injector ( ) a = injector . get ( A ) try : a . fun ( ) except CallError as ce : assert ( ce . args [ ] == a ) function = A . fun try : function = function . __func__ except AttributeError : pass assert ( ce . args [ ] . __name__ == function . __name__ ) assert ( ce . args [ ] == ( ) ) assert ( ce . args [ ] == { '' : str ( ) } ) def test_call_error_is_raised_with_correct_traceback ( ) : class A ( object ) : @ inject ( x = str ) def fun_a ( self , x = '' ) : raise TypeError ( '' ) class B ( object ) : @ inject ( a = A ) def fun_b ( self , a ) : a . fun_a ( ) injector = Injector ( ) b = injector . get ( B ) try : b . fun_b ( ) except : tb = traceback . format_exc ( ) assert '' in tb def test_call_error_str_representation_handles_single_arg ( ) : ce = CallError ( '' ) assert str ( ce ) == '' class NeedsAssistance ( object ) : @ inject ( a = str ) def __init__ ( self , a , b ) : self . a = a self . b = b def test_assisted_builder_works_when_got_directly_from_injector ( ) : injector = Injector ( ) builder = injector . get ( AssistedBuilder ( NeedsAssistance ) ) obj = builder . build ( b = ) assert ( ( obj . a , obj . b ) == ( str ( ) , ) ) def test_assisted_builder_works_when_injected ( ) : class X ( object ) : @ inject ( builder = AssistedBuilder ( NeedsAssistance ) ) def __init__ ( self , builder ) : self . obj = builder . build ( b = ) injector = Injector ( ) x = injector . get ( X ) assert ( ( x . obj . a , x . obj . b ) == ( str ( ) , ) ) def test_assisted_builder_uses_bindings ( ) : Interface = Key ( '' ) def configure ( binder ) : binder . bind ( Interface , to = NeedsAssistance ) injector = Injector ( configure ) builder = injector . get ( AssistedBuilder ( Interface ) ) x = builder . build ( b = ) assert ( ( type ( x ) , x . b ) == ( NeedsAssistance , ) ) def test_assisted_builder_uses_concrete_class_when_specified ( ) : class X ( object ) : pass def configure ( binder ) : binder . bind ( X , to = lambda : / ) injector = Injector ( configure ) builder = injector . get ( AssistedBuilder ( cls = X ) ) builder . build ( ) def test_assisted_builder_accepts_callables ( ) : injector = Injector ( ) builder = injector . get ( AssistedBuilder ( callable = lambda x : x * ) ) assert builder . build ( x = ) == def test_assisted_builder_injection_is_safe_to_use_with_multiple_injectors ( ) : class X ( object ) : @ inject ( builder = AssistedBuilder ( NeedsAssistance ) ) def y ( self , builder ) : return builder i1 , i2 = Injector ( ) , Injector ( ) b1 = i1 . get ( X ) . y ( ) b2 = i2 . get ( X ) . y ( ) assert ( ( b1 . injector , b2 . injector ) == ( i1 , i2 ) ) def test_assisted_builder_injection_uses_the_same_binding_key_every_time ( ) : gen_key = lambda : BindingKey ( AssistedBuilder ( NeedsAssistance ) ) assert gen_key ( ) == gen_key ( ) class TestThreadSafety ( object ) : def setup ( self ) : self . event = threading . Event ( ) def configure ( binder ) : binder . bind ( str , to = lambda : self . event . wait ( ) and '' ) class XXX ( object ) : @ inject ( s = str ) def __init__ ( self , s ) : pass self . injector = Injector ( configure ) self . cls = XXX def gather_results ( self , count ) : objects = [ ] lock = threading . Lock ( ) def target ( ) : o = self . injector . get ( self . cls ) with lock : objects . append ( o ) threads = [ threading . Thread ( target = target ) for i in range ( count ) ] for t in threads : t . start ( ) self . event . set ( ) for t in threads : t . join ( ) return objects def test_injection_is_thread_safe ( self ) : objects = self . gather_results ( ) assert ( len ( objects ) == ) def test_singleton_scope_is_thread_safe ( self ) : self . injector . binder . bind ( self . cls , scope = singleton ) a , b = self . gather_results ( ) assert ( a is b ) class TestClassInjection ( object ) : def setup ( self ) : ", "answer": "class A ( object ) :"}, {"prompt": " \"\"\"\"\"\" import numpy as np import theano import theano . tensor as T import lasagne as nn import data import load import nn_plankton import dihedral import tmp_dnn import tta batch_size = chunk_size = num_chunks_train = momentum = learning_rate_schedule = { : , : , : , } validate_every = save_every = sdir = \"\" train_pred_file = sdir + \"\" valid_pred_file = sdir + \"\" test_pred_file = sdir + \"\" data_loader = load . PredictionsWithMomentsDataLoader ( train_pred_file = train_pred_file , valid_pred_file = valid_pred_file , test_pred_file = test_pred_file , num_chunks_train = num_chunks_train , chunk_size = chunk_size ) create_train_gen = lambda : data_loader . create_random_gen ( ) create_eval_train_gen = lambda : data_loader . create_fixed_gen ( \"\" ) create_eval_valid_gen = lambda : data_loader . create_fixed_gen ( \"\" ) create_eval_test_gen = lambda : data_loader . create_fixed_gen ( \"\" ) def build_model ( ) : l0 = nn . layers . InputLayer ( ( batch_size , data . num_classes ) ) l0_size = nn . layers . InputLayer ( ( batch_size , ) ) l1_size = nn . layers . DenseLayer ( l0_size , num_units = , W = nn_plankton . Orthogonal ( '' ) , b = nn . init . Constant ( ) ) l2_size = nn . layers . DenseLayer ( l1_size , num_units = , W = nn_plankton . Orthogonal ( '' ) , b = nn . init . Constant ( ) ) l3_size = nn . layers . DenseLayer ( l2_size , num_units = data . num_classes , W = nn_plankton . Orthogonal ( ) , b = nn . init . Constant ( ) , nonlinearity = None ) l1 = nn_plankton . NonlinLayer ( l0 , T . log ) ltot = nn . layers . ElemwiseSumLayer ( [ l1 , l3_size ] ) lout = nn_plankton . NonlinLayer ( ltot , nonlinearity = T . nnet . softmax ) return [ l0 , l0_size ] , lout def build_objective ( l_ins , l_out ) : print \"\" lambda_reg = params = nn . layers . get_all_non_bias_params ( l_out ) ", "answer": "reg_term = sum ( T . sum ( p ** ) for p in params )"}, {"prompt": " from itertools import cycle from streamparse import Spout class WordSpout ( Spout ) : outputs = [ '' ] def initialize ( self , stormconf , context ) : self . words = cycle ( [ '' , '' , '' , '' ] ) ", "answer": "def next_tuple ( self ) :"}, {"prompt": " import os import testtools from neutron . common import utils from neutron . tests import base from neutron . tests . common . exclusive_resources import resource_allocator def safe_remove_file ( file_path ) : try : os . remove ( file_path ) except OSError : pass class TestResourceAllocator ( base . DietTestCase ) : def setUp ( self ) : super ( TestResourceAllocator , self ) . setUp ( ) self . ra = resource_allocator . ResourceAllocator ( utils . get_random_string ( ) , lambda : ) self . addCleanup ( safe_remove_file , self . ra . _state_file_path ) def test_allocate_and_release ( self ) : resource = self . ra . allocate ( ) self . assertEqual ( '' , resource ) with testtools . ExpectedException ( ValueError ) : self . ra . allocate ( ) self . ra . release ( resource ) resource = self . ra . allocate ( ) self . assertEqual ( '' , resource ) def test_file_manipulation ( self ) : self . assertFalse ( os . path . exists ( self . ra . _state_file_path ) ) resource = self . ra . allocate ( ) self . assertTrue ( os . path . exists ( self . ra . _state_file_path ) ) self . ra . release ( resource ) ", "answer": "self . assertFalse ( os . path . exists ( self . ra . _state_file_path ) ) "}, {"prompt": " from novaclient . tests . unit . fixture_data import base class V1 ( base . Fixture ) : base_url = '' def setUp ( self ) : super ( V1 , self ) . setUp ( ) get_os_hypervisors = { '' : [ { '' : , '' : '' } , { '' : , '' : '' } , ] } self . headers = self . json_headers self . requests . register_uri ( '' , self . url ( ) , json = get_os_hypervisors , headers = self . headers ) get_os_hypervisors_detail = { '' : [ { '' : , '' : { '' : , '' : '' , } , '' : , '' : * , '' : , '' : , '' : * , '' : , '' : '' , '' : , '' : '' , '' : * , '' : , '' : , '' : , '' : '' , '' : } , { '' : , '' : { '' : , '' : '' , } , '' : , '' : * , '' : , '' : , '' : * , '' : , '' : '' , '' : , '' : '' , '' : * , '' : , '' : , '' : , '' : '' , '' : } ] } self . requests . register_uri ( '' , self . url ( '' ) , json = get_os_hypervisors_detail , headers = self . headers ) get_os_hypervisors_stats = { '' : { '' : , '' : , '' : * , '' : , '' : , '' : * , '' : , '' : * , '' : , '' : , '' : , '' : , } } self . requests . register_uri ( '' , self . url ( '' ) , json = get_os_hypervisors_stats , headers = self . headers ) get_os_hypervisors_search = { '' : [ { '' : , '' : '' } , { '' : , '' : '' } ] } self . requests . register_uri ( '' , self . url ( '' , '' ) , json = get_os_hypervisors_search , headers = self . headers ) get_hyper_server = { '' : [ { '' : , '' : '' , '' : [ { '' : '' , '' : '' } , { '' : '' , '' : '' } ] } , { '' : , '' : '' , '' : [ { '' : '' , '' : '' } , { '' : '' , '' : '' } ", "answer": "]"}, {"prompt": " \"\"\"\"\"\" class BadSearchSpace ( Exception ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" import logging import socket import sys __license__ = '''''' __version__ = '' DEFAULT_HOST = '' DEFAULT_PORT = DEFAULT_PRIORITY = ** DEFAULT_TTR = class BeanstalkcException ( Exception ) : pass class UnexpectedResponse ( BeanstalkcException ) : pass class CommandFailed ( BeanstalkcException ) : pass class DeadlineSoon ( BeanstalkcException ) : pass class SocketError ( BeanstalkcException ) : @ staticmethod def wrap ( wrapped_function , * args , ** kwargs ) : try : return wrapped_function ( * args , ** kwargs ) except socket . error : err = sys . exc_info ( ) [ ] raise SocketError ( err ) class Connection ( object ) : def __init__ ( self , host = DEFAULT_HOST , port = DEFAULT_PORT , parse_yaml = True , connect_timeout = socket . getdefaulttimeout ( ) ) : if parse_yaml is True : try : parse_yaml = __import__ ( '' ) . load except ImportError : logging . error ( '' ) parse_yaml = False self . _connect_timeout = connect_timeout self . _parse_yaml = parse_yaml or ( lambda x : x ) self . host = host self . port = port self . connect ( ) def __enter__ ( self ) : return self def __exit__ ( self , exc_type , exc_value , traceback ) : self . close ( ) def connect ( self ) : \"\"\"\"\"\" self . _socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) self . _socket . settimeout ( self . _connect_timeout ) SocketError . wrap ( self . _socket . connect , ( self . host , self . port ) ) self . _socket . settimeout ( None ) self . _socket_file = self . _socket . makefile ( '' ) def close ( self ) : \"\"\"\"\"\" try : self . _socket . sendall ( '' ) except socket . error : pass try : self . _socket . close ( ) except socket . error : pass def reconnect ( self ) : \"\"\"\"\"\" self . close ( ) self . connect ( ) def _interact ( self , command , expected_ok , expected_err = [ ] ) : ", "answer": "SocketError . wrap ( self . _socket . sendall , command )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " \"\"\"\"\"\" import sys , xmlrpclib , urlparse from twisted . web import resource , server , http from twisted . internet import defer , protocol , reactor from twisted . python import log , reflect , failure NOT_FOUND = FAILURE = Fault = xmlrpclib . Fault Binary = xmlrpclib . Binary Boolean = xmlrpclib . Boolean DateTime = xmlrpclib . DateTime if sys . version_info [ : ] < ( , ) : _decode = DateTime . decode DateTime . decode = lambda self , value : _decode ( self , value . encode ( '' ) ) def withRequest ( f ) : \"\"\"\"\"\" f . withRequest = True return f class NoSuchFunction ( Fault ) : \"\"\"\"\"\" class Handler : \"\"\"\"\"\" def __init__ ( self , resource , * args ) : self . resource = resource self . result = defer . Deferred ( ) self . run ( * args ) def run ( self , * args ) : self . result . errback ( NotImplementedError ( \"\" ) ) class XMLRPC ( resource . Resource ) : \"\"\"\"\"\" NOT_FOUND = FAILURE = isLeaf = separator = '' allowedMethods = ( '' , ) def __init__ ( self , allowNone = False , useDateTime = False ) : resource . Resource . __init__ ( self ) self . subHandlers = { } self . allowNone = allowNone self . useDateTime = useDateTime def __setattr__ ( self , name , value ) : if name == \"\" and value and sys . version_info [ : ] < ( , ) : raise RuntimeError ( \"\" ) self . __dict__ [ name ] = value def putSubHandler ( self , prefix , handler ) : self . subHandlers [ prefix ] = handler def getSubHandler ( self , prefix ) : return self . subHandlers . get ( prefix , None ) def getSubHandlerPrefixes ( self ) : return self . subHandlers . keys ( ) def render_POST ( self , request ) : request . content . seek ( , ) request . setHeader ( \"\" , \"\" ) try : if self . useDateTime : args , functionPath = xmlrpclib . loads ( request . content . read ( ) , use_datetime = True ) else : args , functionPath = xmlrpclib . loads ( request . content . read ( ) ) except Exception , e : f = Fault ( self . FAILURE , \"\" % ( e , ) ) self . _cbRender ( f , request ) else : try : function = self . lookupProcedure ( functionPath ) except Fault , f : self . _cbRender ( f , request ) else : responseFailed = [ ] request . notifyFinish ( ) . addErrback ( responseFailed . append ) if getattr ( function , '' , False ) : d = defer . maybeDeferred ( function , request , * args ) else : d = defer . maybeDeferred ( function , * args ) d . addErrback ( self . _ebRender ) d . addCallback ( self . _cbRender , request , responseFailed ) return server . NOT_DONE_YET def _cbRender ( self , result , request , responseFailed = None ) : if responseFailed : return if isinstance ( result , Handler ) : result = result . result if not isinstance ( result , Fault ) : result = ( result , ) try : try : content = xmlrpclib . dumps ( result , methodresponse = True , allow_none = self . allowNone ) except Exception , e : f = Fault ( self . FAILURE , \"\" % ( e , ) ) content = xmlrpclib . dumps ( f , methodresponse = True , allow_none = self . allowNone ) request . setHeader ( \"\" , str ( len ( content ) ) ) request . write ( content ) except : log . err ( ) request . finish ( ) def _ebRender ( self , failure ) : if isinstance ( failure . value , Fault ) : return failure . value log . err ( failure ) return Fault ( self . FAILURE , \"\" ) def lookupProcedure ( self , procedurePath ) : \"\"\"\"\"\" if procedurePath . find ( self . separator ) != - : prefix , procedurePath = procedurePath . split ( self . separator , ) handler = self . getSubHandler ( prefix ) if handler is None : raise NoSuchFunction ( self . NOT_FOUND , \"\" % prefix ) return handler . lookupProcedure ( procedurePath ) f = getattr ( self , \"\" % procedurePath , None ) if not f : raise NoSuchFunction ( self . NOT_FOUND , \"\" % procedurePath ) elif not callable ( f ) : raise NoSuchFunction ( self . NOT_FOUND , \"\" % procedurePath ) else : return f def listProcedures ( self ) : \"\"\"\"\"\" return reflect . prefixedMethodNames ( self . __class__ , '' ) class XMLRPCIntrospection ( XMLRPC ) : \"\"\"\"\"\" def __init__ ( self , parent ) : \"\"\"\"\"\" XMLRPC . __init__ ( self ) self . _xmlrpc_parent = parent def xmlrpc_listMethods ( self ) : \"\"\"\"\"\" functions = [ ] todo = [ ( self . _xmlrpc_parent , '' ) ] while todo : obj , prefix = todo . pop ( ) functions . extend ( [ prefix + name for name in obj . listProcedures ( ) ] ) todo . extend ( [ ( obj . getSubHandler ( name ) , prefix + name + obj . separator ) for name in obj . getSubHandlerPrefixes ( ) ] ) return functions xmlrpc_listMethods . signature = [ [ '' ] ] def xmlrpc_methodHelp ( self , method ) : \"\"\"\"\"\" method = self . _xmlrpc_parent . lookupProcedure ( method ) return ( getattr ( method , '' , None ) or getattr ( method , '' , None ) or '' ) xmlrpc_methodHelp . signature = [ [ '' , '' ] ] def xmlrpc_methodSignature ( self , method ) : \"\"\"\"\"\" method = self . _xmlrpc_parent . lookupProcedure ( method ) return getattr ( method , '' , None ) or '' xmlrpc_methodSignature . signature = [ [ '' , '' ] , [ '' , '' ] ] def addIntrospection ( xmlrpc ) : \"\"\"\"\"\" xmlrpc . putSubHandler ( '' , XMLRPCIntrospection ( xmlrpc ) ) class QueryProtocol ( http . HTTPClient ) : def connectionMade ( self ) : self . _response = None self . sendCommand ( '' , self . factory . path ) self . sendHeader ( '' , '' ) self . sendHeader ( '' , self . factory . host ) self . sendHeader ( '' , '' ) self . sendHeader ( '' , str ( len ( self . factory . payload ) ) ) if self . factory . user : auth = '' % ( self . factory . user , self . factory . password ) auth = auth . encode ( '' ) . strip ( ) self . sendHeader ( '' , '' % ( auth , ) ) self . endHeaders ( ) self . transport . write ( self . factory . payload ) def handleStatus ( self , version , status , message ) : if status != '' : self . factory . badStatus ( status , message ) def handleResponse ( self , contents ) : \"\"\"\"\"\" self . transport . loseConnection ( ) ", "answer": "self . _response = contents"}, {"prompt": " import sys import os import json import re import cPickle as pkl from nn . func import * import imageqa_test as it import imageqa_ensemble as ie import requests jsonTrainFilename = '' jsonValidFilename = '' htmlHyperLink = '' cssHyperLink = '' daquarImageFolder = '' def renderLatexAnswerList ( correctAnswer , topAnswers , topAnswerScores ) : result = [ ] for i , answer in enumerate ( topAnswers ) : if answer == correctAnswer : colorStr = '' elif i == : colorStr = '' else : colorStr = '' result . append ( colorStr % ( '' % ( answer , topAnswerScores [ i ] ) ) ) return '' . join ( result ) def renderLatexSingleItem ( questionIndex , question , correctAnswer , pictureFolder = '' , comment = None , topAnswers = None , topAnswerScores = None , modelNames = None ) : result = [ ] imgPath = os . path . join ( pictureFolder , '' % questionIndex ) result . append ( '' ) result . append ( '' % imgPath ) result . append ( '' ) result . append ( '' ) result . append ( '' % ( questionIndex , question ) ) result . append ( '' % correctAnswer ) i = if modelNames is not None and len ( modelNames ) > : for modelAnswer , modelAnswerScore , modelName in zip ( topAnswers , topAnswerScores , modelNames ) : result . append ( '' % modelName ) result . append ( renderLatexAnswerList ( correctAnswer , modelAnswer , modelAnswerScore ) ) if i != len ( modelNames ) - : result . append ( '' ) i += result . append ( '' ) elif topAnswers is not None : result . append ( renderLatexAnswerList ( correctAnswer , topAnswers , topAnswerScores ) ) result . append ( '' ) if comment is not None : result . append ( '' + comment ) result . append ( '' ) return '' . join ( result ) def renderLatexSinglePage ( inputData , targetData , questionIdict , ansIdict , urlDict , outputFolder , pictureFolder = '' , topK = , comments = None , caption = None , modelOutputs = None , ", "answer": "modelNames = None ,"}, {"prompt": " import os import json import base64 from django . db . models import F , Q from xos . config import Config from ec2_observer . syncstep import SyncStep from core . models . instance import Instance ", "answer": "from core . models . slice import SlicePrivilege , SliceDeployments"}, {"prompt": " EXECUTORSERVICE_SHUTDOWN = EXECUTORSERVICE_ISSHUTDOWN = EXECUTORSERVICE_CANCELONPARTITION = ", "answer": "EXECUTORSERVICE_CANCELONADDRESS = "}, {"prompt": " import unittest from rx import Observable from rx . testing import TestScheduler , ReactiveTest , is_prime , MockDisposable from rx . disposables import Disposable , SerialDisposable on_next = ReactiveTest . on_next on_completed = ReactiveTest . on_completed on_error = ReactiveTest . on_error subscribe = ReactiveTest . subscribe subscribed = ReactiveTest . subscribed disposed = ReactiveTest . disposed created = ReactiveTest . created class RxException ( Exception ) : pass def _raise ( ex ) : raise RxException ( ex ) class TestTakeUntil ( unittest . TestCase ) : def test_take_until_preempt_somedata_next ( self ) : scheduler = TestScheduler ( ) l_msgs = [ on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_completed ( ) ] r_msgs = [ on_next ( , ) , on_next ( , ) , on_completed ( ) ] l = scheduler . create_hot_observable ( l_msgs ) r = scheduler . create_hot_observable ( r_msgs ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( on_next ( , ) , on_next ( , ) , on_completed ( ) ) def test_take_until_preempt_somedata_error ( self ) : ex = '' scheduler = TestScheduler ( ) l_msgs = [ on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_completed ( ) ] r_msgs = [ on_next ( , ) , on_error ( , ex ) ] l = scheduler . create_hot_observable ( l_msgs ) r = scheduler . create_hot_observable ( r_msgs ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( on_next ( , ) , on_next ( , ) , on_error ( , ex ) ) def test_take_until_nopreempt_somedata_empty ( self ) : scheduler = TestScheduler ( ) l_msgs = [ on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_completed ( ) ] r_msgs = [ on_next ( , ) , on_completed ( ) ] l = scheduler . create_hot_observable ( l_msgs ) r = scheduler . create_hot_observable ( r_msgs ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_completed ( ) ) def test_take_until_nopreempt_somedata_never ( self ) : scheduler = TestScheduler ( ) l_msgs = [ on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_completed ( ) ] l = scheduler . create_hot_observable ( l_msgs ) r = Observable . never ( ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( on_next ( , ) , on_next ( , ) , on_next ( , ) , on_next ( , ) , on_completed ( ) ) def test_take_until_preempt_never_next ( self ) : scheduler = TestScheduler ( ) r_msgs = [ on_next ( , ) , on_next ( , ) , on_completed ( ) ] l = Observable . never ( ) r = scheduler . create_hot_observable ( r_msgs ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( on_completed ( ) ) def test_take_until_preempt_never_error ( self ) : ex = '' scheduler = TestScheduler ( ) r_msgs = [ on_next ( , ) , on_error ( , ex ) ] l = Observable . never ( ) r = scheduler . create_hot_observable ( r_msgs ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( on_error ( , ex ) ) def test_take_until_nopreempt_never_empty ( self ) : scheduler = TestScheduler ( ) r_msgs = [ on_next ( , ) , on_completed ( ) ] l = Observable . never ( ) r = scheduler . create_hot_observable ( r_msgs ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( ) def test_take_until_nopreempt_never_never ( self ) : scheduler = TestScheduler ( ) l = Observable . never ( ) r = Observable . never ( ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( ) def test_take_until_preempt_beforefirstproduced ( self ) : scheduler = TestScheduler ( ) l_msgs = [ on_next ( , ) , on_next ( , ) , on_completed ( ) ] r_msgs = [ on_next ( , ) , on_next ( , ) , on_completed ( ) ] l = scheduler . create_hot_observable ( l_msgs ) r = scheduler . create_hot_observable ( r_msgs ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( on_completed ( ) ) def test_take_until_preempt_beforefirstproduced_remain_silent_and_proper_disposed ( self ) : scheduler = TestScheduler ( ) l_msgs = [ on_next ( , ) , on_error ( , '' ) , on_completed ( ) ] r_msgs = [ on_next ( , ) , on_next ( , ) , on_completed ( ) ] source_not_disposed = [ False ] def action ( ) : source_not_disposed [ ] = True l = scheduler . create_hot_observable ( l_msgs ) . do_action ( on_next = action ) r = scheduler . create_hot_observable ( r_msgs ) def create ( ) : return l . take_until ( r ) results = scheduler . start ( create ) results . messages . assert_equal ( on_completed ( ) ) assert ( not source_not_disposed [ ] ) def test_take_until_nopreempt_afterlastproduced_proper_disposed_signal ( self ) : scheduler = TestScheduler ( ) l_msgs = [ on_next ( , ) , on_next ( , ) , on_completed ( ) ] r_msgs = [ on_next ( , ) , on_next ( , ) , on_completed ( ) ] signal_not_disposed = [ False ] l = scheduler . create_hot_observable ( l_msgs ) def action ( ) : signal_not_disposed [ ] = True ", "answer": "r = scheduler . create_hot_observable ( r_msgs ) . do_action ( on_next = action )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division , print_function , unicode_literals from math import sqrt from textacy import data def readability_stats ( doc ) : \"\"\"\"\"\" if doc . lang != '' : raise NotImplementedError ( '' ) n_sents = doc . n_sents words = list ( doc . words ( filter_punct = True , filter_stops = False , filter_nums = False ) ) n_words = len ( words ) n_unique_words = len ( { word . lower for word in words } ) n_chars = sum ( len ( word ) for word in words ) hyphenator = data . load_hyphenator ( lang = '' ) syllables_per_word = [ len ( hyphenator . positions ( word . lower_ ) ) + for word in words ] n_syllables = sum ( syllables_per_word ) n_polysyllable_words = sum ( for n in syllables_per_word if n >= ) return { '' : n_sents , '' : n_words , '' : n_unique_words , '' : n_chars , '' : n_syllables , '' : n_polysyllable_words , '' : flesch_kincaid_grade_level ( n_syllables , n_words , n_sents ) , '' : flesch_readability_ease ( n_syllables , n_words , n_sents ) , '' : smog_index ( n_polysyllable_words , n_sents ) , '' : gunning_fog_index ( n_words , n_polysyllable_words , n_sents ) , '' : coleman_liau_index ( n_chars , n_words , n_sents ) , '' : automated_readability_index ( n_chars , n_words , n_sents ) } def flesch_kincaid_grade_level ( n_syllables , n_words , n_sents ) : \"\"\"\"\"\" return * ( n_syllables / n_words ) + * ( n_words / n_sents ) - def flesch_readability_ease ( n_syllables , n_words , n_sents ) : \"\"\"\"\"\" return - * ( n_syllables / n_words ) - * ( n_words / n_sents ) + def smog_index ( n_polysyllable_words , n_sents , verbose = False ) : \"\"\"\"\"\" if verbose and n_sents < : print ( '' ) return * sqrt ( * ( n_polysyllable_words / n_sents ) ) + def gunning_fog_index ( n_words , n_polysyllable_words , n_sents ) : \"\"\"\"\"\" return * ( ( n_words / n_sents ) + * ( n_polysyllable_words / n_words ) ) def coleman_liau_index ( n_chars , n_words , n_sents ) : \"\"\"\"\"\" ", "answer": "return * ( n_chars / n_words ) - * ( n_sents / n_words ) - "}, {"prompt": " from django . conf . urls import url ", "answer": "from . import views as user"}, {"prompt": " __author__ = \"\" __credits__ = \"\" import unittest from nose . plugins . attrib import attr from jnpr . junos import Device from jnpr . junos . utils . util import Util from mock import patch @ attr ( '' ) class TestUtil ( unittest . TestCase ) : @ patch ( '' ) def setUp ( self , mock_connect ) : self . dev = Device ( host = '' , user = '' , password = '' , gather_facts = False ) self . dev . open ( ) self . util = Util ( self . dev ) ", "answer": "def test_repr ( self ) :"}, {"prompt": " from __future__ import print_function ", "answer": "import os"}, {"prompt": " \"\"\"\"\"\" from __future__ import with_statement , print_function import re import os import sys import cgi import netrc import socket import fnmatch import getpass import httplib import urllib2 import urlparse import unittest from contextlib import closing from email import parser as rfc2822_parser try : import dputhelper except ImportError : sys . path . insert ( , \"\" ) import dputhelper CHUNK_SIZE = * def trace ( msg , ** kwargs ) : \"\"\"\"\"\" if trace . debug : print ( \"\" + ( msg % kwargs ) ) trace . debug = False def log ( msg , ** kwargs ) : \"\"\"\"\"\" sys . stdout . flush ( ) sys . stderr . write ( \"\" + ( msg % kwargs ) + \"\" ) sys . stderr . flush ( ) def _resolve_credentials ( fqdn , login ) : \"\"\"\"\"\" result = login if \"\" in result : result = os . path . expandvars ( result ) if result . startswith ( \"\" ) : result = result . split ( '' , ) [ ] if result : result = os . path . abspath ( os . path . expanduser ( result ) ) accounts = netrc . netrc ( result or None ) account = accounts . authenticators ( fqdn ) if not account or not ( account [ ] or account [ ] ) : raise dputhelper . DputUploadFatalException ( \"\" % ( fqdn , result or \"\" ) ) user , pwd = account [ ] or account [ ] , account [ ] or \"\" result = \"\" % ( user , pwd ) else : if result . startswith ( \"\" ) : result = os . path . abspath ( os . path . expanduser ( result . split ( '' , ) [ ] ) ) with closing ( open ( result , \"\" ) ) as handle : result = handle . read ( ) . strip ( ) try : user , pwd = result . split ( '' , ) except ValueError : user , pwd = result , \"\" trace ( \"\" , user = user , pwd = '' * len ( pwd ) ) return result class PromptingPasswordMgr ( urllib2 . HTTPPasswordMgr ) : \"\"\"\"\"\" def __init__ ( self , login ) : urllib2 . HTTPPasswordMgr . __init__ ( self ) self . login = login def find_user_password ( self , realm , authuri ) : \"\"\"\"\"\" authuri = self . reduce_uri ( authuri ) [ ] authinfo = urllib2 . HTTPPasswordMgr . find_user_password ( self , realm , authuri ) if authinfo == ( None , None ) : credentials = self . login if '' in credentials : authinfo = credentials . split ( '' , ) else : password = getpass . getpass ( \"\" % realm ) self . add_password ( realm , authuri , credentials , password ) authinfo = credentials , password return authinfo def _distro2repo ( distro , repo_mappings ) : \"\"\"\"\"\" mappings = [ ( i . split ( '' , ) if '' in i else ( i , i ) ) for i in repo_mappings . split ( ) ] result = distro for pattern , target in mappings : if fnmatch . fnmatchcase ( distro . lower ( ) , pattern . lower ( ) ) : result = target break trace ( \"\" , distro = distro , repo = result ) return result def _resolve_incoming ( fqdn , login , incoming , changes = None , cli_params = None , repo_mappings = \"\" ) : \"\"\"\"\"\" scheme , netloc , path , matrix_params , query , anchor = urlparse . urlparse ( incoming , scheme = \"\" , allow_fragments = True ) if scheme not in ( \"\" , \"\" ) : raise dputhelper . DputUploadFatalException ( \"\" % scheme ) url = urlparse . urlunparse ( ( scheme , netloc or fqdn , path . rstrip ( '' ) + '' , '' , query , None ) ) url_params = dict ( cgi . parse_qsl ( anchor or '' , keep_blank_values = True ) ) pkgdata = { } if changes : try : changes . read except AttributeError : with closing ( open ( changes , \"\" ) ) as handle : changes = handle . read ( ) else : changes = changes . read ( ) if changes . startswith ( \"\" ) : trace ( \"\" ) changes = changes . split ( \"\" ) [ ] . replace ( '' , '' ) . split ( '' , ) [ ] pkgdata = dict ( [ ( key . lower ( ) . replace ( '' , '' ) , val . strip ( ) ) for key , val in rfc2822_parser . HeaderParser ( ) . parsestr ( changes ) . items ( ) ] ) if '' in pkgdata : pkgdata [ '' ] = '' . join ( pkgdata [ '' ] . split ( ) ) pkgdata [ \"\" ] = login . split ( '' ) [ ] if \"\" in pkgdata : pkgdata [ \"\" ] = re . split ( r\"\" , pkgdata [ \"\" ] ) [ ] pkgdata . update ( dict ( fqdn = fqdn , repo = _distro2repo ( pkgdata . get ( \"\" , \"\" ) , repo_mappings ) , ) ) pkgdata . update ( cli_params or { } ) trace ( \"\" , meta = \"\" . join ( [ \"\" % ( key , val ) for key , val in sorted ( pkgdata . items ( ) ) if '' not in val ] ) ) try : try : url . format except AttributeError : url = url % pkgdata matrix_params = matrix_params % pkgdata else : url = url . format ( ** pkgdata ) matrix_params = matrix_params . format ( ** pkgdata ) matrix_params = matrix_params . replace ( '' , '' ) except KeyError , exc : raise dputhelper . DputUploadFatalException ( \"\" % ( exc , incoming ) ) trace ( \"\" , url = url , params = url_params ) return url , matrix_params , url_params def _url_connection ( url , method , skip_host = False , skip_accept_encoding = False ) : \"\"\"\"\"\" scheme , netloc , path , params , query , _ = urlparse . urlparse ( url ) result = conn = ( httplib . HTTPSConnection if scheme == \"\" else httplib . HTTPConnection ) ( netloc ) conn . debuglevel = int ( trace . debug ) try : conn . putrequest ( method , urlparse . urlunparse ( ( None , None , path , params , query , None ) ) , skip_host , skip_accept_encoding ) conn . putheader ( \"\" , \"\" ) conn . putheader ( \"\" , \"\" ) conn = None finally : if conn : ", "answer": "conn . close ( )"}, {"prompt": " from django . db import models class MRREL ( models . Model ) : CUI1 = models . CharField ( max_length = ) REL = models . CharField ( max_length = ) RELA = models . CharField ( max_length = ) CUI2 = models . CharField ( max_length = ) SAB = models . CharField ( max_length = ) ", "answer": "class Meta :"}, {"prompt": " from __future__ import unicode_literals from urllib import unquote_plus from django . shortcuts import get_object_or_404 from . models import DocumentMetadata , MetadataType def decode_metadata_from_url ( url_dict ) : \"\"\"\"\"\" metadata_dict = { '' : { } , '' : { } } metadata_list = [ ] for key , value in url_dict . items ( ) : if '' in key : index , element = key [ : ] . split ( '' ) metadata_dict [ element ] [ index ] = value for order , identifier in metadata_dict [ '' ] . items ( ) : if order in metadata_dict [ '' ] . keys ( ) : metadata_list . append ( { '' : identifier , '' : metadata_dict [ '' ] [ order ] } ) return metadata_list def save_metadata_list ( metadata_list , document , create = False ) : \"\"\"\"\"\" for item in metadata_list : save_metadata ( item , document , create ) def save_metadata ( metadata_dict , document , create = False ) : \"\"\"\"\"\" if create : document_metadata , created = DocumentMetadata . objects . get_or_create ( document = document , metadata_type = get_object_or_404 ( MetadataType , pk = metadata_dict [ '' ] ) ) else : try : document_metadata = DocumentMetadata . objects . get ( document = document , metadata_type = get_object_or_404 ( MetadataType , pk = metadata_dict [ '' ] ) , ) except DocumentMetadata . DoesNotExist : document_metadata = None if document_metadata : document_metadata . value = unquote_plus ( metadata_dict [ '' ] ) document_metadata . save ( ) def metadata_repr ( metadata_list ) : \"\"\"\"\"\" return '' . join ( metadata_repr_as_list ( metadata_list ) ) def metadata_repr_as_list ( metadata_list ) : \"\"\"\"\"\" output = [ ] for metadata_dict in metadata_list : try : output . append ( '' % ( MetadataType . objects . get ( pk = metadata_dict [ '' ] ) , metadata_dict . get ( '' , '' ) ) ) except : pass return output def convert_dict_to_dict_list ( dictionary ) : result = [ ] for key , value in dictionary . items ( ) : try : metadata_type = MetadataType . objects . get ( name = key ) except MetadataType . DoesNotExist : raise ValueError ( '' ) result . append ( { '' : metadata_type . pk , '' : value } ) return result def set_bulk_metadata ( document , metadata_dictionary ) : ", "answer": "document_type = document . document_type"}, {"prompt": " from __future__ import print_function import os import shutil import sys from command import Command , GitcClientCommand import gitc_utils from pyversion import is_python3 if not is_python3 ( ) : input = raw_input class GitcDelete ( Command , GitcClientCommand ) : common = True visible_everywhere = False helpSummary = \"\" helpUsage = \"\"\"\"\"\" helpDescription = \"\"\"\"\"\" def _Options ( self , p ) : p . add_option ( '' , '' , dest = '' , action = '' , help = '' ) def Execute ( self , opt , args ) : if not opt . force : prompt = ( '' % self . gitc_manifest . gitc_client_name ) response = input ( prompt ) . lower ( ) if not response == '' : print ( '' ) ", "answer": "sys . exit ( )"}, {"prompt": " from tests import BaseTest from mock import patch import dns from resolverapi . util . dns_query import parse_query TEST_DOMAIN = '' def make_answer ( rdtype , answers = None , additionals = None , authorities = None ) : \"\"\"\"\"\" answer = dns . resolver . Answer ( dns . name . from_text ( TEST_DOMAIN ) , getattr ( dns . rdatatype , rdtype . upper ( ) ) , dns . rdataclass . IN , dns . message . from_text ( '' ) , raise_on_no_answer = False ) if answers : rrset = dns . rrset . from_text ( TEST_DOMAIN , , '' , rdtype , * answers ) answer . response . answer = [ rrset ] if additionals : rrset = dns . rrset . from_text ( TEST_DOMAIN , , '' , rdtype , * additionals ) answer . response . answer = [ rrset ] if authorities : rrset = dns . rrset . from_text ( TEST_DOMAIN , , '' , rdtype , * authorities ) answer . response . authority = [ rrset ] return answer @ patch ( '' ) class ParseQueryTests ( BaseTest ) : def setUp ( self ) : super ( ParseQueryTests , self ) . setUp ( ) def lookup ( self , rdtype ) : return super ( ParseQueryTests , self ) . get ( '' % ( rdtype , TEST_DOMAIN ) ) def test_a_lookup ( self , query , rdtype = '' ) : rrs = [ '' , '' ] query . return_value = make_answer ( rdtype , answers = rrs ) resp , code = self . lookup ( rdtype ) self . assert200 ( code ) self . assertDictContainsSubset ( { '' : { '' : '' , '' : rdtype , '' : TEST_DOMAIN } , '' : [ { '' : TEST_DOMAIN , '' : , '' : rdtype , '' : '' , '' : '' } , { '' : TEST_DOMAIN , '' : , '' : rdtype , '' : '' , '' : '' } ] } , resp ) def test_aaaa_lookup ( self , query , rdtype = '' ) : rrs = [ '' ] query . return_value = make_answer ( rdtype , answers = rrs ) resp , code = self . lookup ( rdtype ) self . assert200 ( code ) self . assertDictContainsSubset ( { '' : { '' : '' , '' : rdtype , '' : TEST_DOMAIN } , '' : [ { '' : TEST_DOMAIN , '' : , '' : rdtype , '' : '' , '' : '' } ] } , resp ) def test_mx_lookup ( self , query , rdtype = '' ) : rrs = [ '' % TEST_DOMAIN , '' % TEST_DOMAIN ] query . return_value = make_answer ( rdtype , answers = rrs ) resp , code = self . lookup ( rdtype ) self . assert200 ( code ) self . assertDictContainsSubset ( { '' : { '' : '' , '' : rdtype , '' : TEST_DOMAIN } , '' : [ { '' : TEST_DOMAIN , '' : , '' : '' % TEST_DOMAIN , '' : , '' : rdtype , '' : '' } , { '' : TEST_DOMAIN , '' : , '' : '' % TEST_DOMAIN , '' : , '' : rdtype , '' : '' } , ] } , resp ) def test_ns_lookup ( self , query , rdtype = '' ) : rrs = [ '' % TEST_DOMAIN , '' % TEST_DOMAIN ] query . return_value = make_answer ( rdtype , answers = rrs ) resp , code = self . lookup ( rdtype ) self . assert200 ( code ) self . assertDictContainsSubset ( { '' : { '' : '' , '' : rdtype , '' : '' } , '' : [ { '' : '' , '' : '' , '' : TEST_DOMAIN , '' : , '' : rdtype } , { '' : '' , '' : '' , '' : TEST_DOMAIN , '' : , '' : rdtype } ] } , resp ) def test_cname_lookup ( self , query , rdtype = '' ) : \"\"\"\"\"\" rrs = [ '' '' . format ( TEST_DOMAIN ) ] query . return_value = make_answer ( rdtype , authorities = rrs ) resp , code = self . lookup ( '' ) self . assert200 ( code ) self . assertDictContainsSubset ( { '' : { '' : '' , '' : rdtype , '' : '' } , '' : [ ] , '' : [ { '' : '' % TEST_DOMAIN , '' : '' % TEST_DOMAIN , '' : , '' : , '' : , '' : , '' : , '' : '' , '' : rdtype , '' : , '' : TEST_DOMAIN } ] } , resp ) def test_txt_lookup ( self , query , rdtype = '' ) : rrs = [ '' , '' ] query . return_value = make_answer ( rdtype , answers = rrs ) resp , code = self . lookup ( rdtype ) self . assert200 ( code ) self . assertDictContainsSubset ( { '' : { '' : '' , '' : rdtype , '' : '' } , '' : [ { '' : '' , '' : , '' : rdtype , '' : '' , '' : '' } , { '' : '' , '' : , '' : rdtype , '' : '' , '' : '' } ] , } , resp ) def test_ptr_lookup ( self , query , rdtype = \"\" ) : rrs = [ '' ] query . return_value = make_answer ( rdtype , answers = rrs ) resp , code = self . lookup ( rdtype ) self . assert200 ( code ) self . assertDictContainsSubset ( { '' : { '' : '' , '' : rdtype , '' : '' } , '' : [ { '' : '' , '' : , '' : rdtype , ", "answer": "'' : '' , '' : TEST_DOMAIN }"}, {"prompt": " import os from unittest import TestCase class Tester ( TestCase ) : def __init__ ( self , * argv , ** kwargs ) : super ( Tester , self ) . __init__ ( * argv , ** kwargs ) def setUp ( self ) : pass ", "answer": "def tearDown ( self ) :"}, {"prompt": " import sys , os , stat import pythoncom from win32com . shell import shell , shellcon import commctrl import winerror from win32com . server . util import wrap from pywintypes import IID IPersist_Methods = [ \"\" ] IColumnProvider_Methods = IPersist_Methods + [ \"\" , \"\" , \"\" ] class ColumnProvider : _reg_progid_ = \"\" _reg_desc_ = \"\" _reg_clsid_ = IID ( \"\" ) _com_interfaces_ = [ pythoncom . IID_IPersist , shell . IID_IColumnProvider , ] ", "answer": "_public_methods_ = IColumnProvider_Methods"}, {"prompt": " import unittest from collections import namedtuple import os import os . path from pwman import set_xsel from pwman . data import factory from pwman . data . database import __DB_FORMAT__ from pwman import ( get_conf , get_conf_options , get_db_version ) ", "answer": "from . test_tools import SetupTester"}, {"prompt": " from flask_reveal . tools . cli import cli_execute if __name__ == '' : ", "answer": "cli_execute ( ) "}, {"prompt": " \"\"\"\"\"\" __author__ = '' from google . appengine . ext import db from google . appengine . api import memcache class Token ( db . Model ) : \"\"\"\"\"\" t = db . BlobProperty ( ) def get_token ( unique_key ) : \"\"\"\"\"\" token_string = memcache . get ( unique_key ) if token_string is None : ", "answer": "token = Token . get_by_key_name ( unique_key )"}, {"prompt": " from stevedore import extension def _load_error_handler ( * args , ** kwds ) : raise ", "answer": "def load_handlers ( ) :"}, {"prompt": " import sys import os on_rtd = os . environ . get ( '' , None ) == '' if not on_rtd : import sphinx_rtd_theme ", "answer": "html_theme = ''"}, {"prompt": " import unittest from devops . helpers import scancodes class TestScancodes ( unittest . TestCase ) : def test_abc ( self ) : codes = scancodes . from_string ( '' ) self . assertEqual ( [ ( , ) , ( , ) , ( , ) ] , codes ) def test_ABC ( self ) : codes = scancodes . from_string ( '' ) self . assertEqual ( [ ( , ) , ( , ) , ( , ) ] , codes ) def test_specials ( self ) : ", "answer": "codes = scancodes . from_string ( '' )"}, {"prompt": " from __future__ import absolute_import , division , with_statement ", "answer": "from revolver . core import sudo"}, {"prompt": " def blur ( elem ) : JS ( \"\"\"\"\"\" ) def createFocusable ( ) : JS ( \"\"\"\"\"\" ) def focus ( elem ) : JS ( \"\"\"\"\"\" ) def getTabIndex ( elem ) : JS ( \"\"\"\"\"\" ) def setAccessKey ( elem , key ) : JS ( \"\"\"\"\"\" ) ", "answer": "def setTabIndex ( elem , index ) :"}, {"prompt": " import time import io import threading import picamera class Camera ( object ) : thread = None frame = None last_access = def initialize ( self ) : if Camera . thread is None : Camera . thread = threading . Thread ( target = self . _thread ) Camera . thread . start ( ) while self . frame is None : time . sleep ( ) def get_frame ( self ) : Camera . last_access = time . time ( ) self . initialize ( ) return self . frame @ classmethod def _thread ( cls ) : with picamera . PiCamera ( ) as camera : camera . resolution = ( , ) camera . hflip = True camera . vflip = True camera . start_preview ( ) time . sleep ( ) stream = io . BytesIO ( ) for foo in camera . capture_continuous ( stream , '' , ", "answer": "use_video_port = True ) :"}, {"prompt": " \"\"\"\"\"\" import nmrglue . fileio . pipe as pipe import nmrglue . process . pipe_proc as p d , a = pipe . read ( \"\" ) d , a = p . em ( d , a , lb = , c = , start = , size = , one = True ) pipe . write ( \"\" , d , a , overwrite = True ) ", "answer": "d , a = pipe . read ( \"\" )"}, {"prompt": " import dns . rdtypes . mxbase ", "answer": "class MX ( dns . rdtypes . mxbase . MXBase ) :"}, {"prompt": " from __future__ import unicode_literals from django import forms from django . utils . translation import ugettext_lazy as _ from reviewboard . hostingsvcs . forms import HostingServiceForm from reviewboard . hostingsvcs . service import HostingService class SourceForgeForm ( HostingServiceForm ) : sourceforge_project_name = forms . CharField ( label = _ ( '' ) , max_length = , required = True , widget = forms . TextInput ( attrs = { '' : '' } ) ) class SourceForge ( HostingService ) : name = '' form = SourceForgeForm supports_repositories = True supports_bug_trackers = True supported_scmtools = [ '' , '' , '' , '' ] repository_fields = { '' : { '' : '' '' '' , '' : '' '' '' , } , '' : { '' : '' ", "answer": "''"}, {"prompt": " from __future__ import with_statement from django . contrib . auth . models import AnonymousUser , User from django . core import cache from django . test . testcases import TestCase from rulez . exceptions import RulesException from rulez . rolez . base import AbstractRole from rulez . rolez . cache_helper import get_counter , increment_counter , get_roles , get_user_pk , roles_key from rulez . rolez . models import ModelRoleMixin class Mock ( ) : pk = class MockUser ( ) : def __init__ ( self ) : self . pk = def is_anonymous ( self ) : return False class Tester ( AbstractRole ) : @ classmethod def is_member ( cls , user , obj ) : return getattr ( user , '' , False ) class TestModel ( ModelRoleMixin ) : pk = roles = [ Tester ] class RolesCacheHelperTestCase ( TestCase ) : def setUp ( self ) : cache . cache . clear ( ) def test_incrementing_counter_works ( self ) : obj = Mock ( ) first = get_counter ( obj ) self . assertEqual ( first , ) increment_counter ( obj ) second = get_counter ( obj ) self . assertNotEqual ( second , first ) def test_incrementing_counter_works_for_none ( self ) : increment_counter ( None ) def test_get_roles_for_None_raises ( self ) : with self . assertRaises ( AttributeError ) : res = get_counter ( None ) self . assertEqual ( res , None ) def test_rulez_invalidate_works ( self ) : model = TestModel ( ) user = MockUser ( ) first = get_counter ( model ) self . assertEqual ( first , ) model . rulez_invalidate ( ) second = get_counter ( model ) self . assertNotEqual ( second , first ) def test_get_empty_roles_works ( self ) : model = TestModel ( ) user = MockUser ( ) res = get_roles ( user , model ) self . assertEqual ( res , [ ] ) def test_user_with_role_works ( self ) : model = TestModel ( ) user = MockUser ( ) setattr ( user , '' , True ) res = get_roles ( user , model ) self . assertEqual ( len ( res ) , ) def test_get_roles_cache_works ( self ) : model = TestModel ( ) user = MockUser ( ) setattr ( user , '' , True ) res = get_roles ( user , model ) self . assertEqual ( len ( res ) , ) res2 = get_roles ( user , model ) self . assertEqual ( len ( res2 ) , ) self . assertEqual ( res , res2 ) def test_has_role_works ( self ) : model = TestModel ( ) ", "answer": "user = MockUser ( )"}, {"prompt": " \"\"\"\"\"\" from __future__ import division import numpy as np from skimage import img_as_bool def rdp_indexes ( points , eps2 , dist2 = None ) : \"\"\"\"\"\" dist2 = point_line_dist2 if dist2 is not None else point_line_dist2 N = len ( points ) keep = [ , N - ] stack = [ ( , N - ) ] for i in xrange ( N ** ) : if not stack : return sorted ( keep ) i0 , i1 = stack . pop ( ) if i1 <= i0 + : continue d = dist2 ( points [ i0 + : i1 ] , points [ i0 ] , points [ i1 ] ) i = np . argmax ( d ) dmax = d [ i ] i += i0 + if dmax > eps2 : keep . append ( i ) stack += [ ( i0 , i ) , ( i , i1 ) ] assert False def point_line_dist2 ( p , l1 , l2 ) : \"\"\"\"\"\" p , l1 , l2 = np . asarray ( p ) , np . asarray ( l1 ) , np . asarray ( l2 ) ap = l1 - p ", "answer": "n = l2 - l1"}, {"prompt": " \"\"\"\"\"\" import itertools import matplotlib from matplotlib import pyplot as plt from matplotlib import mlab import numpy as np from matplotlib . ticker import MaxNLocator from mpl_toolkits . axes_grid1 import make_axes_locatable from matplotlib import gridspec import colormap_adjust from scipy import stats def ci_plot ( x , arr , conf = , ax = None , line_kwargs = None , fill_kwargs = None ) : \"\"\"\"\"\" if ax is None : fig = plt . figure ( ) ax = fig . add_subplot ( ) line_kwargs = line_kwargs or { } fill_kwargs = fill_kwargs or { } m , lo , hi = ci ( arr , conf ) ax . plot ( x , m , ** line_kwargs ) ax . fill_between ( x , lo , hi , ** fill_kwargs ) return ax def imshow ( arr , x = None , ax = None , vmin = None , vmax = None , percentile = True , strip = False , features = None , conf = , sort_by = None , line_kwargs = None , fill_kwargs = None , imshow_kwargs = None , figsize = ( , ) , width_ratios = ( , ) , height_ratios = ( , ) , subplot_params = dict ( wspace = , hspace = ) , subset_by = None , subset_order = None , ) : \"\"\"\"\"\" if ax is None : fig = new_shell ( figsize = figsize , strip = strip , subplot_params = subplot_params , width_ratios = width_ratios , height_ratios = height_ratios ) if x is None : x = np . arange ( arr . shape [ ] + ) if percentile : if vmin is None : vmin = arr . min ( ) else : vmin = mlab . prctile ( arr . ravel ( ) , vmin ) if vmax is None : vmax = arr . max ( ) else : vmax = mlab . prctile ( arr . ravel ( ) , vmax ) else : if vmin is None : vmin = arr . min ( ) if vmax is None : vmax = arr . max ( ) cmap = colormap_adjust . smart_colormap ( vmin , vmax ) _imshow_kwargs = dict ( origin = '' , cmap = cmap , vmin = vmin , vmax = vmax , aspect = '' ) if imshow_kwargs is not None : _imshow_kwargs . update ( imshow_kwargs ) if sort_by is None : sort_by = np . arange ( arr . shape [ ] ) if ax is None : array_ax = fig . array_axes else : array_ax = ax if subset_by is None : subset_by = np . zeros ( arr . shape [ ] ) if not isinstance ( subset_by , np . ndarray ) : subset_by = np . array ( subset_by ) if subset_order is None : subset_order = sorted ( np . unique ( subset_by ) ) inds = [ ] for cls in subset_order : subset_ind = np . nonzero ( subset_by == cls ) [ ] subset_sort_by = sort_by [ subset_ind ] subset_argsort_by = np . argsort ( subset_sort_by ) inds . append ( subset_ind [ subset_argsort_by ] ) ind = np . concatenate ( inds ) mappable = array_ax . imshow ( arr [ ind , : ] , extent = ( x . min ( ) , x . max ( ) , , arr . shape [ ] ) , ** _imshow_kwargs ) if line_kwargs is None : line_kwargs = { } if fill_kwargs is None : fill_kwargs = { } if isinstance ( line_kwargs , dict ) : line_kwargs = [ line_kwargs ] if isinstance ( fill_kwargs , dict ) : fill_kwargs = [ fill_kwargs ] _line_kwargs = itertools . cycle ( line_kwargs ) _fill_kwargs = itertools . cycle ( fill_kwargs ) if ax is None : plt . colorbar ( mappable , fig . cax ) for subset_ind , label , _lkw , _fkw in zip ( inds , subset_order , _line_kwargs , _fill_kwargs ) : ci_plot ( x , arr [ subset_ind ] , ax = fig . line_axes , line_kwargs = _lkw , fill_kwargs = _fkw , ) return fig else : return ax . figure def add_labels_to_subsets ( ax , subset_by , subset_order , text_kwargs = None , add_hlines = True , hline_kwargs = None ) : \"\"\"\"\"\" _text_kwargs = dict ( transform = ax . get_yaxis_transform ( ) ) if text_kwargs : _text_kwargs . update ( text_kwargs ) _hline_kwargs = dict ( color = '' ) if hline_kwargs : _hline_kwargs . update ( hline_kwargs ) pos = for label in subset_order : ind = subset_by == label last_pos = pos pos += sum ( ind ) if add_hlines : ax . axhline ( pos , ** _hline_kwargs ) ax . text ( , last_pos + ( pos - last_pos ) / , label , ** _text_kwargs ) def calculate_limits ( array_dict , method = '' , percentiles = None , limit = ( ) ) : \"\"\"\"\"\" if percentiles is not None : for percentile in percentiles : if not <= percentile <= : raise ValueError ( \"\" ) if method == '' : all_arrays = np . concatenate ( [ i . ravel ( ) for i in array_dict . itervalues ( ) ] ) if percentiles : vmin = mlab . prctile ( all_arrays , percentiles [ ] ) vmax = mlab . prctile ( all_arrays , percentiles [ ] ) else : vmin = all_arrays . min ( ) vmax = all_arrays . max ( ) d = dict ( [ ( i , ( vmin , vmax ) ) for i in array_dict . keys ( ) ] ) elif method == '' : d = { } for k , v in array_dict . iteritems ( ) : d [ k ] = ( v . min ( ) , v . max ( ) ) elif hasattr ( method , '' ) : d = { } sorted_keys = sorted ( array_dict . keys ( ) , key = method ) for group , keys in itertools . groupby ( sorted_keys , method ) : keys = list ( keys ) all_arrays = np . concatenate ( [ array_dict [ i ] for i in keys ] ) if percentiles : vmin = mlab . prctile ( all_arrays , percentiles [ ] ) vmax = mlab . prctile ( all_arrays , percentiles [ ] ) else : vmin = all_arrays . min ( ) vmax = all_arrays . max ( ) for key in keys : d [ key ] = ( vmin , vmax ) return d def ci ( arr , conf = ) : \"\"\"\"\"\" m = arr . mean ( axis = ) n = len ( arr ) se = arr . std ( axis = ) / np . sqrt ( n ) h = se * stats . t . _ppf ( ( + conf ) / , n - ) return m , m - h , m + h def nice_log ( x ) : \"\"\"\"\"\" neg = x < xi = np . log2 ( np . abs ( x ) + ) xi [ neg ] = - xi [ neg ] return xi def tip_zscores ( a ) : \"\"\"\"\"\" weighted = a * a . mean ( axis = ) scores = weighted . sum ( axis = ) zscores = ( scores - scores . mean ( ) ) / scores . std ( ) return zscores def fdrcorrection ( pvals , alpha = , method = '' ) : '''''' pvals = np . asarray ( pvals ) pvals_sortind = np . argsort ( pvals ) pvals_sorted = pvals [ pvals_sortind ] sortrevind = pvals_sortind . argsort ( ) if method in [ '' , '' , '' , '' ] : ecdffactor = _ecdf ( pvals_sorted ) elif method in [ '' , '' ] : cm = np . sum ( / np . arange ( , len ( pvals_sorted ) + ) ) ecdffactor = _ecdf ( pvals_sorted ) / cm else : raise ValueError ( '' ) reject = pvals_sorted <= ecdffactor * alpha if reject . any ( ) : rejectmax = max ( np . nonzero ( reject ) [ ] ) reject [ : rejectmax ] = True pvals_corrected_raw = pvals_sorted / ecdffactor pvals_corrected = np . minimum . accumulate ( pvals_corrected_raw [ : : - ] ) [ : : - ] pvals_corrected [ pvals_corrected > ] = return reject [ sortrevind ] , pvals_corrected [ sortrevind ] def tip_fdr ( a , alpha = ) : \"\"\"\"\"\" zscores = tip_zscores ( a ) pvals = stats . norm . pdf ( zscores ) rejected , fdrs = fdrcorrection ( pvals ) return fdrs def prepare_logged ( x , y ) : \"\"\"\"\"\" xi = np . log2 ( x ) yi = np . log2 ( y ) xv = np . isfinite ( xi ) yv = np . isfinite ( yi ) global_min = min ( xi [ xv ] . min ( ) , yi [ yv ] . min ( ) ) ", "answer": "global_max = max ( xi [ xv ] . max ( ) , yi [ yv ] . max ( ) )"}, {"prompt": " import HydrusConstants as HC import HydrusData import os import sys import time class HydrusLogger ( object ) : def __init__ ( self , log_filename ) : self . _log_filename = log_filename def __enter__ ( self ) : self . _previous_sys_stdout = sys . stdout self . _previous_sys_stderr = sys . stderr self . _problem_with_previous_stdout = False sys . stdout = self sys . stderr = self self . _log_file = open ( os . path . join ( HC . LOGS_DIR , self . _log_filename ) , '' ) return self def __exit__ ( self , exc_type , exc_val , exc_tb ) : ", "answer": "self . _log_file . close ( )"}, {"prompt": " \"\"\"\"\"\" from pytest import yield_fixture , fixture import numpy as np from numpy . testing import assert_array_equal as ae from vispy . util import keys from . . import gui_component from . . gui_component import ( ManualClustering , ) from phy . io . array import _spikes_in_clusters from phy . gui import GUI from . conftest import MockController @ yield_fixture def gui ( tempdir , qtbot ) : gui_component . _show_box = lambda _ : _ gui = GUI ( position = ( , ) , size = ( , ) , config_dir = tempdir ) gui . show ( ) qtbot . waitForWindowShown ( gui ) yield gui qtbot . wait ( ) gui . close ( ) del gui qtbot . wait ( ) @ fixture def manual_clustering ( qtbot , gui , cluster_ids , cluster_groups , quality , similarity ) : spike_clusters = np . array ( cluster_ids ) spikes_per_cluster = lambda c : [ c ] mc = ManualClustering ( spike_clusters , spikes_per_cluster , cluster_groups = cluster_groups , shortcuts = { '' : '' } , quality = quality , similarity = similarity , ) mc . attach ( gui ) mc . set_default_sort ( quality . __name__ ) return mc def test_manual_clustering_edge_cases ( manual_clustering ) : mc = manual_clustering ae ( mc . clustering . cluster_ids , [ , , , , , , ] ) mc . select ( [ ] ) assert mc . selected == [ ] mc . undo ( ) mc . redo ( ) mc . merge ( ) assert mc . selected == [ ] mc . merge ( [ ] ) assert mc . selected == [ ] mc . merge ( [ ] ) assert mc . selected == [ ] mc . split ( [ ] ) assert mc . selected == [ ] mc . move ( [ ] , '' ) mc . save ( ) def test_manual_clustering_skip ( qtbot , gui , manual_clustering ) : mc = manual_clustering expected = [ , , , , ] for clu in expected : mc . cluster_view . next ( ) assert mc . selected == [ clu ] def test_manual_clustering_merge ( manual_clustering ) : mc = manual_clustering mc . cluster_view . select ( [ ] ) mc . similarity_view . select ( [ ] ) assert mc . selected == [ , ] mc . merge ( ) assert mc . selected == [ , ] mc . undo ( ) assert mc . selected == [ , ] mc . redo ( ) assert mc . selected == [ , ] def test_manual_clustering_split ( manual_clustering ) : mc = manual_clustering mc . select ( [ , ] ) mc . split ( [ , ] ) assert mc . selected == [ ] mc . undo ( ) assert mc . selected == [ , ] mc . redo ( ) assert mc . selected == [ ] def test_manual_clustering_split_2 ( gui , quality , similarity ) : spike_clusters = np . array ( [ , , ] ) mc = ManualClustering ( spike_clusters , lambda c : _spikes_in_clusters ( spike_clusters , [ c ] ) , similarity = similarity , ) mc . attach ( gui ) mc . add_column ( quality , name = '' , default = True ) mc . set_default_sort ( '' , '' ) mc . split ( [ ] ) assert mc . selected == [ , ] def test_manual_clustering_state ( tempdir , qtbot , gui , manual_clustering ) : mc = manual_clustering cv = mc . cluster_view cv . sort_by ( '' ) gui . close ( ) assert cv . state [ '' ] == ( '' , '' ) cv . set_state ( cv . state ) assert cv . state [ '' ] == ( '' , '' ) def test_manual_clustering_split_lasso ( tempdir , qtbot ) : controller = MockController ( config_dir = tempdir ) gui = controller . create_gui ( ) mc = controller . manual_clustering view = gui . list_views ( '' , is_visible = False ) [ ] gui . show ( ) mc . select ( ) ev = view . events ev . mouse_press ( pos = ( , ) , button = , modifiers = ( keys . CONTROL , ) ) ev . mouse_press ( pos = ( , ) , button = , modifiers = ( keys . CONTROL , ) ) ev . mouse_press ( pos = ( , ) , button = , modifiers = ( keys . CONTROL , ) ) ev . mouse_press ( pos = ( , ) , button = , modifiers = ( keys . CONTROL , ) ) ups = [ ] @ mc . clustering . connect def on_cluster ( up ) : ups . append ( up ) mc . split ( ) up = ups [ ] assert up . description == '' assert up . added == [ , ] assert up . deleted == [ ] ", "answer": "gui . close ( )"}, {"prompt": " import testify as T from pushmanager . ui_methods import authorized_to_manage_request from pushmanager . ui_methods import sort_pickmes class UIMethodTest ( T . TestCase ) : def test_authorized_to_manage_request_random_user ( self ) : request = { '' : '' , '' : None } T . assert_equal ( False , authorized_to_manage_request ( None , request , '' ) ) def test_authorized_to_manage_request_request_user ( self ) : request = { '' : '' , '' : None } T . assert_equal ( True , authorized_to_manage_request ( None , request , '' ) ) def test_authorized_to_manage_request_pushmaster ( self ) : request = { '' : '' , '' : None } T . assert_equal ( True , authorized_to_manage_request ( None , request , '' , True ) ) def test_authorized_to_manage_request_watcher ( self ) : request = { '' : '' , '' : '' } T . assert_equal ( True , authorized_to_manage_request ( None , request , '' ) ) def test_sort_pickmes_regular_case ( self ) : requests = [ { '' : '' , '' : '' } , { '' : '' , '' : '' } , { '' : '' , '' : '' } , { '' : '' , '' : '' } , { '' : '' , '' : '' } , { '' : '' , '' : '' } , { '' : '' , '' : '' } , { '' : '' , '' : '' } , ] sorted_requests = sort_pickmes ( None , requests , [ '' , '' , '' ] ) ", "answer": "T . assert_equal ( len ( sorted_requests ) , )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from __future__ import unicode_literals"}, {"prompt": " \"\" from . default import DefaultErrorHandler import re class IronwareErrorHandler ( DefaultErrorHandler ) : _ERROR_MATCHES = [ re . compile ( r'' , flags = re . I ) , re . compile ( r'' , flags = re . I ) , re . compile ( r'' , flags = re . I ) , re . compile ( r'' , flags = re . I ) , re . compile ( r'' , flags = re . I ) , re . compile ( r'' , flags = re . I ) ] def __init__ ( self , personality ) : super ( IronwareErrorHandler , self ) . __init__ ( personality ) def has_error ( self , output ) : if any ( m . search ( output ) for m in self . _ERROR_MATCHES ) : return True ", "answer": "return False "}, {"prompt": " from braintree . configuration import Configuration from braintree . resource import Resource class AccountUpdaterDailyReport ( Resource ) : def __init__ ( self , gateway , attributes ) : Resource . __init__ ( self , gateway , attributes ) if \"\" in attributes : self . report_url = attributes . pop ( \"\" ) if \"\" in attributes : self . report_date = attributes . pop ( \"\" ) def __repr__ ( self ) : detail_list = [ \"\" , \"\" ] ", "answer": "return super ( AccountUpdaterDailyReport , self ) . __repr__ ( detail_list ) "}, {"prompt": " import os import logging ONLINE_TIME = if os . environ . get ( \"\" ) : MAX_PING = int ( os . environ . get ( \"\" ) ) else : MAX_PING = if os . environ . get ( \"\" ) : SQLALCHEMY_DATABASE_URI = os . environ . get ( \"\" ) else : SQLALCHEMY_DATABASE_URI = \"\" ", "answer": "DATA_DIR = ''"}, {"prompt": " import os from setuptools import setup , find_packages install_requires = [ '' ] README_PATH = os . path . join ( os . path . abspath ( os . path . dirname ( __file__ ) ) , '' ) description = '' ", "answer": "long_description = open ( README_PATH , '' ) . read ( )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " from PyQt4 import QtGui , QtCore import sys from threading import Thread from LLAMA import Ui_Lake_Level_UI from plot_water_levelui import * from lake_measure import * class ProgressPopup ( QtGui . QWidget ) : update_signal = QtCore . pyqtSignal ( int , int , str , str , int , int ) def __init__ ( self , cancel_function ) : QtGui . QWidget . __init__ ( self ) self . update_signal . connect ( self . apply_update , QtCore . Qt . QueuedConnection ) self . cancel_function = cancel_function self . lake_totals = None self . lake_counts = None ", "answer": "self . progressBar = QtGui . QProgressBar ( self )"}, {"prompt": " import re import sublime from sublime_plugin import WindowCommand from . . git_command import GitCommand from ... common import util NEW_BRANCH_PROMPT = \"\" class GsCheckoutBranchCommand ( WindowCommand , GitCommand ) : \"\"\"\"\"\" def run ( self ) : sublime . set_timeout_async ( self . run_async , ) def run_async ( self ) : stdout = self . git ( \"\" , \"\" ) branch_entries = ( branch . strip ( ) for branch in stdout . split ( \"\" ) if branch ) self . local_inactive_branches = [ branch for branch in branch_entries if not branch [ ] == \"\" ] if not self . local_inactive_branches : self . window . show_quick_panel ( [ \"\" ] , None ) else : self . window . show_quick_panel ( self . local_inactive_branches , self . on_selection , flags = sublime . MONOSPACE_FONT ) def on_selection ( self , branch_name_index ) : if branch_name_index == - : return branch_name = self . local_inactive_branches [ branch_name_index ] self . git ( \"\" , branch_name ) sublime . status_message ( \"\" . format ( branch_name ) ) util . view . refresh_gitsavvy ( self . window . active_view ( ) ) class GsCheckoutNewBranchCommand ( WindowCommand , GitCommand ) : \"\"\"\"\"\" def run ( self ) : sublime . set_timeout_async ( self . run_async ) def run_async ( self , name = \"\" ) : self . window . show_input_panel ( NEW_BRANCH_PROMPT , name , self . on_done , None , None ) def on_done ( self , branch_name ) : pattern = r\"\" match = re . match ( pattern , branch_name ) if not match : sublime . error_message ( \"\" . format ( branch_name ) ) sublime . set_timeout_async ( self . run_async ( branch_name ) ) return None self . git ( \"\" , \"\" , branch_name ) sublime . status_message ( \"\" . format ( branch_name ) ) util . view . refresh_gitsavvy ( self . window . active_view ( ) ) class GsCheckoutRemoteBranchCommand ( WindowCommand , GitCommand ) : \"\"\"\"\"\" def run ( self ) : sublime . set_timeout_async ( self . run_async ) ", "answer": "def run_async ( self ) :"}, {"prompt": " \"\"\"\"\"\" __version__ = \"\" def data_files ( ) : \"\"\"\"\"\" from . gui . utilities import data_files return data_files ( ) ", "answer": "def package_data ( ) :"}, {"prompt": " from __future__ import absolute_import from django . contrib . auth import authenticate , login from django . contrib . auth . models import User from django . contrib . auth . tokens import default_token_generator from django . contrib . sites . models import Site from django . core import exceptions from django . core . urlresolvers import reverse from django . db . models import Q from django . utils . translation import ugettext_lazy as _ from django . utils . translation import pgettext , ugettext from horizon import forms , messages from leonardo . forms import SelfHandlingForm , Layout , InlineCheckboxes from horizon . utils import validators class LoginForm ( SelfHandlingForm ) : username = forms . CharField ( label = _ ( \"\" ) , max_length = , widget = forms . TextInput ( attrs = { '' : _ ( '' ) , '' : '' } ) ) password = forms . CharField ( label = _ ( \"\" ) , widget = forms . PasswordInput ( render_value = False ) ) remember = forms . BooleanField ( label = _ ( \"\" ) , required = False ) def __init__ ( self , * args , ** kwargs ) : super ( LoginForm , self ) . __init__ ( * args , ** kwargs ) ", "answer": "self . helper . layout = Layout ("}, {"prompt": " import unittest import test . test_support class SubclassInstanceTest ( unittest . TestCase ) : def test_subclass_int ( self ) : try : ", "answer": "class foo ( ) : pass"}, {"prompt": " from extensions . interactions import base class EndExploration ( base . BaseInteraction ) : \"\"\"\"\"\" name = '' description = ( ", "answer": "''"}, {"prompt": " from . observer import Observer import json ", "answer": "import time"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " from __future__ import absolute_import from __future__ import unicode_literals import collections import contextlib import io import os . path import sqlite3 import subprocess import pytest import six from git_code_debt . create_tables import create_schema from git_code_debt . create_tables import populate_metric_ids from git_code_debt . repo_parser import Commit from git_code_debt . repo_parser import COMMIT_FORMAT from git_code_debt . util . subprocess import cmd_output from testing . utilities . auto_namedtuple import auto_namedtuple from testing . utilities . cwd import cwd @ pytest . yield_fixture def tempdir_factory ( tmpdir ) : class TmpdirFactory ( object ) : def __init__ ( self ) : self . tmpdir_count = def get ( self ) : path = tmpdir . join ( six . text_type ( self . tmpdir_count ) ) . strpath self . tmpdir_count += os . mkdir ( path ) return path yield TmpdirFactory ( ) class Sandbox ( collections . namedtuple ( '' , [ '' ] ) ) : __slots__ = ( ) @ property def db_path ( self ) : return os . path . join ( self . directory , '' ) @ contextlib . contextmanager def db ( self ) : with sqlite3 . connect ( self . db_path ) as db : yield db @ pytest . yield_fixture def sandbox ( tempdir_factory ) : ret = Sandbox ( tempdir_factory . get ( ) ) with ret . db ( ) as db : create_schema ( db ) populate_metric_ids ( db , tuple ( ) , False ) yield ret @ pytest . yield_fixture def cloneable ( tempdir_factory ) : repo_path = tempdir_factory . get ( ) with cwd ( repo_path ) : subprocess . check_call ( ( '' , '' , '' ) ) subprocess . check_call ( ( '' , '' , '' , '' , '' ) ) yield repo_path @ pytest . yield_fixture def cloneable_with_commits ( cloneable ) : commits = [ ] def append_commit ( ) : output = cmd_output ( '' , '' , COMMIT_FORMAT ) sha , date = output . splitlines ( ) [ : ] commits . append ( Commit ( sha , int ( date ) ) ) def make_commit ( filename , contents ) : with io . open ( filename , '' ) as file_obj : ", "answer": "file_obj . write ( contents )"}, {"prompt": " from st2common . models . db . rule import ( ActionExecutionSpecDB , RuleDB ) from st2common . models . db . sensor import SensorTypeDB from st2common . models . db . trigger import ( TriggerDB , TriggerTypeDB , TriggerInstanceDB ) __all__ = [ ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" import os os . environ . setdefault ( \"\" , \"\" ) from django . core . wsgi import get_wsgi_application ", "answer": "application = get_wsgi_application ( ) "}, {"prompt": " import unittest from pyramid import testing class Test_root_factory ( unittest . TestCase ) : def setUp ( self ) : self . config = testing . setUp ( ) def tearDown ( self ) : testing . tearDown ( ) def _callFUT ( self , request , transaction , get_connection , evolve_packages ) : from . . import root_factory return root_factory ( request , transaction , get_connection , evolve_packages ) def _makeRequest ( self , app_root = None ) : request = Dummy ( ) request . registry = DummyRegistry ( ) request . registry . content = Dummy ( ) request . registry . content . create = lambda * arg : app_root return request def test_without_app_root ( self ) : txn = DummyTransaction ( ) root = { } gc = Dummy_get_connection ( root ) ep = DummyFunction ( True ) app_root = object ( ) request = self . _makeRequest ( app_root ) result = self . _callFUT ( request , txn , gc , ep ) self . assertEqual ( result , app_root ) self . assertTrue ( txn . committed ) self . assertTrue ( txn . savepointed ) self . assertTrue ( ep . called ) def test_with_app_root ( self ) : txn = DummyTransaction ( ) app_root = object ( ) root = { '' : app_root } gc = Dummy_get_connection ( root ) ", "answer": "ep = DummyFunction ( True )"}, {"prompt": " from django . conf . urls import patterns , url , include from haystack . views import search_view_factory , SearchView from offers . feeds import OfferFeed , OfferAtomFeed from offers . forms import OfferSearchForm from . import views as offer_views urlpatterns = patterns ( '' , url ( r'' , '' , name = '' ) , url ( r'' , '' , name = '' ) , url ( r'' , '' , name = \"\" ) , url ( r'' , search_view_factory ( view_class = SearchView , form_class = OfferSearchForm , template = '' , results_per_page = , ) , name = '' , ) , url ( r'' , OfferFeed ( ) , name = '' ) , url ( r'' , OfferAtomFeed ( ) , name = '' ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , url ( r'' , '' , name = \"\" ) , ", "answer": "url ( r'' , '' , name = \"\" ) ,"}, {"prompt": " from __future__ import with_statement , absolute_import import os import sys import re import tempfile import unittest from . import WithReader sys . path . append ( os . path . abspath ( '' ) ) from mysql2pgsql . lib . postgres_writer import PostgresWriter from mysql2pgsql . lib . postgres_file_writer import PostgresFileWriter from mysql2pgsql . lib . postgres_db_writer import PostgresDbWriter def squeeze ( val ) : return re . sub ( r\"\" , \"\" , val ) . strip ( ) class WithTables ( WithReader ) : def setUp ( self ) : super ( WithTables , self ) . setUp ( ) self . table1 = next ( ( t for t in self . reader . tables if t . name == '' ) , None ) self . table2 = next ( ( t for t in self . reader . tables if t . name == '' ) , None ) assert self . table1 assert self . table2 class TestPostgresWriter ( WithTables ) : def setUp ( self ) : super ( self . __class__ , self ) . setUp ( ) self . writer = PostgresWriter ( ) assert self . writer def test_truncate ( self ) : trunc_cmds = self . writer . truncate ( self . table1 ) assert len ( trunc_cmds ) == trunc_stmt , reset_seq = trunc_cmds assert squeeze ( trunc_stmt ) == '' % self . table1 . name if reset_seq : self . assertRegexpMatches ( squeeze ( reset_seq ) , \"\" % self . table1 . name ) def test_write_table ( self ) : write_table_cmds = self . writer . write_table ( self . table1 ) assert len ( write_table_cmds ) == table_cmds , seq_cmds = write_table_cmds assert len ( table_cmds ) == assert squeeze ( table_cmds [ ] ) == '' % self . table1 . name assert '' % self . table1 . name in table_cmds [ ] if seq_cmds : assert len ( seq_cmds ) == self . assertRegexpMatches ( squeeze ( seq_cmds [ ] ) , '' % self . table1 . name ) self . assertRegexpMatches ( squeeze ( seq_cmds [ ] ) , '' % self . table1 . name ) self . assertRegexpMatches ( squeeze ( seq_cmds [ ] ) , \"\" % self . table1 . name ) def test_write_indexex ( self ) : index_cmds = self . writer . write_indexes ( self . table1 ) assert len ( index_cmds ) == def test_write_constraints ( self ) : ", "answer": "constraint_cmds = self . writer . write_constraints ( self . table2 )"}, {"prompt": " import datetime import hashlib import factory import factory . fuzzy from pyblake2 import blake2b from warehouse . packaging . models import ( Project , Release , Role , File , JournalEntry , ) from . accounts import UserFactory from . base import WarehouseFactory class ProjectFactory ( WarehouseFactory ) : class Meta : model = Project name = factory . fuzzy . FuzzyText ( length = ) class ReleaseFactory ( WarehouseFactory ) : class Meta : model = Release name = factory . LazyAttribute ( lambda o : o . project . name ) project = factory . SubFactory ( ProjectFactory ) version = factory . Sequence ( lambda n : str ( n ) + \"\" ) _pypi_ordering = factory . Sequence ( lambda n : n ) uploader = factory . SubFactory ( UserFactory ) class FileFactory ( WarehouseFactory ) : class Meta : model = File name = factory . LazyAttribute ( lambda o : o . release . name ) release = factory . SubFactory ( ReleaseFactory ) python_version = \"\" md5_digest = factory . LazyAttribute ( lambda o : hashlib . md5 ( o . filename . encode ( \"\" ) ) . hexdigest ( ) ) sha256_digest = factory . LazyAttribute ( lambda o : hashlib . sha256 ( o . filename . encode ( \"\" ) ) . hexdigest ( ) ) blake2_256_digest = factory . LazyAttribute ( lambda o : ( blake2b ( o . filename . encode ( \"\" ) , digest_size = ) . hexdigest ( ) ) ) upload_time = factory . fuzzy . FuzzyNaiveDateTime ( datetime . datetime ( , , ) ) path = factory . LazyAttribute ( lambda o : \"\" . join ( [ o . blake2_256_digest [ : ] , o . blake2_256_digest [ : ] , o . blake2_256_digest [ : ] , o . filename , ] ) ) class RoleFactory ( WarehouseFactory ) : class Meta : model = Role role_name = \"\" user = factory . SubFactory ( UserFactory ) project = factory . SubFactory ( ProjectFactory ) class JournalEntryFactory ( WarehouseFactory ) : class Meta : model = JournalEntry id = factory . Sequence ( lambda n : n ) name = factory . fuzzy . FuzzyText ( length = ) ", "answer": "version = factory . Sequence ( lambda n : str ( n ) + \"\" )"}, {"prompt": " import os , collections , simplejson from totalimpact import db , app from totalimpact . providers import pmc from test . unit_tests . providers import common from test . unit_tests . providers . common import ProviderTestCase from totalimpact . providers . provider import Provider , ProviderContentMalformedError , ProviderFactory from totalimpact import provider_batch_data from test . utils import http from test . utils import setup_postgres_for_unittests , teardown_postgres_for_unittests from nose . tools import assert_equals , raises , nottest , assert_items_equal datadir = os . path . join ( os . path . split ( __file__ ) [ ] , \"\" ) SAMPLE_EXTRACT_METRICS_PAGE = os . path . join ( datadir , \"\" ) SAMPLE_EXTRACT_METRICS_PAGE_DIFFERENT_MONTH = os . path . join ( datadir , \"\" ) TEST_PMID = \"\" class TestPmc ( ProviderTestCase ) : provider_name = \"\" testitem_aliases = ( \"\" , TEST_PMID ) testitem_metrics = ( \"\" , TEST_PMID ) def setUp ( self ) : ProviderTestCase . setUp ( self ) self . db = setup_postgres_for_unittests ( db , app ) sample_data_dump = open ( SAMPLE_EXTRACT_METRICS_PAGE , \"\" ) . read ( ) sample_data_dump_different_month = open ( SAMPLE_EXTRACT_METRICS_PAGE_DIFFERENT_MONTH , \"\" ) . read ( ) test_monthly_data = [ { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : sample_data_dump , \"\" : , \"\" : \"\" , \"\" : { \"\" : [ \"\" , \"\" ] } , \"\" : \"\" , \"\" : \"\" } , { \"\" : \"\" , ", "answer": "\"\" : \"\" ,"}, {"prompt": " import hy import imp import sys ", "answer": "if len ( sys . argv ) > :"}, {"prompt": " try : import unittest2 as unittest except ImportError : import unittest from functools import wraps import collections def add_metaclass ( metaclass ) : \"\"\"\"\"\" def wrapper ( cls ) : orig_vars = cls . __dict__ . copy ( ) orig_vars . pop ( '' , None ) orig_vars . pop ( '' , None ) slots = orig_vars . get ( '' ) if slots is not None : if isinstance ( slots , str ) : slots = [ slots ] for slots_var in slots : orig_vars . pop ( slots_var ) return metaclass ( cls . __name__ , cls . __bases__ , orig_vars ) return wrapper def augment_method_docstring ( method , new_class_dict , classname , param_names , param_values , new_method ) : param_assignments_str = '' . join ( [ '' % ( k , v ) for ( k , v ) in zip ( param_names , param_values ) ] ) extra_doc = \"\" % ( method . __name__ , new_class_dict . get ( '' , '' ) , classname , param_assignments_str ) try : new_method . __doc__ = extra_doc + new_method . __doc__ except TypeError : new_method . __doc__ = extra_doc class ParameterizedTestCaseMetaClass ( type ) : method_counter = { } def __new__ ( meta , classname , bases , class_dict ) : new_class_dict = { } for attr_name , attr_value in list ( class_dict . items ( ) ) : if isinstance ( attr_value , collections . Callable ) and hasattr ( attr_value , '' ) : method = attr_value param_names = attr_value . param_names data = attr_value . data func_name_format = attr_value . func_name_format meta . process_method ( classname , method , param_names , data , new_class_dict , func_name_format ) else : new_class_dict [ attr_name ] = attr_value return type . __new__ ( meta , classname , bases , new_class_dict ) @ classmethod def process_method ( cls , classname , method , param_names , data , new_class_dict , func_name_format ) : method_counter = cls . method_counter for param_values in data : new_method = cls . new_method ( method , param_values ) method_counter [ method . __name__ ] = method_counter . get ( method . __name__ , ) + case_data = dict ( list ( zip ( param_names , param_values ) ) ) case_data [ '' ] = method . __name__ case_data [ '' ] = method_counter [ method . __name__ ] new_method . __name__ = func_name_format . format ( ** case_data ) augment_method_docstring ( ", "answer": "method , new_class_dict , classname ,"}, {"prompt": " from contextlib import contextmanager @ contextmanager ", "answer": "def drop_connected_signals ( signal ) :"}, {"prompt": " from . import ValidationTestCase from . models import CustomMessagesModel class CustomMessagesTest ( ValidationTestCase ) : def test_custom_simple_validator_message ( self ) : ", "answer": "cmm = CustomMessagesModel ( number = )"}, {"prompt": " from MailItem import MailItem class MailItems : NUM_ITEMS = FRAGMENTS_PER_EMAIL = senders = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] emails = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] subjects = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] fragments = [ \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" , \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" + \"\" ] def __init__ ( self ) : self . senderIdx = self . emailIdx = self . subjectIdx = self . fragmentIdx = self . items = [ ] i = while ( i < MailItems . NUM_ITEMS ) : self . items . append ( self . createFakeMail ( ) ) i = i + def getMailItemCount ( self ) : return len ( self . items ) ", "answer": "def getMailItem ( self , index ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Ship ( )"}, {"prompt": " import re import traceback from gevent . pywsgi import WSGIServer from gevent . queue import Channel from spinoff . actor import Actor from spinoff . actor . events import Events , Error from spinoff . actor . exceptions import Unhandled from spinoff . util . pattern_matching import ANY from werkzeug import BaseRequest class HttpServer ( Actor ) : def pre_start ( self , address , responders , default_content_type = '' ) : ", "answer": "self . responders = responders"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " from django_services import service from . import models ", "answer": "class BindService ( service . CRUDService ) :"}, {"prompt": " from __future__ import unicode_literals import os from django import forms from django . conf import settings from django . contrib . admin import widgets from django . contrib . auth . decorators import login_required from django . core . exceptions import PermissionDenied from django . http import Http404 , HttpResponseRedirect from django . shortcuts import ( get_object_or_404 , redirect , render , render_to_response ) from django . template import RequestContext from django . utils . encoding import uri_to_iri from django . utils . translation import ugettext_lazy as _ from . management . commands . import_files import FileImporter from . models import Clipboard , File , Folder , FolderRoot , Image , tools class NewFolderForm ( forms . ModelForm ) : class Meta : model = Folder fields = ( '' , ) widgets = { '' : widgets . AdminTextInputWidget , } class ScanFolderForm ( forms . Form ) : folders = forms . CharField ( label = '' , help_text = '' ) class Meta : exclude = ( ) def popup_status ( request ) : return ( '' in request . GET or '' in request . GET or '' in request . POST or '' in request . POST ) def selectfolder_status ( request ) : return '' in request . GET or '' in request . POST def popup_param ( request , separator = \"\" ) : if popup_status ( request ) : return \"\" % separator else : return \"\" def selectfolder_param ( request , separator = \"\" ) : if selectfolder_status ( request ) : return \"\" % separator else : return \"\" def _userperms ( item , request ) : r = [ ] ps = [ '' , '' , '' ] for p in ps : attr = \"\" % p if hasattr ( item , attr ) : x = getattr ( item , attr ) ( request ) if x : r . append ( p ) return r def canonical ( request , uploaded_at , file_id ) : \"\"\"\"\"\" filer_file = get_object_or_404 ( File , pk = file_id , is_public = True ) if ( uploaded_at != filer_file . uploaded_at . strftime ( '' ) or not filer_file . file ) : raise Http404 ( '' % File . _meta . object_name ) return redirect ( filer_file . url ) @ login_required def edit_folder ( request , folder_id ) : folder = None return render_to_response ( '' , { '' : folder , '' : popup_status ( request ) , '' : selectfolder_status ( request ) , } , context_instance = RequestContext ( request ) ) @ login_required def edit_image ( request , folder_id ) : folder = None return render_to_response ( '' , { '' : folder , '' : popup_status ( request ) , '' : selectfolder_status ( request ) , } , context_instance = RequestContext ( request ) ) @ login_required def scan_folder ( request , folder_id = None ) : if folder_id : folder = Folder . objects . get ( id = folder_id ) else : folder = None if request . user . is_superuser : pass elif folder is None : if not settings . MEDIA_ALLOW_REGULAR_USERS_TO_ADD_ROOT_FOLDERS : raise PermissionDenied elif not folder . has_add_children_permission ( request ) : raise PermissionDenied if request . method == '' : scan_folder_form = ScanFolderForm ( request . POST ) if scan_folder_form . is_valid ( ) : kwargs = { '' : os . path . join ( settings . MEDIA_ROOT , scan_folder_form . cleaned_data [ '' ] ) , } if folder : kwargs [ '' ] = folder . name try : importer = FileImporter ( ** kwargs ) importer . walker ( ** kwargs ) except Exception as e : raise e return render_to_response ( '' , context_instance = RequestContext ( request ) ) else : new_folder_form = ScanFolderForm ( ) return render_to_response ( '' , { '' : new_folder_form , '' : popup_status ( request ) , '' : selectfolder_status ( request ) , } , context_instance = RequestContext ( request ) ) @ login_required def make_folder ( request , folder_id = None ) : if not folder_id : folder_id = request . GET . get ( '' ) if not folder_id : folder_id = request . POST . get ( '' ) if folder_id : try : folder = Folder . objects . get ( id = folder_id ) except Folder . DoesNotExist : raise PermissionDenied else : folder = None if request . user . is_superuser : pass elif folder is None : if not settings . MEDIA_ALLOW_REGULAR_USERS_TO_ADD_ROOT_FOLDERS : raise PermissionDenied elif not folder . has_add_children_permission ( request ) : raise PermissionDenied if request . method == '' : new_folder_form = NewFolderForm ( request . POST ) if new_folder_form . is_valid ( ) : new_folder = new_folder_form . save ( commit = False ) if ( folder or FolderRoot ( ) ) . contains_folder ( new_folder . name ) : new_folder_form . _errors [ '' ] = new_folder_form . error_class ( [ _ ( '' ) ] ) else : new_folder . parent = folder new_folder . owner = request . user new_folder . save ( ) return render_to_response ( '' , context_instance = RequestContext ( request ) ) else : new_folder_form = NewFolderForm ( ) return render_to_response ( '' , { '' : new_folder_form , '' : popup_status ( request ) , '' : selectfolder_status ( request ) , } , context_instance = RequestContext ( request ) ) class UploadFileForm ( forms . ModelForm ) : class Meta : model = Image exclude = ( ) @ login_required def upload ( request ) : return render_to_response ( '' , { '' : '' , '' : popup_status ( request ) , '' : selectfolder_status ( request ) , } , context_instance = RequestContext ( request ) ) @ login_required ", "answer": "def paste_clipboard_to_folder ( request ) :"}, {"prompt": " import sys import os sys . path . insert ( , '' ) ", "answer": "sys . path . insert ( , '' )"}, {"prompt": " import pkg_resources from tiget . conf import settings class GitError ( Exception ) : pass def get_config ( name ) : repo = settings . core . repository if repo is None : raise GitError ( '' ) return repo . config [ name ] def is_repo_initialized ( ) : repo = settings . core . repository if repo is None : ", "answer": "return False"}, {"prompt": " from pyjamas import DOM from pyjamas import Window from pyjamas . ui import Event from pyjamas . ui . Button import Button from pyjamas . ui . DialogBox import DialogBox from pyjamas . ui . DockPanel import DockPanel from pyjamas . ui . FlexTable import FlexTable from pyjamas . ui import HasHorizontalAlignment from pyjamas . ui . HorizontalPanel import HorizontalPanel from pyjamas . ui . ListBox import ListBox from pyjamas . ui . VerticalPanel import VerticalPanel from pyjamas . chart . GChart import GChart from pyjamas . chart import AnnotationLocation from pyjamas . chart import SymbolType from pyjamas . chart import TouchedPointUpdateOption LABEL_COL = ; OBJECT_COL = ; N_COLS = ; N_SLICES = ", "answer": "\"\"\"\"\"\""}, {"prompt": " from glob import glob from setuptools import setup , find_packages def read_file ( filename ) : try : return open ( filename , \"\" ) . read ( ) except IOError : return \"\" setup ( name = \"\" , description = \"\" , long_description = open ( \"\" ) . read ( ) . replace ( \"\" , read_file ( \"\" ) ) , author = \"\" , author_email = \"\" , url = \"\" , download_url = \"\" , classifiers = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] , license = \"\" , keywords = \"\" , platforms = \"\" , packages = find_packages ( exclude = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ] ) , scripts = glob ( \"\" ) , install_requires = [ ] , entry_points = { \"\" : [ \"\" , ] } , test_suite = \"\" , zip_safe = True , use_scm_version = { ", "answer": "\"\" : \"\" ,"}, {"prompt": " \"\"\"\"\"\" import supybot import supybot . world as world __version__ = \"\" __author__ = supybot . authors . jemfinch __contributors__ = { } from . import config from . import plugin from imp import reload reload ( plugin ) if world . testing : from . import test Class = plugin . Class ", "answer": "configure = config . configure "}, {"prompt": " from __future__ import unicode_literals from __future__ import print_function import os import click import traceback from types import GeneratorType from prompt_toolkit import AbortAction from prompt_toolkit import Application from prompt_toolkit import CommandLineInterface from prompt_toolkit . enums import DEFAULT_BUFFER from prompt_toolkit . filters import Always , HasFocus , IsDone from prompt_toolkit . layout . processors import HighlightMatchingBracketProcessor , ConditionalProcessor from prompt_toolkit . buffer import Buffer from prompt_toolkit . interface import AcceptAction from prompt_toolkit . shortcuts import create_prompt_layout from prompt_toolkit . shortcuts import create_eventloop from prompt_toolkit . history import FileHistory from . client import DockerClient from . client import DockerPermissionException from . client import DockerTimeoutException from . client import DockerSslException from . completer import DockerCompleter from . lexer import CommandLexer from . formatter import format_data from . formatter import output_stream from . config import write_default_config , read_config from . style import style_factory from . keys import get_key_manager from . toolbar import create_toolbar_handler from . options import OptionError from . logger import create_logger from . __init__ import __version__ click . disable_unicode_literals_warning = True class WharfeeCli ( object ) : \"\"\"\"\"\" dcli = None keyword_completer = None handler = None saved_less_opts = None config = None config_template = '' config_name = '' def __init__ ( self ) : \"\"\"\"\"\" self . config = self . read_configuration ( ) self . theme = self . config [ '' ] [ '' ] log_file = self . config [ '' ] [ '' ] log_level = self . config [ '' ] [ '' ] self . logger = create_logger ( __name__ , log_file , log_level ) self . handler = DockerClient ( self . config [ '' ] . as_int ( '' ) , self . clear , self . set_completer_options ) self . completer = DockerCompleter ( long_option_names = self . get_long_options ( ) , fuzzy = self . get_fuzzy_match ( ) ) self . set_completer_options ( ) self . saved_less_opts = self . set_less_opts ( ) def read_configuration ( self ) : \"\"\"\"\"\" default_config = os . path . join ( self . get_package_path ( ) , self . config_template ) write_default_config ( default_config , self . config_name ) return read_config ( self . config_name , default_config ) def get_package_path ( self ) : \"\"\"\"\"\" from wharfee import __file__ as package_root return os . path . dirname ( package_root ) def set_less_opts ( self ) : \"\"\"\"\"\" opts = os . environ . get ( '' , '' ) os . environ [ '' ] = '' return opts def revert_less_opts ( self ) : \"\"\"\"\"\" os . environ [ '' ] = self . saved_less_opts def write_config_file ( self ) : \"\"\"\"\"\" self . config . write ( ) def clear ( self ) : \"\"\"\"\"\" click . clear ( ) def set_completer_options ( self , cons = True , runs = True , imgs = True , vols = True ) : \"\"\"\"\"\" if cons : cs = self . handler . containers ( all = True ) if cs and len ( cs ) > and isinstance ( cs [ ] , dict ) : containers = [ name for c in cs for name in c [ '' ] ] self . completer . set_containers ( containers ) if runs : cs = self . handler . containers ( ) if cs and len ( cs ) > and isinstance ( cs [ ] , dict ) : running = [ name for c in cs for name in c [ '' ] ] self . completer . set_running ( running ) if imgs : def format_tagged ( tagname , img_id ) : if tagname == '' : return img_id [ : ] return tagname def parse_image_name ( tag , img_id ) : if '' in tag : result = tag . split ( '' , ) [ ] else : result = tag if result == '' : result = img_id [ : ] return result ims = self . handler . images ( ) if ims and len ( ims ) > and isinstance ( ims [ ] , dict ) : images = set ( [ ] ) tagged = set ( [ ] ) for im in ims : repo_tag = '' . format ( im [ '' ] , im [ '' ] ) images . add ( parse_image_name ( repo_tag , im [ '' ] ) ) tagged . add ( format_tagged ( repo_tag , im [ '' ] ) ) self . completer . set_images ( images ) self . completer . set_tagged ( tagged ) if vols : vs = self . handler . volume_ls ( quiet = True ) self . completer . set_volumes ( vs ) def set_fuzzy_match ( self , is_fuzzy ) : \"\"\"\"\"\" self . config [ '' ] [ '' ] = is_fuzzy self . completer . set_fuzzy_match ( is_fuzzy ) def get_fuzzy_match ( self ) : \"\"\"\"\"\" return self . config [ '' ] . as_bool ( '' ) def set_long_options ( self , is_long ) : \"\"\"\"\"\" self . config [ '' ] [ '' ] = is_long self . completer . set_long_options ( is_long ) def get_long_options ( self ) : \"\"\"\"\"\" return self . config [ '' ] . as_bool ( '' ) def refresh_completions ( self ) : \"\"\"\"\"\" self . set_completer_options ( self . handler . is_refresh_containers , self . handler . is_refresh_running , self . handler . is_refresh_images , self . handler . is_refresh_volumes ) def run_cli ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" ", "answer": "from . wrapper import FormWrapper "}, {"prompt": " \"\"\"\"\"\" OPCODE_LIST = [ ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ( \"\" , ) , ", "answer": "( \"\" , ) ,"}, {"prompt": " \"\"\"\"\"\" import hashlib import os import pdb import posixpath import Queue import sys import threading import time import traceback import urllib2 from M2Crypto import BIO from M2Crypto import EVP from M2Crypto import RSA from M2Crypto import X509 import psutil import logging from grr . client import actions from grr . client import client_stats from grr . client import client_utils from grr . lib import communicator from grr . lib import config_lib from grr . lib import flags from grr . lib import queues from grr . lib import rdfvalue from grr . lib import registry from grr . lib import stats from grr . lib import type_info from grr . lib import utils from grr . lib . rdfvalues import client as rdf_client from grr . lib . rdfvalues import crypto as rdf_crypto from grr . lib . rdfvalues import flows as rdf_flows from grr . lib . rdfvalues import protodict as rdf_protodict class HTTPObject ( object ) : \"\"\"\"\"\" def __init__ ( self , url = \"\" , data = \"\" , proxy = \"\" , code = , duration = ) : self . url = url self . data = data self . proxy = proxy self . code = code self . messages = self . source = self . nonce = None self . duration = duration def Success ( self ) : \"\"\"\"\"\" return self . code in ( , ) class HTTPManager ( object ) : \"\"\"\"\"\" def __init__ ( self , heart_beat_cb = None ) : self . heart_beat_cb = heart_beat_cb self . proxies = self . _GetProxies ( ) self . base_urls = self . _GetBaseURLs ( ) self . last_proxy_index = self . last_base_url_index = self . consecutive_connection_errors = self . retry_error_limit = config_lib . CONFIG [ \"\" ] self . active_base_url = None self . error_poll_min = config_lib . CONFIG [ \"\" ] def _GetBaseURLs ( self ) : \"\"\"\"\"\" result = config_lib . CONFIG [ \"\" ] if not result : for control_url in config_lib . CONFIG [ \"\" ] : result . append ( posixpath . dirname ( control_url ) + \"\" ) for url in result : if not url . endswith ( \"\" ) : raise RuntimeError ( \"\" ) ", "answer": "return result"}, {"prompt": " from __future__ import absolute_import from django import forms from django . contrib import messages from django . core . urlresolvers import reverse from django . utils . translation import ugettext_lazy as _ from sentry . models import ( AuditLogEntry , AuditLogEntryEvent , OrganizationMember , Project ) from sentry . signals import member_joined from sentry . web . frontend . base import BaseView ERR_INVITE_INVALID = _ ( '' ) class AcceptInviteForm ( forms . Form ) : pass class AcceptOrganizationInviteView ( BaseView ) : auth_required = False def get_form ( self , request ) : if request . method == '' : return AcceptInviteForm ( request . POST ) return AcceptInviteForm ( ) ", "answer": "def handle ( self , request , member_id , token ) :"}, {"prompt": " from tornado import locale from datetime import datetime from decimal import Decimal from operator import itemgetter import dateutil import hashlib import logging import math import os import random import re import string import time from helper import * class Entity ( ) : \"\"\"\"\"\" __translation = None @ property def __user_id ( self ) : if not self . current_user : return None if not self . current_user . get ( '' ) : return None return self . current_user . get ( '' ) @ property def __language ( self ) : return self . get_user_locale ( ) . code def __get_system_translation ( self , field , entity_definition_keyname = '' , property_definition_keyname = '' ) : if not self . __translation : self . __translation = { } for t in self . db_query ( '' , self . get_user_locale ( ) . code ) : self . __translation [ '' % ( t . get ( '' ) , t . get ( '' ) , t . get ( '' ) ) ] = t . get ( '' ) return self . __translation . get ( '' % ( entity_definition_keyname , property_definition_keyname , field ) , None ) def create_entity ( self , entity_definition_keyname , parent_entity_id = None , ignore_user = False ) : \"\"\"\"\"\" if ignore_user == True : user_id = None else : if not self . __user_id : return user_id = self . __user_id if not entity_definition_keyname : return sql = \"\"\"\"\"\" entity_id = self . db_execute_lastrowid ( sql , entity_definition_keyname , user_id ) if not parent_entity_id : return entity_id parent = self . db_get ( '' , parent_entity_id ) self . db_execute ( '' , parent . get ( '' ) , entity_id ) sql = \"\"\"\"\"\" self . db_execute ( sql , entity_id , user_id , entity_definition_keyname , parent_entity_id , entity_id , user_id ) for row in self . db_query ( \"\" , entity_id ) : self . db_execute ( '' , row . get ( '' ) , entity_id ) self . db_execute ( '' , entity_id , row . get ( '' ) ) sql = \"\"\"\"\"\" self . db_execute ( sql , entity_id , user_id , entity_id ) if user_id : self . set_rights ( entity_id = entity_id , related_entity_id = user_id , right = '' ) for default_value in self . db_query ( '' , entity_definition_keyname ) : self . set_property ( entity_id = entity_id , property_definition_keyname = default_value . get ( '' ) , value = default_value . get ( '' ) ) sql = \"\"\"\"\"\" self . db_execute ( sql , entity_id , user_id , parent_entity_id ) self . db_execute ( \"\"\"\"\"\" , entity_id , user_id , entity_definition_keyname ) if user_id : self . db_execute ( \"\"\"\"\"\" , entity_id , user_id , user_id , entity_definition_keyname ) return entity_id def duplicate_entity ( self , entity_id , copies = , skip_property_definition_keyname = None ) : if not entity_id : return if skip_property_definition_keyname : if type ( skip_property_definition_keyname ) is not list : skip_property_definition_keyname = [ skip_property_definition_keyname ] properties_sql = '' % '' . join ( [ '' % x for x in map ( str , skip_property_definition_keyname ) ] ) else : properties_sql = '' for x in range ( int ( copies ) ) : new_entity_id = self . db_execute_lastrowid ( \"\"\"\"\"\" , self . __user_id , entity_id ) self . db_execute ( \"\"\"\"\"\" % ( new_entity_id , self . __user_id , entity_id , properties_sql ) ) self . db_execute ( \"\"\"\"\"\" , new_entity_id , self . __user_id , entity_id ) self . db_execute ( \"\"\"\"\"\" , new_entity_id , self . __user_id , entity_id ) self . db_execute ( \"\"\"\"\"\" , new_entity_id , self . __user_id , new_entity_id ) self . db_execute ( \"\"\"\"\"\" , new_entity_id , self . __user_id , self . __user_id , new_entity_id ) def delete_entity ( self , entity_id ) : if not self . db_get ( \"\"\"\"\"\" , entity_id , self . __user_id ) : return for child_id in self . get_relatives ( ids_only = True , entity_id = entity_id , relationship_definition_keyname = '' ) : self . delete_entity ( child_id ) self . db_execute ( '' , self . __user_id , entity_id ) self . db_execute ( '' , entity_id , entity_id ) return True def set_property ( self , entity_id = None , relationship_id = None , property_definition_keyname = None , value = None , old_property_id = None , uploaded_file = None , ignore_user = False ) : \"\"\"\"\"\" if not entity_id : return if ignore_user == True : user_id = None else : if not self . __user_id : return user_id = self . __user_id if old_property_id : definition = self . db_get ( '' , old_property_id ) elif property_definition_keyname : definition = self . db_get ( '' , property_definition_keyname ) else : return if not definition : return if old_property_id : self . db_execute ( '' , user_id , old_property_id ) self . db_execute ( '' , user_id , entity_id ) if self . db_get ( \"\"\"\"\"\" , entity_id ) : self . db_execute ( \"\"\"\"\"\" , user_id , entity_id ) else : self . db_execute ( \"\"\"\"\"\" , entity_id , user_id , entity_id ) if user_id : if self . db_get ( \"\"\"\"\"\" , entity_id ) : self . db_execute ( \"\"\"\"\"\" , user_id , user_id , entity_id ) else : self . db_execute ( \"\"\"\"\"\" , entity_id , user_id , user_id , entity_id ) if not value : self . set_mongodb_entity ( entity_id ) return value_display = None if definition . get ( '' ) == : field = '' elif definition . get ( '' ) == '' : field = '' value_display = '' % value value_display = value_display [ : ] elif definition . get ( '' ) == '' : field = '' value_display = '' % value elif definition . get ( '' ) == '' : field = '' value = value . replace ( '' , '' ) value = float ( re . sub ( r'' , '' , value ) ) value_display = round ( value , ) elif definition . get ( '' ) == '' : field = '' value_display = '' % value elif definition . get ( '' ) == '' : field = '' value_display = '' % value elif definition . get ( '' ) == '' : field = '' r = self . __get_properties ( entity_id = value ) if r : value_display = self . __get_properties ( entity_id = value ) [ ] [ '' ] elif definition . get ( '' ) == '' : uploaded_file = value field = '' value_display = uploaded_file [ '' ] [ : ] if uploaded_file . get ( '' ) : value = self . db_execute_lastrowid ( '' , uploaded_file . get ( '' , '' ) , uploaded_file . get ( '' , '' ) , user_id ) elif uploaded_file . get ( '' ) : value = self . db_execute_lastrowid ( '' , uploaded_file . get ( '' , '' ) , uploaded_file . get ( '' , '' ) , uploaded_file . get ( '' , '' ) , user_id ) else : md5 = hashlib . md5 ( uploaded_file . get ( '' ) ) . hexdigest ( ) directory = os . path . join ( '' , '' , '' , self . app_settings ( '' ) , md5 [ ] ) filename = os . path . join ( directory , md5 ) if not os . path . exists ( directory ) : os . makedirs ( directory ) f = open ( filename , '' ) f . write ( uploaded_file . get ( '' , '' ) ) f . close ( ) value = self . db_execute_lastrowid ( '' , md5 , uploaded_file . get ( '' , '' ) , len ( uploaded_file . get ( '' , '' ) ) , user_id ) elif definition . get ( '' ) == '' : field = '' value = if value . lower ( ) == '' else value_display = '' % bool ( value ) elif definition . get ( '' ) == '' : field = '' value_display = '' % value else : field = '' value = value [ : ] value_display = '' % value new_property_id = self . db_execute_lastrowid ( \"\"\"\"\"\" % field , entity_id , definition . get ( '' ) , value , value_display , user_id ) if definition . get ( '' ) == '' and uploaded_file . get ( '' ) : self . db_execute ( '' , new_property_id , value ) self . db_execute ( '' , user_id , entity_id ) self . set_mongodb_entity ( entity_id ) return new_property_id def set_mongodb_entity ( self , entity_id ) : sql = \"\"\"\"\"\" r = self . db_get ( sql , entity_id ) mysql_id = r . get ( '' ) e = { } e [ '' ] = mysql_id e [ '' ] = r . get ( '' ) e [ '' ] = r . get ( '' ) if r . get ( '' ) : e . setdefault ( '' , { } ) [ '' ] = r . get ( '' ) if r . get ( '' ) : e . setdefault ( '' , { } ) [ '' ] = r . get ( '' ) if e . get ( '' ) : e [ '' ] [ '' ] = '' e [ '' ] = [ e . get ( '' ) ] if r . get ( '' ) : e . setdefault ( '' , { } ) [ '' ] = r . get ( '' ) if r . get ( '' ) : e . setdefault ( '' , { } ) [ '' ] = r . get ( '' ) if e . get ( '' ) : e [ '' ] [ '' ] = '' e [ '' ] = [ e . get ( '' ) ] if r . get ( '' ) and r . get ( '' ) : e . setdefault ( '' , { } ) [ '' ] = r . get ( '' ) if r . get ( '' ) and r . get ( '' ) : e . setdefault ( '' , { } ) [ '' ] = r . get ( '' ) if e . get ( '' ) : e [ '' ] [ '' ] = '' e [ '' ] = [ e . get ( '' ) ] viewers = self . __get_mongodb_right ( mysql_id , [ '' , '' , '' , '' ] ) if viewers : e [ '' ] = [ { '' : x , '' : '' } for x in list ( set ( viewers ) ) ] expanders = self . __get_mongodb_right ( mysql_id , [ '' , '' , '' ] ) if expanders : e [ '' ] = [ { '' : x , '' : '' } for x in list ( set ( expanders ) ) ] editors = self . __get_mongodb_right ( mysql_id , [ '' , '' ] ) if editors : e [ '' ] = [ { '' : x , '' : '' } for x in list ( set ( editors ) ) ] owners = self . __get_mongodb_right ( mysql_id , [ '' ] ) if owners : e [ '' ] = [ { '' : x , '' : '' } for x in list ( set ( owners ) ) ] parent = self . __get_mongodb_parent ( entity_id = mysql_id , recursive = False ) if parent : e [ '' ] = [ { '' : x , '' : '' } for x in list ( set ( parent ) ) ] ancestor = self . __get_mongodb_parent ( entity_id = mysql_id , recursive = True ) if ancestor : e [ '' ] = [ { '' : x , '' : '' } for x in list ( set ( ancestor ) ) ] sql = \"\"\"\"\"\" properties = { } for r2 in self . db_query ( sql , mysql_id ) : value = { } if r2 . get ( '' ) == '' and r2 . get ( '' ) : value [ '' ] = r2 . get ( '' ) elif r2 . get ( '' ) == '' and r2 . get ( '' ) : value [ '' ] = r2 . get ( '' ) elif r2 . get ( '' ) == '' and r2 . get ( '' ) != None : value [ '' ] = r2 . get ( '' ) elif r2 . get ( '' ) == '' and r2 . get ( '' ) != None : value [ '' ] = float ( r2 . get ( '' ) ) elif r2 . get ( '' ) == '' and r2 . get ( '' ) != None : value [ '' ] = bool ( r2 . get ( '' ) ) elif r2 . get ( '' ) in [ '' , '' ] and r2 . get ( '' ) != None : value [ '' ] = r2 . get ( '' ) elif r2 . get ( '' ) == '' and r2 . get ( '' ) : value [ '' ] = r2 . get ( '' ) elif r2 . get ( '' ) == '' and r2 . get ( '' ) : value [ '' ] = r2 . get ( '' ) elif r2 . get ( '' ) == '' and r2 . get ( '' ) : value [ '' ] = r2 . get ( '' ) if r2 . get ( '' ) : value [ '' ] = r2 . get ( '' ) else : value [ '' ] = r2 . get ( '' ) if r2 . get ( '' , None ) : value [ '' ] = r2 . get ( '' ) if r2 . get ( '' , None ) : value [ '' ] = r2 . get ( '' ) if not value : continue value [ '' ] = r2 . get ( '' ) value [ '' ] = r2 . get ( '' ) if r2 . get ( '' ) : value [ '' ] = r2 . get ( '' ) e . setdefault ( r2 . get ( '' ) , [ ] ) . append ( value ) try : mongo_entity_version = self . mongodb ( ) . entityVersion . find_one ( { '' : mysql_id } , { '' : False , '' : True } ) if mongo_entity_version : e [ '' ] = mongo_entity_version . get ( '' ) else : e [ '' ] = self . mongodb ( ) . entity . insert_one ( { } ) . inserted_id self . mongodb ( ) . entityVersion . insert_one ( e ) except Exception , err : self . captureException ( ) logging . error ( '' % ( err , e ) ) def __get_mongodb_parent ( self , entity_id , recursive = False ) : sql = \"\"\"\"\"\" % entity_id entities = [ ] for r in self . db_query ( sql ) : entities . append ( r . get ( '' ) ) if recursive : entities = entities + self . __get_mongodb_parent ( entity_id = r . get ( '' ) , recursive = True ) return entities def __get_mongodb_right ( self , entity_id , rights ) : sql = \"\"\"\"\"\" % ( '' . join ( [ '' % x for x in rights ] ) , entity_id ) entities = [ ] for r in self . db_query ( sql ) : entities . append ( r . get ( '' ) ) return entities def set_counter ( self , entity_id ) : \"\"\"\"\"\" if not entity_id : return if self . db_get ( '' , entity_id ) . get ( '' ) == '' : parent = self . get_relatives ( related_entity_id = entity_id , relationship_definition_keyname = '' , reverse_relation = True , limit = ) . values ( ) [ ] [ ] childs = self . get_relatives ( entity_id = parent . get ( '' , None ) , relationship_definition_keyname = '' ) . values ( ) if childs : childs_count = len ( [ y . get ( '' , ) for y in childs [ ] if y . get ( '' , { } ) . get ( '' , { } ) . get ( '' , None ) ] ) + else : childs_count = parent_number = '' . join ( [ '' % x [ '' ] for x in parent . get ( '' , { } ) . get ( '' , { } ) . get ( '' , [ ] ) if x [ '' ] ] ) counter_value = '' % ( parent_number , childs_count ) self . set_property ( entity_id = entity_id , property_definition_keyname = '' , value = counter_value ) return counter_value property_id = self . db_execute_lastrowid ( \"\"\"\"\"\" % { '' : entity_id , '' : self . __user_id } ) self . db_execute ( \"\"\"\"\"\" % { '' : entity_id , '' : self . __user_id } ) self . db_execute ( '' , property_id ) return self . db_get ( '' , property_id ) . get ( '' ) def set_relations ( self , entity_id , related_entity_id , relationship_definition_keyname , delete = False , update = False ) : \"\"\"\"\"\" if type ( entity_id ) is not list : entity_id = [ entity_id ] if type ( related_entity_id ) is not list : related_entity_id = [ related_entity_id ] if type ( relationship_definition_keyname ) is not list : relationship_definition_keyname = [ relationship_definition_keyname ] for e in entity_id : for r in related_entity_id : for t in relationship_definition_keyname : self . db_execute ( '' , r if t == '' else e ) if delete == True : sql = \"\"\"\"\"\" % ( self . __user_id , t , e , r ) self . db_execute ( sql ) elif update == True : sql = \"\"\"\"\"\" % ( self . __user_id , t , e , r ) old = self . db_execute_rowcount ( sql ) if not old : sql = \"\"\"\"\"\" % ( t , e , r , self . __user_id ) self . db_execute ( sql ) else : sql = \"\"\"\"\"\" % ( t , e , r ) old = self . db_get ( sql ) if not old : sql = \"\"\"\"\"\" % ( t , e , r , self . __user_id ) self . db_execute ( sql ) def get_rights ( self , entity_id ) : if not entity_id : return rights = { } for right in [ '' , '' , '' , '' ] : sql = \"\"\"\"\"\" relationship = self . db_query ( sql , right , entity_id ) if not relationship : continue ids = [ x . get ( '' ) for x in relationship if x . get ( '' ) ] if ids : entities = self . __get_properties ( entity_id = ids , full_definition = False , only_public = False ) if entities : rights [ right ] = entities return rights def set_rights ( self , entity_id , related_entity_id , right = None , ignore_user = False ) : if not entity_id or not related_entity_id : return if ignore_user == True : user_id = None else : if not self . __user_id : return user_id = self . __user_id if type ( entity_id ) is not list : entity_id = [ entity_id ] if type ( related_entity_id ) is not list : related_entity_id = [ related_entity_id ] sql = \"\"\"\"\"\" % ( '' . join ( map ( str , entity_id ) ) , '' . join ( map ( str , related_entity_id ) ) ) self . db_execute ( sql , user_id ) if right in [ '' , '' , '' , '' ] : for e in entity_id : for re in related_entity_id : self . db_execute ( '' , right , int ( e ) , int ( re ) , user_id ) self . db_execute ( '' % '' . join ( map ( str , entity_id ) ) ) def set_sharing ( self , entity_id , sharing ) : if not entity_id or not sharing : return if type ( entity_id ) is not list : entity_id = [ entity_id ] sql = \"\"\"\"\"\" % '' . join ( map ( str , entity_id ) ) self . db_execute ( sql , sharing , self . __user_id ) def set_sharing_key ( self , entity_id , generate = False ) : if not entity_id : return if generate : sharing_key = '' . join ( random . choice ( string . ascii_letters + string . digits ) for x in range ( ) ) else : sharing_key = None if type ( entity_id ) is not list : entity_id = [ entity_id ] sql = \"\"\"\"\"\" % '' . join ( map ( str , entity_id ) ) self . db_execute ( sql , sharing_key , self . __user_id ) return sharing_key def get_users ( self , search = None ) : \"\"\"\"\"\" query_re = '' if search != None : join_parts = [ ] for s in search . split ( '' ) [ : ] : if not s : continue join_parts . append ( '' % { '' : s } ) query_re = '' . join ( join_parts ) sql = \"\"\"\"\"\" % { '' : self . __user_id , '' : query_re } ids = self . db_query ( sql ) entities = self . __get_properties ( entity_id = [ x . get ( '' ) for x in ids ] ) if not entities : return [ ] return entities def get_entities ( self , ids_only = False , entity_id = None , search = None , entity_definition_keyname = None , dataproperty = None , limit = None , full_definition = False , only_public = False , sharing_key = None ) : \"\"\"\"\"\" ids = self . __get_id_list ( entity_id = entity_id , search = search , entity_definition_keyname = entity_definition_keyname , limit = limit , only_public = only_public , sharing_key = sharing_key ) if ids_only == True : return ids entities = self . __get_properties ( entity_id = ids , entity_definition_keyname = entity_definition_keyname , dataproperty = dataproperty , full_definition = full_definition , only_public = only_public , sharing_key = sharing_key ) if not entities and full_definition == False and entity_definition_keyname == None : return if limit == and len ( entities ) > : return entities [ ] return entities def __get_id_list ( self , entity_id = None , search = None , entity_definition_keyname = None , limit = None , only_public = False , sharing_key = None ) : \"\"\"\"\"\" select_parts = [ '' ] join_parts = [ ] where_parts = [ '' ] sql_parts = [ ] if search != None : i = for s in search . split ( '' ) [ : ] : if not s : continue i += join_parts . append ( '' % { '' : i } ) if not self . __user_id or only_public == True : join_parts . append ( '' % ( i , i , i ) ) where_parts . append ( '' % ( i , s ) ) where_parts . append ( '' % i ) if entity_definition_keyname != None : if type ( entity_definition_keyname ) is not list : entity_definition_keyname = [ entity_definition_keyname ] where_parts . append ( '' % '' . join ( [ '' % x for x in map ( str , entity_definition_keyname ) ] ) ) if entity_id != None : if type ( entity_id ) is not list : entity_id = [ entity_id ] where_parts . append ( '' % '' . join ( map ( str , entity_id ) ) ) if self . __user_id and only_public == False : where_parts . append ( '' ) join_parts . append ( '' ) where_parts . append ( '' % self . __user_id ) elif sharing_key : where_parts . append ( '' % sharing_key ) else : where_parts . append ( '' ) i = if search != None : for s in search . split ( '' ) : i += where_parts . append ( '' % i ) if len ( select_parts ) > : sql_parts . append ( '' % '' . join ( select_parts ) ) sql_parts . append ( '' ) if len ( join_parts ) > : sql_parts . append ( '' % '' . join ( join_parts ) ) if len ( where_parts ) > : sql_parts . append ( '' % '' . join ( where_parts ) ) if limit : limit = '' % limit else : limit = '' sql_parts . append ( '' % limit ) sql = '' . join ( sql_parts ) items = self . db_query ( sql ) if not items : return [ ] return [ x . get ( '' ) for x in items ] def __get_properties ( self , entity_id = None , entity_definition_keyname = None , dataproperty = None , full_definition = False , only_public = False , sharing_key = None ) : \"\"\"\"\"\" items = None if entity_id : if type ( entity_id ) is not list : entity_id = [ entity_id ] if self . __user_id and only_public == False : rights = '' % self . __user_id public = '' elif sharing_key : rights = '' public = '' % sharing_key else : rights = '' public = '' datapropertysql = '' if dataproperty : if type ( dataproperty ) is not list : dataproperty = [ dataproperty ] datapropertysql = '' % '' . join ( [ '' % x for x in dataproperty ] ) sql = \"\"\"\"\"\" % { '' : self . get_user_locale ( ) . code , '' : public , '' : '' . join ( map ( str , entity_id ) ) , '' : datapropertysql , '' : rights } items = { } for row in self . db_query ( sql ) : if row . get ( '' ) == '' and not row . get ( '' ) and not sharing_key : continue if row . get ( '' ) in [ '' , '' ] and row . get ( '' ) not in [ '' , '' , '' , '' ] and row . get ( '' ) != and not sharing_key : continue items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , entity_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , entity_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , entity_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , entity_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , entity_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , entity_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , entity_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) if row . get ( '' ) else datetime . datetime . now ( ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , property_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , property_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , property_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = self . __get_system_translation ( field = '' , property_definition_keyname = row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = bool ( row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = bool ( row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = bool ( row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = bool ( row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = bool ( row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = bool ( row . get ( '' ) ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = bool ( row . get ( '' ) ) value = row . get ( '' ) if row . get ( '' ) else '' if row . get ( '' ) == : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) value = row . get ( '' ) if row . get ( '' ) else '' elif row . get ( '' ) == '' : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) elif row . get ( '' ) == '' : db_value = row . get ( '' ) else : db_value = '' value = '' items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = value items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = db_value items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) items . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) . setdefault ( '' , { } ) . setdefault ( '' % row . get ( '' ) , { } ) [ '' ] = row . get ( '' ) if not items : if not full_definition : return [ ] if entity_definition_keyname : if type ( entity_definition_keyname ) is not list : entity_definition_keyname = [ entity_definition_keyname ] items = { } for e in entity_definition_keyname : items . setdefault ( '' % e , { } ) [ '' ] = e items . setdefault ( '' % e , { } ) [ '' ] = '' for key , value in items . iteritems ( ) : if value . get ( '' , None ) : items [ key ] = dict ( items [ key ] . items ( ) + self . __get_displayfields ( value ) . items ( ) ) items [ key ] [ '' ] = self . __get_picture_url ( value [ '' ] , value [ '' ] ) items [ key ] [ '' ] = True for d in self . get_definition ( entity_definition_keyname = value [ '' ] ) : if not value . get ( '' , None ) : items [ key ] [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = d [ '' ] if d [ '' ] and len ( value . get ( '' , { } ) . get ( '' % d [ '' ] , { } ) . get ( '' , { } ) . values ( ) ) < : items [ key ] [ '' ] = False if full_definition : if not d [ '' ] or d [ '' ] > len ( value . get ( '' , { } ) . get ( '' % d [ '' ] , { } ) . get ( '' , { } ) . values ( ) ) : items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) . setdefault ( '' , { } ) [ '' ] = { '' : '' , '' : '' , '' : '' , '' : '' } if not d [ '' ] or d [ '' ] > len ( value . get ( '' , { } ) . get ( '' % d [ '' ] , { } ) . get ( '' , { } ) . values ( ) ) : items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = True else : items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) [ '' ] = False if d [ '' ] and d [ '' ] != '' : for c in self . get_entities ( entity_definition_keyname = d [ '' ] , only_public = True ) : if c . get ( '' , None ) : items [ key ] . setdefault ( '' , { } ) . setdefault ( '' % d [ '' ] , { } ) . setdefault ( '' , [ ] ) . append ( { '' : c . get ( '' , '' ) , '' : c . get ( '' , '' ) } ) for p_key , p_value in value . get ( '' , { } ) . iteritems ( ) : if p_value . get ( '' ) : items [ key ] [ '' ] [ p_key ] [ '' ] = sorted ( p_value . get ( '' , { } ) . values ( ) , key = itemgetter ( '' ) ) if p_value [ '' ] == '' : reference_definition = self . db_get ( '' , p_value [ '' ] ) if reference_definition : if reference_definition . get ( '' ) : items [ key ] [ '' ] [ p_key ] [ '' ] = reference_definition . get ( '' ) if p_value [ '' ] == '' : for f_key , f_value in enumerate ( p_value . get ( '' , { } ) ) : if not f_value . get ( '' ) : continue file_result = self . db_get ( '' , f_value . get ( '' ) ) if not file_result : continue items [ key ] [ '' ] [ p_key ] [ '' ] [ f_key ] [ '' ] = file_result . get ( '' ) items [ key ] [ '' ] [ p_key ] [ '' ] [ f_key ] [ '' ] = file_result . get ( '' ) items [ key ] [ '' ] [ p_key ] [ '' ] [ f_key ] [ '' ] = file_result . get ( '' ) return items . values ( ) def __get_displayfields ( self , entity_dict ) : \"\"\"\"\"\" result = { } for displayfield in [ '' , '' , '' , '' ] : result [ displayfield ] = entity_dict . get ( displayfield , '' ) if entity_dict . get ( displayfield , '' ) else None for data_property in findTags ( entity_dict . get ( displayfield , '' ) , '' , '' ) : dataproperty_dict = entity_dict . get ( '' , { } ) . get ( data_property , { } ) result [ displayfield ] = result [ displayfield ] . replace ( '' % data_property , '' . join ( [ '' % x [ '' ] for x in dataproperty_dict . get ( '' , { } ) . values ( ) ] ) ) . replace ( '' , '' ) result [ '' ] = self . __get_system_translation ( field = '' , entity_definition_keyname = entity_dict . get ( '' ) ) if not result [ '' ] : result [ '' ] = entity_dict . get ( '' , '' ) if entity_dict . get ( '' , '' ) else None for data_property in findTags ( entity_dict . get ( '' , '' ) , '' , '' ) : result [ '' ] = result [ '' ] . replace ( '' % data_property , entity_dict . get ( '' , { } ) . get ( data_property , { } ) . get ( '' , '' ) ) result [ '' ] = result [ '' ] . split ( '' ) if result [ '' ] else None result [ '' ] = result [ '' ] . split ( '' ) if result [ '' ] else None if entity_dict . get ( '' , None ) and entity_dict . get ( '' , None ) != result [ '' ] : self . db_execute ( '' , result [ '' ] , entity_dict . get ( '' ) ) return result def __get_picture_url ( self , entity_id , entity_definition_keyname ) : \"\"\"\"\"\" sql = \"\"\"\"\"\" f = self . db_get ( sql , entity_id ) if f : return '' % entity_id elif entity_definition_keyname in [ '' , '' , '' , '' , '' , '' ] : return '' % entity_id elif entity_definition_keyname == '' : return '' % ( hashlib . md5 ( str ( entity_id ) ) . hexdigest ( ) ) else : return '' % ( hashlib . md5 ( str ( entity_id ) ) . hexdigest ( ) ) def get_definition ( self , entity_definition_keyname ) : \"\"\"\"\"\" if not entity_definition_keyname : return if type ( entity_definition_keyname ) is not list : entity_definition_keyname = [ entity_definition_keyname ] sql = \"\"\"\"\"\" % '' . join ( [ '' % x for x in map ( str , entity_definition_keyname ) ] ) defs = [ ] for r in self . db_query ( sql ) : defs . append ( { '' : r . get ( '' ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = r . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = r . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = r . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = r . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = r . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = r . get ( '' ) ) , '' : r . get ( '' ) , '' : self . __get_system_translation ( field = '' , property_definition_keyname = r . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , property_definition_keyname = r . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , property_definition_keyname = r . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , property_definition_keyname = r . get ( '' ) ) , '' : r . get ( '' ) , '' : r . get ( '' ) , '' : bool ( r . get ( '' ) ) , '' : bool ( r . get ( '' ) ) , '' : r . get ( '' ) , '' : r . get ( '' ) , '' : bool ( r . get ( '' ) ) , '' : bool ( r . get ( '' ) ) , '' : bool ( r . get ( '' ) ) , '' : r . get ( '' ) , } ) return defs def get_entity_definition ( self , entity_definition_keyname ) : \"\"\"\"\"\" if entity_definition_keyname : if type ( entity_definition_keyname ) is not list : entity_definition_keyname = [ entity_definition_keyname ] sql = \"\"\"\"\"\" % '' . join ( [ '' % x for x in map ( str , entity_definition_keyname ) ] ) defs = [ ] for d in self . db_query ( sql ) : defs . append ( { '' : d . get ( '' ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = d . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = d . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = d . get ( '' ) ) , '' : self . __get_system_translation ( field = '' , entity_definition_keyname = d . get ( '' ) ) , '' : d . get ( '' ) , '' : d . get ( '' ) , '' : d . get ( '' ) } ) return defs def get_relatives ( self , ids_only = False , relationship_ids_only = False , entity_id = None , related_entity_id = None , relationship_definition_keyname = None , reverse_relation = False , entity_definition_keyname = None , full_definition = False , limit = None , only_public = False ) : \"\"\"\"\"\" if entity_id : if type ( entity_id ) is not list : entity_id = [ entity_id ] if related_entity_id : if type ( related_entity_id ) is not list : related_entity_id = [ related_entity_id ] if relationship_definition_keyname : if type ( relationship_definition_keyname ) is not list : relationship_definition_keyname = [ relationship_definition_keyname ] if entity_definition_keyname : if type ( entity_definition_keyname ) is not list : entity_definition_keyname = [ entity_definition_keyname ] unionsql = '' if reverse_relation == True : sql = \"\"\"\"\"\" else : sql = \"\"\"\"\"\" if not ids_only : unionsql = \"\"\"\"\"\" if entity_id : sql += '' % '' . join ( map ( str , entity_id ) ) if related_entity_id : sql += '' % '' . join ( map ( str , related_entity_id ) ) if self . __user_id and only_public == False : sql += '' % self . __user_id else : sql += '' if relationship_definition_keyname : sql += '' % '' . join ( [ '' % x for x in relationship_definition_keyname ] ) if entity_definition_keyname : sql += '' % '' . join ( [ '' % x for x in entity_definition_keyname ] ) if unionsql : sql += unionsql if entity_id : sql += '' % '' . join ( map ( str , entity_id ) ) if self . __user_id and only_public == False : sql += '' % self . __user_id else : sql += '' if entity_definition_keyname : sql += '' % '' . join ( [ '' % x for x in entity_definition_keyname ] ) sql += '' if limit : sql += '' % limit sql += '' if ids_only == True : items = [ ] for item in self . db_query ( sql ) : items . append ( item . get ( '' ) ) elif relationship_ids_only == True : items = [ ] for item in self . db_query ( sql ) : items . append ( item . get ( '' ) ) else : items = { } for item in self . db_query ( sql ) : ent = self . __get_properties ( entity_id = item . get ( '' ) , full_definition = full_definition , entity_definition_keyname = entity_definition_keyname , only_public = only_public ) if not ent : continue ent = ent [ ] items . setdefault ( '' % ent . get ( '' , '' ) , [ ] ) . append ( ent ) return items def get_file ( self , file_id , sharing_key = None ) : \"\"\"\"\"\" ", "answer": "if type ( file_id ) is not list :"}, {"prompt": " import os import mimetypes mimetypes . add_type ( '' , '' ) mimetypes . add_type ( '' , '' ) from zope . structuredtext import stx2html from pyramid . response import Response from pyramid . httpexceptions import HTTPFound from pyramid . view import render_view_to_response from pyramid . view import view_config from virginia . models import File from virginia . models import Directory @ view_config ( context = File ) def file_view ( context , request ) : dirname , filename = os . path . split ( context . path ) name , ext = os . path . splitext ( filename ) result = render_view_to_response ( context , request , ext ) return result @ view_config ( context = Directory ) def directory_view ( context , request ) : path_info = request . environ [ '' ] if not path_info . endswith ( '' ) : response = HTTPFound ( location = path_info + '' ) return response defaults = ( '' , '' , '' ) for name in defaults : try : index = context [ name ] except KeyError : ", "answer": "continue"}, {"prompt": " \"\"\"\"\"\" from traits . api import HasTraits , List , Str , Tuple class EventTracker ( HasTraits ) : \"\"\"\"\"\" events = List ( Tuple ) event_names = List ( Str ) subscriptions = List ( Tuple ) def _subscriptions_changed ( self , old , new ) : \"\"\"\"\"\" ", "answer": "for subscription in old :"}, {"prompt": " import os import shutil DIR = os . path . dirname ( os . path . realpath ( __file__ ) ) TEST_DIR = os . path . join ( DIR , \"\" ) TEST_DIR_2 = os . path . join ( TEST_DIR , \"\" ) TEST_DIR_3 = os . path . join ( TEST_DIR , \"\" ) TEST_FILE = os . path . join ( TEST_DIR , \"\" ) TEST_FILE_2 = os . path . join ( TEST_DIR , \"\" ) def setup_module ( module ) : \"\"\"\"\"\" ", "answer": "pass"}, {"prompt": " import logging import statsd ", "answer": "from . import compat"}, {"prompt": " from config import * import midi def instrument_num ( instrument ) : \"\"\"\"\"\" for key , name in GUS_INSTR_PATCHES . items ( ) : if name == instrument : return key raise Exception ( '' % instrument ) pattern = midi . Pattern ( resolution = ) track = midi . Track ( ) track . append ( midi . ControlChangeEvent ( tick = , channel = , data = [ , ] ) ) time = for group in SIMILAR_GROUPS : print \"\" empty = True for instrument in group : inum = instrument_num ( instrument ) if inum <= : print \"\" % ( instrument , inum ) track . extend ( [ midi . ProgramChangeEvent ( tick = time , channel = , data = [ inum ] ) , ", "answer": "midi . NoteOnEvent ( tick = , channel = ,"}, {"prompt": " \"\"\"\"\"\" ", "answer": "revision = ''"}, {"prompt": " \"\"\"\"\"\" import sys if sys . version_info [ ] < : ", "answer": "raise ImportError ( '' )"}, {"prompt": " import logging import pprint from ryu . services . protocols . bgp . operator . command import Command from ryu . services . protocols . bgp . operator . command import CommandsResponse from ryu . services . protocols . bgp . operator . command import STATUS_ERROR from ryu . services . protocols . bgp . operator . command import STATUS_OK from ryu . services . protocols . bgp . operator . commands . responses import WrongParamResp from ryu . services . protocols . bgp . operator . views . conf import ConfDetailView from ryu . services . protocols . bgp . operator . views . conf import ConfDictView from route_formatter_mixin import RouteFormatterMixin LOG = logging . getLogger ( '' ) class Routes ( Command , RouteFormatterMixin ) : help_msg = '' param_help_msg = '' command = '' def __init__ ( self , * args , ** kwargs ) : super ( Routes , self ) . __init__ ( * args , ** kwargs ) ", "answer": "self . subcommands = {"}, {"prompt": " \"\"\"\"\"\" import re import string from jsbeautifier . unpackers import UnpackingError PRIORITY = def detect ( source ) : \"\"\"\"\"\" return source . replace ( '' , '' ) . startswith ( '' ) def unpack ( source ) : \"\"\"\"\"\" payload , symtab , radix , count = _filterargs ( source ) if count != len ( symtab ) : raise UnpackingError ( '' ) try : unbase = Unbaser ( radix ) except TypeError : raise UnpackingError ( '' ) def lookup ( match ) : \"\"\"\"\"\" word = match . group ( ) return symtab [ unbase ( word ) ] or word source = re . sub ( r'' , lookup , payload ) return _replacestrings ( source ) def _filterargs ( source ) : \"\"\"\"\"\" argsregex = ( r\"\" r\"\" ) args = re . search ( argsregex , source , re . DOTALL ) . groups ( ) try : return args [ ] , args [ ] . split ( '' ) , int ( args [ ] ) , int ( args [ ] ) except ValueError : raise UnpackingError ( '' ) def _replacestrings ( source ) : \"\"\"\"\"\" match = re . search ( r'' , source , re . DOTALL ) if match : varname , strings = match . groups ( ) startpoint = len ( match . group ( ) ) lookup = strings . split ( '' ) variable = '' % varname for index , value in enumerate ( lookup ) : source = source . replace ( variable % index , '' % value ) return source [ startpoint : ] return source class Unbaser ( object ) : \"\"\"\"\"\" ALPHABET = { : '' , : ( '' '' ) } def __init__ ( self , base ) : self . base = base if <= base <= : self . unbase = lambda string : int ( string , base ) else : ", "answer": "try :"}, {"prompt": " import math import numpy as np from wavelet import dwt3D from wavelet import idwt3D def hsm ( fimau , fimao ) : '''''' s = fimau . shape ; p = [ , , ] p [ ] = ** math . ceil ( math . log ( s [ ] , ) ) ", "answer": "p [ ] = ** math . ceil ( math . log ( s [ ] , ) )"}, {"prompt": " from __future__ import absolute_import __author__ = '' from enum import IntEnum from . base import PebblePacket from . base . types import * __all__ = [ \"\" , \"\" , \"\" ] class ScreenshotRequest ( PebblePacket ) : class Meta : endpoint = register = False _command = Uint8 ( default = ) class ScreenshotResponse ( PebblePacket ) : ", "answer": "class Meta :"}, {"prompt": " from __future__ import absolute_import from . impl import * ", "answer": "__version__ = ( , , ) "}, {"prompt": " from django . db import models from django . db . models import Q class CountrySearchManager ( models . Manager ) : def search ( self , ** kwargs ) : qs = self . get_query_set ( ) query = kwargs . get ( '' , '' ) government = kwargs . get ( '' , '' ) ", "answer": "if government :"}, {"prompt": " \"\"\"\"\"\" import os import random import uuid from urllib . parse import quote import requests OAUTH_ENDPOINT_TEMPLATE = '' MANAGEMENT_ROOT = '' SUBSCRIPTION_ENDPOINT = '' RESOURCE_ENDPOINT = '' DEPLOYMENT_URI = '' RESOURCES = ( '' , '' , '' , '' ) def setup_requests_session ( token ) : session = requests . Session ( ) session . params = { '' : AzureClient . API_VERSION } session . headers = { '' : '' . format ( token ) } return session class AzureClientException ( Exception ) : pass class AzureClientTemplateException ( AzureClientException ) : def __init__ ( self , template , errors ) : self . message = '' . format ( template , errors ) self . template = template self . errors = errors super ( AzureClientTemplateException , self ) . __init__ ( self . message ) class AzureClient ( object ) : API_VERSION = '' @ staticmethod def create_from_env_creds ( ** kwargs ) : subscription_id = os . environ . get ( '' ) tenant_id = os . environ . get ( '' ) client_id = os . environ . get ( '' ) client_secret = os . environ . get ( '' ) return AzureClient ( subscription_id = subscription_id , tenant_id = tenant_id , client_id = client_id , client_secret = client_secret , ** kwargs ) def __init__ ( self , subscription_id , tenant_id , client_id , client_secret , random_resource_group_name_prefix = '' , ** kwargs ) : self . _subscription_id = subscription_id self . _tenant_id = tenant_id self . _client_id = client_id self . _client_secret = client_secret self . _token = None self . _random_resource_group_name_prefix = random_resource_group_name_prefix self . _resource_group_name = self . get_random_resource_group_name ( ) self . _deployment_name = self . get_random_deployment_name ( ) self . _session = setup_requests_session ( self . get_auth_token ( ) ) ", "answer": "self . _url_space = self . _generate_api_urls ( )"}, {"prompt": " from django . contrib import admin ", "answer": "from . models import Inbox , Message , MessageArchive"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " \"\"\"\"\"\" __docformat__ = '' from os import curdir from os . path import exists , join as opj from . base import Interface from . . support . param import Parameter from . . support . constraints import EnsureStr , EnsureBool , EnsureNone from . . support . collectionrepo import CollectionRepo from datalad . support . collection_backends import CollectionRepoBackend from datalad . support . handle_backends import CollectionRepoHandleBackend from . . support . handlerepo import HandleRepo from . . cmdline . helpers import get_repo_instance from . . log import lgr from datalad . cmdline . helpers import get_datalad_master class Update ( Interface ) : \"\"\"\"\"\" _params_ = dict ( key = Parameter ( args = ( '' , ) , nargs = '' , doc = \"\" , constraints = EnsureStr ( ) | EnsureNone ( ) ) ) def __call__ ( self , key = curdir ) : local_master = get_datalad_master ( ) if key == curdir : try : repo = get_repo_instance ( ) except RuntimeError as e : repo = local_master elif exists ( key ) : try : repo = get_repo_instance ( path = key ) except RuntimeError as e : lgr . error ( str ( e ) ) return - else : if key in local_master . git_get_remotes ( ) : path = CollectionRepoBackend ( local_master , key ) . url if exists ( path ) : try : repo = CollectionRepo ( path ) ", "answer": "except RuntimeError as e :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) ", "answer": "result . template = \"\""}, {"prompt": " \"\"\"\"\"\" def create_pandas_abc_type ( name , attr , comp ) : @ classmethod def _check ( cls , inst ) : return getattr ( inst , attr , '' ) in comp dct = dict ( __instancecheck__ = _check , __subclasscheck__ = _check ) meta = type ( \"\" , ( type , ) , dct ) return meta ( name , tuple ( ) , dct ) ABCIndex = create_pandas_abc_type ( \"\" , \"\" , ( \"\" , ) ) ABCInt64Index = create_pandas_abc_type ( \"\" , \"\" , ( \"\" , ) ) ABCRangeIndex = create_pandas_abc_type ( \"\" , \"\" , ( \"\" , ) ) ABCFloat64Index = create_pandas_abc_type ( \"\" , \"\" , ( \"\" , ) ) ABCMultiIndex = create_pandas_abc_type ( \"\" , \"\" , ", "answer": "( \"\" , ) )"}, {"prompt": " from mrjob . retry import RetryGoRound from mrjob . retry import RetryWrapper from tests . py2 import Mock from tests . py2 import TestCase class RetryGoRoundTestCase ( TestCase ) : def test_empty ( self ) : self . assertRaises ( ValueError , RetryGoRound , [ ] , lambda ex : isinstance ( ex , IOError ) ) def test_success ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , return_value = ) a2 = Mock ( ) a2 . f = Mock ( __name__ = '' , return_value = ) a = RetryGoRound ( [ a1 , a2 ] , lambda ex : isinstance ( ex , IOError ) ) self . assertEqual ( a . f ( ) , ) self . assertEqual ( a1 . f . call_count , ) self . assertEqual ( a2 . f . call_count , ) def test_one_failure ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , side_effect = IOError ) a1 . x = a2 = Mock ( ) a2 . f = Mock ( __name__ = '' , return_value = ) a2 . x = a = RetryGoRound ( [ a1 , a2 ] , lambda ex : isinstance ( ex , IOError ) ) self . assertEqual ( a . x , ) self . assertEqual ( a . f ( ) , ) self . assertEqual ( a . x , ) self . assertEqual ( a . f ( ) , ) self . assertEqual ( a1 . f . call_count , ) self . assertEqual ( a2 . f . call_count , ) def test_all_fail ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , side_effect = IOError ) a1 . x = a2 = Mock ( ) a2 . f = Mock ( __name__ = '' , side_effect = IOError ) a2 . x = a = RetryGoRound ( [ a1 , a2 ] , lambda ex : isinstance ( ex , IOError ) ) self . assertEqual ( a . x , ) self . assertRaises ( IOError , a . f ) self . assertEqual ( a . x , ) self . assertRaises ( IOError , a . f ) self . assertEqual ( a1 . f . call_count , ) self . assertEqual ( a2 . f . call_count , ) def test_unrecoverable_error ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , side_effect = ValueError ) a2 = Mock ( ) a2 . f = Mock ( __name__ = '' , return_value = ) a = RetryGoRound ( [ a1 , a2 ] , lambda ex : isinstance ( ex , IOError ) ) self . assertRaises ( ValueError , a . f ) self . assertRaises ( ValueError , a . f ) self . assertEqual ( a1 . f . call_count , ) self . assertEqual ( a2 . f . call_count , ) def test_can_wrap_around ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , side_effect = [ IOError , ] ) a2 = Mock ( ) a2 . f = Mock ( __name__ = '' , side_effect = [ , IOError ] ) a = RetryGoRound ( [ a1 , a2 ] , lambda ex : isinstance ( ex , IOError ) ) self . assertEqual ( a . f ( ) , ) self . assertEqual ( a . f ( ) , ) self . assertEqual ( a1 . f . call_count , ) self . assertEqual ( a2 . f . call_count , ) def test_wrapping ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , side_effect = IOError ) a2 = Mock ( ) a2 . f = Mock ( __name__ = '' , return_value = ) a = RetryGoRound ( [ a1 , a2 ] , lambda ex : isinstance ( ex , IOError ) ) self . assertEqual ( a . f ( '' , bar = '' ) , ) a1 . f . assert_called_once_with ( '' , bar = '' ) a2 . f . assert_called_once_with ( '' , bar = '' ) self . assertEqual ( a . f . __name__ , '' ) class RetryWrapperTestCase ( TestCase ) : def test_success ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , side_effect = None ) a = RetryWrapper ( a1 , retry_if = lambda x : True , backoff = , max_tries = ) a . f ( ) a1 . f . assert_called_once_with ( ) def test_failure ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , side_effect = [ IOError , ] ) a = RetryWrapper ( a1 , retry_if = lambda x : True , backoff = , max_tries = ) self . assertEqual ( a . f ( ) , ) self . assertEqual ( a1 . f . call_count , ) def test_failure_raises_if_all_tries_fail ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , side_effect = [ IOError , IOError ] ) a = RetryWrapper ( a1 , retry_if = lambda x : True , backoff = , max_tries = ) with self . assertRaises ( IOError ) : a . f ( ) self . assertEqual ( a1 . f . call_count , ) def test_try_till_success ( self ) : a1 = Mock ( ) a1 . f = Mock ( __name__ = '' , side_effect = [ IOError , IOError , None ] ) a = RetryWrapper ( a1 , retry_if = lambda x : True , backoff = , max_tries = ) a . f ( ) ", "answer": "self . assertEqual ( a1 . f . call_count , ) "}, {"prompt": " import os test = { \"\" : os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , \"\" ) , \"\" : [ os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , \"\" ) , os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , \"\" ) , ", "answer": "os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , \"\" ) ] ,"}, {"prompt": " import pyb led = pyb . LED ( ) def blink_millis ( ) : start = pyb . millis ( ) led . on ( ) while pyb . elapsed_millis ( start ) < : pass led . off ( ) while pyb . elapsed_millis ( start ) < : pass led . on ( ) while pyb . elapsed_millis ( start ) < : pass led . off ( ) while pyb . elapsed_millis ( start ) < : ", "answer": "pass"}, {"prompt": " import unittest import collections_and_iterators \"\"\"\"\"\" class TestObjectMethods ( unittest . TestCase ) : def setUp ( self ) : self . singleLinkList = collections_and_iterators . SinglyLinkedList ( ) self . singleLinkListData = collections_and_iterators . SinglyLinkedList ( ) self . singleLinkListData . append ( \"\" ) self . singleLinkListData . append ( \"\" ) self . singleLinkListData . append ( \"\" ) self . doubleLinkList = collections_and_iterators . DoublyLinkedList ( ) self . doubleLinkListData = collections_and_iterators . DoublyLinkedList ( ) self . doubleLinkListData . append ( \"\" ) self . doubleLinkListData . append ( \"\" ) self . doubleLinkListData . append ( \"\" ) ", "answer": "def test_empty_single_list ( self ) :"}, {"prompt": " \"\"\"\"\"\" import logging logger = logging . getLogger ( __name__ ) import os import base64 from lino_xl . lib . beid import Plugin as BeIdPlugin class Plugin ( BeIdPlugin ) : site_js_snippets = [ '' ] media_name = '' media_base_url = \"\" media_root = None \"\"\"\"\"\" def get_js_includes ( self , settings , language ) : yield self . build_media_url ( '' ) yield self . build_media_url ( '' ) def get_body_lines ( self , site , request ) : p = self . build_media_url ( ) p = request . build_absolute_uri ( p ) yield '' yield '' % p yield '' yield '' yield '' yield '' yield '' yield '' ", "answer": "yield ''"}, {"prompt": " from django . conf . urls import patterns , url from crate . web . packages . simple . views import PackageIndex , PackageDetail ", "answer": "handler404 = \"\""}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" result . attribute_template_id = ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " from lux . forms import ValidationError POLICY = dict ( effect = ( str , frozenset ( ( '' , '' ) ) ) , action = ( ( str , list ) , None ) , resource = ( ( str , list ) , None ) , condition = ( dict , None ) ) EFFECTS = { '' : True , '' : False } def has_permission ( request , permissions , resource , action ) : '''''' while resource : permission = _check_policies ( permissions , resource , action ) if permission is not None : return permission else : default = request . config [ '' ] . get ( resource ) if default is not None : return _has_policy_actions ( action , default ) resource = resource . rpartition ( '' ) [ ] default = request . config [ '' ] return _has_policy_actions ( action , default ) def validate_policy ( policy ) : if isinstance ( policy , dict ) : return validate_single_policy ( policy ) elif isinstance ( policy , list ) : if not policy : raise ValidationError ( '' ) policies = [ ] for single in policy : policies . append ( validate_single_policy ( single ) ) return policies else : raise ValidationError ( '' ) def validate_single_policy ( policy ) : if not isinstance ( policy , dict ) : raise ValidationError ( '' ) p = { } for key , value in policy . items ( ) : ", "answer": "key = str ( key ) . lower ( )"}, {"prompt": " import os try : from urllib import urlretrieve except ImportError : from urllib . request import urlretrieve def check_destination_path ( path , name , overwrite = False ) : \"\"\"\"\"\" file_path = os . path . join ( path , name ) if not os . path . isdir ( path ) : raise IOError ( '' . format ( path ) ) ", "answer": "if os . path . exists ( file_path ) and not overwrite :"}, {"prompt": " '''''' __docformat__ = '' __version__ = '' import unittest from render_base import RenderBase import scene2d from scene2d . debug import gen_rect_map class OOBTest ( RenderBase ) : def test_main ( self ) : self . init_window ( , ) self . set_map ( gen_rect_map ( [ [ { } ] * ] * , , ) ) def on_text ( text ) : ", "answer": "if text == '' :"}, {"prompt": " \"\"\"\"\"\" import logging from homeassistant . components . binary_sensor import ( SENSOR_CLASSES , BinarySensorDevice ) ", "answer": "from homeassistant . const import ATTR_BATTERY_LEVEL , STATE_OFF , STATE_ON"}, {"prompt": " from openstackclient . tests . volume . v2 import fakes as service_fakes from openstackclient . volume . v2 import service class TestService ( service_fakes . TestService ) : def setUp ( self ) : super ( TestService , self ) . setUp ( ) self . service_mock = self . app . client_manager . volume . services self . service_mock . reset_mock ( ) class TestServiceList ( TestService ) : services = service_fakes . FakeService . create_one_service ( ) def setUp ( self ) : super ( TestServiceList , self ) . setUp ( ) self . service_mock . list . return_value = [ self . services ] self . cmd = service . ListService ( self . app , None ) def test_service_list ( self ) : arglist = [ '' , self . services . host , '' , self . services . binary , ] verifylist = [ ( '' , self . services . host ) , ( '' , self . services . binary ) , ] parsed_args = self . check_parser ( self . cmd , arglist , verifylist ) columns , data = self . cmd . take_action ( parsed_args ) expected_columns = [ '' , '' , '' , '' , '' , '' , ] self . assertEqual ( expected_columns , columns ) datalist = ( ( self . services . binary , self . services . host , self . services . zone , self . services . status , ", "answer": "self . services . state ,"}, {"prompt": " import abc import six import struct from . import packet_base from . import icmpv6 from . import tcp from . import udp from . import sctp from . import in_proto as inet from ryu . lib import addrconv from ryu . lib import stringify IPV6_ADDRESS_PACK_STR = '' IPV6_ADDRESS_LEN = struct . calcsize ( IPV6_ADDRESS_PACK_STR ) IPV6_PSEUDO_HEADER_PACK_STR = '' class ipv6 ( packet_base . PacketBase ) : \"\"\"\"\"\" _PACK_STR = '' _MIN_LEN = struct . calcsize ( _PACK_STR ) _IPV6_EXT_HEADER_TYPE = { } _TYPE = { '' : [ '' , '' ] } @ staticmethod def register_header_type ( type_ ) : def _register_header_type ( cls ) : ipv6 . _IPV6_EXT_HEADER_TYPE [ type_ ] = cls return cls return _register_header_type def __init__ ( self , version = , traffic_class = , flow_label = , payload_length = , nxt = inet . IPPROTO_TCP , hop_limit = , src = '' , dst = '' , ext_hdrs = None ) : super ( ipv6 , self ) . __init__ ( ) self . version = version self . traffic_class = traffic_class self . flow_label = flow_label self . payload_length = payload_length self . nxt = nxt self . hop_limit = hop_limit self . src = src self . dst = dst ext_hdrs = ext_hdrs or [ ] assert isinstance ( ext_hdrs , list ) for ext_hdr in ext_hdrs : assert isinstance ( ext_hdr , header ) self . ext_hdrs = ext_hdrs @ classmethod def parser ( cls , buf ) : ( v_tc_flow , payload_length , nxt , hlim , src , dst ) = struct . unpack_from ( cls . _PACK_STR , buf ) version = v_tc_flow >> traffic_class = ( v_tc_flow >> ) & flow_label = v_tc_flow & hop_limit = hlim offset = cls . _MIN_LEN last = nxt ext_hdrs = [ ] while True : cls_ = cls . _IPV6_EXT_HEADER_TYPE . get ( last ) if not cls_ : break hdr = cls_ . parser ( buf [ offset : ] ) ext_hdrs . append ( hdr ) offset += len ( hdr ) last = hdr . nxt msg = cls ( version , traffic_class , flow_label , payload_length , nxt , hop_limit , addrconv . ipv6 . bin_to_text ( src ) , addrconv . ipv6 . bin_to_text ( dst ) , ext_hdrs ) return ( msg , ipv6 . get_packet_type ( last ) , buf [ offset : offset + payload_length ] ) def serialize ( self , payload , prev ) : hdr = bytearray ( ) v_tc_flow = ( self . version << | self . traffic_class << | self . flow_label ) struct . pack_into ( ipv6 . _PACK_STR , hdr , , v_tc_flow , self . payload_length , self . nxt , self . hop_limit , addrconv . ipv6 . text_to_bin ( self . src ) , addrconv . ipv6 . text_to_bin ( self . dst ) ) if self . ext_hdrs : for ext_hdr in self . ext_hdrs : hdr . extend ( ext_hdr . serialize ( ) ) if == self . payload_length : payload_length = len ( payload ) for ext_hdr in self . ext_hdrs : payload_length += len ( ext_hdr ) self . payload_length = payload_length struct . pack_into ( '' , hdr , , self . payload_length ) return hdr def __len__ ( self ) : ext_hdrs_len = for ext_hdr in self . ext_hdrs : ext_hdrs_len += len ( ext_hdr ) return self . _MIN_LEN + ext_hdrs_len ipv6 . register_packet_type ( icmpv6 . icmpv6 , inet . IPPROTO_ICMPV6 ) ipv6 . register_packet_type ( tcp . tcp , inet . IPPROTO_TCP ) ipv6 . register_packet_type ( udp . udp , inet . IPPROTO_UDP ) ipv6 . register_packet_type ( sctp . sctp , inet . IPPROTO_SCTP ) @ six . add_metaclass ( abc . ABCMeta ) class header ( stringify . StringifyMixin ) : \"\"\"\"\"\" def __init__ ( self , nxt ) : self . nxt = nxt @ classmethod @ abc . abstractmethod def parser ( cls , buf ) : pass @ abc . abstractmethod def serialize ( self ) : pass @ abc . abstractmethod def __len__ ( self ) : pass class opt_header ( header ) : \"\"\"\"\"\" _PACK_STR = '' _MIN_LEN = struct . calcsize ( _PACK_STR ) _FIX_SIZE = _class_prefixes = [ '' ] @ abc . abstractmethod def __init__ ( self , nxt , size , data ) : super ( opt_header , self ) . __init__ ( nxt ) assert not ( size % ) self . size = size self . data = data @ classmethod def parser ( cls , buf ) : ( nxt , len_ ) = struct . unpack_from ( cls . _PACK_STR , buf ) data_len = cls . _FIX_SIZE + int ( len_ ) data = [ ] size = cls . _MIN_LEN while size < data_len : ( type_ , ) = struct . unpack_from ( '' , buf [ size : ] ) if type_ == : opt = option ( type_ , - , None ) size += else : opt = option . parser ( buf [ size : ] ) size += len ( opt ) data . append ( opt ) return cls ( nxt , len_ , data ) def serialize ( self ) : buf = struct . pack ( self . _PACK_STR , self . nxt , self . size ) buf = bytearray ( buf ) if self . data is None : self . data = [ option ( type_ = , len_ = , data = b'' ) ] for opt in self . data : buf . extend ( opt . serialize ( ) ) return buf def __len__ ( self ) : return self . _FIX_SIZE + self . size @ ipv6 . register_header_type ( inet . IPPROTO_HOPOPTS ) class hop_opts ( opt_header ) : \"\"\"\"\"\" TYPE = inet . IPPROTO_HOPOPTS def __init__ ( self , nxt = inet . IPPROTO_TCP , size = , data = None ) : super ( hop_opts , self ) . __init__ ( nxt , size , data ) @ ipv6 . register_header_type ( inet . IPPROTO_DSTOPTS ) class dst_opts ( opt_header ) : \"\"\"\"\"\" TYPE = inet . IPPROTO_DSTOPTS def __init__ ( self , nxt = inet . IPPROTO_TCP , size = , data = None ) : super ( dst_opts , self ) . __init__ ( nxt , size , data ) class option ( stringify . StringifyMixin ) : \"\"\"\"\"\" _PACK_STR = '' _MIN_LEN = struct . calcsize ( _PACK_STR ) def __init__ ( self , type_ = , len_ = - , data = None ) : self . type_ = type_ self . len_ = len_ self . data = data @ classmethod def parser ( cls , buf ) : ( type_ , ) = struct . unpack_from ( '' , buf ) if not type_ : cls_ = cls ( type_ , - , None ) else : data = None ( type_ , len_ ) = struct . unpack_from ( cls . _PACK_STR , buf ) if len_ : form = \"\" % len_ ( data , ) = struct . unpack_from ( form , buf , cls . _MIN_LEN ) cls_ = cls ( type_ , len_ , data ) return cls_ def serialize ( self ) : data = None if not self . type_ : data = struct . pack ( '' , self . type_ ) elif not self . len_ : data = struct . pack ( self . _PACK_STR , self . type_ , self . len_ ) else : form = \"\" % self . len_ data = struct . pack ( self . _PACK_STR + form , self . type_ , self . len_ , self . data ) return data def __len__ ( self ) : return self . _MIN_LEN + self . len_ @ ipv6 . register_header_type ( inet . IPPROTO_ROUTING ) class routing ( header ) : \"\"\"\"\"\" TYPE = inet . IPPROTO_ROUTING _OFFSET_LEN = struct . calcsize ( '' ) ROUTING_TYPE_2 = ROUTING_TYPE_3 = @ classmethod def parser ( cls , buf ) : ( type_ , ) = struct . unpack_from ( '' , buf , cls . _OFFSET_LEN ) switch = { cls . ROUTING_TYPE_2 : None , cls . ROUTING_TYPE_3 : routing_type3 } cls_ = switch . get ( type_ ) if cls_ : return cls_ . parser ( buf ) else : return None class routing_type3 ( header ) : \"\"\"\"\"\" _PACK_STR = '' _MIN_LEN = struct . calcsize ( _PACK_STR ) _TYPE = { '' : [ '' ] } def __init__ ( self , nxt = inet . IPPROTO_TCP , size = , type_ = , seg = , cmpi = , cmpe = , adrs = None ) : super ( routing_type3 , self ) . __init__ ( nxt ) self . size = size self . type_ = type_ self . seg = seg self . cmpi = cmpi self . cmpe = cmpe adrs = adrs or [ ] assert isinstance ( adrs , list ) self . adrs = adrs self . _pad = ( - ( ( len ( self . adrs ) - ) * ( - self . cmpi ) + ( - self . cmpe ) % ) ) % @ classmethod def _get_size ( cls , size ) : return ( int ( size ) + ) * @ classmethod def parser ( cls , buf ) : ( nxt , size , type_ , seg , cmp_ , pad ) = struct . unpack_from ( cls . _PACK_STR , buf ) data = cls . _MIN_LEN header_len = cls . _get_size ( size ) cmpi = int ( cmp_ >> ) cmpe = int ( cmp_ & ) pad = int ( pad >> ) adrs = [ ] if size : adrs_len_i = - cmpi adrs_len_e = - cmpe form_i = \"\" % adrs_len_i form_e = \"\" % adrs_len_e while data < ( header_len - ( adrs_len_e + pad ) ) : ( adr , ) = struct . unpack_from ( form_i , buf [ data : ] ) adr = ( b'' * cmpi ) + adr adrs . append ( addrconv . ipv6 . bin_to_text ( adr ) ) data += adrs_len_i ( adr , ) = struct . unpack_from ( form_e , buf [ data : ] ) adr = ( b'' * cmpe ) + adr adrs . append ( addrconv . ipv6 . bin_to_text ( adr ) ) return cls ( nxt , size , type_ , seg , cmpi , cmpe , adrs ) def serialize ( self ) : if self . size == : self . size = ( ( len ( self . adrs ) - ) * ( - self . cmpi ) + ( - self . cmpe ) + self . _pad ) // buf = struct . pack ( self . _PACK_STR , self . nxt , self . size , self . type_ , self . seg , ( self . cmpi << ) | self . cmpe , self . _pad << ) buf = bytearray ( buf ) if self . size : form_i = \"\" % ( - self . cmpi ) form_e = \"\" % ( - self . cmpe ) slice_i = slice ( self . cmpi , ) slice_e = slice ( self . cmpe , ) for adr in self . adrs [ : - ] : buf . extend ( ", "answer": "struct . pack ("}, {"prompt": " import numpy as np import matplotlib . pyplot as plt from matplotlib import style style . use ( \"\" ) from sklearn import svm X = np . array ( [ [ , ] , ", "answer": "[ , ] ,"}, {"prompt": " import sys import numpy as np def chunks ( l , n ) : \"\"\"\"\"\" for i in xrange ( , len ( l ) , n ) : yield l [ i : i + n ] class ChunkedTransform ( object ) : verbose = def transform ( self , X ) : features = None for chunk in chunks ( X , self . batch_size ) : if features is not None : features = np . vstack ( ", "answer": "[ features , self . _compute_features ( chunk ) ] )"}, {"prompt": " \"\"\"\"\"\" import sys import os import imp from . import log from telex . plugin import NormalizePluginNameForModuleName from telex . plugin . IPlugin import IPlugin from telex . plugin . IPluginLocator import IPluginLocator from telex . plugin . PluginFileLocator import PluginFileAnalyzerWithInfoFile from telex . plugin . PluginFileLocator import PluginFileLocator from telex . plugin import PLUGIN_NAME_FORBIDEN_STRING from telex . plugin . PluginInfo import PluginInfo class PluginManager ( object ) : \"\"\"\"\"\" def __init__ ( self , categories_filter = None , directories_list = None , plugin_info_ext = None , plugin_locator = None ) : \"\"\"\"\"\" if categories_filter is None : categories_filter = { \"\" : IPlugin } self . setCategoriesFilter ( categories_filter ) plugin_locator = self . _locatorDecide ( plugin_info_ext , plugin_locator ) self . setPluginLocator ( plugin_locator , directories_list ) def _locatorDecide ( self , plugin_info_ext , plugin_locator ) : \"\"\"\"\"\" specific_info_ext = plugin_info_ext is not None specific_locator = plugin_locator is not None if not specific_info_ext and not specific_locator : res = PluginFileLocator ( ) elif not specific_info_ext and specific_locator : res = plugin_locator elif not specific_locator and specific_info_ext : res = PluginFileLocator ( ) res . setAnalyzers ( [ PluginFileAnalyzerWithInfoFile ( \"\" , plugin_info_ext ) ] ) elif specific_info_ext and specific_locator : msg = ( \"\" , \"\" , \"\" ) raise ValueError ( \"\" . join ( msg ) % self . __class__ . __name__ ) return res def setCategoriesFilter ( self , categories_filter ) : \"\"\"\"\"\" self . categories_interfaces = categories_filter . copy ( ) self . category_mapping = { } self . _category_file_mapping = { } for categ in categories_filter : self . category_mapping [ categ ] = [ ] self . _category_file_mapping [ categ ] = [ ] def setPluginPlaces ( self , directories_list ) : \"\"\"\"\"\" self . getPluginLocator ( ) . setPluginPlaces ( directories_list ) def updatePluginPlaces ( self , directories_list ) : \"\"\"\"\"\" self . getPluginLocator ( ) . updatePluginPlaces ( directories_list ) def setPluginInfoExtension ( self , ext ) : \"\"\"\"\"\" try : self . getPluginLocator ( ) . setPluginInfoExtension ( ext ) except KeyError : log . error ( \"\" ) def setPluginInfoClass ( self , picls , strategies = None ) : \"\"\"\"\"\" if strategies : for name in strategies : self . getPluginLocator ( ) . setPluginInfoClass ( picls , name ) else : self . getPluginLocator ( ) . setPluginInfoClass ( picls ) def getPluginInfoClass ( self ) : \"\"\"\"\"\" return self . getPluginLocator ( ) . getPluginInfoClass ( ) def setPluginLocator ( self , plugin_locator , dir_list = None , picls = None ) : \"\"\"\"\"\" if isinstance ( plugin_locator , IPluginLocator ) : self . _plugin_locator = plugin_locator if dir_list is not None : self . _plugin_locator . updatePluginPlaces ( dir_list ) if picls is not None : self . setPluginInfoClass ( picls ) else : raise TypeError ( \"\" % plugin_locator ) def getPluginLocator ( self ) : \"\"\"\"\"\" return self . _plugin_locator def _gatherCorePluginInfo ( self , directory , plugin_info_filename ) : \"\"\"\"\"\" return self . getPluginLocator ( ) . gatherCorePluginInfo ( directory , plugin_info_filename ) def _getPluginNameAndModuleFromStream ( self , infoFileObject , candidate_infofile = \"\" ) : \"\"\"\"\"\" return self . getPluginLocator ( ) . getPluginNameAndModuleFromStream ( infoFileObject , candidate_infofile ) def getCategories ( self ) : \"\"\"\"\"\" return list ( self . category_mapping . keys ( ) ) def removePluginFromCategory ( self , plugin , category_name ) : \"\"\"\"\"\" self . category_mapping [ category_name ] . remove ( plugin ) def appendPluginToCategory ( self , plugin , category_name ) : \"\"\"\"\"\" self . category_mapping [ category_name ] . append ( plugin ) def getPluginsOfCategory ( self , category_name ) : \"\"\"\"\"\" return self . category_mapping [ category_name ] [ : ] def getAllPlugins ( self ) : \"\"\"\"\"\" allPlugins = set ( ) for pluginsOfOneCategory in self . category_mapping . values ( ) : allPlugins . update ( pluginsOfOneCategory ) return list ( allPlugins ) def getPluginCandidates ( self ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : raise RuntimeError ( \"\" ) return self . _candidates [ : ] def removePluginCandidate ( self , candidateTuple ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : raise ValueError ( \"\" ) self . _candidates . remove ( candidateTuple ) def appendPluginCandidate ( self , candidateTuple ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : raise ValueError ( \"\" ) self . _candidates . append ( candidateTuple ) def locatePlugins ( self ) : \"\"\"\"\"\" self . _candidates , npc = self . getPluginLocator ( ) . locatePlugins ( ) def loadPlugins ( self , callback = None ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : raise ValueError ( \"\" ) processed_plugins = [ ] for candidate_infofile , candidate_filepath , plugin_info in self . _candidates : plugin_module_name_template = NormalizePluginNameForModuleName ( \"\" + plugin_info . name ) + \"\" for plugin_name_suffix in range ( len ( sys . modules ) ) : plugin_module_name = plugin_module_name_template % plugin_name_suffix if plugin_module_name not in sys . modules : break if candidate_filepath . endswith ( \"\" ) : candidate_filepath = candidate_filepath [ : - ] if callback is not None : callback ( plugin_info ) if \"\" in os . path . basename ( candidate_filepath ) : candidate_filepath = os . path . dirname ( candidate_filepath ) try : if os . path . isdir ( candidate_filepath ) : candidate_module = imp . load_module ( plugin_module_name , None , candidate_filepath , ( \"\" , \"\" , imp . PKG_DIRECTORY ) ) else : with open ( candidate_filepath + \"\" , \"\" ) as plugin_file : candidate_module = imp . load_module ( plugin_module_name , plugin_file , candidate_filepath + \"\" , ( \"\" , \"\" , imp . PY_SOURCE ) ) except Exception : exc_info = sys . exc_info ( ) log . error ( \"\" % candidate_filepath , exc_info = exc_info ) plugin_info . error = exc_info processed_plugins . append ( plugin_info ) continue processed_plugins . append ( plugin_info ) if \"\" in os . path . basename ( candidate_filepath ) : sys . path . remove ( plugin_info . path ) for element in ( getattr ( candidate_module , name ) for name in dir ( candidate_module ) ) : plugin_info_reference = None for category_name in self . categories_interfaces : try : is_correct_subclass = issubclass ( element , self . categories_interfaces [ category_name ] ) except Exception : continue if is_correct_subclass and element is not self . categories_interfaces [ category_name ] : current_category = category_name if candidate_infofile not in self . _category_file_mapping [ current_category ] : if not plugin_info_reference : try : plugin_info . plugin_object = self . instanciateElement ( element ) plugin_info_reference = plugin_info except Exception : exc_info = sys . exc_info ( ) log . error ( \"\" % candidate_filepath , exc_info = exc_info ) plugin_info . error = exc_info break plugin_info . categories . append ( current_category ) self . category_mapping [ current_category ] . append ( plugin_info_reference ) self . _category_file_mapping [ current_category ] . append ( candidate_infofile ) delattr ( self , '' ) return processed_plugins def instanciateElement ( self , element ) : \"\"\"\"\"\" return element ( ) def collectPlugins ( self ) : \"\"\"\"\"\" self . locatePlugins ( ) self . loadPlugins ( ) def getPluginByName ( self , name , category = \"\" ) : \"\"\"\"\"\" if category in self . category_mapping : for item in self . category_mapping [ category ] : if item . name == name : return item return None def activatePluginByName ( self , name , category = \"\" ) : \"\"\"\"\"\" ", "answer": "pta_item = self . getPluginByName ( name , category )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from __future__ import unicode_literals ", "answer": "default_app_config = '' "}, {"prompt": " import logging import sys from kmip . core import enums from kmip . demos import utils from kmip . pie import client from kmip . pie import objects if __name__ == '' : ", "answer": "logger = utils . build_console_logger ( logging . INFO )"}, {"prompt": " from neat . config import * import neat . common as common config = read_and_validate_config ( [ DEFAILT_CONFIG_PATH , CONFIG_PATH ] , REQUIRED_FIELDS ) ", "answer": "compute_hosts = common . parse_compute_hosts ( config [ '' ] )"}, {"prompt": " from __future__ import absolute_import , print_function , division from nose . plugins . skip import SkipTest import numpy import unittest import theano from theano import shared , function import theano . tensor as T from theano . tensor . nnet . neighbours import images2neibs , neibs2images , Images2Neibs from theano . tests import unittest_tools mode_without_gpu = theano . compile . mode . get_default_mode ( ) . excluding ( '' ) class T_Images2Neibs ( unittest_tools . InferShapeTester ) : mode = mode_without_gpu op = Images2Neibs dtypes = [ '' , '' , '' ] def test_neibs ( self ) : for shape , pshape in [ ( ( , , , ) , ( , ) ) , ( ( , , , ) , ( , ) ) , ( ( , , , ) , ( , ) ) , ( ( , , , ) , ( , ) ) ] : for border in [ '' , '' ] : for dtype in self . dtypes : images = shared ( numpy . arange ( numpy . prod ( shape ) , dtype = dtype ) . reshape ( shape ) ) neib_shape = T . as_tensor_variable ( pshape ) f = function ( [ ] , images2neibs ( images , neib_shape , mode = border ) , mode = self . mode ) neibs = f ( ) g = function ( [ ] , neibs2images ( neibs , neib_shape , images . shape ) , mode = self . mode ) assert any ( [ isinstance ( node . op , self . op ) for node in f . maker . fgraph . toposort ( ) ] ) assert numpy . allclose ( images . get_value ( borrow = True ) , g ( ) ) def test_neibs_manual ( self ) : shape = ( , , , ) for dtype in self . dtypes : images = shared ( numpy . arange ( numpy . prod ( shape ) , dtype = dtype ) . reshape ( shape ) ) neib_shape = T . as_tensor_variable ( ( , ) ) for border in [ '' , '' ] : f = function ( [ ] , images2neibs ( images , neib_shape , mode = border ) , mode = self . mode ) assert any ( [ isinstance ( node . op , self . op ) for node in f . maker . fgraph . toposort ( ) ] ) neibs = f ( ) assert numpy . allclose ( neibs , [ [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , [ , , , ] , ", "answer": "[ , , , ] ,"}, {"prompt": " import copy from django . conf import settings from django . core . urlresolvers import reverse from django import http ", "answer": "from django . test . utils import override_settings"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from __future__ import absolute_import , division , print_function , unicode_literals \"\"\"\"\"\" import demo import pi3d DISPLAY = pi3d . Display . create ( x = , y = ) shader = pi3d . Shader ( \"\" ) tex = pi3d . Texture ( \"\" ) box = pi3d . Cuboid ( w = , h = , d = , x = , y = , z = ) box . set_draw_details ( shader , [ tex ] ) tm = dt = sc = ds = mykeys = pi3d . Keyboard ( ) ASPECT = DISPLAY . width / DISPLAY . height camera1 = pi3d . Camera ( ( , , ) , ( , , - ) , ( , , , ASPECT ) , is_3d = True ) ", "answer": "camera2 = pi3d . Camera ( is_3d = False )"}, {"prompt": " \"\"\"\"\"\" from django . http import Http404 from django . utils . translation import ugettext as _ from django . views . generic . list_detail import object_list from tagging . models import Tag , TaggedItem from tagging . utils import get_tag , get_queryset_and_model def tagged_object_list ( request , queryset_or_model = None , tag = None , related_tags = False , related_tag_counts = True , ** kwargs ) : \"\"\"\"\"\" if queryset_or_model is None : try : queryset_or_model = kwargs . pop ( '' ) except KeyError : raise AttributeError ( _ ( '' ) ) if tag is None : try : tag = kwargs . pop ( '' ) except KeyError : raise AttributeError ( _ ( '' ) ) tag_instance = get_tag ( tag ) if tag_instance is None : raise Http404 ( _ ( '' ) % tag ) queryset = TaggedItem . objects . get_by_model ( queryset_or_model , tag_instance ) ", "answer": "if not kwargs . has_key ( '' ) :"}, {"prompt": " \"\"\"\"\"\" import base64 import exceptions import hmac import json import logging import time from google . appengine . api import mail from google . appengine . ext import deferred from cauliflowervest . server import crypto from cauliflowervest . server import models from cauliflowervest . server import settings JSON_PREFIX = \"\" XSRF_DELIMITER = '' XSRF_VALID_TIME = def _Send ( recipients , subject , body , sender , reply_to , bcc_recipients ) : \"\"\"\"\"\" try : message = mail . EmailMessage ( to = recipients , sender = sender or settings . DEFAULT_EMAIL_SENDER , subject = subject , body = body ) if reply_to or settings . DEFAULT_EMAIL_REPLY_TO : message . reply_to = reply_to or settings . DEFAULT_EMAIL_REPLY_TO except mail . InvalidEmailError : logging . warning ( '' ) return if bcc_recipients : message . bcc = bcc_recipients message . send ( ) def SendEmail ( recipients , subject , body , sender = None , reply_to = None , bcc_recipients = None , defer = True ) : \"\"\"\"\"\" if settings . DEVELOPMENT : logging . warning ( '' ) logging . info ( '' , recipients , subject , body ) else : if defer : deferred . defer ( _Send , recipients , subject , body , sender , reply_to , bcc_recipients ) else : _Send ( recipients , subject , body , sender , reply_to , bcc_recipients ) def XsrfTokenGenerate ( action , user = None , timestamp = None ) : \"\"\"\"\"\" if not user : user = models . GetCurrentUser ( ) . email if not timestamp : timestamp = time . time ( ) timestr = str ( timestamp ) secret = crypto . ENCRYPTION_KEY_TYPES [ settings . KEY_TYPE_DEFAULT_XSRF ] ( ) h = hmac . new ( secret , XSRF_DELIMITER . join ( ( user , action , timestr ) ) ) return base64 . urlsafe_b64encode ( ", "answer": "'' . join ( ( h . digest ( ) , XSRF_DELIMITER , timestr ) ) )"}, {"prompt": " __author__ = \"\" ", "answer": "''''''"}, {"prompt": " import sys import traceback import copy import listservers import buckets import info import util_cli as util import mc_bin_client import stats_buffer class StatsCollector : def __init__ ( self , log ) : self . log = log def seg ( self , k , v ) : ka = k . split ( '' ) k = '' . join ( ka [ : - ] ) kstart , kend = [ int ( x ) for x in ka [ - ] . split ( '' ) ] return ( ( k , kstart , kend ) , int ( v ) ) def retrieve_node_stats ( self , nodeInfo , nodeStats ) : nodeStats [ '' ] = nodeInfo [ '' ] [ '' ] nodeStats [ '' ] = nodeInfo [ '' ] [ '' ] nodeStats [ '' ] = nodeInfo [ '' ] nodeStats [ '' ] = nodeInfo [ '' ] nodeStats [ '' ] = nodeInfo [ '' ] nodeStats [ '' ] = nodeInfo [ '' ] nodeStats [ '' ] = { } nodeStats [ '' ] [ '' ] = nodeInfo [ '' ] nodeStats [ '' ] [ '' ] = nodeInfo [ '' ] nodeStats [ '' ] [ '' ] = nodeInfo [ '' ] nodeStats [ '' ] [ '' ] = nodeInfo [ '' ] nodeStats [ '' ] [ '' ] = nodeInfo [ '' ] nodeStats [ '' ] = { } if nodeInfo [ '' ] is not None : hdd = nodeInfo [ '' ] [ '' ] if hdd is not None : nodeStats [ '' ] [ '' ] = { } nodeStats [ '' ] [ '' ] [ '' ] = hdd [ '' ] nodeStats [ '' ] [ '' ] [ '' ] = hdd [ '' ] nodeStats [ '' ] [ '' ] [ '' ] = hdd [ '' ] nodeStats [ '' ] [ '' ] [ '' ] = hdd [ '' ] nodeStats [ '' ] [ '' ] [ '' ] = hdd [ '' ] ram = nodeInfo [ '' ] [ '' ] if ram is not None : nodeStats [ '' ] [ '' ] = { } nodeStats [ '' ] [ '' ] [ '' ] = ram [ '' ] nodeStats [ '' ] [ '' ] [ '' ] = ram [ '' ] nodeStats [ '' ] [ '' ] [ '' ] = ram [ '' ] nodeStats [ '' ] [ '' ] [ '' ] = ram [ '' ] if ram . has_key ( '' ) : nodeStats [ '' ] [ '' ] [ '' ] = ram [ '' ] else : nodeStats [ '' ] [ '' ] [ '' ] = nodeStats [ '' ] = { } nodeStats [ '' ] [ '' ] = nodeInfo [ '' ] [ '' ] nodeStats [ '' ] [ '' ] = nodeInfo [ '' ] [ '' ] nodeStats [ '' ] [ '' ] = nodeInfo [ '' ] [ '' ] curr_items = curr_items_tot = vb_rep_curr_items = if nodeInfo [ '' ] is not None : if nodeInfo [ '' ] . has_key ( '' ) : curr_items = nodeInfo [ '' ] [ '' ] else : curr_items = if nodeInfo [ '' ] . has_key ( '' ) : curr_items_tot = nodeInfo [ '' ] [ '' ] else : curr_items_tot = if nodeInfo [ '' ] . has_key ( '' ) : vb_rep_curr_items = nodeInfo [ '' ] [ '' ] else : vb_rep_curr_items = nodeStats [ '' ] [ '' ] = curr_items nodeStats [ '' ] [ '' ] = curr_items_tot nodeStats [ '' ] [ '' ] = vb_rep_curr_items def get_hostlist ( self , server , port , user , password , opts ) : try : opts . append ( ( \"\" , \"\" ) ) nodes = listservers . ListServers ( ) . runCmd ( '' , server , port , user , password , opts ) for node in nodes : ( node_server , node_port ) = util . hostport ( node [ '' ] ) node_stats = { \"\" : node_server , \"\" : node_port , \"\" : node [ '' ] , \"\" : server } stats_buffer . nodes [ node [ '' ] ] = node_stats if node [ '' ] == '' : node_info = info . Info ( ) . runCmd ( '' , node_server , node_port , user , password , opts ) self . retrieve_node_stats ( node_info , node_stats ) else : self . log . error ( \"\" % ( node_server , node [ '' ] ) ) return nodes except Exception , err : traceback . print_exc ( ) sys . exit ( ) def get_bucketlist ( self , server , port , user , password , opts ) : try : bucketlist = buckets . Buckets ( ) . runCmd ( '' , server , port , user , password , opts ) for bucket in bucketlist : bucket_name = bucket [ '' ] self . log . info ( \"\" % bucket_name ) bucketinfo = { } bucketinfo [ '' ] = bucket_name bucketinfo [ '' ] = bucket [ '' ] bucketinfo [ '' ] = bucket [ '' ] bucketinfo [ '' ] = bucket [ '' ] bucketinfo [ '' ] = bucket [ '' ] bucketinfo [ '' ] = bucket [ '' ] [ '' ] bucketinfo [ '' ] = server bucketStats = bucket [ '' ] bucketinfo [ '' ] = { } bucketinfo [ '' ] [ '' ] = bucketStats [ '' ] bucketinfo [ '' ] [ '' ] = bucketStats [ '' ] bucketinfo [ '' ] [ '' ] = bucketStats [ '' ] bucketinfo [ '' ] [ '' ] = bucketStats [ '' ] bucketinfo [ '' ] [ '' ] = bucketStats [ '' ] bucketinfo [ '' ] [ '' ] = bucketStats [ '' ] stats_buffer . bucket_info [ bucket_name ] = bucketinfo c = buckets . BucketStats ( bucket_name ) json = c . runCmd ( '' , server , port , user , password , opts ) stats_buffer . buckets_summary [ bucket_name ] = json return bucketlist except Exception , err : traceback . print_exc ( ) sys . exit ( ) def get_mc_stats_per_node ( self , mc , stats ) : cmd_list = [ \"\" , \"\" , \"\" , \"\" , \"\" ] try : for cmd in cmd_list : node_stats = mc . stats ( cmd ) if node_stats : if cmd == \"\" : vals = sorted ( [ self . seg ( * kv ) for kv in node_stats . items ( ) ] ) dd = { } totals = { } longest = for s in vals : avg = ( s [ ] [ ] + s [ ] [ ] ) / k = s [ ] [ ] l = dd . get ( k , [ ] ) l . append ( ( avg , s [ ] ) ) dd [ k ] = l totals [ k ] = totals . get ( k , ) + s [ ] for k in sorted ( dd ) : ccount = for lbl , v in dd [ k ] : ccount += v * lbl stats [ k ] = ccount / totals [ k ] else : for key , val in node_stats . items ( ) : stats [ key ] = val except Exception , err : traceback . print_exc ( ) def get_mc_stats ( self , server , bucketlist , nodes ) : for bucket in bucketlist : bucket_name = bucket [ '' ] stats_buffer . node_stats [ bucket_name ] = { } for node in nodes : ( node_server , node_port ) = util . hostport ( node [ '' ] ) self . log . info ( \"\" % ( node_server , node [ '' ] [ '' ] ) ) stats = { } mc = mc_bin_client . MemcachedClient ( node_server , node [ '' ] [ '' ] ) if bucket [ \"\" ] != \"\" : mc . sasl_auth_plain ( bucket_name . encode ( \"\" ) , bucket [ \"\" ] . encode ( \"\" ) ) self . get_mc_stats_per_node ( mc , stats ) stats_buffer . node_stats [ bucket_name ] [ node [ '' ] ] = stats def get_ns_stats ( self , bucketlist , server , port , user , password , opts ) : for bucket in bucketlist : bucket_name = bucket [ '' ] stats_buffer . buckets [ bucket_name ] = copy . deepcopy ( stats_buffer . stats ) cmd = '' for scale , stat_set in stats_buffer . buckets [ bucket_name ] . iteritems ( ) : for stat in stat_set . iterkeys ( ) : sys . stderr . write ( '' ) self . log . debug ( \"\" % stat ) c = buckets . BucketNodeStats ( bucket_name , stat , scale ) json = c . runCmd ( '' , server , port , user , password , opts ) stats_buffer . buckets [ bucket_name ] [ scale ] [ stat ] = json sys . stderr . write ( '' ) def collect_data ( self , cluster , user , password , opts ) : server , port = util . hostport ( cluster ) nodes = self . get_hostlist ( server , port , user , password , opts ) self . log . debug ( util . pretty_print ( stats_buffer . nodes ) ) bucketlist = self . get_bucketlist ( server , port , user , password , opts ) self . log . debug ( util . pretty_print ( stats_buffer . bucket_info ) ) self . get_mc_stats ( server , bucketlist , nodes ) self . log . debug ( util . pretty_print ( stats_buffer . node_stats ) ) self . get_ns_stats ( bucketlist , server , port , user , password , opts ) ", "answer": "self . log . debug ( util . pretty_print ( stats_buffer . buckets ) ) "}, {"prompt": " from . common import * class Bookmark : def __init__ ( self , uid , name , window , activeView ) : self . uid = int ( uid ) self . name = str ( name ) self . filePath = str ( activeView . file_name ( ) ) self . projectPath = getCurrentProjectPath ( window ) region = getCurrentLineRegion ( activeView ) self . regionA = int ( region . a ) self . regionB = int ( region . b ) self . group = getCurrentActiveGroup ( window ) self . lineStr = activeView . substr ( region ) cursorPos = activeView . sel ( ) [ ] . begin ( ) self . lineNumber = activeView . rowcol ( cursorPos ) [ ] self . bufferID = activeView . buffer_id ( ) def getBufferID ( self ) : return self . bufferID def getName ( self ) : return self . name def getUid ( self ) : return self . uid def getRegion ( self ) : return sublime . Region ( self . regionA , self . regionB ) def getFilePath ( self ) : return self . filePath def getProjectPath ( self ) : return self . projectPath def getLineNumber ( self ) : return self . lineNumber def getLineStr ( self ) : return self . lineStr def getGroup ( self ) : ", "answer": "return self . group"}, {"prompt": " import logging import six import struct import time import json from ryu import cfg from ryu . topology import event from ryu . base import app_manager from ryu . controller import ofp_event from ryu . controller . handler import set_ev_cls from ryu . controller . handler import MAIN_DISPATCHER , DEAD_DISPATCHER from ryu . exception import RyuException from ryu . lib import addrconv , hub from ryu . lib . mac import DONTCARE_STR from ryu . lib . dpid import dpid_to_str , str_to_dpid from ryu . lib . port_no import port_no_to_str from ryu . lib . packet import packet , ethernet from ryu . lib . packet import lldp , ether_types from ryu . lib . packet import arp , ipv4 , ipv6 from ryu . ofproto . ether import ETH_TYPE_LLDP from ryu . ofproto import nx_match from ryu . ofproto import ofproto_v1_0 from ryu . ofproto import ofproto_v1_2 from ryu . ofproto import ofproto_v1_3 from ryu . ofproto import ofproto_v1_4 LOG = logging . getLogger ( __name__ ) CONF = cfg . CONF CONF . register_cli_opts ( [ cfg . BoolOpt ( '' , default = False , help = '' ) , cfg . BoolOpt ( '' , default = True , help = '' '' ) , cfg . BoolOpt ( '' , default = True , help = '' ) ] ) class Port ( object ) : def __init__ ( self , dpid , ofproto , ofpport ) : super ( Port , self ) . __init__ ( ) self . dpid = dpid self . _ofproto = ofproto self . _config = ofpport . config self . _state = ofpport . state self . port_no = ofpport . port_no self . hw_addr = ofpport . hw_addr self . name = ofpport . name def is_reserved ( self ) : return self . port_no > self . _ofproto . OFPP_MAX def is_down ( self ) : return ( self . _state & self . _ofproto . OFPPS_LINK_DOWN ) > or ( self . _config & self . _ofproto . OFPPC_PORT_DOWN ) > def is_live ( self ) : return not self . is_down ( ) def to_dict ( self ) : return { '' : dpid_to_str ( self . dpid ) , '' : port_no_to_str ( self . port_no ) , '' : self . hw_addr , '' : self . name . rstrip ( '' ) } def __eq__ ( self , other ) : return self . dpid == other . dpid and self . port_no == other . port_no def __ne__ ( self , other ) : return not self . __eq__ ( other ) def __hash__ ( self ) : return hash ( ( self . dpid , self . port_no ) ) def __str__ ( self ) : LIVE_MSG = { False : '' , True : '' } return '' % ( self . dpid , self . port_no , LIVE_MSG [ self . is_live ( ) ] ) class Switch ( object ) : def __init__ ( self , dp ) : super ( Switch , self ) . __init__ ( ) self . dp = dp self . ports = [ ] def add_port ( self , ofpport ) : port = Port ( self . dp . id , self . dp . ofproto , ofpport ) if not port . is_reserved ( ) : self . ports . append ( port ) def del_port ( self , ofpport ) : self . ports . remove ( Port ( ofpport ) ) def to_dict ( self ) : d = { '' : dpid_to_str ( self . dp . id ) , '' : [ port . to_dict ( ) for port in self . ports ] } return d def __str__ ( self ) : msg = '' % self . dp . id for port in self . ports : msg += str ( port ) + '' msg += '>' return msg class Link ( object ) : def __init__ ( self , src , dst ) : super ( Link , self ) . __init__ ( ) self . src = src self . dst = dst def to_dict ( self ) : d = { '' : self . src . to_dict ( ) , '' : self . dst . to_dict ( ) } return d def __eq__ ( self , other ) : return self . src == other . src and self . dst == other . dst def __ne__ ( self , other ) : return not self . __eq__ ( other ) def __hash__ ( self ) : return hash ( ( self . src , self . dst ) ) def __str__ ( self ) : return '' % ( self . src , self . dst ) class Host ( object ) : def __init__ ( self , mac , port ) : super ( Host , self ) . __init__ ( ) self . port = port self . mac = mac self . ipv4 = [ ] self . ipv6 = [ ] def to_dict ( self ) : d = { '' : self . mac , '' : self . ipv4 , '' : self . ipv6 , '' : self . port . to_dict ( ) } return d def __eq__ ( self , host ) : return self . mac == host . mac and self . port == host . port def __str__ ( self ) : msg = '' % ( self . mac , str ( self . port ) ) msg += '' . join ( self . ipv4 ) msg += '' . join ( self . ipv6 ) msg += '>' return msg class HostState ( dict ) : def __init__ ( self ) : super ( HostState , self ) . __init__ ( ) def add ( self , host ) : mac = host . mac self . setdefault ( mac , host ) def update_ip ( self , host , ip_v4 = None , ip_v6 = None ) : mac = host . mac host = None if mac in self : host = self [ mac ] if not host : return if ip_v4 != None : if ip_v4 in host . ipv4 : host . ipv4 . remove ( ip_v4 ) host . ipv4 . append ( ip_v4 ) if ip_v6 != None : if ip_v6 in host . ipv6 : host . ipv6 . remove ( ip_v6 ) host . ipv6 . append ( ip_v6 ) def get_by_dpid ( self , dpid ) : result = [ ] for mac in self : host = self [ mac ] if host . port . dpid == dpid : result . append ( host ) return result class PortState ( dict ) : def __init__ ( self ) : super ( PortState , self ) . __init__ ( ) def add ( self , port_no , port ) : self [ port_no ] = port def remove ( self , port_no ) : del self [ port_no ] def modify ( self , port_no , port ) : self [ port_no ] = port class PortData ( object ) : def __init__ ( self , is_down , lldp_data ) : super ( PortData , self ) . __init__ ( ) self . is_down = is_down self . lldp_data = lldp_data self . timestamp = None self . sent = ", "answer": "def lldp_sent ( self ) :"}, {"prompt": " \"\"\"\"\"\" import collections import logging import uuid import pika . frame as frame import pika . exceptions as exceptions import pika . spec as spec from pika . utils import is_callable from pika . compat import unicode_type , dictkeys , is_integer LOGGER = logging . getLogger ( __name__ ) MAX_CHANNELS = class Channel ( object ) : \"\"\"\"\"\" CLOSED = OPENING = OPEN = CLOSING = _STATE_NAMES = { CLOSED : '' , OPENING : '' , OPEN : '' , CLOSING : '' } _ON_CHANNEL_CLEANUP_CB_KEY = '' def __init__ ( self , connection , channel_number , on_open_callback ) : \"\"\"\"\"\" if not isinstance ( channel_number , int ) : raise exceptions . InvalidChannelNumber self . channel_number = channel_number self . callbacks = connection . callbacks self . connection = connection self . flow_active = True self . _content_assembler = ContentFrameAssembler ( ) self . _blocked = collections . deque ( list ( ) ) self . _blocking = None self . _has_on_flow_callback = False self . _cancelled = set ( ) self . _consumers = dict ( ) self . _consumers_with_noack = set ( ) self . _on_flowok_callback = None self . _on_getok_callback = None self . _on_openok_callback = on_open_callback self . _state = self . CLOSED self . _closing_code_and_text = ( , '' ) self . _cookie = None def __int__ ( self ) : \"\"\"\"\"\" return self . channel_number def __repr__ ( self ) : return '' % ( self . __class__ . __name__ , self . channel_number , self . _STATE_NAMES [ self . _state ] , self . connection ) def add_callback ( self , callback , replies , one_shot = True ) : \"\"\"\"\"\" for reply in replies : self . callbacks . add ( self . channel_number , reply , callback , one_shot ) def add_on_cancel_callback ( self , callback ) : \"\"\"\"\"\" self . callbacks . add ( self . channel_number , spec . Basic . Cancel , callback , False ) def add_on_close_callback ( self , callback ) : \"\"\"\"\"\" self . callbacks . add ( self . channel_number , '' , callback , False , self ) def add_on_flow_callback ( self , callback ) : \"\"\"\"\"\" self . _has_on_flow_callback = True self . callbacks . add ( self . channel_number , spec . Channel . Flow , callback , False ) def add_on_return_callback ( self , callback ) : \"\"\"\"\"\" self . callbacks . add ( self . channel_number , '' , callback , False ) def basic_ack ( self , delivery_tag = , multiple = False ) : \"\"\"\"\"\" if not self . is_open : raise exceptions . ChannelClosed ( ) return self . _send_method ( spec . Basic . Ack ( delivery_tag , multiple ) ) def basic_cancel ( self , callback = None , consumer_tag = '' , nowait = False ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) if nowait : if callback is not None : raise ValueError ( '' ) else : if callback is None : raise ValueError ( '' ) if consumer_tag in self . _cancelled : LOGGER . warning ( '' , consumer_tag ) return if consumer_tag not in self . _consumers : LOGGER . warning ( '' , consumer_tag ) return LOGGER . debug ( '' , consumer_tag , nowait ) if nowait : del self . _consumers [ consumer_tag ] if callback is not None : if nowait : raise ValueError ( '' ) self . callbacks . add ( self . channel_number , spec . Basic . CancelOk , callback ) self . _cancelled . add ( consumer_tag ) self . _rpc ( spec . Basic . Cancel ( consumer_tag = consumer_tag , nowait = nowait ) , self . _on_cancelok if not nowait else None , [ ( spec . Basic . CancelOk , { '' : consumer_tag } ) ] if nowait is False else [ ] ) def basic_consume ( self , consumer_callback , queue = '' , no_ack = False , exclusive = False , consumer_tag = None , arguments = None ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( consumer_callback ) if not consumer_tag : consumer_tag = self . _generate_consumer_tag ( ) if consumer_tag in self . _consumers or consumer_tag in self . _cancelled : raise exceptions . DuplicateConsumerTag ( consumer_tag ) if no_ack : self . _consumers_with_noack . add ( consumer_tag ) self . _consumers [ consumer_tag ] = consumer_callback self . _rpc ( spec . Basic . Consume ( queue = queue , consumer_tag = consumer_tag , no_ack = no_ack , exclusive = exclusive , arguments = arguments or dict ( ) ) , self . _on_eventok , [ ( spec . Basic . ConsumeOk , { '' : consumer_tag } ) ] ) return consumer_tag def _generate_consumer_tag ( self ) : \"\"\"\"\"\" return '' % ( self . channel_number , uuid . uuid4 ( ) . hex ) def basic_get ( self , callback = None , queue = '' , no_ack = False ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) if self . _on_getok_callback is not None : raise exceptions . DuplicateGetOkCallback ( ) self . _on_getok_callback = callback self . _send_method ( spec . Basic . Get ( queue = queue , no_ack = no_ack ) ) def basic_nack ( self , delivery_tag = None , multiple = False , requeue = True ) : \"\"\"\"\"\" if not self . is_open : raise exceptions . ChannelClosed ( ) return self . _send_method ( spec . Basic . Nack ( delivery_tag , multiple , requeue ) ) def basic_publish ( self , exchange , routing_key , body , properties = None , mandatory = False , immediate = False ) : \"\"\"\"\"\" if not self . is_open : raise exceptions . ChannelClosed ( ) if immediate : LOGGER . warning ( '' ) if isinstance ( body , unicode_type ) : body = body . encode ( '' ) properties = properties or spec . BasicProperties ( ) self . _send_method ( spec . Basic . Publish ( exchange = exchange , routing_key = routing_key , mandatory = mandatory , immediate = immediate ) , ( properties , body ) ) def basic_qos ( self , callback = None , prefetch_size = , prefetch_count = , all_channels = False ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) return self . _rpc ( spec . Basic . Qos ( prefetch_size , prefetch_count , all_channels ) , callback , [ spec . Basic . QosOk ] ) def basic_reject ( self , delivery_tag , requeue = True ) : \"\"\"\"\"\" if not self . is_open : raise exceptions . ChannelClosed ( ) if not is_integer ( delivery_tag ) : raise TypeError ( '' ) return self . _send_method ( spec . Basic . Reject ( delivery_tag , requeue ) ) def basic_recover ( self , callback = None , requeue = False ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) return self . _rpc ( spec . Basic . Recover ( requeue ) , callback , [ spec . Basic . RecoverOk ] ) def close ( self , reply_code = , reply_text = \"\" ) : \"\"\"\"\"\" if self . is_closed : raise exceptions . ChannelClosed ( '' % self ) if self . is_closing : raise exceptions . ChannelAlreadyClosing ( '' % self ) LOGGER . info ( '' , reply_code , reply_text , self ) for consumer_tag in dictkeys ( self . _consumers ) : if consumer_tag not in self . _cancelled : self . basic_cancel ( consumer_tag = consumer_tag ) self . _set_state ( self . CLOSING ) self . _rpc ( spec . Channel . Close ( reply_code , reply_text , , ) , self . _on_closeok , [ spec . Channel . CloseOk ] ) def confirm_delivery ( self , callback = None , nowait = False ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) if not ( self . connection . publisher_confirms and self . connection . basic_nack ) : raise exceptions . MethodNotImplemented ( '' ) if callback is not None : self . callbacks . add ( self . channel_number , spec . Basic . Ack , callback , False ) self . callbacks . add ( self . channel_number , spec . Basic . Nack , callback , False ) self . _rpc ( spec . Confirm . Select ( nowait ) , self . _on_selectok if not nowait else None , [ spec . Confirm . SelectOk ] if nowait is False else [ ] ) @ property def consumer_tags ( self ) : \"\"\"\"\"\" return dictkeys ( self . _consumers ) def exchange_bind ( self , callback = None , destination = None , source = None , routing_key = '' , nowait = False , arguments = None ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) return self . _rpc ( spec . Exchange . Bind ( , destination , source , routing_key , nowait , arguments or dict ( ) ) , callback , [ spec . Exchange . BindOk ] if nowait is False else [ ] ) def exchange_declare ( self , callback = None , exchange = None , exchange_type = '' , passive = False , durable = False , auto_delete = False , internal = False , nowait = False , arguments = None ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) return self . _rpc ( spec . Exchange . Declare ( , exchange , exchange_type , passive , durable , auto_delete , internal , nowait , arguments or dict ( ) ) , callback , [ spec . Exchange . DeclareOk ] if nowait is False else [ ] ) def exchange_delete ( self , callback = None , exchange = None , if_unused = False , nowait = False ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) return self . _rpc ( spec . Exchange . Delete ( , exchange , if_unused , nowait ) , callback , [ spec . Exchange . DeleteOk ] if nowait is False else [ ] ) def exchange_unbind ( self , callback = None , destination = None , source = None , routing_key = '' , nowait = False , arguments = None ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) return self . _rpc ( spec . Exchange . Unbind ( , destination , source , routing_key , nowait , arguments ) , callback , [ spec . Exchange . UnbindOk ] if nowait is False else [ ] ) def flow ( self , callback , active ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) self . _on_flowok_callback = callback self . _rpc ( spec . Channel . Flow ( active ) , self . _on_flowok , [ spec . Channel . FlowOk ] ) @ property def is_closed ( self ) : \"\"\"\"\"\" return self . _state == self . CLOSED @ property def is_closing ( self ) : \"\"\"\"\"\" return self . _state == self . CLOSING @ property def is_open ( self ) : \"\"\"\"\"\" return self . _state == self . OPEN def open ( self ) : \"\"\"\"\"\" self . _set_state ( self . OPENING ) self . _add_callbacks ( ) self . _rpc ( spec . Channel . Open ( ) , self . _on_openok , [ spec . Channel . OpenOk ] ) def queue_bind ( self , callback , queue , exchange , routing_key = None , nowait = False , arguments = None ) : \"\"\"\"\"\" self . _validate_channel_and_callback ( callback ) replies = [ spec . Queue . BindOk ] if nowait is False else [ ] if routing_key is None : routing_key = queue return self . _rpc ( spec . Queue . Bind ( , queue , exchange , routing_key , nowait , arguments or dict ( ) ) , callback , replies ) def queue_declare ( self , callback , queue = '' , passive = False , durable = False , exclusive = False , auto_delete = False , nowait = False , arguments = None ) : \"\"\"\"\"\" if queue : condition = ( spec . Queue . DeclareOk , { '' : queue } ) else : condition = spec . Queue . DeclareOk replies = [ condition ] if nowait is False else [ ] self . _validate_channel_and_callback ( callback ) return self . _rpc ( spec . Queue . Declare ( , queue , passive , durable , exclusive , auto_delete , nowait , arguments or dict ( ) ) , callback , replies ) def queue_delete ( self , callback = None , queue = '' , if_unused = False , if_empty = False , nowait = False ) : \"\"\"\"\"\" replies = [ spec . Queue . DeleteOk ] if nowait is False else [ ] self . _validate_channel_and_callback ( callback ) return self . _rpc ( spec . Queue . Delete ( , queue , if_unused , if_empty , nowait ) , callback , replies ) def queue_purge ( self , callback = None , queue = '' , nowait = False ) : \"\"\"\"\"\" replies = [ spec . Queue . PurgeOk ] if nowait is False else [ ] self . _validate_channel_and_callback ( callback ) ", "answer": "return self . _rpc ( spec . Queue . Purge ( , queue , nowait ) , callback , replies )"}, {"prompt": " from ethereum import tester import hydrachain . native_contracts as nc from fungible_contract import IOU import ethereum . slogging as slogging log = slogging . get_logger ( '' ) def test_iou_template ( ) : \"\"\"\"\"\" nc . registry . register ( IOU ) state = tester . state ( ) logs = [ ] issuer_address = tester . a0 issuer_key = tester . k0 for evt_class in IOU . events : ", "answer": "nc . listen_logs ( state , evt_class , callback = lambda e : logs . append ( e ) )"}, {"prompt": " from unittest . mock import MagicMock import pytest class TestAnnotate : @ pytest . fixture def annotate ( self ) : from palladium . interfaces import annotate return annotate def test_with_existing_data ( self , annotate ) : model = MagicMock ( __metadata__ = { '' : , '' : } ) annotate ( model , { '' : '' } ) assert model . __metadata__ [ '' ] == '' assert model . __metadata__ [ '' ] == assert annotate ( model ) == { '' : '' , '' : } def test_without_existing_data ( self , annotate ) : ", "answer": "model = TestAnnotate ( )"}, {"prompt": " class FilterBase : def __init__ ( self , verbose ) : self . verbose = verbose def filter_css ( self , css ) : raise NotImplementedError ", "answer": "def filter_js ( self , js ) :"}, {"prompt": " \"\"\"\"\"\" import ast import sys import _pytest . _code import py from _pytest . assertion import util u = py . builtin . _totext class AssertionError ( util . BuiltinAssertionError ) : def __init__ ( self , * args ) : util . BuiltinAssertionError . __init__ ( self , * args ) if args : if len ( args ) > : toprint = args else : toprint = args [ ] try : self . msg = u ( toprint ) except Exception : self . msg = u ( \"\" % ( toprint . __class__ , id ( toprint ) ) ) else : f = _pytest . _code . Frame ( sys . _getframe ( ) ) try : source = f . code . fullsource if source is not None : try : source = source . getstatement ( f . lineno , assertion = True ) except IndexError : source = None else : source = str ( source . deindent ( ) ) . strip ( ) except py . error . ENOENT : source = None if source : self . msg = reinterpret ( source , f , should_fail = True ) else : self . msg = \"\" if not self . args : self . args = ( self . msg , ) if sys . version_info > ( , ) : AssertionError . __module__ = \"\" if sys . platform . startswith ( \"\" ) : _exprs = ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) _stmts = ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) _expr_nodes = set ( getattr ( ast , name ) for name in _exprs ) _stmt_nodes = set ( getattr ( ast , name ) for name in _stmts ) def _is_ast_expr ( node ) : return node . __class__ in _expr_nodes def _is_ast_stmt ( node ) : return node . __class__ in _stmt_nodes else : def _is_ast_expr ( node ) : return isinstance ( node , ast . expr ) def _is_ast_stmt ( node ) : return isinstance ( node , ast . stmt ) try : _Starred = ast . Starred except AttributeError : class _Starred ( object ) : pass class Failure ( Exception ) : \"\"\"\"\"\" def __init__ ( self , explanation = \"\" ) : self . cause = sys . exc_info ( ) self . explanation = explanation def reinterpret ( source , frame , should_fail = False ) : mod = ast . parse ( source ) visitor = DebugInterpreter ( frame ) try : visitor . visit ( mod ) except Failure : failure = sys . exc_info ( ) [ ] return getfailure ( failure ) if should_fail : return ( \"\" \"\" \"\" ) def run ( offending_line , frame = None ) : if frame is None : frame = _pytest . _code . Frame ( sys . _getframe ( ) ) return reinterpret ( offending_line , frame ) def getfailure ( e ) : explanation = util . format_explanation ( e . explanation ) value = e . cause [ ] if str ( value ) : lines = explanation . split ( '' ) lines [ ] += \"\" % ( value , ) explanation = '' . join ( lines ) text = \"\" % ( e . cause [ ] . __name__ , explanation ) if text . startswith ( '' ) : text = text [ : ] return text operator_map = { ast . BitOr : \"\" , ast . BitXor : \"\" , ast . BitAnd : \"\" , ast . LShift : \"\" , ast . RShift : \"\" , ast . Add : \"\" , ast . Sub : \"\" , ast . Mult : \"\" , ast . Div : \"\" , ast . FloorDiv : \"\" , ast . Mod : \"\" , ast . Eq : \"\" , ast . NotEq : \"\" , ast . Lt : \"\" , ast . LtE : \"\" , ast . Gt : \">\" , ast . GtE : \"\" , ast . Pow : \"\" , ast . Is : \"\" , ast . IsNot : \"\" , ast . In : \"\" , ast . NotIn : \"\" } unary_map = { ast . Not : \"\" , ast . Invert : \"\" , ast . USub : \"\" , ast . UAdd : \"\" } class DebugInterpreter ( ast . NodeVisitor ) : \"\"\"\"\"\" def __init__ ( self , frame ) : self . frame = frame def generic_visit ( self , node ) : if _is_ast_expr ( node ) : mod = ast . Expression ( node ) co = self . _compile ( mod ) try : result = self . frame . eval ( co ) except Exception : raise Failure ( ) explanation = self . frame . repr ( result ) return explanation , result elif _is_ast_stmt ( node ) : mod = ast . Module ( [ node ] ) co = self . _compile ( mod , \"\" ) try : self . frame . exec_ ( co ) except Exception : raise Failure ( ) return None , None else : raise AssertionError ( \"\" % ( node , ) ) def _compile ( self , source , mode = \"\" ) : return compile ( source , \"\" , mode ) def visit_Expr ( self , expr ) : return self . visit ( expr . value ) def visit_Module ( self , mod ) : for stmt in mod . body : self . visit ( stmt ) def visit_Name ( self , name ) : explanation , result = self . generic_visit ( name ) source = \"\" % ( name . id , ) co = self . _compile ( source ) try : local = self . frame . eval ( co ) except Exception : local = None if local is None or not self . frame . is_true ( local ) : return name . id , result return explanation , result def visit_Compare ( self , comp ) : left = comp . left left_explanation , left_result = self . visit ( left ) for op , next_op in zip ( comp . ops , comp . comparators ) : next_explanation , next_result = self . visit ( next_op ) op_symbol = operator_map [ op . __class__ ] explanation = \"\" % ( left_explanation , op_symbol , next_explanation ) source = \"\" % ( op_symbol , ) co = self . _compile ( source ) try : result = self . frame . eval ( co , __exprinfo_left = left_result , __exprinfo_right = next_result ) except Exception : raise Failure ( explanation ) try : if not self . frame . is_true ( result ) : break except KeyboardInterrupt : raise except : break left_explanation , left_result = next_explanation , next_result if util . _reprcompare is not None : res = util . _reprcompare ( op_symbol , left_result , next_result ) if res : explanation = res return explanation , result def visit_BoolOp ( self , boolop ) : is_or = isinstance ( boolop . op , ast . Or ) explanations = [ ] for operand in boolop . values : explanation , result = self . visit ( operand ) explanations . append ( explanation ) if result == is_or : break name = is_or and \"\" or \"\" explanation = \"\" + name . join ( explanations ) + \"\" return explanation , result def visit_UnaryOp ( self , unary ) : pattern = unary_map [ unary . op . __class__ ] operand_explanation , operand_result = self . visit ( unary . operand ) explanation = pattern % ( operand_explanation , ) co = self . _compile ( pattern % ( \"\" , ) ) try : result = self . frame . eval ( co , __exprinfo_expr = operand_result ) except Exception : raise Failure ( explanation ) return explanation , result def visit_BinOp ( self , binop ) : left_explanation , left_result = self . visit ( binop . left ) right_explanation , right_result = self . visit ( binop . right ) symbol = operator_map [ binop . op . __class__ ] explanation = \"\" % ( left_explanation , symbol , right_explanation ) source = \"\" % ( symbol , ) co = self . _compile ( source ) try : result = self . frame . eval ( co , __exprinfo_left = left_result , __exprinfo_right = right_result ) except Exception : raise Failure ( explanation ) return explanation , result def visit_Call ( self , call ) : func_explanation , func = self . visit ( call . func ) arg_explanations = [ ] ns = { \"\" : func } arguments = [ ] for arg in call . args : arg_explanation , arg_result = self . visit ( arg ) if isinstance ( arg , _Starred ) : arg_name = \"\" ns [ arg_name ] = arg_result arguments . append ( \"\" % ( arg_name , ) ) arg_explanations . append ( \"\" % ( arg_explanation , ) ) ", "answer": "else :"}, {"prompt": " import os from urlparse import urlparse from lockfile import FileLock ", "answer": "from . import CatalogCoordinator"}, {"prompt": " from xlwt import * w = Workbook ( ) ws = w . add_sheet ( '' ) for i in range ( , ) : ", "answer": "fnt = Font ( )"}, {"prompt": " \"\"\"\"\"\" from django . contrib . messages import constants as message_constants import os from configurations import Configuration , values import redis class Common ( Configuration ) : from mongoengine import connect connect ( '' ) BASE_DIR = os . path . dirname ( os . path . dirname ( __file__ ) ) SECRET_KEY = values . SecretValue ( ) API_KEY = \"\" DEBUG = values . BooleanValue ( False ) TEMPLATE_DEBUG = values . BooleanValue ( DEBUG ) ALLOWED_HOSTS = [ ] INSTALLED_APPS = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ) BOWER_INSTALLED_APPS = ( '' , '' , '' , '' , '' , '' , '' , ) MIDDLEWARE_CLASSES = ( '' , '' , '' , '' , '' , '' , '' , ) TEMPLATE_CONTEXT_PROCESSORS = ( '' , '' , ) ROOT_URLCONF = '' WSGI_APPLICATION = '' DATABASES = { '' : { '' : '' , '' : '' , } } SESSION_ENGINE = '' SESSION_SERIALIZER = '' LANGUAGE_CODE = '' TIME_ZONE = '' USE_I18N = True ", "answer": "USE_L10N = True"}, {"prompt": " \"\"\"\"\"\" import sys import mock from mox3 import mox from oslo_concurrency import processutils from oslo_config import cfg from oslo_service import service as _service import testtools from nova import exception from nova import manager from nova import objects from nova import rpc from nova import service from nova import test from nova . tests . unit import utils from nova import wsgi test_service_opts = [ cfg . StrOpt ( \"\" , default = \"\" , help = \"\" ) , cfg . StrOpt ( \"\" , default = '' , help = \"\" ) , cfg . IntOpt ( \"\" , default = , help = \"\" ) , ] CONF = cfg . CONF CONF . register_opts ( test_service_opts ) class FakeManager ( manager . Manager ) : \"\"\"\"\"\" def test_method ( self ) : return '' class ExtendedService ( service . Service ) : def test_method ( self ) : return '' class ServiceManagerTestCase ( test . NoDBTestCase ) : \"\"\"\"\"\" def test_message_gets_to_manager ( self ) : serv = service . Service ( '' , '' , '' , '' ) self . assertEqual ( '' , serv . test_method ( ) ) def test_override_manager_method ( self ) : serv = ExtendedService ( '' , '' , '' , ", "answer": "'' )"}, {"prompt": " \"\"\"\"\"\" from setuptools import setup setup ( name = '' , version = '' , url = '' , license = '' , author = '' , author_email = '' , description = '' , long_description = __doc__ , py_modules = [ '' ] , ", "answer": "zip_safe = False ,"}, {"prompt": " \"\"\"\"\"\" from . . common . behaviors_test import * from cloudcafe . blockstorage . volumes_api . v1 . behaviors import VolumesAPI_Behaviors from cloudcafe . blockstorage . volumes_api . v1 . models import requests , responses ", "answer": "from cloudcafe . blockstorage . volumes_api . v1 . client import VolumesClient "}, {"prompt": " '''''' import tensorflow as tf import numpy import input_data mnist = input_data . read_data_sets ( \"\" , one_hot = True ) learning_rate = training_epochs = batch_size = display_step = x = tf . placeholder ( \"\" , [ None , ] , name = '' ) y = tf . placeholder ( \"\" , [ None , ] , name = '' ) W = tf . Variable ( tf . zeros ( [ , ] ) , name = \"\" ) b = tf . Variable ( tf . zeros ( [ ] ) , name = \"\" ) activation = tf . nn . softmax ( tf . matmul ( x , W ) + b ) cost = - tf . reduce_sum ( y * tf . log ( activation ) ) optimizer = tf . train . GradientDescentOptimizer ( learning_rate ) . minimize ( cost ) init = tf . initialize_all_variables ( ) with tf . Session ( ) as sess : sess . run ( init ) summary_writer = tf . train . SummaryWriter ( '' , graph_def = sess . graph_def ) for epoch in range ( training_epochs ) : avg_cost = total_batch = int ( mnist . train . num_examples / batch_size ) for i in range ( total_batch ) : batch_xs , batch_ys = mnist . train . next_batch ( batch_size ) sess . run ( optimizer , feed_dict = { x : batch_xs , y : batch_ys } ) avg_cost += sess . run ( cost , feed_dict = { x : batch_xs , y : batch_ys } ) / total_batch if epoch % display_step == : print \"\" , '' % ( epoch + ) , \"\" , \"\" . format ( avg_cost ) print \"\" correct_prediction = tf . equal ( tf . argmax ( activation , ) , tf . argmax ( y , ) ) ", "answer": "accuracy = tf . reduce_mean ( tf . cast ( correct_prediction , \"\" ) )"}, {"prompt": " import os import sys import codecs import glob base_path = os . path . split ( __file__ ) [ ] if os . path . exists ( os . path . join ( base_path , '' ) ) : test_dir = os . path . join ( base_path , '' ) else : test_dir = os . path . abspath ( os . path . join ( base_path , os . path . pardir , os . path . pardir , os . path . pardir , '' ) ) assert os . path . exists ( test_dir ) , \"\" sys . path . insert ( , os . path . abspath ( os . path . join ( base_path , os . path . pardir , os . path . pardir ) ) ) import html5lib from html5lib import html5parser , treebuilders del base_path treeTypes = { \"\" : treebuilders . getTreeBuilder ( \"\" ) , \"\" : treebuilders . getTreeBuilder ( \"\" ) } try : import xml . etree . ElementTree as ElementTree treeTypes [ '' ] = treebuilders . getTreeBuilder ( \"\" , ElementTree , fullTree = True ) except ImportError : try : import elementtree . ElementTree as ElementTree treeTypes [ '' ] = treebuilders . getTreeBuilder ( \"\" , ElementTree , fullTree = True ) except ImportError : pass try : import xml . etree . cElementTree as cElementTree treeTypes [ '' ] = treebuilders . getTreeBuilder ( \"\" , cElementTree , fullTree = True ) except ImportError : try : import cElementTree treeTypes [ '' ] = treebuilders . getTreeBuilder ( \"\" , cElementTree , fullTree = True ) except ImportError : pass try : import lxml . etree as lxml treeTypes [ '' ] = treebuilders . getTreeBuilder ( \"\" , lxml , fullTree = True ) except ImportError : pass try : import BeautifulSoup treeTypes [ \"\" ] = treebuilders . getTreeBuilder ( \"\" , fullTree = True ) except ImportError : pass def html5lib_test_files ( subdirectory , files = '' ) : return glob . glob ( os . path . join ( test_dir , subdirectory , files ) ) class DefaultDict ( dict ) : def __init__ ( self , default , * args , ** kwargs ) : self . default = default dict . __init__ ( self , * args , ** kwargs ) def __getitem__ ( self , key ) : return dict . get ( self , key , self . default ) class TestData ( object ) : def __init__ ( self , filename , newTestHeading = \"\" ) : self . f = codecs . open ( filename , encoding = \"\" ) self . newTestHeading = newTestHeading def __iter__ ( self ) : data = DefaultDict ( None ) key = None for line in self . f : heading = self . isSectionHeading ( line ) if heading : if data and heading == self . newTestHeading : data [ key ] = data [ key ] [ : - ] yield self . normaliseOutput ( data ) data = DefaultDict ( None ) key = heading data [ key ] = \"\" elif key is not None : data [ key ] += line if data : yield self . normaliseOutput ( data ) def isSectionHeading ( self , line ) : \"\"\"\"\"\" if line . startswith ( \"\" ) : return line [ : ] . strip ( ) else : return False def normaliseOutput ( self , data ) : for key , value in data . iteritems ( ) : if value . endswith ( \"\" ) : data [ key ] = value [ : - ] return data def convert ( stripChars ) : def convertData ( data ) : \"\"\"\"\"\" data = data . split ( \"\" ) rv = [ ] for line in data : if line . startswith ( \"\" ) : rv . append ( line [ stripChars : ] ) else : rv . append ( line ) ", "answer": "return \"\" . join ( rv )"}, {"prompt": " from django . contrib . sites . models import Site from django . db import models from django . utils . encoding import python_2_unicode_compatible from django . utils . translation import ugettext_lazy as _ @ python_2_unicode_compatible class Redirect ( models . Model ) : site = models . ForeignKey ( Site , models . CASCADE , verbose_name = _ ( '' ) ) old_path = models . CharField ( _ ( '' ) , max_length = , db_index = True , help_text = _ ( \"\" ) , ", "answer": ")"}, {"prompt": " import genie2 . client . wrapper import genie2 . model . ClusterCriteria import genie2 . model . Job import genie2 . model . FileAttachment import time genie = genie2 . client . wrapper . Genie2 ( \"\" , genie2 . client . wrapper . RetryPolicy ( tries = , none_on_404 = True , no_retry_http_codes = range ( , ) ) ) job = genie2 . model . Job . Job ( ) job . name = \"\" job . user = \"\" job . version = \"\" job . clusterCriterias = list ( ) cluster_criteria = genie2 . model . ClusterCriteria . ClusterCriteria ( ) criteria = set ( ) criteria . add ( \"\" ) criteria . add ( \"\" ) cluster_criteria . tags = criteria job . clusterCriterias . append ( cluster_criteria ) command_criteria = set ( ) command_criteria . add ( \"\" ) job . commandCriteria = command_criteria job . fileDependencies = \"\" job . commandArgs = \"\" job = genie . submitJob ( job ) ", "answer": "while job . status != \"\" and job . status != \"\" and job . status != \"\" :"}, {"prompt": " import numpy as np from scipy import linalg , fftpack from . io . pick import pick_types , pick_channels from . io . base import _BaseRaw from . io . constants import FIFF from . forward import ( _magnetic_dipole_field_vec , _create_meg_coils , _concatenate_coils , _read_coil_defs ) from . cov import make_ad_hoc_cov , _get_whitener_data from . transforms import ( apply_trans , invert_transform , _angle_between_quats , quat_to_rot , rot_to_quat ) from . utils import ( verbose , logger , check_version , use_log_level , deprecated , _check_fname , warn ) from . fixes import partial from . externals . six import string_types @ deprecated ( '' '' '' ) @ verbose def get_chpi_positions ( raw , t_step = None , return_quat = False , verbose = None ) : \"\"\"\"\"\" if isinstance ( raw , _BaseRaw ) : if t_step is None : t_step = t_step = float ( t_step ) picks = pick_types ( raw . info , meg = False , ref_meg = False , chpi = True , exclude = [ ] ) if len ( picks ) == : raise RuntimeError ( '' ) time_idx = raw . time_as_index ( np . arange ( , raw . times [ - ] , t_step ) ) data = [ raw [ picks , ti ] for ti in time_idx ] t = np . array ( [ d [ ] for d in data ] ) data = np . array ( [ d [ ] [ : , ] for d in data ] ) data = np . c_ [ t , data ] else : if not isinstance ( raw , string_types ) : raise TypeError ( '' ) if t_step is not None : raise ValueError ( '' ) data = read_head_pos ( raw ) out = head_pos_to_trans_rot_t ( data ) if return_quat : out = out + ( data [ : , : ] , ) return out def read_head_pos ( fname ) : \"\"\"\"\"\" _check_fname ( fname , must_exist = True , overwrite = True ) data = np . loadtxt ( fname , skiprows = ) data . shape = ( - , ) return data def write_head_pos ( fname , pos ) : \"\"\"\"\"\" _check_fname ( fname , overwrite = True ) pos = np . array ( pos , np . float64 ) ", "answer": "if pos . ndim != or pos . shape [ ] != :"}, {"prompt": " import os import re from tproxy import config from tproxy . util import parse_address try : import simplejson as json except ImportError : import json from . util import base_uri , get_host ROUTE_RE = re . compile ( \"\" ) def validate_path ( value ) : if value is not None and not os . path . exists ( value ) : raise IOError ( \"\" % value ) return value class SpoolDir ( config . Setting ) : name = \"\" section = \"\" cli = [ \"\" , \"\" ] meta = \"\" validator = validate_path default = None desc = \"\"\"\"\"\" class Hostname ( config . Setting ) : name = \"\" section = \"\" cli = [ \"\" ] meta = \"\" validator = config . validate_string default = None ", "answer": "desc = \"\"\"\"\"\""}, {"prompt": " from __future__ import absolute_import , division , print_function , unicode_literals \"\"\"\"\"\" import math , random import demo import pi3d DISPLAY = pi3d . Display . create ( ) DISPLAY . set_background ( , , , ) mylight = pi3d . Light ( lightpos = ( - , - , ) , lightcol = ( , , ) , lightamb = ( , , ) ) CAMERA = pi3d . Camera . instance ( ) shader = pi3d . Shader ( \"\" ) shinesh = pi3d . Shader ( \"\" ) flatsh = pi3d . Shader ( \"\" ) tree2img = pi3d . Texture ( \"\" ) tree1img = pi3d . Texture ( \"\" ) hb2img = pi3d . Texture ( \"\" ) bumpimg = pi3d . Texture ( \"\" ) reflimg = pi3d . Texture ( \"\" ) rockimg = pi3d . Texture ( \"\" ) FOG = ( ( , , , ) , ) TFOG = ( ( , , , ) , ) ectex = pi3d . loadECfiles ( \"\" , \"\" ) myecube = pi3d . EnvironmentCube ( size = , maptype = \"\" , name = \"\" ) myecube . set_draw_details ( flatsh , ectex ) mapwidth = mapdepth = mapheight = mountimg1 = pi3d . Texture ( \"\" ) mymap = pi3d . ElevationMap ( \"\" , name = \"\" , width = mapwidth , depth = mapdepth , height = mapheight , divx = , divy = ) mymap . set_draw_details ( shader , [ mountimg1 , bumpimg , bumpimg ] , , ) mymap . set_fog ( * FOG ) treeplane = pi3d . Plane ( w = , h = ) treemodel1 = pi3d . MergeShape ( name = \"\" ) treemodel1 . merge ( [ [ treeplane , , , , , , , , , ] , [ treeplane , , , , , , , , , ] ] ) treemodel2 = pi3d . MergeShape ( name = \"\" ) treemodel2 . merge ( [ [ treeplane , , , , , , , , , ] , [ treeplane , , , , , , , , , ] , [ treeplane , , , , , , , , , ] ] ) mytrees1 = pi3d . MergeShape ( name = \"\" ) mytrees1 . cluster ( treemodel1 . buf [ ] , mymap , , , , , , \"\" , , ) mytrees1 . set_draw_details ( flatsh , [ tree2img ] , , ) mytrees1 . set_fog ( * TFOG ) mytrees2 = pi3d . MergeShape ( name = \"\" ) mytrees2 . cluster ( treemodel2 . buf [ ] , mymap , , , , , , \"\" , , ) mytrees2 . set_draw_details ( flatsh , [ tree1img ] , , ) mytrees2 . set_fog ( * TFOG ) mytrees3 = pi3d . MergeShape ( name = \"\" ) mytrees3 . cluster ( treemodel2 , mymap , , , , , , \"\" , , ) mytrees3 . set_draw_details ( flatsh , [ hb2img ] , , ) mytrees3 . set_fog ( * TFOG ) myplane = pi3d . Plane ( h = , w = ) myplane . set_draw_details ( shinesh , [ rockimg , bumpimg , reflimg ] , , ) xrot , yrot , zrot = , , dxrot , dyrot , dzrot = , , radius = angle = rotn = elev = scshots = rot = tilt = avhgt = xm = zm = ym = mymap . calcHeight ( xm , zm ) + avhgt myshadows = pi3d . ShadowCaster ( position = [ xm , ym , zm ] , light = mylight ) mykeys = pi3d . Keyboard ( ) mymouse = pi3d . Mouse ( restrict = False ) mymouse . start ( ) omx , omy = mymouse . position ( ) while DISPLAY . loop_running ( ) : CAMERA . reset ( ) CAMERA . rotate ( tilt , rot , ) CAMERA . position ( ( xm , ym , zm ) ) xrot += dxrot yrot += dyrot zrot += dzrot angle += rotn myplane . position ( radius * math . cos ( angle ) - radius , elev , radius * math . sin ( angle ) ) myplane . rotateToX ( xrot ) myplane . rotateToY ( yrot ) myplane . rotateToZ ( zrot ) myshadows . start_cast ( [ xm , ym , zm ] ) myshadows . cast_shadow ( mytrees1 ) myshadows . cast_shadow ( mytrees2 ) myshadows . cast_shadow ( mytrees3 ) myshadows . cast_shadow ( myplane ) myshadows . cast_shadow ( mymap ) myshadows . end_cast ( ) myplane . draw ( ) mymap . draw ( shader , [ mountimg1 , bumpimg , myshadows ] , , , light_camera = myshadows . LIGHT_CAM ) myecube . draw ( ) mytrees2 . draw ( ) mytrees3 . draw ( ) mytrees1 . draw ( ) mx , my = mymouse . position ( ) rot -= ( mx - omx ) * tilt += ( my - omy ) * omx = mx omy = my k = mykeys . read ( ) if k > - : if k == : xm -= math . sin ( math . radians ( rot ) ) zm += math . cos ( math . radians ( rot ) ) ym = mymap . calcHeight ( xm , zm ) + avhgt elif k == : xm += math . sin ( math . radians ( rot ) ) zm -= math . cos ( math . radians ( rot ) ) ym = mymap . calcHeight ( xm , zm ) + avhgt elif k == : tilt -= elif k == : ", "answer": "tilt += "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " from django . conf . urls import url ", "answer": "from oscar . apps . promotions . models import KeywordPromotion , PagePromotion"}, {"prompt": " import xmlrpclib class SafeTransportWithCert ( xmlrpclib . SafeTransport ) : def __init__ ( self , use_datetime = , keyfile = None , certfile = None ) : xmlrpclib . SafeTransport . __init__ ( self , use_datetime ) self . __x509 = dict ( ) if keyfile : self . __x509 [ '' ] = keyfile if certfile : ", "answer": "self . __x509 [ '' ] = certfile"}, {"prompt": " from nose . tools import ok_ import unittest from db . models import ComradeBaseModel def check_direct_to_template ( prefix , pattern ) : from django import test ", "answer": "from django . core . urlresolvers import reverse"}, {"prompt": " import sys import os import nibabel try : import numpydoc except ImportError : raise RuntimeError ( '' ) try : import texext except ImportError : raise RuntimeError ( '' ) sys . path . append ( os . path . abspath ( '' ) ) rel = { } with open ( os . path . join ( '' , '' , '' , '' ) , '' ) as fobj : exec ( fobj . read ( ) , rel ) with open ( '' , '' ) as fobj : fobj . write ( rel [ '' ] ) extensions = [ '' , '' , ", "answer": "'' ,"}, {"prompt": " '''''' from __future__ import print_function from keras . models import Sequential from keras . layers . core import Dense , Dropout , Layer , Activation from keras . datasets import mnist from keras import backend as K from keras . utils import np_utils class Antirectifier ( Layer ) : '''''' def get_output_shape_for ( self , input_shape ) : shape = list ( input_shape ) assert len ( shape ) == shape [ - ] *= return tuple ( shape ) def call ( self , x , mask = None ) : x -= K . mean ( x , axis = , keepdims = True ) x = K . l2_normalize ( x , axis = ) pos = K . relu ( x ) neg = K . relu ( - x ) return K . concatenate ( [ pos , neg ] , axis = ) batch_size = nb_classes = nb_epoch = ( X_train , y_train ) , ( X_test , y_test ) = mnist . load_data ( ) X_train = X_train . reshape ( , ) X_test = X_test . reshape ( , ) X_train = X_train . astype ( '' ) X_test = X_test . astype ( '' ) X_train /= X_test /= print ( X_train . shape [ ] , '' ) print ( X_test . shape [ ] , '' ) Y_train = np_utils . to_categorical ( y_train , nb_classes ) Y_test = np_utils . to_categorical ( y_test , nb_classes ) model = Sequential ( ) model . add ( Dense ( , input_shape = ( , ) ) ) model . add ( Antirectifier ( ) ) model . add ( Dropout ( ) ) model . add ( Dense ( ) ) model . add ( Antirectifier ( ) ) model . add ( Dropout ( ) ) model . add ( Dense ( ) ) model . add ( Activation ( '' ) ) model . compile ( loss = '' , optimizer = '' , metrics = [ '' ] ) model . fit ( X_train , Y_train , ", "answer": "batch_size = batch_size , nb_epoch = nb_epoch ,"}, {"prompt": " from __future__ import unicode_literals from django . conf import settings from django . contrib . gis . maps . google . overlays import ( GMarker , GPolygon , GPolyline , ) from django . template . loader import render_to_string from django . utils . html import format_html from django . utils . safestring import mark_safe from django . utils . six . moves import range class GoogleMapException ( Exception ) : pass GOOGLE_MAPS_URL = '' class GoogleMap ( object ) : \"\" onunload = mark_safe ( '' ) vml_css = mark_safe ( '' ) xmlns = mark_safe ( '' ) def __init__ ( self , key = None , api_url = None , version = None , center = None , zoom = None , dom_id = '' , kml_urls = [ ] , polylines = None , polygons = None , markers = None , template = '' , js_module = '' , extra_context = { } ) : if not key : try : self . key = settings . GOOGLE_MAPS_API_KEY except AttributeError : raise GoogleMapException ( '' '' ) else : self . key = key if not version : self . version = getattr ( settings , '' , '' ) else : self . version = version if not api_url : self . api_url = getattr ( settings , '' , GOOGLE_MAPS_URL ) % self . version else : self . api_url = api_url self . dom_id = dom_id self . extra_context = extra_context self . js_module = js_module self . template = template self . kml_urls = kml_urls overlay_info = [ [ GMarker , markers , '' ] , [ GPolygon , polygons , '' ] , [ GPolyline , polylines , '' ] ] for overlay_class , overlay_list , varname in overlay_info : setattr ( self , varname , [ ] ) if overlay_list : for overlay in overlay_list : if isinstance ( overlay , overlay_class ) : getattr ( self , varname ) . append ( overlay ) else : getattr ( self , varname ) . append ( overlay_class ( overlay ) ) self . calc_zoom = False if self . polygons or self . polylines or self . markers : if center is None or zoom is None : self . calc_zoom = True if zoom is None : zoom = self . zoom = zoom if center is None : center = ( , ) self . center = center def render ( self ) : \"\"\"\"\"\" params = { '' : self . calc_zoom , '' : self . center , '' : self . dom_id , '' : self . js_module , '' : self . kml_urls , '' : self . zoom , '' : self . polygons , '' : self . polylines , '' : self . icons , '' : self . markers , } params . update ( self . extra_context ) return render_to_string ( self . template , params ) @ property def body ( self ) : \"\" return format_html ( '' , self . onload , self . onunload ) @ property def onload ( self ) : \"\" return format_html ( '' , self . js_module , self . dom_id ) @ property ", "answer": "def api_script ( self ) :"}, {"prompt": " import os import re import sys from setuptools import setup , find_packages def get_version ( package ) : '''''' init_py = open ( os . path . join ( package , '' ) ) . read ( ) return re . search ( '' , init_py , re . MULTILINE ) . group ( ) version = get_version ( '' ) if sys . argv [ - ] == '' : os . system ( '' ) os . system ( '' ) args = { '' : version } print ( '' ) ", "answer": "print ( '' . format ("}, {"prompt": " \"\"\"\"\"\" __revision__ = \"\" from Crypto . Cipher import blockalgo from Crypto . Cipher import _DES class DESCipher ( blockalgo . BlockAlgo ) : \"\"\"\"\"\" def __init__ ( self , key , * args , ** kwargs ) : \"\"\"\"\"\" blockalgo . BlockAlgo . __init__ ( self , _DES , key , * args , ** kwargs ) def new ( key , * args , ** kwargs ) : \"\"\"\"\"\" return DESCipher ( key , * args , ** kwargs ) MODE_ECB = MODE_CBC = MODE_CFB = MODE_PGP = MODE_OFB = MODE_CTR = ", "answer": "MODE_OPENPGP = "}, {"prompt": " import sys from biicode . server . rest . rest_api_server import RestApiServer from biicode . server . conf import BII_MONGO_URI , BII_MEMCACHE_SERVERS , BII_MEMCACHE_USERNAME , BII_MEMCACHE_PASSWORD , BII_MAX_MONGO_POOL_SIZE from biicode . server . store . mongo_server_store import MongoServerStore ", "answer": "from biicode . server . store . mongo_store import MongoStore"}, {"prompt": " from rx . observable import Observable from rx . anonymousobservable import AnonymousObservable from rx . internal import extensionmethod def find_value ( source , predicate , yield_index ) : def subscribe ( observer ) : i = [ ] def on_next ( x ) : should_run = False try : should_run = predicate ( x , i , source ) except Exception as ex : observer . on_error ( ex ) return if should_run : observer . on_next ( i [ ] if yield_index else x ) observer . on_completed ( ) else : i [ ] += def on_completed ( ) : observer . on_next ( - if yield_index else None ) observer . on_completed ( ) return source . subscribe ( on_next , observer . on_error , on_completed ) ", "answer": "return AnonymousObservable ( subscribe )"}, {"prompt": " from __future__ import absolute_import ", "answer": "from libmodernize . main import main"}, {"prompt": " \"\"\"\"\"\" import struct from jasmin . vendor . smpp . pdu import gsm_constants , gsm_types from jasmin . vendor . smpp . pdu . encoding import IEncoder from jasmin . vendor . smpp . pdu . error import PDUParseError class UDHParseError ( Exception ) : pass class UDHInformationElementIdentifierUnknownError ( UDHParseError ) : pass class Int8Encoder ( IEncoder ) : def encode ( self , value ) : return struct . pack ( '' , value ) def decode ( self , file ) : byte = self . read ( file , ) return struct . unpack ( '' , byte ) [ ] class Int16Encoder ( IEncoder ) : def encode ( self , value ) : return struct . pack ( '' , value ) def decode ( self , file ) : bytes = self . read ( file , ) return struct . unpack ( '' , bytes ) [ ] class InformationElementIdentifierEncoder ( IEncoder ) : int8Encoder = Int8Encoder ( ) nameMap = gsm_constants . information_element_identifier_name_map valueMap = gsm_constants . information_element_identifier_value_map def encode ( self , value ) : name = str ( value ) if name not in self . nameMap : raise ValueError ( \"\" % name ) return self . int8Encoder . encode ( self . nameMap [ name ] ) def decode ( self , file ) : intVal = self . int8Encoder . decode ( file ) if intVal not in self . valueMap : errStr = \"\" % intVal raise UDHInformationElementIdentifierUnknownError ( errStr ) name = self . valueMap [ intVal ] return getattr ( gsm_types . InformationElementIdentifier , name ) class IEConcatenatedSMEncoder ( IEncoder ) : int8Encoder = Int8Encoder ( ) int16Encoder = Int16Encoder ( ) def __init__ ( self , is16bitRefNum ) : self . is16bitRefNum = is16bitRefNum def encode ( self , cms ) : bytes = '' if self . is16bitRefNum : bytes += self . int16Encoder . encode ( cms . referenceNum ) else : bytes += self . int8Encoder . encode ( cms . referenceNum ) bytes += self . int8Encoder . encode ( cms . maximumNum ) bytes += self . int8Encoder . encode ( cms . sequenceNum ) return bytes def decode ( self , file ) : refNum = None if self . is16bitRefNum : refNum = self . int16Encoder . decode ( file ) else : refNum = self . int8Encoder . decode ( file ) maxNum = self . int8Encoder . decode ( file ) seqNum = self . int8Encoder . decode ( file ) return gsm_types . IEConcatenatedSM ( refNum , maxNum , seqNum ) class InformationElementEncoder ( IEncoder ) : int8Encoder = Int8Encoder ( ) iEIEncoder = InformationElementIdentifierEncoder ( ) dataEncoders = { gsm_types . InformationElementIdentifier . CONCATENATED_SM_8BIT_REF_NUM : IEConcatenatedSMEncoder ( False ) , gsm_types . InformationElementIdentifier . CONCATENATED_SM_16BIT_REF_NUM : IEConcatenatedSMEncoder ( True ) , } def encode ( self , iElement ) : dataBytes = None if iElement . identifier in self . dataEncoders : dataBytes = self . dataEncoders [ iElement . identifier ] . encode ( iElement . data ) else : dataBytes = iElement . data length = len ( dataBytes ) bytes = '' bytes += self . iEIEncoder . encode ( iElement . identifier ) bytes += self . int8Encoder . encode ( length ) bytes += dataBytes return bytes def decode ( self , file ) : fStart = file . tell ( ) identifier = None ", "answer": "try :"}, {"prompt": " import foursquare from foursquare_accounts import accounts ", "answer": "app = accounts [ \"\" ]"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from __future__ import absolute_import"}, {"prompt": " from __future__ import absolute_import , division , print_function import binascii from cryptography . hazmat . backends import default_backend from cryptography . hazmat . primitives . ciphers import algorithms , base , modes def encrypt ( mode , key , iv , plaintext ) : cipher = base . Cipher ( algorithms . CAST5 ( binascii . unhexlify ( key ) ) , mode ( binascii . unhexlify ( iv ) ) , default_backend ( ) ) encryptor = cipher . encryptor ( ) ct = encryptor . update ( binascii . unhexlify ( plaintext ) ) ct += encryptor . finalize ( ) return binascii . hexlify ( ct ) def build_vectors ( mode , filename ) : vector_file = open ( filename , \"\" ) count = output = [ ] key = None iv = None plaintext = None for line in vector_file : line = line . strip ( ) ", "answer": "if line . startswith ( \"\" ) :"}, {"prompt": " import regex def separate_string ( string ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from threading import Thread import datetime import logging import time import numpy as np import netCDF4 import pandas as pd from bokeh . plotting import vplot , hplot , cursession , curdoc , output_server , show from bokeh . models . widgets import Button , Icon from viz import climate_map , timeseries , legend , get_slice data = netCDF4 . Dataset ( '' ) t = data . variables [ '' ] df = pd . read_csv ( '' , parse_dates = [ ] ) output_server ( \"\" ) from bokeh . plotting import figure year = month = years = [ str ( x ) for x in np . arange ( , , ) ] months = [ str ( x ) for x in np . arange ( , , ) ] months_str = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] month_str = months_str [ month - ] date = datetime . date ( year , month , ) df [ '' ] = pd . rolling_mean ( df [ '' ] , ) df = df . fillna ( ) title = figure ( width = , height = , x_range = ( , ) , y_range = ( , ) , toolbar_location = None , x_axis_type = None , y_axis_type = None , outline_line_color = \"\" , tools = \"\" , min_border = ) title . text ( x = , y = , text = [ month_str ] , text_font_size = '' , text_color = '' , name = \"\" , text_font = \"\" ) title . text ( x = , y = , text = [ str ( year ) ] , text_font_size = '' , text_color = '' , name = \"\" , text_font = \"\" ) climate_map = climate_map ( ) timeseries = timeseries ( ) legend = legend ( ) play = True def play_handler ( ) : print ( \"\" ) global play play = True def stop_handler ( ) : print ( \"\" ) global play play = False button_start = Button ( label = \"\" , type = \"\" ) button_start . on_click ( play_handler ) button_stop = Button ( label = \"\" , type = \"\" ) button_stop . on_click ( stop_handler ) controls = hplot ( button_start , button_stop ) timeseries . circle ( x = [ date ] , y = [ df [ df . datetime == date ] . moving_average ] , size = , name = \"\" ) map_legend = hplot ( climate_map , legend ) layout = vplot ( controls , title , map_legend , timeseries ) show ( layout ) renderer = climate_map . select ( dict ( name = \"\" ) ) ds = renderer [ ] . data_source month_renderer = title . select ( dict ( name = \"\" ) ) month_ds = month_renderer [ ] . data_source year_renderer = title . select ( dict ( name = \"\" ) ) year_ds = year_renderer [ ] . data_source timeseries_renderer = timeseries . select ( dict ( name = \"\" ) ) timeseries_ds = timeseries_renderer [ ] . data_source def should_play ( ) : \"\"\"\"\"\" global play while True : if play : return True else : time . sleep ( ) def background_thread ( ds , year_ds , month_ds , timeseries_ds ) : \"\"\"\"\"\" try : while True : for year_index in np . arange ( , , ) : year_ds . data [ \"\" ] = [ str ( year_index ) ] for month_index in np . arange ( , , ) : if should_play ( ) : month_ds . data [ \"\" ] = [ months_str [ month_index - ] ] image = get_slice ( t , year_index , month_index ) date = datetime . date ( year_index , month_index , ) timeseries_ds . data [ \"\" ] = [ date ] timeseries_ds . data [ \"\" ] = [ df [ df . datetime == date ] . moving_average ] ds . data [ \"\" ] = [ image ] cursession ( ) . store_objects ( ds , year_ds , month_ds , timeseries_ds ) time . sleep ( ) time . sleep ( ) except : logger . exception ( \"\" ) ", "answer": "raise"}, {"prompt": " \"\"\"\"\"\" from st2common . models . db . stormbase import UIDFieldMixin __all__ = [ '' ] def parse_uid ( uid ) : \"\"\"\"\"\" if UIDFieldMixin . UID_SEPARATOR not in uid : raise ValueError ( '' % ( uid ) ) parsed = uid . split ( UIDFieldMixin . UID_SEPARATOR ) if len ( parsed ) < : raise ValueError ( '' % ( uid ) ) resource_type = parsed [ ] uid_remainder = parsed [ : ] ", "answer": "return ( resource_type , uid_remainder ) "}, {"prompt": " \"\"\"\"\"\" from __future__ import division , absolute_import import socket , random , errno from functools import wraps from zope . interface import implementer from twisted . trial import unittest from twisted . python . log import msg , err from twisted . internet import protocol , reactor , defer , interfaces from twisted . internet import error from twisted . internet . address import IPv4Address from twisted . internet . interfaces import IHalfCloseableProtocol , IPullProducer from twisted . protocols import policies from twisted . test . proto_helpers import AccumulatingProtocol def loopUntil ( predicate , interval = ) : \"\"\"\"\"\" from twisted . internet import task d = defer . Deferred ( ) def check ( ) : res = predicate ( ) if res : d . callback ( res ) call = task . LoopingCall ( check ) def stop ( result ) : call . stop ( ) return result d . addCallback ( stop ) d2 = call . start ( interval ) d2 . addErrback ( d . errback ) return d class ClosingProtocol ( protocol . Protocol ) : def connectionMade ( self ) : msg ( \"\" ) self . transport . loseConnection ( ) def connectionLost ( self , reason ) : msg ( \"\" ) reason . trap ( error . ConnectionDone ) class ClosingFactory ( protocol . ServerFactory ) : \"\"\"\"\"\" _cleanerUpper = None def buildProtocol ( self , conn ) : self . _cleanerUpper = self . port . stopListening ( ) return ClosingProtocol ( ) def cleanUp ( self ) : \"\"\"\"\"\" if self . _cleanerUpper is None : return self . port . stopListening ( ) return self . _cleanerUpper class MyProtocolFactoryMixin ( object ) : \"\"\"\"\"\" protocolFactory = AccumulatingProtocol protocolConnectionMade = None protocolConnectionLost = None protocol = None called = def __init__ ( self ) : self . peerAddresses = [ ] def buildProtocol ( self , addr ) : \"\"\"\"\"\" self . peerAddresses . append ( addr ) self . called += p = self . protocolFactory ( ) p . factory = self p . closedDeferred = self . protocolConnectionLost self . protocolConnectionLost = None self . protocol = p return p class MyServerFactory ( MyProtocolFactoryMixin , protocol . ServerFactory ) : \"\"\"\"\"\" class MyClientFactory ( MyProtocolFactoryMixin , protocol . ClientFactory ) : \"\"\"\"\"\" failed = stopped = def __init__ ( self ) : MyProtocolFactoryMixin . __init__ ( self ) self . deferred = defer . Deferred ( ) self . failDeferred = defer . Deferred ( ) def clientConnectionFailed ( self , connector , reason ) : self . failed = self . reason = reason self . failDeferred . callback ( None ) def clientConnectionLost ( self , connector , reason ) : self . lostReason = reason self . deferred . callback ( None ) def stopFactory ( self ) : self . stopped = class ListeningTestCase ( unittest . TestCase ) : def test_listen ( self ) : \"\"\"\"\"\" f = MyServerFactory ( ) p1 = reactor . listenTCP ( , f , interface = \"\" ) self . addCleanup ( p1 . stopListening ) self . failUnless ( interfaces . IListeningPort . providedBy ( p1 ) ) def testStopListening ( self ) : \"\"\"\"\"\" f = MyServerFactory ( ) port = reactor . listenTCP ( , f , interface = \"\" ) n = port . getHost ( ) . port def cbStopListening ( ignored ) : port = reactor . listenTCP ( n , f , interface = \"\" ) return port . stopListening ( ) d = defer . maybeDeferred ( port . stopListening ) d . addCallback ( cbStopListening ) return d def testNumberedInterface ( self ) : f = MyServerFactory ( ) p1 = reactor . listenTCP ( , f , interface = '' ) return p1 . stopListening ( ) def testPortRepr ( self ) : f = MyServerFactory ( ) p = reactor . listenTCP ( , f ) portNo = str ( p . getHost ( ) . port ) self . failIf ( repr ( p ) . find ( portNo ) == - ) def stoppedListening ( ign ) : self . failIf ( repr ( p ) . find ( portNo ) != - ) d = defer . maybeDeferred ( p . stopListening ) return d . addCallback ( stoppedListening ) def test_serverRepr ( self ) : \"\"\"\"\"\" server = MyServerFactory ( ) serverConnMade = server . protocolConnectionMade = defer . Deferred ( ) port = reactor . listenTCP ( , server ) self . addCleanup ( port . stopListening ) client = MyClientFactory ( ) clientConnMade = client . protocolConnectionMade = defer . Deferred ( ) connector = reactor . connectTCP ( \"\" , port . getHost ( ) . port , client ) self . addCleanup ( connector . disconnect ) def check ( result ) : serverProto , clientProto = result portNumber = port . getHost ( ) . port self . assertEqual ( repr ( serverProto . transport ) , \"\" % ( portNumber , ) ) serverProto . transport . loseConnection ( ) clientProto . transport . loseConnection ( ) return defer . gatherResults ( [ serverConnMade , clientConnMade ] ) . addCallback ( check ) def test_restartListening ( self ) : \"\"\"\"\"\" serverFactory = MyServerFactory ( ) port = reactor . listenTCP ( , serverFactory , interface = \"\" ) self . addCleanup ( port . stopListening ) def cbStopListening ( ignored ) : port . startListening ( ) client = MyClientFactory ( ) serverFactory . protocolConnectionMade = defer . Deferred ( ) client . protocolConnectionMade = defer . Deferred ( ) connector = reactor . connectTCP ( \"\" , port . getHost ( ) . port , client ) self . addCleanup ( connector . disconnect ) return defer . gatherResults ( [ serverFactory . protocolConnectionMade , client . protocolConnectionMade ] ) . addCallback ( close ) def close ( result ) : serverProto , clientProto = result clientProto . transport . loseConnection ( ) serverProto . transport . loseConnection ( ) d = defer . maybeDeferred ( port . stopListening ) d . addCallback ( cbStopListening ) return d def test_exceptInStop ( self ) : \"\"\"\"\"\" serverFactory = MyServerFactory ( ) def raiseException ( ) : raise RuntimeError ( \"\" ) serverFactory . stopFactory = raiseException port = reactor . listenTCP ( , serverFactory , interface = \"\" ) return self . assertFailure ( port . stopListening ( ) , RuntimeError ) def test_restartAfterExcept ( self ) : \"\"\"\"\"\" serverFactory = MyServerFactory ( ) def raiseException ( ) : raise RuntimeError ( \"\" ) serverFactory . stopFactory = raiseException port = reactor . listenTCP ( , serverFactory , interface = \"\" ) self . addCleanup ( port . stopListening ) def cbStopListening ( ignored ) : del serverFactory . stopFactory port . startListening ( ) client = MyClientFactory ( ) serverFactory . protocolConnectionMade = defer . Deferred ( ) client . protocolConnectionMade = defer . Deferred ( ) connector = reactor . connectTCP ( \"\" , port . getHost ( ) . port , client ) self . addCleanup ( connector . disconnect ) return defer . gatherResults ( [ serverFactory . protocolConnectionMade , client . protocolConnectionMade ] ) . addCallback ( close ) def close ( result ) : serverProto , clientProto = result clientProto . transport . loseConnection ( ) serverProto . transport . loseConnection ( ) return self . assertFailure ( port . stopListening ( ) , RuntimeError ) . addCallback ( cbStopListening ) def test_directConnectionLostCall ( self ) : \"\"\"\"\"\" serverFactory = MyServerFactory ( ) port = reactor . listenTCP ( , serverFactory , interface = \"\" ) portNumber = port . getHost ( ) . port port . connectionLost ( None ) client = MyClientFactory ( ) serverFactory . protocolConnectionMade = defer . Deferred ( ) client . protocolConnectionMade = defer . Deferred ( ) reactor . connectTCP ( \"\" , portNumber , client ) def check ( ign ) : client . reason . trap ( error . ConnectionRefusedError ) return client . failDeferred . addCallback ( check ) def test_exceptInConnectionLostCall ( self ) : \"\"\"\"\"\" serverFactory = MyServerFactory ( ) def raiseException ( ) : raise RuntimeError ( \"\" ) serverFactory . stopFactory = raiseException port = reactor . listenTCP ( , serverFactory , interface = \"\" ) self . assertRaises ( RuntimeError , port . connectionLost , None ) class LoopbackTestCase ( unittest . TestCase ) : \"\"\"\"\"\" def test_closePortInProtocolFactory ( self ) : \"\"\"\"\"\" f = ClosingFactory ( ) port = reactor . listenTCP ( , f , interface = \"\" ) f . port = port self . addCleanup ( f . cleanUp ) portNumber = port . getHost ( ) . port clientF = MyClientFactory ( ) reactor . connectTCP ( \"\" , portNumber , clientF ) def check ( x ) : self . assertTrue ( clientF . protocol . made ) self . assertTrue ( port . disconnected ) clientF . lostReason . trap ( error . ConnectionDone ) return clientF . deferred . addCallback ( check ) def _trapCnxDone ( self , obj ) : getattr ( obj , '' , lambda x : None ) ( error . ConnectionDone ) def _connectedClientAndServerTest ( self , callback ) : \"\"\"\"\"\" serverFactory = MyServerFactory ( ) serverConnMade = defer . Deferred ( ) serverFactory . protocolConnectionMade = serverConnMade port = reactor . listenTCP ( , serverFactory , interface = \"\" ) self . addCleanup ( port . stopListening ) portNumber = port . getHost ( ) . port clientF = MyClientFactory ( ) clientConnMade = defer . Deferred ( ) clientF . protocolConnectionMade = clientConnMade reactor . connectTCP ( \"\" , portNumber , clientF ) connsMade = defer . gatherResults ( [ serverConnMade , clientConnMade ] ) def connected ( result ) : serverProtocol , clientProtocol = result callback ( serverProtocol , clientProtocol ) serverProtocol . transport . loseConnection ( ) clientProtocol . transport . loseConnection ( ) connsMade . addCallback ( connected ) return connsMade def test_tcpNoDelay ( self ) : \"\"\"\"\"\" ", "answer": "def check ( serverProtocol , clientProtocol ) :"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . delete_column ( '' , '' ) db . delete_column ( '' , '' ) db . rename_column ( '' , '' , '' ) db . alter_column ( '' , '' , self . gf ( '' ) ( to = orm [ '' ] ) ) def backwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = , blank = True ) , keep_default = False ) db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = ) , keep_default = False ) db . rename_column ( '' , '' , '' ) db . alter_column ( '' , '' , self . gf ( '' ) ( max_length = ) ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : \"\" , '' : '' } ) ,"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from __future__ import absolute_import"}, {"prompt": " \"\"\"\"\"\" import django from django . core . cache import cache from django . utils import six ", "answer": "from parler import appsettings"}, {"prompt": " \"\"\"\"\"\" import sys import github ", "answer": "def usage ( ) :"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from django . contrib import admin from django . utils . translation import ugettext_lazy as _ from django . contrib . auth . admin import UserAdmin try : from django . utils . encoding import force_text except ImportError : from django . utils . encoding import force_unicode as force_text from . models import DemoUser , UserProfile from . forms import DemoUserAdminForm class UserProfileAdmin ( admin . ModelAdmin ) : ", "answer": "search_fields = ( '' , '' )"}, {"prompt": " '''''' import random import subprocess import platform import sys import time __author__ = '' __version__ = '' DEBUG = True class Concertina : osName = platform . system ( ) '''''' isLinux = ( osName == '' ) isDarwin = ( osName == '' ) PHRASES = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ", "answer": "\"\" ,"}, {"prompt": " import sys import subprocess import socket import time import os from global_parameters import GlobalParams import rospy from rapp_tools import * from rapp_platform_ros_communications . srv import ( AudioProcessingDenoiseSrv , AudioProcessingDenoiseSrvRequest , AudioProcessingDetectSilenceSrv , AudioProcessingDetectSilenceSrvRequest , AudioProcessingTransformAudioSrv , AudioProcessingTransformAudioSrvResponse , AudioProcessingTransformAudioSrvRequest ) class Sphinx4Wrapper ( GlobalParams ) : def __init__ ( self ) : GlobalParams . __init__ ( self ) self . _conf = '' self . _sphinxDied = False self . _sphinx_socket = None self . _sphinx_socket_PORT = None self . _sphinxSubprocess = None denoise_topic = rospy . get_param ( \"\" ) energy_denoise_topic = rospy . get_param ( \"\" ) detect_silence_topic = rospy . get_param ( \"\" ) audio_trans_topic = rospy . get_param ( \"\" ) if ( not denoise_topic ) : rospy . logerror ( \"\" ) if ( not energy_denoise_topic ) : rospy . logerror ( \"\" ) if ( not detect_silence_topic ) : ", "answer": "rospy . logerror ( \"\" )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) ", "answer": "result . template = \"\""}, {"prompt": " from __future__ import unicode_literals import pytest from django . core . urlresolvers import reverse from localshop . apps . packages . tasks import fetch_package from tests . factories import ReleaseFileFactory @ pytest . mark . django_db def test_success ( app , admin_user , repository , pypi_stub ) : repository . upstream_pypi_url = pypi_stub . url repository . save ( ) release_file = ReleaseFileFactory ( release__package__repository = repository ) response = app . get ( reverse ( '' , kwargs = { '' : release_file . release . package . name , '' : release_file . release . package . repository . slug } ) ) assert response . status_code == assert '' in response . unicode_body a_elms = response . html . select ( '' ) assert len ( a_elms ) == assert a_elms [ ] [ '' ] == ( '' + '' ) assert a_elms [ ] [ '' ] [ ] == '' @ pytest . mark . django_db def test_missing_package_local_package ( app , admin_user , repository , pypi_stub ) : repository . upstream_pypi_url = pypi_stub . url repository . save ( ) fetch_package . run ( repository . pk , '' ) response = app . get ( reverse ( '' , kwargs = { '' : '' , '' : repository . slug , ", "answer": "} ) )"}, {"prompt": " \"\"\"\"\"\" import re import sublime import sublime_plugin try : from . helpers import BaseBlockCommand except ValueError : from helpers import BaseBlockCommand ORDER_LIST_PATTERN = re . compile ( r\"\" ) UNORDER_LIST_PATTERN = re . compile ( r\"\" ) EMPTY_LIST_PATTERN = re . compile ( r\"\" ) NONLIST_PATTERN = re . compile ( r\"\" ) ROMAN_PATTERN = re . compile ( r\"\" , re . IGNORECASE ) ROMAN_MAP = ( ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) ) class RomanError ( Exception ) : pass class NotIntegerError ( RomanError ) : pass class InvalidRomanNumeralError ( RomanError ) : pass def to_roman ( n ) : \"\"\"\"\"\" if not ( < n < ) : raise Exception ( \"\" ) result = \"\" for numeral , integer in ROMAN_MAP : while n >= integer : result += numeral n -= integer return result def from_roman ( s ) : \"\"\"\"\"\" result = index = for numeral , integer in ROMAN_MAP : while s [ index : index + len ( numeral ) ] == numeral : result += integer index += len ( numeral ) return result class SmartListCommand ( BaseBlockCommand ) : def run ( self , edit ) : def update_ordered_list ( lines ) : new_lines = [ ] next_num = None kind = lambda a : a for line in lines : match = ORDER_LIST_PATTERN . match ( line ) if not match : new_lines . append ( line ) continue new_line = match . group ( ) + ( kind ( next_num ) or match . group ( ) ) + match . group ( ) + match . group ( ) new_lines . append ( new_line ) if not next_num : try : next_num = int ( match . group ( ) ) kind = str except ValueError : next_num = ord ( match . group ( ) ) kind = chr next_num += return new_lines def update_roman_list ( lines ) : new_lines = [ ] next_num = None kind = lambda a : a for line in lines : match = ROMAN_PATTERN . match ( line ) if not match : new_lines . append ( line ) continue new_line = match . group ( ) + ( kind ( next_num ) or match . group ( ) ) + match . group ( ) + match . group ( ) new_lines . append ( new_line ) if not next_num : actual = match . group ( ) next_num = from_roman ( actual . upper ( ) ) if actual == actual . lower ( ) : kind = lambda a : to_roman ( a ) . lower ( ) else : kind = to_roman next_num += return new_lines for region in self . view . sel ( ) : line_region = self . view . line ( region ) before_point_region = sublime . Region ( line_region . a , region . a ) before_point_content = self . view . substr ( before_point_region ) folded = False for i in self . view . folded_regions ( ) : if i . contains ( before_point_region ) : self . view . insert ( edit , region . a , '' ) folded = True if folded : break match = EMPTY_LIST_PATTERN . match ( before_point_content ) if match : insert_text = match . group ( ) + re . sub ( r'' , '' , str ( match . group ( ) ) ) + match . group ( ) self . view . erase ( edit , before_point_region ) self . view . insert ( edit , line_region . a , insert_text ) break match = ROMAN_PATTERN . match ( before_point_content ) if match : actual = match . group ( ) next_num = to_roman ( from_roman ( actual . upper ( ) ) + ) if actual == actual . lower ( ) : next_num = next_num . lower ( ) insert_text = match . group ( ) + next_num + match . group ( ) self . view . insert ( edit , region . a , \"\" + insert_text ) pos = self . view . sel ( ) [ ] . a region , lines , indent = self . get_block_bounds ( ) new_list = update_roman_list ( lines ) self . view . replace ( edit , region , '' . join ( new_list ) + '' ) self . view . sel ( ) . clear ( ) self . view . sel ( ) . add ( sublime . Region ( pos , pos ) ) self . view . show ( pos ) break match = ORDER_LIST_PATTERN . match ( before_point_content ) if match : ", "answer": "try :"}, {"prompt": " \"\"\"\"\"\" from pyface . widget import Widget class Viewer ( Widget ) : \"\"\"\"\"\" ", "answer": "pass "}, {"prompt": " import unittest from stix . test import EntityTestCase from stix . test . common import structured_text_tests from stix . common import InformationSource class InformationSourceTests ( EntityTestCase , unittest . TestCase ) : klass = InformationSource _full_dict = { '' : \"\" , '' : { '' : \"\" , } , '' : [ { '' : '' , '' : '' } , { '' : '' , '' : '' } ] , '' : { '' : [ { '' : { '' : \"\" , } , '' : '' } , { '' : { '' : \"\" , } , '' : '' } ] } , '' : [ '' ] , '' : { '' : \"\" , '' : \"\" , '' : \"\" , '' : \"\" , } , '' : [ { '' : \"\" , '' : \"\" , } , { '' : \"\" , ", "answer": "'' : \"\" ,"}, {"prompt": " from sympy . matrices . expressions import Identity from . visualization_frame import VisualizationFrame __all__ = [ '' ] class PointLight ( VisualizationFrame ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : \"\"\"\"\"\" try : self . _color = kwargs [ '' ] except KeyError : self . _color = '' i = if isinstance ( args [ i ] , str ) : self . _name = args [ i ] i += else : self . _name = '' try : self . _reference_frame = args [ i ] . get_frame ( ) self . _origin = args [ i ] . masscenter except AttributeError : try : dcm = args [ i ] . _dcm_dict self . _reference_frame = args [ i ] i += except AttributeError : raise TypeError ( '''''' ) try : self . _origin = args [ i ] . point except AttributeError : self . _origin = args [ i ] self . _transform = Identity ( ) . as_mutable ( ) def __str__ ( self ) : return '' + self . _name def __repr__ ( self ) : return '' @ property def color ( self ) : \"\"\"\"\"\" return self . _color @ color . setter def color ( self , new_color ) : \"\"\"\"\"\" if not isinstance ( new_color , str ) : raise TypeError ( '''''' ) else : self . _color = new_color def color_in_rgb ( self ) : \"\"\"\"\"\" return self . _color_rgb def generate_scene_dict ( self ) : \"\"\"\"\"\" scene_dict = { id ( self ) : { } } scene_dict [ id ( self ) ] [ '' ] = self . name scene_dict [ id ( self ) ] [ '' ] = self . __repr__ ( ) scene_dict [ id ( self ) ] [ '' ] = self . color scene_dict [ id ( self ) ] [ \"\" ] = id ( self ) ", "answer": "scene_dict [ id ( self ) ] [ \"\" ] = self . _visualization_matrix [ ]"}, {"prompt": " import datetime from sqlalchemy import orm from dssg import db class BaseModel : \"\"\"\"\"\" def __init__ ( self , ** kwargs ) : for k , v in kwargs . iteritems ( ) : setattr ( self , k , v ) @ classmethod def by_id ( cls , id ) : \"\"\"\"\"\" return db . session . query ( cls ) . get ( id ) def create ( self ) : \"\"\"\"\"\" db . session . add ( self ) db . session . commit ( ) def delete ( self ) : \"\"\"\"\"\" db . session . delete ( self ) db . session . commit ( ) def as_dict ( self ) : \"\"\"\"\"\" _dict = { } table = orm . class_mapper ( self . __class__ ) . mapped_table for col in table . c : val = getattr ( self , col . name ) if isinstance ( val , datetime . date ) : val = str ( val ) if isinstance ( val , datetime . datetime ) : val = val . isoformat ( ) _dict [ col . name ] = val return _dict @ classmethod def create_all ( cls , entries = [ ] ) : \"\"\"\"\"\" for row in entries : ", "answer": "db . session . add ( row )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division , print_function try : import unittest2 as unittest except ImportError : import unittest from tls . c import api class TestSSLMethod ( unittest . TestCase ) : @ unittest . skipIf ( api . OPENTLS_NO_SSL2 , '' ) def test_ssl_v2 ( self ) : \"\"\"\"\"\" self . assertTrue ( api . SSLv2_method ( ) ) @ unittest . skipIf ( not api . OPENTLS_NO_SSL2 , '' ) def test_ssl_v2_disabled ( self ) : \"\"\"\"\"\" with self . assertRaises ( NotImplementedError ) : api . SSLv2_method ( ) @ unittest . skipIf ( api . OPENTLS_NO_SSL2 , '' ) def test_ssl_v2_client ( self ) : \"\"\"\"\"\" self . assertTrue ( api . SSLv2_client_method ( ) ) @ unittest . skipIf ( not api . OPENTLS_NO_SSL2 , '' ) def test_ssl_v2_client_disabled ( self ) : \"\"\"\"\"\" with self . assertRaises ( NotImplementedError ) : api . SSLv2_client_method ( ) @ unittest . skipIf ( api . OPENTLS_NO_SSL2 , '' ) def test_ssl_v2_server ( self ) : \"\"\"\"\"\" self . assertTrue ( api . SSLv2_server_method ( ) ) ", "answer": "@ unittest . skipIf ( not api . OPENTLS_NO_SSL2 , '' )"}, {"prompt": " from os . path import join , dirname , abspath ROOT = abspath ( dirname ( __file__ ) ) TREEBANKS_DIR = join ( ROOT , \"\" ) TEMP_DIR = join ( ROOT , \"\" ) QUESTIONBANK_DIR = join ( TREEBANKS_DIR , \"\" ) QUESTIONBANK_DATA = join ( QUESTIONBANK_DIR , \"\" ) ", "answer": "QUESTIONBANK_PENN_DATA = join ( TEMP_DIR , \"\" )"}, {"prompt": " from errors import OperationError , TimeoutExpiredError , MissingCapabilityError from rpc import RPC , RPCReply , RPCError , RaiseMode from retrieve import Get , GetConfig , GetReply , Dispatch from edit import EditConfig , CopyConfig , DeleteConfig , Validate , Commit , DiscardChanges from session import CloseSession , KillSession from lock import Lock , Unlock , LockContext from flowmon import PoweroffMachine , RebootMachine __all__ = [ '' , '' , ", "answer": "'' ,"}, {"prompt": " from __future__ import print_function import argparse import datetime import logging import os import random import sys import threading import time import unittest import pyrax import pyrax . exceptions as exc import pyrax . utils as utils class SmokeTester ( object ) : def __init__ ( self , context , region , logname = None , nolog = False , clean = False ) : self . context = context self . region = region self . clean = clean self . failures = [ ] self . cleanup_items = [ ] self . smoke_server = None self . smoke_volume = None self . smoke_snapshot = None logname = \"\" % ( logname or \"\" , self . region ) self . log = logging . getLogger ( logname ) if nolog : handler = logging . NullHandler ( ) else : handler = logging . FileHandler ( filename = logname , mode = \"\" , encoding = \"\" ) formatter = logging . Formatter ( \"\" ) handler . setFormatter ( formatter ) self . log . addHandler ( handler ) self . log . setLevel ( logging . DEBUG ) self . cs = self . context . get_client ( \"\" , self . region ) self . cf = self . context . get_client ( \"\" , self . region ) self . cbs = self . context . get_client ( \"\" , self . region ) self . cdb = self . context . get_client ( \"\" , self . region ) self . clb = self . context . get_client ( \"\" , self . region ) self . dns = self . context . get_client ( \"\" , self . region ) self . cnw = self . context . get_client ( \"\" , self . region ) self . cmn = self . context . get_client ( \"\" , self . region ) self . au = self . context . get_client ( \"\" , self . region ) self . pq = self . context . get_client ( \"\" , self . region ) self . services = ( { \"\" : self . cs , \"\" : \"\" } , { \"\" : self . cf , \"\" : \"\" } , { \"\" : self . cbs , \"\" : \"\" } , { \"\" : self . cdb , \"\" : \"\" } , { \"\" : self . clb , \"\" : \"\" } , { \"\" : self . dns , \"\" : \"\" } , { \"\" : self . cnw , \"\" : \"\" } , { \"\" : self . cmn , \"\" : \"\" } , { \"\" : self . au , \"\" : \"\" } , { \"\" : self . pq , \"\" : \"\" } , ) def logit ( self , * args , ** kwargs ) : txtargs = [ \"\" % arg for arg in args ] msg = \"\" . join ( txtargs ) print ( \"\" % ( self . region , msg ) , ** kwargs ) self . log . debug ( msg ) def check_services ( self ) : for service in self . services : self . logit ( \"\" , service [ \"\" ] , end = '' ) if service [ \"\" ] : self . logit ( \"\" ) else : self . logit ( \"\" ) self . failures . append ( \"\" % service [ \"\" ] ) def run_clean ( self ) : def cleanup_smoke ( svc , list_method = None , * list_params ) : list_method = list_method or \"\" mthd = getattr ( svc , list_method ) try : svcname = svc . name except AttributeError : svcname = \"\" % svc try : ents = [ ent for ent in mthd ( * list_params ) if ent . name . startswith ( \"\" ) ] except Exception as e : self . logit ( \"\" , svcname ) self . logit ( \"\" , e ) return if ents : try : ent . delete ( ) self . logit ( \"\" , svcname , \"\" , ent . id ) except Exception as e : self . logit ( \"\" , svcname , \"\" , ent . id ) self . logit ( \"\" , e ) else : self . logit ( \"\" , self . region , \"\" , svcname ) cleanup_smoke ( self . cnw ) cleanup_smoke ( self . cs ) cleanup_smoke ( self . cdb ) cleanup_smoke ( self . cf , \"\" , \"\" ) cleanup_smoke ( self . cf ) cleanup_smoke ( self . clb ) cleanup_smoke ( self . dns , \"\" , \"\" ) cleanup_smoke ( self . dns ) cleanup_smoke ( self . cmn , \"\" , \"\" ) cleanup_smoke ( self . cmn , \"\" ) cleanup_smoke ( self . cmn , \"\" ) cleanup_smoke ( self . cmn , \"\" ) cleanup_smoke ( self . cmn , \"\" , \"\" ) cleanup_smoke ( self . cbs ) return def run_tests ( self ) : if self . clean : return self . run_clean ( ) if self . cs : self . logit ( \"\" ) self . cs_list_flavors ( ) self . cs_list_images ( ) self . cs_create_server ( ) self . cs_reboot_server ( ) self . cs_list_servers ( ) if self . cnw : self . logit ( \"\" ) try : self . cnw_create_network ( ) self . cnw_list_networks ( ) except exc . NotFound : self . logit ( \"\" ) except exc . NetworkCountExceeded : self . logit ( \"\" ) if self . cdb : self . logit ( \"\" ) self . cdb_list_flavors ( ) self . cdb_create_instance ( ) self . cdb_create_db ( ) self . cdb_create_user ( ) if self . cf : self . logit ( \"\" ) self . cf_create_container ( ) self . cf_list_containers ( ) self . cf_make_container_public ( ) self . cf_make_container_private ( ) self . cf_upload_file ( ) if self . clb : self . logit ( \"\" ) self . lb_list ( ) self . lb_create ( ) if self . dns : self . logit ( \"\" ) self . dns_list ( ) self . dns_create_domain ( ) self . dns_create_record ( ) if self . cmn : if not self . smoke_server : self . logit ( \"\" ) return self . cmn_create_entity ( ) self . cmn_list_check_types ( ) self . cmn_list_monitoring_zones ( ) self . cmn_create_check ( ) self . cmn_create_notification ( ) self . cmn_create_notification_plan ( ) self . cmn_create_alarm ( ) if self . cbs : self . cbs_list_volumes ( ) self . cbs_list_types ( ) self . cbs_list_snapshots ( ) self . cbs_create_volume ( ) self . cbs_attach_to_instance ( ) self . cbs_detach_from_instance ( ) self . cbs_create_snapshot ( ) self . cbs_delete_snapshot ( ) def cs_list_flavors ( self ) : self . logit ( \"\" , end = '' ) self . cs_flavors = self . cs . list_flavors ( ) if self . cs_flavors : self . logit ( ) for flavor in self . cs_flavors : self . logit ( \"\" , flavor ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) self . logit ( ) def cs_list_images ( self ) : self . logit ( \"\" , end = '' ) self . cs_images = self . cs . list_base_images ( ) if self . cs_images : for image in self . cs_images : self . logit ( \"\" , image ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) def cnw_create_network ( self ) : self . logit ( \"\" ) new_network_name = \"\" new_network_cidr = \"\" self . logit ( \"\" , end = '' ) self . logit ( \"\" , self . cnw ) self . smoke_network = self . cnw . create ( new_network_name , cidr = new_network_cidr ) self . cleanup_items . append ( self . smoke_network ) if self . smoke_network : self . logit ( \"\" ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) def cnw_list_networks ( self ) : self . logit ( \"\" ) try : networks = self . cnw . list ( ) except exc . NotFound : self . logit ( \"\" ) return for network in networks : self . logit ( \"\" % ( network . id , network . name , network . cidr ) ) if not networks : self . failures . append ( \"\" ) def log_wait ( self , obj , att = \"\" , desired = None , verbose_atts = None ) : start = time . time ( ) self . logit ( \"\" , obj . name , obj ) if not desired : desired = [ \"\" , \"\" ] ret = utils . wait_until ( obj , \"\" , desired = desired , interval = , verbose = True , verbose_atts = \"\" ) end = time . time ( ) duration = str ( datetime . timedelta ( seconds = ( end - start ) ) ) self . logit ( \"\" , obj . name , obj ) self . logit ( \"\" % duration ) return ret def cs_create_server ( self ) : self . logit ( \"\" ) img = [ img for img in self . cs_images if \"\" in img . name ] [ ] flavor = self . cs_flavors [ ] self . smoke_server = self . cs . servers . create ( \"\" , img . id , flavor . id ) self . cleanup_items . append ( self . smoke_server ) self . smoke_server = self . log_wait ( self . smoke_server ) if self . smoke_server . status == \"\" : self . logit ( \"\" ) self . failures . append ( \"\" ) else : self . logit ( \"\" ) def cs_reboot_server ( self ) : self . logit ( \"\" ) self . smoke_server . reboot ( ) self . smoke_server = self . log_wait ( self . smoke_server ) if self . smoke_server . status == \"\" : self . logit ( \"\" ) self . failures . append ( \"\" ) else : self . logit ( \"\" ) def cs_list_servers ( self ) : self . logit ( \"\" ) servers = self . cs . servers . list ( ) if not servers : self . logit ( \"\" ) self . failures . append ( \"\" ) else : for server in servers : self . logit ( \"\" , server . id , server . name ) def cdb_list_flavors ( self ) : self . logit ( \"\" , end = '' ) try : self . cdb_flavors = self . cdb . list_flavors ( ) except Exception as e : self . logit ( \"\" , e ) self . cdb_flavors = None if self . cdb_flavors : for flavor in self . cdb_flavors : self . logit ( \"\" , flavor ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) def cdb_create_instance ( self ) : if not self . cdb_flavors : self . logit ( \"\" ) self . smoke_instance = None return self . logit ( \"\" ) self . smoke_instance = self . cdb . create ( \"\" , flavor = self . cdb_flavors [ ] , volume = ) self . cleanup_items . append ( self . smoke_instance ) self . smoke_instance = self . log_wait ( self . smoke_instance ) if self . smoke_instance . status == \"\" : self . logit ( \"\" ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) def cdb_create_db ( self ) : if not self . smoke_instance : self . logit ( \"\" ) return self . logit ( \"\" ) self . smoke_db = self . smoke_instance . create_database ( \"\" ) self . cleanup_items . append ( self . smoke_db ) dbs = self . smoke_instance . list_databases ( ) if self . smoke_db in dbs : self . logit ( \"\" ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) def cdb_create_user ( self ) : if not self . smoke_instance : self . logit ( \"\" ) return self . logit ( \"\" ) self . smoke_user = self . smoke_instance . create_user ( \"\" , \"\" , database_names = [ self . smoke_db ] ) self . cleanup_items . append ( self . smoke_user ) users = self . smoke_instance . list_users ( ) if self . smoke_user in users : self . logit ( \"\" ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) def cf_create_container ( self ) : self . logit ( \"\" ) self . smoke_cont = self . cf . create_container ( \"\" ) self . cleanup_items . append ( self . smoke_cont ) if self . smoke_cont : self . logit ( \"\" ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) def cf_list_containers ( self ) : self . logit ( \"\" ) conts = self . cf . get_all_containers ( ) if conts : for cont in conts : try : nm = cont . name num = cont . object_count size = cont . total_bytes self . logit ( \"\" % ( nm , num , size ) ) except Exception as e : self . logit ( \"\" , e ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) def cf_make_container_public ( self ) : self . logit ( \"\" ) self . smoke_cont . make_public ( ) uri = self . smoke_cont . cdn_uri if uri : self . logit ( \"\" ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) def cf_make_container_private ( self ) : self . logit ( \"\" ) try : self . smoke_cont . make_private ( ) self . logit ( \"\" ) except Exception as e : self . logit ( \"\" , e ) self . failures . append ( \"\" ) def cf_upload_file ( self ) : self . logit ( \"\" ) cont = self . smoke_cont text = utils . random_ascii ( ) obj = cont . store_object ( \"\" , text ) self . cleanup_items . insert ( , obj ) all_objs = cont . get_object_names ( ) if obj . name in all_objs : self . logit ( \"\" ) else : self . logit ( \"\" ) self . failures . append ( \"\" ) ", "answer": "def lb_list ( self ) :"}, {"prompt": " import re import struct from django import forms from django . core . validators import MaxValueValidator from django . core . validators import MinValueValidator from django . core . validators import RegexValidator from django . db import models , connection from django . utils import six from django . utils . translation import ugettext_lazy as _ UNSIGNED_64BIT_INT_MIN_VALUE = UNSIGNED_64BIT_INT_MAX_VALUE = ** - __all__ = [ \"\" , \"\" ] hex_re = re . compile ( r\"\" ) signed_integer_engines = [ \"\" , \"\" , \"\" ] def _using_signed_storage ( ) : return connection . settings_dict [ \"\" ] in signed_integer_engines def _signed_to_unsigned_integer ( value ) : return struct . unpack ( \"\" , struct . pack ( \"\" , value ) ) [ ] def _unsigned_to_signed_integer ( value ) : return struct . unpack ( \"\" , struct . pack ( \"\" , value ) ) [ ] def _hex_string_to_unsigned_integer ( value ) : return int ( value , ) def _unsigned_integer_to_hex_string ( value ) : return hex ( value ) . rstrip ( \"\" ) class HexadecimalField ( forms . CharField ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : self . default_validators = [ RegexValidator ( hex_re , _ ( \"\" ) , \"\" ) ] super ( HexadecimalField , self ) . __init__ ( * args , ** kwargs ) def prepare_value ( self , value ) : if value and not isinstance ( value , six . string_types ) and connection . vendor in ( \"\" , \"\" ) : value = _unsigned_integer_to_hex_string ( value ) return super ( forms . CharField , self ) . prepare_value ( value ) class HexIntegerField ( models . BigIntegerField ) : \"\"\"\"\"\" validators = [ MinValueValidator ( UNSIGNED_64BIT_INT_MIN_VALUE ) , MaxValueValidator ( UNSIGNED_64BIT_INT_MAX_VALUE ) ] def db_type ( self , connection ) : engine = connection . settings_dict [ \"\" ] if \"\" in engine : return \"\" elif \"\" in engine : return \"\" else : return super ( HexIntegerField , self ) . db_type ( connection = connection ) def get_prep_value ( self , value ) : \"\"\"\"\"\" if value is None or value == \"\" : return None if isinstance ( value , six . string_types ) : value = _hex_string_to_unsigned_integer ( value ) if _using_signed_storage ( ) : value = _unsigned_to_signed_integer ( value ) return value def from_db_value ( self , value , expression , connection , context ) : \"\"\"\"\"\" if value is None : return value if _using_signed_storage ( ) : value = _signed_to_unsigned_integer ( value ) return value def to_python ( self , value ) : \"\"\"\"\"\" if isinstance ( value , six . string_types ) : return value if value is None : return value return _unsigned_integer_to_hex_string ( value ) def formfield ( self , ** kwargs ) : defaults = { \"\" : HexadecimalField } defaults . update ( kwargs ) ", "answer": "return super ( models . IntegerField , self ) . formfield ( ** defaults )"}, {"prompt": " import pickle import io import collections from test import support from test . pickletester import AbstractPickleTests from test . pickletester import AbstractPickleModuleTests from test . pickletester import AbstractPersistentPicklerTests from test . pickletester import AbstractPicklerUnpicklerObjectTests from test . pickletester import AbstractDispatchTableTests from test . pickletester import BigmemPickleTests try : import _pickle has_c_implementation = True except ImportError : has_c_implementation = False class PickleTests ( AbstractPickleModuleTests ) : pass class PyPicklerTests ( AbstractPickleTests ) : pickler = pickle . _Pickler unpickler = pickle . _Unpickler def dumps ( self , arg , proto = None ) : f = io . BytesIO ( ) p = self . pickler ( f , proto ) p . dump ( arg ) f . seek ( ) return bytes ( f . read ( ) ) def loads ( self , buf , ** kwds ) : f = io . BytesIO ( buf ) u = self . unpickler ( f , ** kwds ) return u . load ( ) class InMemoryPickleTests ( AbstractPickleTests , BigmemPickleTests ) : pickler = pickle . _Pickler unpickler = pickle . _Unpickler def dumps ( self , arg , protocol = None ) : return pickle . dumps ( arg , protocol ) def loads ( self , buf , ** kwds ) : return pickle . loads ( buf , ** kwds ) class PyPersPicklerTests ( AbstractPersistentPicklerTests ) : ", "answer": "pickler = pickle . _Pickler"}, {"prompt": " from get_var import task_echo from custom_task_def import sample ", "answer": "def task_hello ( ) :"}, {"prompt": " import ginga . canvas . types . all class RenderContext ( object ) : def __init__ ( self , viewer ) : self . viewer = viewer self . cr = None def __get_color ( self , color , alpha ) : clr = None return clr def set_line_from_shape ( self , shape ) : pass def set_fill_from_shape ( self , shape ) : pass def set_font_from_shape ( self , shape ) : pass def initialize_from_shape ( self , shape , line = True , fill = True , font = True ) : if line : self . set_line_from_shape ( shape ) if fill : self . set_fill_from_shape ( shape ) if font : self . set_font_from_shape ( shape ) def set_line ( self , color , alpha = , linewidth = , style = '' ) : pass def set_fill ( self , color , alpha = ) : pass def set_font ( self , fontname , fontsize , color = '' , alpha = ) : pass def text_extents ( self , text ) : ", "answer": "width = "}, {"prompt": " import sys import os on_rtd = os . environ . get ( '' , None ) == '' if not on_rtd : import sphinx_rtd_theme html_theme = '' html_theme_path = [ sphinx_rtd_theme . get_html_theme_path ( ) ] project = '' package = '' author = '' copyright = '' sys . path . insert ( , os . path . abspath ( '' . format ( package ) ) ) sys . path . insert ( , os . path . abspath ( '' ) ) sys . path . insert ( , os . path . abspath ( '' ) ) extensions = [ '' , '' , '' , '' , '' ] templates_path = [ '' ] source_suffix = '' master_doc = '' import pkg_resources try : release = pkg_resources . get_distribution ( project ) . version except pkg_resources . DistributionNotFound : print '' print '' print '' print '' sys . exit ( ) except Exception as e : print e del pkg_resources version = '' . join ( release . split ( '' ) [ : ] ) exclude_patterns = [ '' ] pygments_style = '' html_static_path = [ '' ] ", "answer": "htmlhelp_basename = '' . format ( project )"}, {"prompt": " import pprint from planetlab . model import * from users import user_list legacy_network_remap = { '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } , '' : { : '' , : '' , : '' } } Network . legacy_network_remap = legacy_network_remap site_list = [ makesite ( '' , '' , None , '' , '' , , - , user_list , exclude = [ , , ] , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , - , , user_list , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , , user_list , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , , user_list , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , , user_list , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , , user_list , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , , user_list , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , , user_list , count = , v6gw = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , , user_list , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , , user_list , arch = '' , nodegroup = '' ) , makesite ( '' , '' , None , '' , '' , , - , user_list , exclude = [ , , ] , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , makesite ( '' , '' , '' , '' , '' , , - , user_list , count = , arch = '' , nodegroup = '' ) , ", "answer": "makesite ( '' , '' , '' , '' , '' , , - , user_list , nodegroup = '' ) ,"}, {"prompt": " \"\"\"\"\"\" from IPython . parallel import Client rc = Client ( ) def sleep_and_echo ( t , msg ) : import time time . sleep ( t ) return msg ", "answer": "view = rc . load_balanced_view ( )"}, {"prompt": " import os import logging import re import sys import traceback import pkg_resources import desktop from desktop . lib . paths import get_desktop_root from django . utils . translation import ugettext as _ APP_DIRS = [ get_desktop_root ( '' ) , get_desktop_root ( '' ) , get_desktop_root ( '' ) ] LOG = logging . getLogger ( __name__ ) DESKTOP_LIBS = None DESKTOP_APPS = None DESKTOP_MODULES = [ ] def _import_module_or_none ( module ) : \"\"\"\"\"\" try : __import__ ( module ) return sys . modules [ module ] except ImportError , ie : tb = sys . exc_info ( ) [ ] top_frame = traceback . extract_tb ( tb ) [ - ] err_file = re . sub ( r'' , '' , top_frame [ ] ) my_file = re . sub ( r'' , '' , __file__ ) if err_file == my_file : ", "answer": "return None"}, {"prompt": " from __future__ import unicode_literals import logging from django . utils . module_loading import import_string from . settings import setting_graphics_backend ", "answer": "logger = logging . getLogger ( __name__ )"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from __future__ import division"}, {"prompt": " from setuptools import setup setup ( name = \"\" , version = \"\" , author = \"\" , ", "answer": "packages = [ '' ] ,"}, {"prompt": " import sys , os extensions = [ ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' version = '' release = '' exclude_patterns = [ '' ] pygments_style = '' html_theme = '' html_static_path = [ '' ] htmlhelp_basename = '' ", "answer": "latex_elements = {"}, {"prompt": " from pyjamas . Canvas . GWTCanvas import GWTCanvas from pyjamas . ui . RootPanel import RootPanel from pyjamas . DOM import getFirstChild from pyjamas import Window from pyjamas . ui . HTML import HTML import math ", "answer": "from __pyjamas__ import jsinclude"}, {"prompt": " import azurerm import json try : with open ( '' ) as configFile : configData = json . load ( configFile ) except FileNotFoundError : print ( \"\" ) sys . exit ( ) tenant_id = configData [ '' ] app_id = configData [ '' ] app_secret = configData [ '' ] subscription_id = configData [ '' ] access_token = azurerm . get_access_token ( tenant_id , app_id , app_secret ) locations = azurerm . list_locations ( access_token , subscription_id ) for location in locations [ '' ] : ", "answer": "print ( location [ '' ]"}, {"prompt": " import logging import socket from bagpipe . bgp . common import utils from bagpipe . bgp . common import logDecorator from bagpipe . bgp . vpn . vpn_instance import VPNInstance from bagpipe . bgp . engine import RouteEvent from bagpipe . bgp . vpn . dataplane_drivers import DummyDataplaneDriver as _DummyDataplaneDriver from bagpipe . bgp . common . looking_glass import LookingGlass , LGMap from bagpipe . exabgp . structure . vpn import RouteDistinguisher , VPNLabelledPrefix from bagpipe . exabgp . structure . mpls import LabelStackEntry ", "answer": "from bagpipe . exabgp . structure . address import AFI , SAFI"}, {"prompt": " \"\"\"\"\"\" __revision__ = \"\" import sys , os , string from distutils . core import Command from distutils . util import get_platform from distutils . dir_util import create_tree , remove_tree from distutils . errors import * from distutils . sysconfig import get_python_version from distutils import log class bdist_wininst ( Command ) : description = \"\" user_options = [ ( '' , None , \"\" ) , ( '' , '' , \"\" + \"\" ) , ( '' , None , \"\" + \"\" ) , ( '' , '' , \"\" ) , ( '' , '' , \"\" \"\" ) , ( '' , '' , \"\" ) , ( '' , '' , \"\" ) , ( '' , '' , \"\" ) , ( '' , None , \"\" ) , ( '' , None , \"\" \"\" ) , ( '' , None , \"\" \"\" \"\" ) , ] boolean_options = [ '' , '' , '' , '' ] def initialize_options ( self ) : self . bdist_dir = None self . keep_temp = self . no_target_compile = self . no_target_optimize = self . target_version = None self . dist_dir = None self . bitmap = None self . title = None self . skip_build = self . install_script = None self . pre_install_script = None def finalize_options ( self ) : if self . bdist_dir is None : bdist_base = self . get_finalized_command ( '' ) . bdist_base self . bdist_dir = os . path . join ( bdist_base , '' ) if not self . target_version : self . target_version = \"\" if not self . skip_build and self . distribution . has_ext_modules ( ) : short_version = get_python_version ( ) if self . target_version and self . target_version != short_version : raise DistutilsOptionError , \"\" \"\" % ( short_version , ) self . target_version = short_version self . set_undefined_options ( '' , ( '' , '' ) ) if self . install_script : for script in self . distribution . scripts : if self . install_script == os . path . basename ( script ) : break else : raise DistutilsOptionError , \"\" % self . install_script def run ( self ) : if ( sys . platform != \"\" and ( self . distribution . has_ext_modules ( ) or self . distribution . has_c_libraries ( ) ) ) : raise DistutilsPlatformError ( \"\" \"\" ) if not self . skip_build : self . run_command ( '' ) install = self . reinitialize_command ( '' , reinit_subcommands = ) install . root = self . bdist_dir install . skip_build = self . skip_build install . warn_dir = install_lib = self . reinitialize_command ( '' ) install_lib . compile = install_lib . optimize = if self . distribution . has_ext_modules ( ) : target_version = self . target_version if not target_version : assert self . skip_build , \"\" target_version = sys . version [ : ] plat_specifier = \"\" % ( get_platform ( ) , target_version ) build = self . get_finalized_command ( '' ) build . build_lib = os . path . join ( build . build_base , '' + plat_specifier ) for key in ( '' , '' , '' , '' , '' ) : value = string . upper ( key ) if key == '' : value = value + '' setattr ( install , '' + key , value ) log . info ( \"\" , self . bdist_dir ) install . ensure_finalized ( ) sys . path . insert ( , os . path . join ( self . bdist_dir , '' ) ) install . run ( ) del sys . path [ ] from tempfile import mktemp archive_basename = mktemp ( ) fullname = self . distribution . get_fullname ( ) arcname = self . make_archive ( archive_basename , \"\" , root_dir = self . bdist_dir ) self . create_exe ( arcname , fullname , self . bitmap ) if self . distribution . has_ext_modules ( ) : pyversion = get_python_version ( ) else : pyversion = '' self . distribution . dist_files . append ( ( '' , pyversion , self . get_installer_filename ( fullname ) ) ) log . debug ( \"\" , arcname ) os . remove ( arcname ) if not self . keep_temp : remove_tree ( self . bdist_dir , dry_run = self . dry_run ) def get_inidata ( self ) : lines = [ ] metadata = self . distribution . metadata lines . append ( \"\" ) info = ( metadata . long_description or '' ) + '' def escape ( s ) : return string . replace ( s , \"\" , \"\" ) for name in [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] : data = getattr ( metadata , name , \"\" ) if data : info = info + ( \"\" % ( string . capitalize ( name ) , escape ( data ) ) ) lines . append ( \"\" % ( name , escape ( data ) ) ) lines . append ( \"\" ) if self . install_script : lines . append ( \"\" % self . install_script ) lines . append ( \"\" % escape ( info ) ) lines . append ( \"\" % ( not self . no_target_compile ) ) lines . append ( \"\" % ( not self . no_target_optimize ) ) if self . target_version : lines . append ( \"\" % self . target_version ) title = self . title or self . distribution . get_fullname ( ) lines . append ( \"\" % escape ( title ) ) import time import distutils build_info = \"\" % ( time . ctime ( time . time ( ) ) , distutils . __version__ ) lines . append ( \"\" % build_info ) return string . join ( lines , \"\" ) def create_exe ( self , arcname , fullname , bitmap = None ) : import struct self . mkpath ( self . dist_dir ) cfgdata = self . get_inidata ( ) installer_name = self . get_installer_filename ( fullname ) self . announce ( \"\" % installer_name ) if bitmap : bitmapdata = open ( bitmap , \"\" ) . read ( ) bitmaplen = len ( bitmapdata ) else : bitmaplen = file = open ( installer_name , \"\" ) file . write ( self . get_exe_bytes ( ) ) if bitmap : file . write ( bitmapdata ) try : ", "answer": "unicode"}, {"prompt": " import errno import logging from socket import error as SocketError , timeout as SocketTimeout import socket try : from queue import LifoQueue , Empty , Full except ImportError : from Queue import LifoQueue , Empty , Full import Queue as _ from . exceptions import ( ClosedPoolError , ConnectTimeoutError , EmptyPoolError , HostChangedError , MaxRetryError , SSLError , TimeoutError , ReadTimeoutError , ProxyError , ) from . packages . ssl_match_hostname import CertificateError from . packages import six from . connection import ( DummyConnection , HTTPConnection , HTTPSConnection , VerifiedHTTPSConnection , HTTPException , BaseSSLError , ) from . request import RequestMethods from . response import HTTPResponse from . util import ( assert_fingerprint , get_host , is_connection_dropped , Timeout , ) xrange = six . moves . xrange log = logging . getLogger ( __name__ ) _Default = object ( ) port_by_scheme = { '' : , '' : , } class ConnectionPool ( object ) : \"\"\"\"\"\" scheme = None QueueCls = LifoQueue def __init__ ( self , host , port = None ) : host = host . strip ( '' ) self . host = host self . port = port def __str__ ( self ) : return '' % ( type ( self ) . __name__ , self . host , self . port ) _blocking_errnos = set ( [ errno . EAGAIN , errno . EWOULDBLOCK ] ) class HTTPConnectionPool ( ConnectionPool , RequestMethods ) : \"\"\"\"\"\" scheme = '' ConnectionCls = HTTPConnection def __init__ ( self , host , port = None , strict = False , timeout = Timeout . DEFAULT_TIMEOUT , maxsize = , block = False , headers = None , _proxy = None , _proxy_headers = None ) : ConnectionPool . __init__ ( self , host , port ) RequestMethods . __init__ ( self , headers ) self . strict = strict if not isinstance ( timeout , Timeout ) : timeout = Timeout . from_float ( timeout ) self . timeout = timeout self . pool = self . QueueCls ( maxsize ) self . block = block self . proxy = _proxy self . proxy_headers = _proxy_headers or { } for _ in xrange ( maxsize ) : self . pool . put ( None ) self . num_connections = self . num_requests = def _new_conn ( self ) : \"\"\"\"\"\" self . num_connections += log . info ( \"\" % ( self . num_connections , self . host ) ) extra_params = { } if not six . PY3 : extra_params [ '' ] = self . strict return self . ConnectionCls ( host = self . host , port = self . port , timeout = self . timeout . connect_timeout , ** extra_params ) def _get_conn ( self , timeout = None ) : \"\"\"\"\"\" conn = None try : conn = self . pool . get ( block = self . block , timeout = timeout ) except AttributeError : raise ClosedPoolError ( self , \"\" ) except Empty : if self . block : raise EmptyPoolError ( self , \"\" \"\" ) pass if conn and is_connection_dropped ( conn ) : log . info ( \"\" % self . host ) conn . close ( ) return conn or self . _new_conn ( ) def _put_conn ( self , conn ) : \"\"\"\"\"\" try : self . pool . put ( conn , block = False ) return except AttributeError : pass except Full : log . warning ( \"\" % self . host ) if conn : conn . close ( ) def _get_timeout ( self , timeout ) : \"\"\"\"\"\" if timeout is _Default : return self . timeout . clone ( ) if isinstance ( timeout , Timeout ) : return timeout . clone ( ) else : return Timeout . from_float ( timeout ) def _make_request ( self , conn , method , url , timeout = _Default , ** httplib_request_kw ) : \"\"\"\"\"\" self . num_requests += timeout_obj = self . _get_timeout ( timeout ) try : timeout_obj . start_connect ( ) conn . timeout = timeout_obj . connect_timeout conn . request ( method , url , ** httplib_request_kw ) except SocketTimeout : raise ConnectTimeoutError ( self , \"\" % ( self . host , timeout_obj . connect_timeout ) ) read_timeout = timeout_obj . read_timeout if hasattr ( conn , '' ) : if read_timeout == : raise ReadTimeoutError ( self , url , \"\" % read_timeout ) if read_timeout is Timeout . DEFAULT_TIMEOUT : conn . sock . settimeout ( socket . getdefaulttimeout ( ) ) else : conn . sock . settimeout ( read_timeout ) try : try : httplib_response = conn . getresponse ( buffering = True ) except TypeError : httplib_response = conn . getresponse ( ) except SocketTimeout : raise ReadTimeoutError ( self , url , \"\" % read_timeout ) except BaseSSLError as e : if '' in str ( e ) or '' in str ( e ) : raise ReadTimeoutError ( self , url , \"\" ) raise except SocketError as e : if e . errno in _blocking_errnos : raise ReadTimeoutError ( self , url , \"\" % read_timeout ) raise http_version = getattr ( conn , '' , '' ) log . debug ( \"\" % ( method , url , http_version , httplib_response . status , httplib_response . length ) ) return httplib_response def close ( self ) : \"\"\"\"\"\" old_pool , self . pool = self . pool , None try : while True : conn = old_pool . get ( block = False ) if conn : conn . close ( ) except Empty : pass def is_same_host ( self , url ) : \"\"\"\"\"\" if url . startswith ( '' ) : return True scheme , host , port = get_host ( url ) if self . port and not port : port = port_by_scheme . get ( scheme ) return ( scheme , host , port ) == ( self . scheme , self . host , self . port ) def urlopen ( self , method , url , body = None , headers = None , retries = , redirect = True , assert_same_host = True , timeout = _Default , ", "answer": "pool_timeout = None , release_conn = None , ** response_kw ) :"}, {"prompt": " \"\"\"\"\"\" import gevent from gevent import event , coros from pika . credentials import PlainCredentials from pika . connection import ConnectionParameters from pika . adapters import SelectConnection from pika import channel as pikachannel from pika . exceptions import NoFreeChannels from pyon . core . bootstrap import CFG , get_sys_name from pyon . net import channel from pyon . util . async import blocking_cb from pyon . util . containers import for_name from pyon . util . log import log from pyon . util . pool import IDPool from pyon . net . transport import LocalTransport , LocalRouter , AMQPTransport , ComposableTransport from collections import defaultdict import traceback class BaseNode ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . client = None self . running = False self . ready = event . Event ( ) self . _lock = coros . RLock ( ) self . interceptors = { } def on_connection_open ( self , client ) : \"\"\"\"\"\" log . debug ( \"\" ) log . debug ( \"\" % str ( client ) ) client . add_on_close_callback ( self . on_connection_close ) self . client = client self . start_node ( ) def on_connection_close ( self , * a ) : \"\"\"\"\"\" log . debug ( \"\" ) def start_node ( self ) : \"\"\"\"\"\" log . debug ( \"\" ) self . running = True self . ready . set ( ) def stop_node ( self ) : \"\"\"\"\"\" log . debug ( \"\" ) self . running = False def channel ( self , ch_type ) : \"\"\"\"\"\" log . debug ( \"\" ) def _new_channel ( self , ch_type , ch_number = None , transport = None ) : \"\"\"\"\"\" chan = ch_type ( ) new_transport = self . _new_transport ( ch_number = ch_number ) if transport is not None : new_transport = ComposableTransport ( transport , new_transport , * ComposableTransport . common_methods ) chan . on_channel_open ( new_transport ) return chan def _new_transport ( self , ch_number = None ) : \"\"\"\"\"\" raise NotImplementedError ( ) def setup_interceptors ( self , interceptor_cfg ) : stack = interceptor_cfg [ \"\" ] defs = interceptor_cfg [ \"\" ] interceptors = defaultdict ( list ) by_name_dict = { } for type_and_direction in stack : interceptor_names = stack [ type_and_direction ] for name in interceptor_names : if name in by_name_dict : classinst = by_name_dict [ name ] else : interceptor_def = defs [ name ] modpath , classname = interceptor_def [ '' ] . rsplit ( '' , ) classinst = for_name ( modpath , classname ) classinst . configure ( config = interceptor_def [ \"\" ] if \"\" in interceptor_def else None ) by_name_dict [ name ] = classinst interceptors [ type_and_direction ] . append ( classinst ) self . interceptors = dict ( interceptors ) class NodeB ( BaseNode ) : \"\"\"\"\"\" def __init__ ( self ) : log . debug ( \"\" ) BaseNode . __init__ ( self ) self . _pool = IDPool ( ) self . _bidir_pool = { } self . _pool_map = { } self . _dead_pool = [ ] BaseNode . __init__ ( self ) def stop_node ( self ) : \"\"\"\"\"\" log . debug ( \"\" , self . running ) if self . running : self . _destroy_pool ( ) self . client . close ( ) ", "answer": "BaseNode . stop_node ( self )"}, {"prompt": " import re from pprint import pformat def e ( string , * args ) : \"\"\"\"\"\" return string . format ( * [ pformat ( arg ) for arg in args ] ) def one_of ( * args ) : \"\"\"\"\"\" if len ( args ) == and isinstance ( args [ ] , list ) : items = args [ ] else : items = list ( args ) def validate ( value ) : if not value in items : return e ( \"\" , value , items ) return validate def gte ( min_value ) : \"\"\"\"\"\" def validate ( value ) : if value < min_value : return e ( \"\" , value , min_value ) return validate def lte ( max_value ) : \"\"\"\"\"\" def validate ( value ) : if value > max_value : return e ( \"\" , value , max_value ) return validate def gt ( gt_value ) : \"\"\"\"\"\" def validate ( value ) : if value <= gt_value : return e ( \"\" , value , gt_value ) return validate def lt ( lt_value ) : \"\"\"\"\"\" def validate ( value ) : if value >= lt_value : return e ( \"\" , value , lt_value ) return validate def between ( min_value , max_value ) : \"\"\"\"\"\" def validate ( value ) : if value < min_value : return e ( \"\" , value , min_value ) if value > max_value : return e ( \"\" , value , max_value ) return validate def length ( min = None , max = None ) : \"\"\"\"\"\" def validate ( value ) : if min and len ( value ) < min : return e ( \"\" , value , min ) if max and len ( value ) > max : ", "answer": "return e ( \"\" , value , max )"}, {"prompt": " \"\"\"\"\"\" from pycompiler . transformer import parse , parseFile from pycompiler . visitor import walk from pycompiler import ast ", "answer": "from pycompiler import transformer "}, {"prompt": " import numpy as _np def eye ( gain = ) : def init ( shape , fan ) : ", "answer": "return gain * _np . eye ( * shape )"}, {"prompt": " import os from datetime import date from . models import MockObject , ExtendedMockObject from postgres_copy import CopyMapping from django . test import TestCase class PostgresCopyTest ( TestCase ) : def setUp ( self ) : ", "answer": "self . data_dir = os . path . join ( os . path . dirname ( __file__ ) , '' )"}, {"prompt": " import os class BaseConfig ( object ) : SECRET_KEY = '' PROJECT_ROOT = os . path . abspath ( os . path . dirname ( __file__ ) ) SQLALCHEMY_DATABASE_URI = '' % ( os . path . join ( PROJECT_ROOT , \"\" ) ) DEBUG = False AUTHORIZATIONS = { '' : { '' : '' , '' : '' , '' : { } , '' : '' , } , } ENABLED_MODULES = ( '' , '' , '' , '' , ", "answer": ")"}, {"prompt": " from gensim . models . doc2vec import Doc2Vec ", "answer": "from gensim . models . doc2vec import LabeledSentence"}, {"prompt": " from __future__ import with_statement from alembic import context from logging . config import fileConfig from subunit2sql . db import api as db_api config = context . config subunit2sql_config = config . subunit2sql_config fileConfig ( config . config_file_name ) target_metadata = None def run_migrations_offline ( ) : \"\"\"\"\"\" kwargs = dict ( ) if subunit2sql_config . database . connection : kwargs [ '' ] = subunit2sql_config . database . connection elif subunit2sql_config . database . engine : kwargs [ '' ] = subunit2sql_config . database . engine else : kwargs [ '' ] = config . get_main_option ( \"\" ) kwargs [ '' ] = target_metadata kwargs [ '' ] = True context . configure ( ** kwargs ) ", "answer": "with context . begin_transaction ( ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " import socket import sys from oslo_config import cfg from oslo_serialization import jsonutils from oslo_utils import importutils from neutron . common import config as common_config from dragonflow . common import common_params from dragonflow . common import exceptions as df_exceptions cfg . CONF . register_opts ( common_params . df_opts , '' ) db_tables = [ '' , '' , '' , '' , '' , '' , '' , '' ] usage_str = \"\" \"\" \"\" \"\" \"\" \"\" \"\" def print_tables ( ) : print ( '' ) print ( '' ) print ( '' ) for table in db_tables : print table print ( '' ) def print_table ( db_driver , table ) : try : keys = db_driver . get_all_keys ( table ) except df_exceptions . DBKeyNotFound : keys = [ ] print ( '' ) print ( '' + table ) print ( '' ) for key in keys : print key print ( '' ) def print_whole_table ( db_driver , table ) : try : keys = db_driver . get_all_keys ( table ) except df_exceptions . DBKeyNotFound : print ( '' + table ) return print ( '' ) print ( '' ) print ( '' + table ) print ( '' ) for key in keys : value = db_driver . get_key ( table , key ) if value : print ( '' + key + '' + value ) print ( '' ) def print_key ( db_driver , table , key ) : try : value = db_driver . get_key ( table , key ) except df_exceptions . DBKeyNotFound : print ( '' + table ) return print ( '' ) print ( '' + table + '' + key ) print ( '' ) print value print ( '' ) def bind_port_to_localhost ( db_driver , port_id ) : lport_str = db_driver . get_key ( '' , port_id ) lport = jsonutils . loads ( lport_str ) chassis_name = socket . gethostname ( ) lport [ '' ] = chassis_name lport_json = jsonutils . dumps ( lport ) db_driver . set_key ( '' , port_id , lport_json ) def clean_whole_table ( db_driver , table ) : try : keys = db_driver . get_all_keys ( table ) except df_exceptions . DBKeyNotFound : print ( '' + table ) return for key in keys : db_driver . delete_key ( table , key ) print ( '' ) def remove_record ( db_driver , table , key ) : try : db_driver . delete_key ( table , key ) except df_exceptions . DBKeyNotFound : print ( '' % ( key , table ) ) def main ( ) : if len ( sys . argv ) < : print usage_str return common_config . init ( [ '' , '' ] ) db_driver_class = importutils . import_class ( cfg . CONF . df . nb_db_class ) db_driver = db_driver_class ( ) db_driver . initialize ( db_ip = cfg . CONF . df . remote_db_ip , db_port = cfg . CONF . df . remote_db_port , config = cfg . CONF . df ) action = sys . argv [ ] if action == '' : if len ( sys . argv ) == : print_tables ( ) return table = sys . argv [ ] if table not in db_tables : print \"\" print db_tables return print_table ( db_driver , table ) return if action == '' : if len ( sys . argv ) < : print \"\" print usage_str return table = sys . argv [ ] if table not in db_tables : print \"\" print db_tables return key = sys . argv [ ] print_key ( db_driver , table , key ) return if action == '' : for table in db_tables : print_whole_table ( db_driver , table ) return if action == '' : port_id = sys . argv [ ] ", "answer": "bind_port_to_localhost ( db_driver , port_id )"}, {"prompt": " '''''' import xmlrpclib import logging import urllib2 import requests import mc_states . api from salt . utils . odict import OrderedDict import salt . exceptions ", "answer": "class ClientNotActivated ( salt . exceptions . SaltException ) :"}, {"prompt": " import sublime import sublime_plugin st_version = if sublime . version ( ) == '' : st_version = print ( '' ) elif int ( sublime . version ( ) ) > : st_version = if st_version == : from . lib . api import CdnjsApiCall from . lib . download import CdnjsDownloadFile from . lib . search import CdnjsSearchCall else : from lib . search import CdnjsSearchCall from lib . api import CdnjsApiCall from lib . download import CdnjsDownloadFile class CdnjsCommand ( sublime_plugin . TextCommand ) : def run ( self , edit ) : CdnjsApiCall ( self . view , ) . start ( ) class CdnjsFileCommand ( sublime_plugin . TextCommand ) : def run ( self , edit ) : CdnjsApiCall ( self . view , , True , True ) . start ( ) class CdnjsUrlCommand ( sublime_plugin . TextCommand ) : def run ( self , edit ) : CdnjsApiCall ( self . view , , True ) . start ( ) class CdnjsPlaceTextCommand ( sublime_plugin . TextCommand ) : def run ( self , edit , ** args ) : self . view . insert ( edit , self . view . sel ( ) [ ] . begin ( ) , args [ \"\" ] ) class CdnjsDownloadFileCommand ( sublime_plugin . TextCommand ) : def run ( self , edit , ** args ) : sublime . status_message ( \"\" % args [ \"\" ] ) CdnjsDownloadFile ( self . view , , \"\" + args [ \"\" ] ) . start ( ) class CdnjsSearchCommand ( sublime_plugin . TextCommand ) : def run ( self , edit , ** args ) : ", "answer": "CdnjsSearchCall ( self . view , ) . start ( ) "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) ", "answer": "result . template = \"\""}, {"prompt": " import logging import asyncio class Logger : DEFAULT = '' RED = '' GREEN = '' YELLOW = '' BLUE = '' MAGENTA = '' CYAN = '' WHITE = '' @ classmethod def c ( cls , color , msg ) : return \"\" % ( color , msg , cls . DEFAULT ) ", "answer": "def __init__ ( self ) :"}, {"prompt": " import sys from twisted . internet import reactor from twisted . python import log from autobahn . twisted . websocket import WebSocketClientFactory , WebSocketClientProtocol , connectWS class EchoClientProtocol ( WebSocketClientProtocol ) : def sendHello ( self ) : self . sendMessage ( \"\" . encode ( '' ) ) def onOpen ( self ) : self . sendHello ( ) def onClose ( self , wasClean , code , reason ) : print ( reason ) def onMessage ( self , payload , isBinary ) : if not isBinary : print ( \"\" . format ( payload . decode ( '' ) ) ) reactor . callLater ( , self . sendHello ) class EchoClientFactory ( WebSocketClientFactory ) : protocol = EchoClientProtocol def clientConnectionLost ( self , connector , reason ) : print ( reason ) reactor . stop ( ) def clientConnectionFailed ( self , connector , reason ) : print ( reason ) reactor . stop ( ) if __name__ == '' : if len ( sys . argv ) < : print ( \"\" ) sys . exit ( ) ", "answer": "factory = EchoClientFactory ( sys . argv [ ] )"}, {"prompt": " from __future__ import absolute_import , division , print_function import os import sys try : ", "answer": "import sphinx_rtd_theme"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " \"\"\"\"\"\" __all__ = [ '' , '' , '' , '' ] import hmac from hashlib import sha1 from time import time from six . moves . urllib . parse import quote from swift . common . exceptions import MimeInvalid from swift . common . middleware . tempurl import get_tempurl_keys_from_metadata from swift . common . utils import streq_const_time , register_swift_info , parse_content_disposition , parse_mime_headers , iter_multipart_mime_documents from swift . common . wsgi import make_pre_authed_env from swift . common . swob import HTTPUnauthorized from swift . proxy . controllers . base import get_account_info , get_container_info READ_CHUNK_SIZE = MAX_VALUE_LENGTH = class FormInvalid ( Exception ) : pass class FormUnauthorized ( Exception ) : pass class _CappedFileLikeObject ( object ) : \"\"\"\"\"\" def __init__ ( self , fp , max_file_size ) : self . fp = fp self . max_file_size = max_file_size self . amount_read = self . file_size_exceeded = False def read ( self , size = None ) : ret = self . fp . read ( size ) self . amount_read += len ( ret ) if self . amount_read > self . max_file_size : self . file_size_exceeded = True raise EOFError ( '' ) return ret def readline ( self ) : ret = self . fp . readline ( ) self . amount_read += len ( ret ) if self . amount_read > self . max_file_size : self . file_size_exceeded = True raise EOFError ( '' ) return ret class FormPost ( object ) : \"\"\"\"\"\" def __init__ ( self , app , conf ) : self . app = app self . conf = conf def __call__ ( self , env , start_response ) : \"\"\"\"\"\" if env [ '' ] == '' : try : content_type , attrs = parse_content_disposition ( env . get ( '' ) or '' ) if content_type == '' and '' in attrs : http_user_agent = \"\" % ( env . get ( '' , '' ) ) env [ '' ] = http_user_agent . strip ( ) status , headers , body = self . _translate_form ( env , attrs [ '' ] ) start_response ( status , headers ) return [ body ] except MimeInvalid : body = '' start_response ( '' , ( ( '' , '' ) , ( '' , str ( len ( body ) ) ) ) ) return [ body ] except ( FormInvalid , EOFError ) as err : body = '' % err start_response ( '' , ( ( '' , '' ) , ( '' , str ( len ( body ) ) ) ) ) return [ body ] except FormUnauthorized as err : message = '' % str ( err ) . title ( ) return HTTPUnauthorized ( body = message ) ( env , start_response ) return self . app ( env , start_response ) def _translate_form ( self , env , boundary ) : \"\"\"\"\"\" keys = self . _get_keys ( env ) status = message = '' attributes = { } subheaders = [ ] file_count = for fp in iter_multipart_mime_documents ( ", "answer": "env [ '' ] , boundary , read_chunk_size = READ_CHUNK_SIZE ) :"}, {"prompt": " from south . db import db from django . db import models from django_lean . experiments . models import * class Migration : def forwards ( self , orm ) : db . create_table ( '' , ( ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_unique ( '' , [ '' , '' ] ) def backwards ( self , orm ) : db . delete_table ( '' ) db . delete_table ( '' ) db . delete_table ( '' ) db . delete_unique ( '' , [ '' , '' ] ) models = { '' : { '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) } , '' : { '' : { '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : \"\" } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' } ) ,"}, {"prompt": " f1 = lambda x : lommels1 ( - , , x ) f2 = lambda x : lommels1 ( , , x ) ", "answer": "f3 = lambda x : lommels1 ( , , x )"}, {"prompt": " \"\"\"\"\"\" import sys import threading sys . path [ : ] = [ \"\" ] from pymongo . errors import AutoReconnect , InvalidOperation from pymongo . server_selectors import writable_server_selector from pymongo . topology_description import TOPOLOGY_TYPE from test import unittest , client_context , MockClientTest from test . pymongo_mocks import MockClient from test . utils import connected , wait_until @ client_context . require_connection def setUpModule ( ) : pass class SimpleOp ( threading . Thread ) : def __init__ ( self , client ) : super ( SimpleOp , self ) . __init__ ( ) self . client = client self . passed = False def run ( self ) : self . client . db . command ( '' ) self . passed = True def do_simple_op ( client , nthreads ) : threads = [ SimpleOp ( client ) for _ in range ( nthreads ) ] for t in threads : t . start ( ) for t in threads : t . join ( ) for t in threads : assert t . passed def writable_addresses ( topology ) : return set ( server . description . address for server in topology . select_servers ( writable_server_selector ) ) class TestMongosLoadBalancing ( MockClientTest ) : def mock_client ( self , ** kwargs ) : mock_client = MockClient ( standalones = [ ] , members = [ ] , mongoses = [ '' , '' , '' ] , host = '' , connect = False , ** kwargs ) mock_client . mock_rtts [ '' ] = mock_client . mock_rtts [ '' ] = mock_client . mock_rtts [ '' ] = return mock_client def test_lazy_connect ( self ) : nthreads = client = self . mock_client ( ) self . assertEqual ( , len ( client . nodes ) ) do_simple_op ( client , nthreads ) wait_until ( lambda : len ( client . nodes ) == , '' ) def test_reconnect ( self ) : nthreads = client = connected ( self . mock_client ( ) ) wait_until ( lambda : len ( client . nodes ) == , '' ) client . close ( ) do_simple_op ( client , nthreads ) wait_until ( lambda : len ( client . nodes ) == , '' ) def test_failover ( self ) : nthreads = client = connected ( self . mock_client ( localThresholdMS = ) ) ", "answer": "wait_until ( lambda : len ( client . nodes ) == , '' )"}, {"prompt": " \"\"\"\"\"\" from sqlalchemy . sql import select , and_ , func TBL_MASTER = '' TBL_CHAT_PATTERN = '' class Conversation : MSG_TYPES = { '' : , '' : , '' : , '' : , ", "answer": "'' : ,"}, {"prompt": " import sys import ast import pythonjs class TransformSuperCalls ( ast . NodeVisitor ) : def __init__ ( self , node , class_names ) : self . _class_names = class_names self . visit ( node ) def visit_Call ( self , node ) : if isinstance ( node . func , ast . Attribute ) and isinstance ( node . func . value , ast . Name ) and node . func . value . id in self . _class_names : node . func . attr = '' + node . func . attr class CollectNames ( ast . NodeVisitor ) : def __init__ ( self ) : self . _names = [ ] def visit_Name ( self , node ) : self . _names . append ( node ) def collect_names ( node ) : a = CollectNames ( ) a . visit ( node ) return a . _names class DartGenerator ( pythonjs . JSGenerator ) : def __init__ ( self , requirejs = False , insert_runtime = False ) : pythonjs . JSGenerator . __init__ ( self , requirejs = False , insert_runtime = False ) self . _classes = dict ( ) self . _class_props = dict ( ) self . _raw_dict = False def visit_With ( self , node ) : s = [ ] for b in node . body : a = self . visit ( b ) a = a . replace ( '' , '' ) a = a . strip ( ) [ : - ] s . append ( a ) return '' . join ( s ) def _visit_subscript_ellipsis ( self , node ) : name = self . visit ( node . value ) return '' % name def visit_List ( self , node ) : return '' % '' . join ( map ( self . visit , node . elts ) ) def visit_Dict ( self , node ) : a = [ ] for i in range ( len ( node . keys ) ) : k = self . visit ( node . keys [ i ] ) v = self . visit ( node . values [ i ] ) a . append ( '' % ( k , v ) ) b = '' . join ( a ) if self . _raw_dict : return '' % b else : return '' % b def visit_ClassDef ( self , node ) : node . _parents = set ( ) out = [ ] extends = False props = set ( [ '' ] ) bases = set ( ) base_classes = set ( ) self . _classes [ node . name ] = node self . _class_props [ node . name ] = props for decor in node . decorator_list : if isinstance ( decor , ast . Call ) : props . update ( [ self . visit ( a ) for a in decor . args ] ) elif isinstance ( decor , ast . Attribute ) and isinstance ( decor . value , ast . Name ) and decor . value . id == '' : if decor . attr == '' : extends = True props . add ( '' ) for name_node in collect_names ( node ) : if name_node . id == '' : name_node . id = '' else : raise SyntaxError for base in node . bases : n = self . visit ( base ) if n == '' : continue node . _parents . add ( n ) bases . add ( n ) if n in self . _class_props : props . update ( self . _class_props [ n ] ) base_classes . add ( self . _classes [ n ] ) else : continue for p in self . _classes [ n ] . _parents : bases . add ( p ) props . update ( self . _class_props [ p ] ) base_classes . add ( self . _classes [ p ] ) if bases : if extends : assert len ( bases ) == out . append ( '' % ( node . name , '' . join ( bases ) ) ) else : out . append ( '' % ( node . name , '' . join ( bases ) ) ) else : out . append ( '' % node . name ) self . push ( ) for p in props : out . append ( self . indent ( ) + '' % p ) method_names = set ( ) for b in node . body : if isinstance ( b , ast . With ) : out . append ( self . visit ( b ) ) elif isinstance ( b , ast . FunctionDef ) and len ( b . decorator_list ) : for name_node in collect_names ( b ) : if name_node . id == '' : name_node . id = '' b . args . args = b . args . args [ : ] out . append ( self . visit ( b ) ) elif extends : if isinstance ( b , ast . FunctionDef ) : b . args . args = b . args . args [ : ] if b . name == node . name : args = [ self . visit ( a ) for a in b . args . args ] args = '' . join ( args ) out . append ( self . indent ( ) + '' % ( node . name , args , args ) ) b . name = '' elif b . name == '' : b . name = '' b . _prefix = '' elif b . name == '' : b . name = '' b . _prefix = '' elif b . name == '' : b . name = '' b . _prefix = '' ", "answer": "elif b . name == '' :"}, {"prompt": " \"\"\"\"\"\" from traits . api import List from tvtk . api import tvtk def _err_msg ( obj , cls_name ) : return '' '' % ( cls_name , str ( obj ) ) def save_ctfs ( volume_property ) : \"\"\"\"\"\" vp = volume_property ctf = vp . rgb_transfer_function otf = vp . get_scalar_opacity ( ) s1 , s2 = ctf . range nc = ctf . size rgb = [ ] if hasattr ( ctf , '' ) : for i in range ( nc ) : x = ctf . nodes [ i ] r , g , b = ctf . get_color ( x ) rgb . append ( [ x , r , g , b ] ) elif hasattr ( ctf , '' ) : val = [ ] * for i in range ( nc ) : ctf . get_node_value ( i , val ) rgb . append ( val [ : ] ) else : raise TypeError ( _err_msg ( ctf , '' ) ) na = otf . size a = [ ] if hasattr ( otf , '' ) : for i in range ( na ) : x = otf . nodes [ i ] val = otf . get_value ( x ) a . append ( [ x , val ] ) elif hasattr ( otf , '' ) : val = [ ] * for i in range ( na ) : ", "answer": "otf . get_node_value ( i , val )"}, {"prompt": " import threading import socket import time import pytest import requests from tests . testserver . server import Server class TestTestServer : def test_basic ( self ) : \"\"\"\"\"\" question = b\"\" answer = b\"\" def handler ( sock ) : text = sock . recv ( ) assert text == question sock . sendall ( answer ) with Server ( handler ) as ( host , port ) : sock = socket . socket ( ) sock . connect ( ( host , port ) ) sock . sendall ( question ) text = sock . recv ( ) assert text == answer sock . close ( ) def test_server_closes ( self ) : \"\"\"\"\"\" with Server . basic_response_server ( ) as ( host , port ) : sock = socket . socket ( ) sock . connect ( ( host , port ) ) sock . close ( ) with pytest . raises ( socket . error ) : new_sock = socket . socket ( ) new_sock . connect ( ( host , port ) ) def test_text_response ( self ) : \"\"\"\"\"\" server = Server . text_response_server ( \"\" + \"\" + \"\" ) with server as ( host , port ) : r = requests . get ( '' . format ( host , port ) ) assert r . status_code == assert r . text == u'' assert r . headers [ '' ] == '' def test_basic_response ( self ) : \"\"\"\"\"\" with Server . basic_response_server ( ) as ( host , port ) : r = requests . get ( '' . format ( host , port ) ) assert r . status_code == assert r . text == u'' assert r . headers [ '' ] == '' def test_basic_waiting_server ( self ) : \"\"\"\"\"\" block_server = threading . Event ( ) with Server . basic_response_server ( wait_to_close_event = block_server ) as ( host , port ) : sock = socket . socket ( ) sock . connect ( ( host , port ) ) sock . sendall ( b'' ) time . sleep ( ) sock . sendall ( b'' ) block_server . set ( ) def test_multiple_requests ( self ) : \"\"\"\"\"\" requests_to_handle = server = Server . basic_response_server ( requests_to_handle = requests_to_handle ) with server as ( host , port ) : server_url = '' . format ( host , port ) for _ in range ( requests_to_handle ) : r = requests . get ( server_url ) assert r . status_code == with pytest . raises ( requests . exceptions . ConnectionError ) : r = requests . get ( server_url ) def test_request_recovery ( self ) : \"\"\"\"\"\" server = Server . basic_response_server ( requests_to_handle = ) first_request = b'' second_request = b'' with server as address : sock1 = socket . socket ( ) sock2 = socket . socket ( ) sock1 . connect ( address ) sock1 . sendall ( first_request ) sock1 . close ( ) sock2 . connect ( address ) sock2 . sendall ( second_request ) sock2 . close ( ) assert server . handler_results [ ] == first_request assert server . handler_results [ ] == second_request def test_requests_after_timeout_are_not_received ( self ) : \"\"\"\"\"\" server = Server . basic_response_server ( request_timeout = ) with server as address : sock = socket . socket ( ) sock . connect ( address ) time . sleep ( ) sock . sendall ( b'' ) sock . close ( ) assert server . handler_results [ ] == b'' def test_request_recovery_with_bigger_timeout ( self ) : \"\"\"\"\"\" server = Server . basic_response_server ( request_timeout = ) data = b'' with server as address : sock = socket . socket ( ) ", "answer": "sock . connect ( address )"}, {"prompt": " __author__ = '' from scipy import append , zeros from pybrain . utilities import abstractMethod , Named class Module ( Named ) : \"\"\"\"\"\" sequential = False paramdim = offset = bufferlist = None def __init__ ( self , indim , outdim , name = None , ** args ) : \"\"\"\"\"\" self . setArgs ( name = name , ** args ) self . bufferlist = [ ] if not self . bufferlist else self . bufferlist self . bufferlist += [ ( '' , indim ) , ( '' , indim ) , ( '' , outdim ) , ( '' , outdim ) , ] self . indim = indim self . outdim = outdim self . _resetBuffers ( ) def _resetBuffers ( self , length = ) : \"\"\"\"\"\" for buffername , dim in self . bufferlist : setattr ( self , buffername , zeros ( ( length , dim ) ) ) if length == : self . offset = def _growBuffers ( self ) : \"\"\"\"\"\" currentlength = getattr ( self , self . bufferlist [ ] [ ] ) . shape [ ] tmp = [ getattr ( self , n ) for n , _ in self . bufferlist ] Module . _resetBuffers ( self , currentlength * ) for previous , ( buffername , _dim ) in zip ( tmp , self . bufferlist ) : buffer_ = getattr ( self , buffername ) buffer_ [ : currentlength ] = previous def forward ( self ) : \"\"\"\"\"\" self . _forwardImplementation ( self . inputbuffer [ self . offset ] , self . outputbuffer [ self . offset ] ) def backward ( self ) : \"\"\"\"\"\" self . _backwardImplementation ( self . outputerror [ self . offset ] , self . inputerror [ self . offset ] , self . outputbuffer [ self . offset ] , self . inputbuffer [ self . offset ] ) def reset ( self ) : \"\"\"\"\"\" self . offset = for buffername , l in self . bufferlist : buf = getattr ( self , buffername ) buf [ : ] = zeros ( l ) def shift ( self , items ) : \"\"\"\"\"\" if items == : return self . offset += items for buffername , _ in self . bufferlist : buf = getattr ( self , buffername ) assert abs ( items ) <= len ( buf ) , \"\" fill = zeros ( ( abs ( items ) , len ( buf [ ] ) ) ) if items < : buf [ : ] = append ( buf [ - items : ] , fill , ) else : buf [ : ] = append ( fill , buf [ : - items ] , ) def activateOnDataset ( self , dataset ) : \"\"\"\"\"\" dataset . reset ( ) self . reset ( ) out = zeros ( ( len ( dataset ) , self . outdim ) ) for i , sample in enumerate ( dataset ) : out [ i , : ] = self . activate ( sample [ ] ) self . reset ( ) dataset . reset ( ) return out def activate ( self , inpt ) : \"\"\"\"\"\" assert len ( self . inputbuffer [ self . offset ] ) == len ( inpt ) , str ( ( len ( self . inputbuffer [ self . offset ] ) , len ( inpt ) ) ) self . inputbuffer [ self . offset ] = inpt self . forward ( ) return self . outputbuffer [ self . offset ] . copy ( ) def backActivate ( self , outerr ) : \"\"\"\"\"\" self . outputerror [ self . offset ] = outerr self . backward ( ) ", "answer": "return self . inputerror [ self . offset ] . copy ( )"}, {"prompt": " from django . conf . urls . defaults import * from django . conf import settings urlpatterns = patterns ( '' , url ( r'' , '' , { '' : settings . STATIC_MEDIA_PATH } , name = '' ) , ", "answer": ") "}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from datetime import date from kitsune . customercare . badges import AOA_BADGE from kitsune . customercare . tests import ReplyFactory from kitsune . kbadge . tests import BadgeFactory from kitsune . sumo . tests import TestCase from kitsune . users . tests import UserFactory from kitsune . customercare . badges import register_signals class TestAOABadges ( TestCase ) : def setUp ( self ) : register_signals ( ) def test_aoa_badge ( self ) : \"\"\"\"\"\" year = date . today ( ) . year u = UserFactory ( ) b = BadgeFactory ( slug = AOA_BADGE [ '' ] . format ( year = year ) , title = AOA_BADGE [ '' ] . format ( year = year ) , description = AOA_BADGE [ '' ] . format ( year = year ) ) for _ in range ( ) : ReplyFactory ( user = u ) ", "answer": "assert not b . is_awarded_to ( u )"}, {"prompt": " import re log_translation_LI = re . compile ( r\"\" ) log_translation_LE = re . compile ( r\"\" ) log_translation_LW = re . compile ( r\"\" ) log_translation_LC = re . compile ( r\"\" ) accepted_log_level = re . compile ( r\"\" ) def validate_log_translations ( logical_line , filename ) : \"\"\"\"\"\" ignore_dirs = [ \"\" , \"\" , \"\" ] for directory in ignore_dirs : if directory in filename : return msg = \"\" if log_translation_LI . search ( logical_line ) : yield ( , msg ) msg = ( \"\" \"\" ) if log_translation_LE . search ( logical_line ) : yield ( , msg ) msg = \"\" if log_translation_LW . search ( logical_line ) : yield ( , msg ) msg = \"\" if log_translation_LC . search ( logical_line ) : yield ( , msg ) def no_translate_debug_logs ( logical_line , filename ) : \"\"\"\"\"\" msg = \"\" if logical_line . startswith ( \"\" ) : yield ( , msg ) def accepted_log_levels ( logical_line , filename ) : \"\"\"\"\"\" ignore_dirs = [ \"\" , \"\" , \"\" ] for directory in ignore_dirs : if directory in filename : return msg = ( \"\" \"\" ) if logical_line . startswith ( \"\" ) : if not accepted_log_level . search ( logical_line ) : ", "answer": "yield ( , msg ) "}, {"prompt": " import mock from oslo_utils import uuidutils from neutron import context from neutron . db . quota import api as quota_db_api from neutron . tests . unit . api import test_extensions from neutron . tests . unit . extensions import test_l3 from neutron . tests . unit . extensions import test_securitygroup from neutron . tests . unit . plugins . ml2 import base as ml2_base ", "answer": "from neutron . tests . unit . plugins . ml2 import test_plugin"}, {"prompt": " import math import unittest from scipy import stats import numpy as np import theano import theano . tensor as T from neupy . utils import asfloat from neupy import layers from neupy . algorithms import GradientDescent from neupy . layers . connections import NetworkConnectionError from neupy . layers import * from base import BaseTestCase class LayersBasicsTestCase ( BaseTestCase ) : def test_without_output_layer ( self ) : with self . assertRaises ( NetworkConnectionError ) : GradientDescent ( layers . Sigmoid ( ) > layers . Sigmoid ( ) ) def test_list_of_layers ( self ) : bpnet = GradientDescent ( [ Sigmoid ( ) , Sigmoid ( ) , Sigmoid ( ) , Output ( ) ] ) self . assertEqual ( [ layer . size for layer in bpnet . all_layers ] , [ , , , ] ) def test_layers_iteratinos ( self ) : network = GradientDescent ( ( , , ) ) layers = list ( network . all_layers ) output_layer = layers . pop ( ) self . assertIsNone ( output_layer . relate_to_layer ) for layer in layers : self . assertIsNotNone ( layer . relate_to_layer ) def test_connection_initializations ( self ) : possible_connections = ( ( , , ) , [ Sigmoid ( ) , Tanh ( ) , Output ( ) ] , Relu ( ) > Tanh ( ) > Output ( ) , ) for connection in possible_connections : network = GradientDescent ( connection ) self . assertEqual ( len ( network . all_layers ) , ) @ unittest . skip ( \"\" ) def test_recurrent_connections ( self ) : inp = Sigmoid ( ) hd = [ Sigmoid ( ) , Sigmoid ( ) ] out = Output ( ) GradientDescent ( connection = ( inp > hd [ ] > out , hd [ ] > hd [ ] , hd [ ] > hd [ ] , ) ) def test_activation_layers_without_size ( self ) : input_data = np . array ( [ , , - , ] ) expected_output = np . array ( [ , , , ] ) ", "answer": "layer = layers . Relu ( )"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ) MANAGERS = ADMINS DATABASES = { '' : { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } } ALLOWED_HOSTS = [ ] TIME_ZONE = '' LANGUAGE_CODE = '' SITE_ID = USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = '' MEDIA_URL = '' STATIC_ROOT = '' STATIC_URL = '' STATICFILES_DIRS = ( ) STATICFILES_FINDERS = ( '' , ", "answer": "'' ,"}, {"prompt": " '''''' import socket import logging from django . core . management . base import NoArgsCommand from django_dust import retry_storage from django_dust . storage import DistributedStorage from django_dust . http import HTTPError logger = logging . getLogger ( '' ) def _to_unicode ( retry ) : return u'' % retry class Command ( NoArgsCommand ) : help = \"\" def handle_noargs ( self , ** options ) : logger . info ( '' ) storage = DistributedStorage ( ) retries = retry_storage . all ( ) logger . info ( '' % len ( retries ) ) for retry in retries : logger . info ( '' % _to_unicode ( retry ) ) try : if retry [ '' ] == '' : ", "answer": "body = storage . transport . get ( retry [ '' ] , retry [ '' ] )"}, {"prompt": " \"\"\"\"\"\" import sys import types PY2 = sys . version_info [ ] == PY3 = sys . version_info [ ] == if PY3 : string_types = str , integer_types = int , class_types = type , text_type = str binary_type = bytes else : string_types = basestring , ", "answer": "integer_types = ( int , long )"}, {"prompt": " from south . utils import datetime_utils as datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( u'' , '' , self . gf ( '' ) ( to = orm [ '' ] , null = True , blank = True ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( u'' , '' ) models = { u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) } , u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } } ", "answer": "complete_apps = [ '' ] "}, {"prompt": " import datetime import sys import tempfile import fixtures import mock from oslo_config import cfg from subunit2sql import exceptions from subunit2sql . migrations import cli as migration_cli from subunit2sql import shell from subunit2sql . tests import base class TestShell ( base . TestCase ) : def test_run_totals ( self ) : fake_results = { } for num in range ( ) : test_name = '' + str ( num ) fake_results [ test_name ] = { '' : '' } for num in range ( ) : test_name = '' + str ( num ) fake_results [ test_name ] = { '' : '' } for num in range ( ) : test_name = '' + str ( num ) fake_results [ test_name ] = { '' : '' } totals = shell . get_run_totals ( fake_results ) self . assertEqual ( totals [ '' ] , ) self . assertEqual ( totals [ '' ] , ) self . assertEqual ( totals [ '' ] , ) def test_running_avg ( self ) : fake_test = mock . MagicMock ( ) fake_test . success = fake_test . run_time = fake_result = { '' : datetime . datetime ( , , , , , ) , '' : datetime . datetime ( , , , , , ) , } fake_values = { } result = shell . running_avg ( fake_test , fake_values , fake_result ) expected_avg = ( ( * ) + ) / self . assertEqual ( expected_avg , result [ '' ] ) def test_running_avg_no_prev ( self ) : fake_test = mock . MagicMock ( ) fake_test . success = fake_test . run_time = None fake_result = { '' : datetime . datetime ( , , , , , ) , '' : datetime . datetime ( , , , , , ) , } fake_values = { } result = shell . running_avg ( fake_test , fake_values , fake_result ) expected_avg = self . assertEqual ( expected_avg , result [ '' ] ) def test_increment_counts_success ( self ) : fake_test = mock . MagicMock ( ) fake_test . run_count = fake_test . success = fake_test . run_time = fake_result = { '' : '' , '' : datetime . datetime ( , , , , , ) , '' : datetime . datetime ( , , , , , ) , } values = shell . increment_counts ( fake_test , fake_result ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) expected_avg = ( ( * ) + ) / self . assertEqual ( values [ '' ] , expected_avg ) def test_increment_counts_failure ( self ) : fake_test = mock . MagicMock ( ) fake_test . run_count = fake_test . success = fake_test . failure = fake_test . run_time = fake_result = { '' : '' , '' : datetime . datetime ( , , , , , ) , '' : datetime . datetime ( , , , , , ) , } values = shell . increment_counts ( fake_test , fake_result ) self . assertEqual ( values [ '' ] , ) self . assertEqual ( values [ '' ] , ) self . assertNotIn ( '' , values ) def test_increment_counts_skip ( self ) : fake_test = mock . MagicMock ( ) fake_test . run_count = fake_test . success = fake_test . failure = fake_test . run_time = fake_result = { '' : '' , '' : datetime . datetime ( , , , , , ) , '' : datetime . datetime ( , , , , , ) , } values = shell . increment_counts ( fake_test , fake_result ) self . assertEqual ( values , { } ) def test_increment_counts_unknown_status ( self ) : fake_test = mock . MagicMock ( ) fake_result = { '' : '' , '' : datetime . datetime ( , , , , , ) , '' : datetime . datetime ( , , , , , ) , } self . assertRaises ( exceptions . UnknownStatus , shell . increment_counts , fake_test , fake_result ) class TestMain ( base . TestCase ) : def setUp ( self ) : super ( TestMain , self ) . setUp ( ) cfg . CONF . reset ( ) cfg . CONF . unregister_opt ( migration_cli . command_opt ) self . fake_args = [ '' ] self . useFixture ( fixtures . MonkeyPatch ( '' , self . fake_args ) ) @ mock . patch ( '' ) @ mock . patch ( '' ) def test_main ( self , process_results_mock , read_subunit_mock ) : fake_read_subunit = mock . MagicMock ( '' ) fake_get_results = '' fake_read_subunit . get_results = mock . MagicMock ( '' ) fake_read_subunit . get_results . return_value = fake_get_results read_subunit_mock . return_value = fake_read_subunit shell . main ( ) read_subunit_mock . assert_called_once_with ( sys . stdin , attachments = False , ", "answer": "attr_regex = '' ,"}, {"prompt": " from . sync import * from . interchange import * from . gpx import * ", "answer": "from . statistics import * "}, {"prompt": " \"\"\"\"\"\" import textwrap import itertools from ganeti . cli import * from ganeti import constants from ganeti import opcodes from ganeti import utils from ganeti import errors from ganeti import objects _LIST_DEF_FIELDS = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] def _HandleReservedIPs ( ips ) : if ips is None : return None elif not ips : return [ ] else : return utils . UnescapeAndSplit ( ips , sep = \"\" ) def AddNetwork ( opts , args ) : \"\"\"\"\"\" ( network_name , ) = args if opts . network is None : raise errors . OpPrereqError ( \"\" , errors . ECODE_INVAL ) if opts . tags is not None : tags = opts . tags . split ( \"\" ) else : tags = [ ] reserved_ips = _HandleReservedIPs ( opts . add_reserved_ips ) op = opcodes . OpNetworkAdd ( network_name = network_name , gateway = opts . gateway , network = opts . network , gateway6 = opts . gateway6 , network6 = opts . network6 , mac_prefix = opts . mac_prefix , add_reserved_ips = reserved_ips , conflicts_check = opts . conflicts_check , tags = tags ) SubmitOrSend ( op , opts ) def _GetDefaultGroups ( cl , groups ) : \"\"\"\"\"\" if groups : return groups return list ( itertools . chain ( * cl . QueryGroups ( [ ] , [ \"\" ] , False ) ) ) def ConnectNetwork ( opts , args ) : \"\"\"\"\"\" cl = GetClient ( ) network = args [ ] nicparams = objects . FillDict ( constants . NICC_DEFAULTS , opts . nicparams ) groups = _GetDefaultGroups ( cl , args [ : ] ) for group in groups : op = opcodes . OpNetworkConnect ( group_name = group , network_name = network , network_mode = nicparams [ constants . NIC_MODE ] , network_link = nicparams [ constants . NIC_LINK ] , network_vlan = nicparams [ constants . NIC_VLAN ] , conflicts_check = opts . conflicts_check ) SubmitOpCode ( op , opts = opts , cl = cl ) def DisconnectNetwork ( opts , args ) : \"\"\"\"\"\" cl = GetClient ( ) ( network , ) = args [ : ] groups = _GetDefaultGroups ( cl , args [ : ] ) for group in groups : op = opcodes . OpNetworkDisconnect ( group_name = group , network_name = network ) SubmitOpCode ( op , opts = opts , cl = cl ) def ListNetworks ( opts , args ) : \"\"\"\"\"\" desired_fields = ParseFields ( opts . output , _LIST_DEF_FIELDS ) fmtoverride = { \"\" : ( lambda data : utils . CommaJoin ( \"\" % ( name , mode , link , vlan ) for ( name , mode , link , vlan ) in data ) , ", "answer": "False ) ,"}, {"prompt": " from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from builtins import range from future import standard_library standard_library . install_aliases ( ) import sys PYTHON_VERSION = sys . version_info [ : ] PY2 = ( PYTHON_VERSION [ ] == ) if PY2 : if PYTHON_VERSION < ( , , ) : raise Exception ( '' ) elif PYTHON_VERSION < ( , ) : raise Exception ( '' ) import hpOneView as hpov from pprint import pprint ", "answer": "import json"}, {"prompt": " \"\"\"\"\"\" import logging import os import os . path import resource import shutil import sys from . proxy import run_subprocess_through_proxy from . subproc import run_subprocess from . util import temp_directory log = logging . getLogger ( \"\" ) COMMANDS = { } def configure ( command , bin_path , user = None ) : \"\"\"\"\"\" cmd_argv = [ bin_path ] if command == \"\" : cmd_argv . extend ( [ '' , '' ] ) COMMANDS [ command ] = { '' : cmd_argv , '' : user , } def is_configured ( command ) : \"\"\"\"\"\" return command in COMMANDS if hasattr ( sys , '' ) : if os . path . isdir ( sys . prefix + \"\" ) : configure ( \"\" , sys . prefix + \"\" , \"\" ) LIMITS = { \"\" : , \"\" : , \"\" : , \"\" : , \"\" : None , } def set_limit ( limit_name , value ) : \"\"\"\"\"\" LIMITS [ limit_name ] = value class JailResult ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . stdout = self . stderr = self . status = None def jail_code ( command , code = None , files = None , extra_files = None , argv = None , stdin = None , slug = None ) : \"\"\"\"\"\" if not is_configured ( command ) : raise Exception ( \"\" % command ) with temp_directory ( ) as homedir : os . chmod ( homedir , ) tmptmp = os . path . join ( homedir , \"\" ) os . mkdir ( tmptmp ) os . chmod ( tmptmp , ) argv = argv or [ ] for filename in files or ( ) : dest = os . path . join ( homedir , os . path . basename ( filename ) ) if os . path . islink ( filename ) : os . symlink ( os . readlink ( filename ) , dest ) elif os . path . isfile ( filename ) : shutil . copy ( filename , homedir ) else : shutil . copytree ( filename , dest , symlinks = True ) if code : ", "answer": "with open ( os . path . join ( homedir , \"\" ) , \"\" ) as jailed :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " import os import re from django . conf import settings from django . contrib . auth . models import User from django . test import TestCase from django . core import mail class PasswordResetTest ( TestCase ) : fixtures = [ '' ] urls = '' def test_email_not_found ( self ) : \"\" response = self . client . get ( '' ) self . assertEquals ( response . status_code , ) response = self . client . post ( '' , { '' : '' } ) self . assertContains ( response , \"\" ) self . assertEquals ( len ( mail . outbox ) , ) def test_email_found ( self ) : \"\" response = self . client . post ( '' , { '' : '' } ) self . assertEquals ( response . status_code , ) self . assertEquals ( len ( mail . outbox ) , ) self . assert_ ( \"\" in mail . outbox [ ] . body ) def _test_confirm_start ( self ) : response = self . client . post ( '' , { '' : '' } ) self . assertEquals ( response . status_code , ) self . assertEquals ( len ( mail . outbox ) , ) return self . _read_signup_email ( mail . outbox [ ] ) def _read_signup_email ( self , email ) : urlmatch = re . search ( r\"\" , email . body ) self . assert_ ( urlmatch is not None , \"\" ) return urlmatch . group ( ) , urlmatch . groups ( ) [ ] def test_confirm_valid ( self ) : url , path = self . _test_confirm_start ( ) response = self . client . get ( path ) self . assertEquals ( response . status_code , ) self . assert_ ( \"\" in response . content ) def test_confirm_invalid ( self ) : url , path = self . _test_confirm_start ( ) path = path [ : - ] + ( \"\" * ) + path [ - ] response = self . client . get ( path ) self . assertEquals ( response . status_code , ) self . assert_ ( \"\" in response . content ) def test_confirm_invalid_post ( self ) : url , path = self . _test_confirm_start ( ) path = path [ : - ] + ( \"\" * ) + path [ - ] response = self . client . post ( path , { '' : '' , '' : '' } ) u = User . objects . get ( email = '' ) self . assert_ ( not u . check_password ( \"\" ) ) def test_confirm_complete ( self ) : url , path = self . _test_confirm_start ( ) ", "answer": "response = self . client . post ( path , { '' : '' ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function from collections import deque from copy import copy from itertools import count import theano from theano import config from theano . gof import utils from six import string_types , integer_types , iteritems from theano . misc . ordered_set import OrderedSet __docformat__ = \"\" is_same_graph_with_merge = None equal_computations = None NoParams = object ( ) class Node ( utils . object2 ) : \"\"\"\"\"\" def get_parents ( self ) : \"\"\"\"\"\" raise NotImplementedError ( ) class Apply ( Node ) : \"\"\"\"\"\" def __init__ ( self , op , inputs , outputs ) : self . op = op self . inputs = [ ] self . tag = utils . scratchpad ( ) if not isinstance ( inputs , ( list , tuple ) ) : raise TypeError ( \"\" ) if not isinstance ( outputs , ( list , tuple ) ) : raise TypeError ( \"\" ) for input in inputs : if isinstance ( input , Variable ) : self . inputs . append ( input ) else : raise TypeError ( \"\" % input ) self . outputs = [ ] for i , output in enumerate ( outputs ) : if isinstance ( output , Variable ) : if output . owner is None : output . owner = self output . index = i elif output . owner is not self or output . index != i : raise ValueError ( \"\" ) self . outputs . append ( output ) else : raise TypeError ( \"\" % output ) def run_params ( self ) : \"\"\"\"\"\" if hasattr ( self . op , '' ) : return self . op . get_params ( self ) return NoParams def __getstate__ ( self ) : d = self . __dict__ if hasattr ( self . tag , '' ) : d = copy ( self . __dict__ ) t = d [ \"\" ] del t . ufunc d [ \"\" ] = t return d def default_output ( self ) : \"\"\"\"\"\" do = getattr ( self . op , '' , None ) if do is None : if len ( self . outputs ) == : return self . outputs [ ] else : raise AttributeError ( \"\" % self . op ) elif not isinstance ( do , integer_types ) : raise AttributeError ( \"\" % self . op ) elif do < or do >= len ( self . outputs ) : raise AttributeError ( \"\" % self . op ) return self . outputs [ do ] out = property ( default_output , doc = \"\" ) \"\"\"\"\"\" def __str__ ( self ) : return op_as_string ( self . inputs , self ) def __repr__ ( self ) : return str ( self ) def __asapply__ ( self ) : return self def clone ( self ) : \"\"\"\"\"\" cp = self . __class__ ( self . op , self . inputs , [ output . clone ( ) for output in self . outputs ] ) cp . tag = copy ( self . tag ) return cp def clone_with_new_inputs ( self , inputs , strict = True ) : \"\"\"\"\"\" assert isinstance ( inputs , ( list , tuple ) ) remake_node = False new_inputs = inputs [ : ] for i , ( curr , new ) in enumerate ( zip ( self . inputs , new_inputs ) ) : if not curr . type == new . type : if strict : new_inputs [ i ] = curr . type . filter_variable ( new ) else : remake_node = True if remake_node : new_node = self . op . make_node ( * new_inputs ) new_node . tag = copy ( self . tag ) . __update__ ( new_node . tag ) else : new_node = self . clone ( ) new_node . inputs = new_inputs return new_node def get_parents ( self ) : return list ( self . inputs ) nin = property ( lambda self : len ( self . inputs ) , doc = '' ) \"\"\"\"\"\" nout = property ( lambda self : len ( self . outputs ) , doc = '' ) \"\"\"\"\"\" params_type = property ( lambda self : self . op . params_type , doc = '' ) class Variable ( Node ) : \"\"\"\"\"\" __count__ = count ( ) def __init__ ( self , type , owner = None , index = None , name = None ) : super ( Variable , self ) . __init__ ( ) self . tag = utils . scratchpad ( ) self . type = type if owner is not None and not isinstance ( owner , Apply ) : raise TypeError ( \"\" , owner ) self . owner = owner if index is not None and not isinstance ( index , int ) : raise TypeError ( \"\" , index ) self . index = index if name is not None and not isinstance ( name , string_types ) : raise TypeError ( \"\" , name ) self . name = name self . auto_name = '' + str ( next ( self . __count__ ) ) def __str__ ( self ) : \"\"\"\"\"\" if self . name is not None : return self . name if self . owner is not None : op = self . owner . op if self . index == op . default_output : return str ( self . owner . op ) + \"\" else : return str ( self . owner . op ) + \"\" + str ( self . index ) else : return \"\" % str ( self . type ) def __repr_test_value__ ( self ) : \"\"\"\"\"\" return repr ( theano . gof . op . get_test_value ( self ) ) def __repr__ ( self , firstPass = True ) : \"\"\"\"\"\" to_print = [ str ( self ) ] if config . print_test_value and firstPass : try : to_print . append ( self . __repr_test_value__ ( ) ) except AttributeError : pass return '' . join ( to_print ) def clone ( self ) : \"\"\"\"\"\" cp = self . __class__ ( self . type , None , None , self . name ) cp . tag = copy ( self . tag ) return cp def __lt__ ( self , other ) : raise NotImplementedError ( '' , self . __class__ . __name__ ) def __le__ ( self , other ) : raise NotImplementedError ( '' , self . __class__ . __name__ ) def __gt__ ( self , other ) : raise NotImplementedError ( '' , self . __class__ . __name__ ) def __ge__ ( self , other ) : raise NotImplementedError ( '' , self . __class__ . __name__ ) def get_parents ( self ) : if self . owner is not None : return [ self . owner ] return [ ] def eval ( self , inputs_to_values = None ) : \"\"\"\"\"\" if inputs_to_values is None : inputs_to_values = { } if not hasattr ( self , '' ) : self . _fn_cache = dict ( ) inputs = tuple ( sorted ( inputs_to_values . keys ( ) , key = id ) ) if inputs not in self . _fn_cache : self . _fn_cache [ inputs ] = theano . function ( inputs , self ) args = [ inputs_to_values [ param ] for param in inputs ] rval = self . _fn_cache [ inputs ] ( * args ) return rval def __getstate__ ( self ) : d = self . __dict__ . copy ( ) d . pop ( \"\" , None ) return d class Constant ( Variable ) : \"\"\"\"\"\" def __init__ ( self , type , data , name = None ) : Variable . __init__ ( self , type , None , None , name ) self . data = type . filter ( data ) def equals ( self , other ) : return isinstance ( other , Constant ) and self . signature ( ) == other . signature ( ) def signature ( self ) : return ( self . type , self . data ) def merge_signature ( self ) : return self . signature ( ) def __str__ ( self ) : if self . name is not None : return self . name else : name = str ( self . data ) if len ( name ) > : name = name [ : ] + '' + name [ - : ] return '' % name def clone ( self ) : \"\"\"\"\"\" cp = self . __class__ ( self . type , self . data , self . name ) cp . tag = copy ( self . tag ) return cp def __set_owner ( self , value ) : \"\"\"\"\"\" if value is not None : raise ValueError ( \"\" ) owner = property ( lambda self : None , __set_owner ) value = property ( lambda self : self . data , doc = '' ) def stack_search ( start , expand , mode = '' , build_inv = False ) : \"\"\"\"\"\" if mode not in ( '' , '' ) : raise ValueError ( '' , mode ) rval_set = set ( ) rval_list = list ( ) if mode == '' : start_pop = start . popleft else : start_pop = start . pop expand_inv = { } while start : l = start_pop ( ) if id ( l ) not in rval_set : rval_list . append ( l ) rval_set . add ( id ( l ) ) expand_l = expand ( l ) if expand_l : if build_inv : for r in expand_l : expand_inv . setdefault ( r , [ ] ) . append ( l ) start . extend ( expand_l ) assert len ( rval_list ) == len ( rval_set ) if build_inv : return rval_list , expand_inv return rval_list def ancestors ( variable_list , blockers = None ) : \"\"\"\"\"\" def expand ( r ) : if r . owner and ( not blockers or r not in blockers ) : return reversed ( r . owner . inputs ) dfs_variables = stack_search ( deque ( variable_list ) , expand , '' ) return dfs_variables def inputs ( variable_list , blockers = None ) : \"\"\"\"\"\" vlist = ancestors ( variable_list , blockers ) rval = [ r for r in vlist if r . owner is None ] return rval def variables_and_orphans ( i , o ) : \"\"\"\"\"\" def expand ( r ) : if r . owner and r not in i : l = list ( r . owner . inputs ) + list ( r . owner . outputs ) l . reverse ( ) return l variables = stack_search ( deque ( o ) , expand , '' ) orphans = [ r for r in variables if r . owner is None and r not in i ] return variables , orphans def ops ( i , o ) : \"\"\"\"\"\" ops = set ( ) variables , orphans = variables_and_orphans ( i , o ) for r in variables : if r not in i and r not in orphans : if r . owner is not None : ops . add ( r . owner ) return ops def variables ( i , o ) : \"\"\"\"\"\" return variables_and_orphans ( i , o ) [ ] def orphans ( i , o ) : \"\"\"\"\"\" return variables_and_orphans ( i , o ) [ ] def clone ( i , o , copy_inputs = True ) : \"\"\"\"\"\" equiv = clone_get_equiv ( i , o , copy_inputs ) return [ equiv [ input ] for input in i ] , [ equiv [ output ] for output in o ] def clone_get_equiv ( inputs , outputs , copy_inputs_and_orphans = True , memo = None ) : \"\"\"\"\"\" if memo is None : memo = { } for input in inputs : if copy_inputs_and_orphans : cpy = input . clone ( ) cpy . owner = None cpy . index = None memo . setdefault ( input , cpy ) else : memo . setdefault ( input , input ) for apply in io_toposort ( inputs , outputs ) : for input in apply . inputs : if input not in memo : if copy_inputs_and_orphans : cpy = input . clone ( ) memo [ input ] = cpy else : memo [ input ] = input new_apply = apply . clone_with_new_inputs ( [ memo [ i ] for i in apply . inputs ] ) memo . setdefault ( apply , new_apply ) for output , new_output in zip ( apply . outputs , new_apply . outputs ) : memo . setdefault ( output , new_output ) for output in outputs : if output not in memo : memo [ output ] = output . clone ( ) return memo def general_toposort ( r_out , deps , debug_print = False , compute_deps_cache = None , deps_cache = None , clients = None ) : \"\"\"\"\"\" if compute_deps_cache is None : deps_cache = { } def compute_deps_cache ( io ) : if io not in deps_cache : d = deps ( io ) if d : if not isinstance ( d , ( list , OrderedSet ) ) : raise TypeError ( \"\" \"\" ) deps_cache [ io ] = list ( d ) else : deps_cache [ io ] = d return d else : return deps_cache [ io ] assert deps_cache is not None assert isinstance ( r_out , ( tuple , list , deque ) ) reachable , _clients = stack_search ( deque ( r_out ) , compute_deps_cache , '' , True ) if clients is not None : clients . update ( _clients ) sources = deque ( [ r for r in reachable if not deps_cache . get ( r , None ) ] ) rset = set ( ) rlist = [ ] while sources : node = sources . popleft ( ) if node not in rset : rlist . append ( node ) rset . add ( node ) for client in _clients . get ( node , [ ] ) : deps_cache [ client ] = [ a for a in deps_cache [ client ] if a is not node ] if not deps_cache [ client ] : sources . append ( client ) if len ( rlist ) != len ( reachable ) : if debug_print : print ( '' ) print ( reachable ) print ( rlist ) raise ValueError ( '' ) return rlist def io_toposort ( inputs , outputs , orderings = None , clients = None ) : \"\"\"\"\"\" iset = set ( inputs ) deps_cache = { } compute_deps = None compute_deps_cache = None if not orderings : def compute_deps_cache ( obj ) : if obj in deps_cache : return deps_cache [ obj ] rval = [ ] if obj not in iset : if isinstance ( obj , Variable ) : if obj . owner : rval = [ obj . owner ] elif isinstance ( obj , Apply ) : rval = list ( obj . inputs ) if rval : if not isinstance ( rval , ( list , OrderedSet ) ) : raise TypeError ( \"\" \"\" ) deps_cache [ obj ] = list ( rval ) else : deps_cache [ obj ] = rval else : deps_cache [ obj ] = rval return rval else : def compute_deps ( obj ) : rval = [ ] if obj not in iset : if isinstance ( obj , Variable ) : if obj . owner : rval = [ obj . owner ] elif isinstance ( obj , Apply ) : rval = list ( obj . inputs ) rval . extend ( orderings . get ( obj , [ ] ) ) else : assert not orderings . get ( obj , [ ] ) return rval topo = general_toposort ( outputs , deps = compute_deps , compute_deps_cache = compute_deps_cache , deps_cache = deps_cache , clients = clients ) return [ o for o in topo if isinstance ( o , Apply ) ] default_leaf_formatter = str def default_node_formatter ( op , argstrings ) : return \"\" % ( op . op , \"\" . join ( argstrings ) ) def io_connection_pattern ( inputs , outputs ) : \"\"\"\"\"\" inner_nodes = io_toposort ( inputs , outputs ) connect_pattern_by_var = { } nb_inputs = len ( inputs ) for i in range ( nb_inputs ) : input = inputs [ i ] inp_connection_pattern = [ i == j for j in range ( nb_inputs ) ] connect_pattern_by_var [ input ] = inp_connection_pattern for n in inner_nodes : try : op_connection_pattern = n . op . connection_pattern ( n ) except AttributeError : op_connection_pattern = ( [ [ True ] * len ( n . outputs ) ] * len ( n . inputs ) ) for out_idx in range ( len ( n . outputs ) ) : out = n . outputs [ out_idx ] out_connection_pattern = [ False ] * nb_inputs for inp_idx in range ( len ( n . inputs ) ) : inp = n . inputs [ inp_idx ] if inp in connect_pattern_by_var : inp_connection_pattern = connect_pattern_by_var [ inp ] if op_connection_pattern [ inp_idx ] [ out_idx ] : out_connection_pattern = [ out_connection_pattern [ i ] or inp_connection_pattern [ i ] for i in range ( nb_inputs ) ] connect_pattern_by_var [ out ] = out_connection_pattern global_connection_pattern = [ [ ] for o in range ( len ( inputs ) ) ] for out in outputs : out_connection_pattern = connect_pattern_by_var [ out ] for i in range ( len ( inputs ) ) : global_connection_pattern [ i ] . append ( out_connection_pattern [ i ] ) return global_connection_pattern def is_same_graph ( var1 , var2 , givens = None , debug = False ) : \"\"\"\"\"\" if givens is None : givens = { } global equal_computations , is_same_graph_with_merge if equal_computations is None : from theano . gof . opt import is_same_graph_with_merge from theano . scan_module . scan_utils import equal_computations if not isinstance ( givens , dict ) : givens = dict ( givens ) rval1 = is_same_graph_with_merge ( var1 = var1 , var2 = var2 , givens = givens ) use_equal_computations = True if givens : ok = True in_xs = [ ] in_ys = [ ] inputs_var = list ( map ( inputs , ( [ var1 ] , [ var2 ] ) ) ) all_vars = [ set ( variables ( v_i , v_o ) ) for v_i , v_o in ( ( inputs_var [ ] , [ var1 ] ) , ( inputs_var [ ] , [ var2 ] ) ) ] def in_var ( x , k ) : return x in all_vars [ k - ] for to_replace , replace_by in iteritems ( givens ) : inside = dict ( ( v , [ in_var ( v , k ) for k in ( , ) ] ) for v in ( to_replace , replace_by ) ) if ( inside [ to_replace ] [ ] and not inside [ to_replace ] [ ] and inside [ replace_by ] [ ] and not inside [ replace_by ] [ ] ) : in_xs . append ( to_replace ) in_ys . append ( replace_by ) elif ( inside [ to_replace ] [ ] and not inside [ to_replace ] [ ] and inside [ replace_by ] [ ] and not inside [ replace_by ] [ ] ) : in_xs . append ( replace_by ) in_ys . append ( to_replace ) ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" import logging from . tests import * ", "answer": "logger = logging . getLogger ( \"\" )"}, {"prompt": " from collections import OrderedDict class StructuresParameters ( object ) : INF = \"\"\"\"\"\" structureTypes = OrderedDict ( ) structureTypes [ \"\" ] = ( , , , \"\" , , , , - INF , INF , '' ) slicePlane = \"\" structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' ) ", "answer": "structureTypes [ '' + slicePlane ] = ( , , , '' , , , , , , '' )"}, {"prompt": " from pandas . msgpack . _version import version from pandas . msgpack . exceptions import * from collections import namedtuple class ExtType ( namedtuple ( '' , '' ) ) : \"\"\"\"\"\" def __new__ ( cls , code , data ) : if not isinstance ( code , int ) : raise TypeError ( \"\" ) if not isinstance ( data , bytes ) : raise TypeError ( \"\" ) if not <= code <= : raise ValueError ( \"\" ) return super ( ExtType , cls ) . __new__ ( cls , code , data ) import os from pandas . msgpack . _packer import Packer from pandas . msgpack . _unpacker import unpack , unpackb , Unpacker def pack ( o , stream , ** kwargs ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals import datetime from django . test import TestCase , RequestFactory from django . core . urlresolvers import reverse from django . core . cache import cache from django . contrib . auth import get_user_model , HASH_SESSION_KEY from django . core import mail from django . utils . translation import ugettext as _ from django . utils import timezone from django . test . utils import override_settings from djconfig . utils import override_djconfig from . . core . tests import utils from . forms import UserProfileForm , EmailChangeForm , UserForm , EmailCheckForm from . . comment . like . models import CommentLike from . . topic . models import Topic from . . comment . models import Comment from . . comment . bookmark . models import CommentBookmark from . utils . tokens import UserActivationTokenGenerator , UserEmailChangeTokenGenerator from . utils . email import send_activation_email , send_email_change_email , sender from . utils import email User = get_user_model ( ) class UserViewTest ( TestCase ) : def setUp ( self ) : cache . clear ( ) self . user = utils . create_user ( ) self . user2 = utils . create_user ( ) self . category = utils . create_category ( ) self . topic = utils . create_topic ( self . category , user = self . user2 ) self . topic2 = utils . create_topic ( self . category ) def test_user_views_denied_to_non_logged_users ( self ) : \"\"\"\"\"\" pk = self . user . pk slug = self . user . st . slug response = self . client . get ( reverse ( '' , kwargs = { '' : pk , '' : slug } ) ) self . assertEqual ( response . status_code , ) response = self . client . get ( reverse ( '' , kwargs = { '' : pk , '' : slug } ) ) self . assertEqual ( response . status_code , ) response = self . client . get ( reverse ( '' , kwargs = { '' : pk , '' : slug } ) ) self . assertEqual ( response . status_code , ) response = self . client . get ( reverse ( '' ) ) self . assertEqual ( response . status_code , ) response = self . client . get ( reverse ( '' ) ) self . assertEqual ( response . status_code , ) response = self . client . get ( reverse ( '' ) ) self . assertEqual ( response . status_code , ) response = self . client . get ( reverse ( '' , kwargs = { '' : \"\" } ) ) self . assertEqual ( response . status_code , ) def test_profile_topics ( self ) : \"\"\"\"\"\" utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( response . status_code , ) self . assertEqual ( list ( response . context [ '' ] ) , [ self . topic , ] ) self . assertEqual ( response . context [ '' ] , self . user2 ) def test_profile_topics_order ( self ) : \"\"\"\"\"\" Topic . objects . all ( ) . delete ( ) category = utils . create_category ( ) topic_a = utils . create_topic ( category = category , user = self . user2 ) topic_b = utils . create_topic ( category = category , user = self . user2 ) topic_c = utils . create_topic ( category = category , user = self . user2 ) Topic . objects . filter ( pk = topic_a . pk ) . update ( date = timezone . now ( ) - datetime . timedelta ( days = ) ) Topic . objects . filter ( pk = topic_c . pk ) . update ( date = timezone . now ( ) - datetime . timedelta ( days = ) ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( list ( response . context [ '' ] ) , [ topic_b , topic_c , topic_a ] ) def test_profile_topics_bookmarks ( self ) : \"\"\"\"\"\" bookmark = CommentBookmark . objects . create ( topic = self . topic , user = self . user ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( response . status_code , ) self . assertEqual ( list ( response . context [ '' ] ) , [ self . topic , ] ) self . assertEqual ( response . context [ '' ] [ ] . bookmark , bookmark ) @ override_djconfig ( topics_per_page = ) def test_profile_topics_paginate ( self ) : \"\"\"\"\"\" topic = utils . create_topic ( self . category , user = self . user2 ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( response . status_code , ) self . assertEqual ( list ( response . context [ '' ] ) , [ topic , ] ) def test_profile_topics_dont_show_removed_or_private ( self ) : \"\"\"\"\"\" Topic . objects . all ( ) . delete ( ) category = utils . create_category ( ) category_removed = utils . create_category ( is_removed = True ) subcategory = utils . create_category ( parent = category_removed ) subcategory_removed = utils . create_category ( parent = category , is_removed = True ) utils . create_private_topic ( user = self . user2 ) utils . create_topic ( category = category , user = self . user2 , is_removed = True ) utils . create_topic ( category = category_removed , user = self . user2 ) utils . create_topic ( category = subcategory , user = self . user2 ) utils . create_topic ( category = subcategory_removed , user = self . user2 ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( list ( response . context [ '' ] ) , [ ] ) def test_profile_topics_invalid_slug ( self ) : \"\"\"\"\"\" utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : \"\" } ) ) expected_url = reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) self . assertRedirects ( response , expected_url , status_code = ) def test_profile_comments ( self ) : \"\"\"\"\"\" utils . login ( self ) comment = utils . create_comment ( user = self . user2 , topic = self . topic ) utils . create_comment ( user = self . user , topic = self . topic ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( response . status_code , ) self . assertEqual ( list ( response . context [ '' ] ) , [ comment , ] ) self . assertEqual ( response . context [ '' ] , self . user2 ) def test_profile_comments_order ( self ) : \"\"\"\"\"\" comment_a = utils . create_comment ( user = self . user2 , topic = self . topic ) comment_b = utils . create_comment ( user = self . user2 , topic = self . topic ) comment_c = utils . create_comment ( user = self . user2 , topic = self . topic ) Comment . objects . filter ( pk = comment_a . pk ) . update ( date = timezone . now ( ) - datetime . timedelta ( days = ) ) Comment . objects . filter ( pk = comment_c . pk ) . update ( date = timezone . now ( ) - datetime . timedelta ( days = ) ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( list ( response . context [ '' ] ) , [ comment_b , comment_c , comment_a ] ) @ override_djconfig ( comments_per_page = ) def test_profile_comments_paginate ( self ) : \"\"\"\"\"\" utils . create_comment ( user = self . user2 , topic = self . topic ) comment = utils . create_comment ( user = self . user2 , topic = self . topic ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( response . status_code , ) self . assertEqual ( list ( response . context [ '' ] ) , [ comment , ] ) def test_profile_comments_dont_show_removed_or_private ( self ) : \"\"\"\"\"\" category = utils . create_category ( ) category_removed = utils . create_category ( is_removed = True ) subcategory = utils . create_category ( parent = category_removed ) subcategory_removed = utils . create_category ( parent = category , is_removed = True ) topic_a = utils . create_private_topic ( user = self . user2 ) topic_b = utils . create_topic ( category = category , is_removed = True ) topic_c = utils . create_topic ( category = category_removed ) topic_d = utils . create_topic ( category = subcategory ) topic_e = utils . create_topic ( category = subcategory_removed ) utils . create_comment ( user = self . user2 , topic = topic_a . topic ) utils . create_comment ( user = self . user2 , topic = topic_b ) utils . create_comment ( user = self . user2 , topic = topic_c ) utils . create_comment ( user = self . user2 , topic = topic_d ) utils . create_comment ( user = self . user2 , topic = topic_e ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( list ( response . context [ '' ] ) , [ ] ) def test_profile_comments_invalid_slug ( self ) : \"\"\"\"\"\" utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : \"\" } ) ) expected_url = reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) self . assertRedirects ( response , expected_url , status_code = ) def test_profile_likes ( self ) : \"\"\"\"\"\" utils . login ( self ) comment = utils . create_comment ( user = self . user , topic = self . topic ) comment2 = utils . create_comment ( user = self . user2 , topic = self . topic ) like = CommentLike . objects . create ( user = self . user2 , comment = comment ) CommentLike . objects . create ( user = self . user , comment = comment2 ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( response . status_code , ) self . assertEqual ( list ( response . context [ '' ] ) , [ like . comment , ] ) self . assertEqual ( response . context [ '' ] , self . user2 ) def test_profile_likes_order ( self ) : \"\"\"\"\"\" comment_a = utils . create_comment ( user = self . user , topic = self . topic ) comment_b = utils . create_comment ( user = self . user , topic = self . topic ) comment_c = utils . create_comment ( user = self . user , topic = self . topic ) like_a = CommentLike . objects . create ( user = self . user2 , comment = comment_a ) CommentLike . objects . create ( user = self . user2 , comment = comment_b ) like_c = CommentLike . objects . create ( user = self . user2 , comment = comment_c ) CommentLike . objects . filter ( pk = like_a . pk ) . update ( date = timezone . now ( ) - datetime . timedelta ( days = ) ) CommentLike . objects . filter ( pk = like_c . pk ) . update ( date = timezone . now ( ) - datetime . timedelta ( days = ) ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( list ( response . context [ '' ] ) , [ comment_b , comment_c , comment_a ] ) def test_profile_likes_dont_show_removed_or_private ( self ) : \"\"\"\"\"\" category = utils . create_category ( ) category_removed = utils . create_category ( is_removed = True ) subcategory = utils . create_category ( parent = category_removed ) subcategory_removed = utils . create_category ( parent = category , is_removed = True ) topic_a = utils . create_private_topic ( user = self . user2 ) topic_b = utils . create_topic ( category = category , is_removed = True ) topic_c = utils . create_topic ( category = category_removed ) topic_d = utils . create_topic ( category = subcategory ) topic_e = utils . create_topic ( category = subcategory_removed ) comment_a = utils . create_comment ( user = self . user2 , topic = topic_a . topic ) comment_b = utils . create_comment ( user = self . user , topic = topic_b ) comment_c = utils . create_comment ( user = self . user , topic = topic_c ) comment_d = utils . create_comment ( user = self . user , topic = topic_d ) comment_e = utils . create_comment ( user = self . user , topic = topic_e ) CommentLike . objects . create ( user = self . user2 , comment = comment_a ) CommentLike . objects . create ( user = self . user2 , comment = comment_b ) CommentLike . objects . create ( user = self . user2 , comment = comment_c ) CommentLike . objects . create ( user = self . user2 , comment = comment_d ) CommentLike . objects . create ( user = self . user2 , comment = comment_e ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( list ( response . context [ '' ] ) , [ ] ) def test_profile_likes_invalid_slug ( self ) : \"\"\"\"\"\" utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : \"\" } ) ) expected_url = reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) self . assertRedirects ( response , expected_url , status_code = ) @ override_djconfig ( comments_per_page = ) def test_profile_likes_paginate ( self ) : \"\"\"\"\"\" comment = utils . create_comment ( user = self . user2 , topic = self . topic ) comment2 = utils . create_comment ( user = self . user2 , topic = self . topic ) CommentLike . objects . create ( user = self . user2 , comment = comment ) like = CommentLike . objects . create ( user = self . user2 , comment = comment2 ) utils . login ( self ) response = self . client . get ( reverse ( \"\" , kwargs = { '' : self . user2 . pk , '' : self . user2 . st . slug } ) ) self . assertEqual ( response . status_code , ) self . assertEqual ( list ( response . context [ '' ] ) , [ like . comment , ] ) def test_profile_update ( self ) : \"\"\"\"\"\" utils . login ( self ) response = self . client . get ( reverse ( '' ) ) self . assertEqual ( response . status_code , ) form_data = { '' : '' , '' : '' , '' : '' , '' : self . user . st . timezone } response = self . client . post ( reverse ( '' ) , form_data ) expected_url = reverse ( '' ) self . assertRedirects ( response , expected_url , status_code = ) def test_profile_password_change ( self ) : \"\"\"\"\"\" user = utils . create_user ( password = \"\" ) utils . login ( self , user = user , password = \"\" ) form_data = { '' : '' , '' : '' , '' : '' } response = self . client . post ( reverse ( '' ) , form_data ) expected_url = reverse ( \"\" ) self . assertRedirects ( response , expected_url , status_code = ) utils . login ( self , user = user , password = \"\" ) response = self . client . get ( reverse ( '' ) ) self . assertEqual ( response . status_code , ) def test_profile_password_change_re_login ( self ) : \"\"\"\"\"\" user = utils . create_user ( password = \"\" ) utils . login ( self , user = user , password = \"\" ) old_hash = self . client . session [ HASH_SESSION_KEY ] form_data = { '' : '' , '' : '' , '' : '' } response = self . client . post ( reverse ( '' ) , form_data ) expected_url = reverse ( \"\" ) self . assertRedirects ( response , expected_url , status_code = ) self . assertNotEqual ( old_hash , self . client . session [ HASH_SESSION_KEY ] ) def test_email_change_confirm ( self ) : \"\"\"\"\"\" utils . login ( self ) new_email = \"\" token = UserEmailChangeTokenGenerator ( ) . generate ( self . user , new_email ) response = self . client . get ( reverse ( '' , kwargs = { '' : token } ) ) expected_url = reverse ( \"\" ) self . assertRedirects ( response , expected_url , status_code = ) self . assertEqual ( User . objects . get ( pk = self . user . pk ) . email , new_email ) def test_email_change_confirm_invalid ( self ) : \"\"\"\"\"\" utils . login ( self ) old_email = \"\" token = UserEmailChangeTokenGenerator ( ) . generate ( self . user , old_email ) new_email = \"\" User . objects . filter ( pk = self . user . pk ) . update ( email = new_email ) response = self . client . get ( reverse ( '' , kwargs = { '' : token } ) ) expected_url = reverse ( \"\" ) self . assertRedirects ( response , expected_url , status_code = ) self . assertEqual ( User . objects . get ( pk = self . user . pk ) . email , new_email ) def test_email_change_duplicated ( self ) : \"\"\"\"\"\" utils . login ( self ) utils . create_user ( email = \"\" ) new_email = \"\" old_email = self . user . email token = UserEmailChangeTokenGenerator ( ) . generate ( self . user , new_email ) self . client . get ( reverse ( '' , kwargs = { '' : token } ) ) self . assertEqual ( User . objects . get ( pk = self . user . pk ) . email , old_email ) @ override_settings ( ST_UNIQUE_EMAILS = False ) def test_email_change_duplicated_allowed ( self ) : \"\"\"\"\"\" utils . login ( self ) utils . create_user ( email = \"\" ) new_email = \"\" token = UserEmailChangeTokenGenerator ( ) . generate ( self . user , new_email ) self . client . get ( reverse ( '' , kwargs = { '' : token } ) ) self . assertEqual ( User . objects . get ( pk = self . user . pk ) . email , new_email ) def test_profile_email_change ( self ) : \"\"\"\"\"\" user = utils . create_user ( password = \"\" ) utils . login ( self , user = user , password = \"\" ) form_data = { '' : '' , '' : '' } response = self . client . post ( reverse ( '' ) , form_data ) expected_url = reverse ( \"\" ) self . assertRedirects ( response , expected_url , status_code = ) self . assertEquals ( len ( mail . outbox ) , ) self . assertIn ( _ ( \"\" ) , mail . outbox [ ] . subject ) response = self . client . get ( reverse ( '' ) ) self . assertEqual ( response . status_code , ) class UserFormTest ( TestCase ) : def setUp ( self ) : cache . clear ( ) self . user = utils . create_user ( ) def test_profile ( self ) : \"\"\"\"\"\" form_data = { '' : '' , '' : '' , '' : '' , '' : self . user . st . timezone } form = UserProfileForm ( data = form_data , instance = self . user . st ) self . assertEqual ( form . is_valid ( ) , True ) form = UserForm ( data = form_data , instance = self . user ) self . assertEqual ( form . is_valid ( ) , True ) def test_email_change ( self ) : \"\"\"\"\"\" user = utils . create_user ( password = \"\" ) form_data = { '' : '' , '' : '' } form = EmailChangeForm ( data = form_data , user = user ) self . assertEqual ( form . is_valid ( ) , True ) def test_email_change_invalid ( self ) : \"\"\"\"\"\" user = utils . create_user ( password = \"\" , email = \"\" ) form_data = { '' : '' , '' : '' } form = EmailChangeForm ( data = form_data , user = user ) self . assertEqual ( form . is_valid ( ) , False ) self . assertNotIn ( '' , form . cleaned_data ) self . assertNotIn ( '' , form . cleaned_data ) def test_email_change_email_duplication ( self ) : \"\"\"\"\"\" utils . create_user ( email = \"\" ) user = utils . create_user ( password = \"\" ) form_data = { '' : '' , '' : '' } form = EmailChangeForm ( data = form_data , user = user ) self . assertEqual ( form . is_valid ( ) , False ) self . assertNotIn ( '' , form . cleaned_data ) @ override_settings ( ST_UNIQUE_EMAILS = False ) def test_email_change_email_duplication_allowed ( self ) : \"\"\"\"\"\" utils . create_user ( email = \"\" ) user = utils . create_user ( password = \"\" ) form_data = { '' : '' , '' : '' } form = EmailChangeForm ( data = form_data , user = user ) self . assertEqual ( form . is_valid ( ) , True ) @ override_settings ( ST_CASE_INSENSITIVE_EMAILS = True ) def test_email_change_email_case_insensitive ( self ) : \"\"\"\"\"\" utils . create_user ( email = \"\" ) user = utils . create_user ( password = \"\" ) form_data = { '' : '' , '' : '' } form = EmailChangeForm ( data = form_data , user = user ) self . assertEqual ( form . is_valid ( ) , False ) @ override_settings ( ST_CASE_INSENSITIVE_EMAILS = False ) def test_email_change_email_case_sensitive ( self ) : \"\"\"\"\"\" utils . create_user ( email = \"\" ) user = utils . create_user ( password = \"\" ) form_data = { '' : '' , '' : '' } form = EmailChangeForm ( data = form_data , user = user ) self . assertEqual ( form . is_valid ( ) , True ) def test_email_check ( self ) : \"\"\"\"\"\" form_data = { '' : '' , } form = EmailCheckForm ( form_data ) self . assertTrue ( form . is_valid ( ) ) utils . create_user ( email = \"\" ) form_data [ '' ] = \"\" form = EmailCheckForm ( form_data ) self . assertFalse ( form . is_valid ( ) ) @ override_settings ( ST_UNIQUE_EMAILS = False ) def test_email_check_non_unique ( self ) : \"\"\"\"\"\" utils . create_user ( email = \"\" ) form_data = { '' : '' , } form = EmailCheckForm ( form_data ) self . assertTrue ( form . is_valid ( ) ) @ override_settings ( ST_CASE_INSENSITIVE_EMAILS = True ) def test_email_check_case_insensitive ( self ) : \"\"\"\"\"\" utils . create_user ( email = \"\" ) form_data = { '' : '' , } form = EmailCheckForm ( form_data ) ", "answer": "self . assertFalse ( form . is_valid ( ) )"}, {"prompt": " import json from pytest import raises from graphql . core . error import GraphQLError , format_error from graphql . core . execution import execute from graphql . core . language . parser import parse from graphql . core . type import ( GraphQLArgument , GraphQLField , GraphQLInputObjectField , GraphQLInputObjectType , GraphQLList , GraphQLNonNull , GraphQLObjectType , GraphQLScalarType , GraphQLSchema , GraphQLString ) TestComplexScalar = GraphQLScalarType ( name = '' , serialize = lambda v : '' if v == '' else None , parse_value = lambda v : '' if v == '' else None , parse_literal = lambda v : '' if v . value == '' else None ) TestInputObject = GraphQLInputObjectType ( '' , { '' : GraphQLInputObjectField ( GraphQLString ) , '' : GraphQLInputObjectField ( GraphQLList ( GraphQLString ) ) , '' : GraphQLInputObjectField ( GraphQLNonNull ( GraphQLString ) ) , '' : GraphQLInputObjectField ( TestComplexScalar ) } ) stringify = lambda obj : json . dumps ( obj , sort_keys = True ) def input_to_json ( obj , args , info ) : input = args . get ( '' ) ", "answer": "if input :"}, {"prompt": " import pytest from helpers import * from Bits import Bits def test_get_nbits ( ) : assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( - ) == assert get_nbits ( - ) == assert get_nbits ( - ) == assert get_nbits ( - ) == assert get_nbits ( - ) == assert get_nbits ( - ) == assert get_nbits ( - ) == assert get_nbits ( - ) == def test_clog2 ( ) : assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert clog2 ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == assert get_nbits ( ) == with pytest . raises ( AssertionError ) : assert clog2 ( ) == with pytest . raises ( AssertionError ) : assert clog2 ( - ) == def test_zext ( ) : assert zext ( Bits ( , ) , ) == Bits ( , ) assert zext ( Bits ( , ) , ) == Bits ( , ) assert zext ( Bits ( , ) , ) == Bits ( , ) assert zext ( Bits ( , - ) , ) == Bits ( , ) assert zext ( Bits ( , - ) , ) == Bits ( , ) def test_sext ( ) : assert sext ( Bits ( , ) , ) == Bits ( , ) assert sext ( Bits ( , ) , ) == Bits ( , ) assert sext ( Bits ( , ) , ) == Bits ( , ) assert sext ( Bits ( , - ) , ) == Bits ( , ) assert sext ( Bits ( , - ) , ) == Bits ( , ) def test_concat ( ) : assert concat ( Bits ( , ) , Bits ( , ) ) == Bits ( , ) assert concat ( Bits ( , ) , Bits ( , ) ) == Bits ( , ) assert concat ( Bits ( , ) , Bits ( , ) , Bits ( , ) ) == Bits ( , ) assert concat ( Bits ( , ) , Bits ( , ) , Bits ( , ) ) == Bits ( , ) def test_reduce_and ( ) : assert reduce_and ( Bits ( , ) ) == assert reduce_and ( Bits ( , ) ) == assert reduce_and ( Bits ( , ) ) == assert reduce_and ( Bits ( , ) ) == assert reduce_and ( Bits ( , ) ) == assert reduce_and ( Bits ( , ) ) == assert reduce_and ( Bits ( , ) ) == assert reduce_and ( Bits ( , ) ) == def test_reduce_or ( ) : assert reduce_or ( Bits ( , ) ) == assert reduce_or ( Bits ( , ) ) == assert reduce_or ( Bits ( , ) ) == assert reduce_or ( Bits ( , ) ) == ", "answer": "assert reduce_or ( Bits ( , ) ) == "}, {"prompt": " import sys if sys . version_info [ ] == : import struct def _build_fmt ( length , endianess ) : format_ = \"\" if endianess == \"\" : format_ += \">\" elif endianess == \"\" : format_ += \"\" if length == : format_ += \"\" elif length == : format_ += \"\" elif length == : ", "answer": "format_ += \"\""}, {"prompt": " \"\"\"\"\"\" import eventlet from oslo_config import cfg import oslo_messaging as messaging from oslo_serialization import jsonutils import solum . common . context from solum import objects eventlet . monkey_patch ( ) TRANSPORT_ALIASES = { '' : '' , '' : '' , '' : '' , } class JsonPayloadSerializer ( messaging . NoOpSerializer ) : @ staticmethod def serialize_entity ( context , entity ) : return jsonutils . to_primitive ( entity , convert_instances = True ) class RequestContextSerializer ( messaging . Serializer ) : def __init__ ( self , base = None ) : self . _base = base or messaging . NoOpSerializer ( ) def serialize_entity ( self , context , entity ) : if not self . _base : return entity return self . _base . serialize_entity ( context , entity ) def deserialize_entity ( self , context , entity ) : if not self . _base : return entity return self . _base . deserialize_entity ( context , entity ) def serialize_context ( self , context ) : return context . to_dict ( ) def deserialize_context ( self , context ) : return solum . common . context . RequestContext . from_dict ( context ) class Service ( object ) : ", "answer": "_server = None"}, {"prompt": " from tddspry . django import TestCase from django . contrib . auth . models import User , check_password from testproject . testapp . models import UserProfile TEST_BIO = u'' class TestBaseHelpers ( TestCase ) : def test_create_profile ( self ) : old_counter = UserProfile . objects . count ( ) user = self . helper ( '' ) profile = self . helper ( '' , user , UserProfile , bio = TEST_BIO ) new_counter = UserProfile . objects . count ( ) self . assert_equal ( new_counter - , old_counter ) self . assert_equal ( profile . user , user ) self . assert_equal ( profile . bio , TEST_BIO ) def test_create_staff ( self ) : old_counter = User . objects . count ( ) user = self . helper ( '' ) new_counter = User . objects . count ( ) self . assert_equal ( new_counter - , old_counter ) self . assert_true ( user . is_staff ) def test_create_superuser ( self ) : old_counter = User . objects . count ( ) user = self . helper ( '' ) new_counter = User . objects . count ( ) self . assert_equal ( new_counter - , old_counter ) self . assert_true ( user . is_staff ) self . assert_true ( user . is_superuser ) def test_create_user ( self ) : ", "answer": "old_counter = User . objects . count ( )"}, {"prompt": " from south . utils import datetime_utils as datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . alter_column ( u'' , '' , self . gf ( '' ) ( max_length = ) ) def backwards ( self , orm ) : db . alter_column ( u'' , '' , self . gf ( '' ) ( ) ) models = { u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) ,"}, {"prompt": " import os import sys import glob from setuptools import find_packages , setup ", "answer": "from pkg_resources import parse_requirements"}, {"prompt": " \"\"\"\"\"\" import tables def setUp ( filename ) : fileh = tables . open_file ( filename , mode = \"\" , title = \"\" ) fileh . create_group ( \"\" , \"\" , \"\" ) fileh . create_group ( \"\" , \"\" , \"\" ) fileh . create_array ( \"\" , \"\" , [ , ] , \"\" ) fileh . enable_undo ( ) return fileh def tearDown ( fileh ) : fileh . disable_undo ( ) fileh . close ( ) def demo_6times3marks ( ) : \"\"\"\"\"\" fileh = setUp ( \"\" ) fileh . create_array ( '' , '' , [ , ] , \"\" ) fileh . create_array ( '' , '' , [ , ] , \"\" ) fileh . mark ( ) fileh . create_array ( '' , '' , [ , ] , \"\" ) fileh . create_array ( '' , '' , [ , ] , \"\" ) fileh . mark ( ) fileh . create_array ( '' , '' , [ , ] , \"\" ) fileh . create_array ( '' , '' , [ , ] , \"\" ) fileh . undo ( ) assert \"\" in fileh assert \"\" in fileh assert \"\" in fileh assert \"\" in fileh assert \"\" not in fileh assert \"\" not in fileh fileh . undo ( ) assert \"\" in fileh assert \"\" in fileh assert \"\" not in fileh assert \"\" not in fileh assert \"\" not in fileh assert \"\" not in fileh fileh . undo ( ) assert \"\" not in fileh assert \"\" not in fileh assert \"\" not in fileh assert \"\" not in fileh assert \"\" not in fileh assert \"\" not in fileh fileh . redo ( ) assert \"\" in fileh assert \"\" in fileh assert \"\" not in fileh assert \"\" not in fileh assert \"\" not in fileh ", "answer": "assert \"\" not in fileh"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import os import sys if __name__ == \"\" : os . environ . setdefault ( \"\" , \"\" ) from django . core . management import execute_from_command_line ", "answer": "execute_from_command_line ( sys . argv ) "}, {"prompt": " from rx import Lock class InnerSubscription ( object ) : def __init__ ( self , subject , observer ) : ", "answer": "self . subject = subject"}, {"prompt": " from autobahn . twisted . websocket import WebSocketClientProtocol , WebSocketClientFactory class MyClientProtocol ( WebSocketClientProtocol ) : def onConnect ( self , response ) : print ( \"\" . format ( response . peer ) ) def onOpen ( self ) : print ( \"\" ) def hello ( ) : self . sendMessage ( u\"\" . encode ( '' ) ) self . sendMessage ( b\"\" , isBinary = True ) self . factory . reactor . callLater ( , hello ) hello ( ) def onMessage ( self , payload , isBinary ) : if isBinary : print ( \"\" . format ( len ( payload ) ) ) else : print ( \"\" . format ( payload . decode ( '' ) ) ) def onClose ( self , wasClean , code , reason ) : print ( \"\" . format ( reason ) ) if __name__ == '' : import sys from twisted . python import log from twisted . internet import reactor log . startLogging ( sys . stdout ) factory = WebSocketClientFactory ( u\"\" , debug = False ) factory . protocol = MyClientProtocol ", "answer": "reactor . connectTCP ( \"\" , , factory )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import copy from wsme import types as wtypes from solum . api . controllers . camp . v1_1 import uris from solum . api . controllers import common_types from solum . api . controllers . v1 . datamodel import types as api_types class ParameterDefinitionLink ( common_types . Link ) : \"\"\"\"\"\" required = bool \"\"\"\"\"\" default_value = wtypes . Base \"\"\"\"\"\" class ParameterDefinitions ( api_types . Base ) : \"\"\"\"\"\" parameter_definition_links = [ ParameterDefinitionLink ] \"\"\"\"\"\" def __init__ ( self , ** kwds ) : super ( ParameterDefinitions , self ) . __init__ ( ** kwds ) ", "answer": "def fix_uris ( self , host_url ) :"}, {"prompt": " from hTools2 . modules . encoding import paint_groups from hTools2 . modules . messages import no_font_open f = CurrentFont ( ) ", "answer": "if f is not None :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division from sympy . physics . mechanics import ReferenceFrame , Point , Particle , RigidBody from sympy . physics . mechanics import cross , dot , Vector from sympy . physics . mechanics import MechanicsStrPrinter from sympy . physics . mechanics import inertia_of_point_mass def msprint ( expr ) : pr = MechanicsStrPrinter ( ) return pr . doprint ( expr ) def subs ( x , * args , ** kwargs ) : if x == : return x if not hasattr ( x , '' ) : if hasattr ( x , '' ) : return map ( lambda x : subs ( x , * args , ** kwargs ) , x ) return x . subs ( * args , ** kwargs ) . doit ( ) class PartialVelocity ( dict ) : def __init__ ( self , frame , ulist , * args , ** kwargs ) : self . _set_frame ( frame ) self . _set_ulist ( ulist ) dict . __init__ ( self , * args , ** kwargs ) def _set_frame ( self , f ) : if not isinstance ( f , ReferenceFrame ) : raise TypeError ( '' . format ( f ) ) self . _frame = f def _set_ulist ( self , u ) : if not isinstance ( u , list ) : raise TypeError ( '' . format ( f ) ) self . _ulist = u @ property def frame ( self ) : ", "answer": "return self . _frame"}, {"prompt": " from __future__ import unicode_literals class ExitException ( Exception ) : pass class ScriptError ( Exception ) : ", "answer": "pass"}, {"prompt": " import abc from . context_manager_type_type import ContextManagerTypeType class ContextManagerType ( abc . ABCMeta ) : '''''' __metaclass__ = ContextManagerTypeType def __new__ ( mcls , name , bases , namespace ) : '''''' if '' in namespace : from . context_manager import ContextManager manage_context = namespace [ '' ] if '' in namespace : raise Exception ( '' '' '' '' ) ", "answer": "if '' in namespace :"}, {"prompt": " import sys import os import json import sphinx_rtd_theme import sphinx . environment from docutils . utils import get_source_line HERE = os . path . dirname ( __file__ ) sys . path . insert ( , os . path . abspath ( '' ) ) github_project_url = \"\" def _warn_node ( self , msg , node ) : if not msg . startswith ( '' ) : self . _warnfunc ( msg , '' % get_source_line ( node ) ) sphinx . environment . BuildEnvironment . warn_node = _warn_node extensions = [ '' , '' , '' , '' , '' , ", "answer": "]"}, {"prompt": " from os import * from os import _exit import os class FakeOS : def __init__ ( self ) : self . orig_uid = os . getuid ( ) self . orig_gid = os . getgid ( ) def setgroups ( * args ) : return def getuid ( ) : return def setuid ( arg ) : self . uid = arg self . setuid_called = def setgid ( arg ) : self . gid = arg self . setgid_called = def clear ( ) : self . uid = orig_uid self . gid = orig_gid self . setuid_called = ", "answer": "self . setgid_called = "}, {"prompt": " from . . import syntax from . . ndtypes import ScalarT , TupleT from . . syntax import Expr , While , ForLoop , Const from . . syntax . helpers import zero , one , zero_i32 , zero_i64 , wrap_if_constant from array_builder import ArrayBuilder class LoopBuilder ( ArrayBuilder ) : \"\"\"\"\"\" def loop_var ( self , name = \"\" , start_val = syntax . zero_i64 ) : \"\"\"\"\"\" start_val = wrap_if_constant ( start_val ) counter_type = start_val . type counter_before = self . assign_name ( start_val , name + \"\" ) counter = self . fresh_var ( counter_type , name ) counter_after = self . fresh_var ( counter_type , name + \"\" ) merge = { counter . name : ( counter_before , counter_after ) } return counter , counter_after , merge def loop ( self , start , niters , loop_body , return_stmt = False , while_loop = False , step = None , merge = None ) : if isinstance ( start , ( int , long ) ) : start = self . int ( start ) assert isinstance ( start , Expr ) if isinstance ( niters , ( int , long ) ) : niters = self . int ( niters ) assert isinstance ( niters , Expr ) if step is None : step = one ( start . type ) elif isinstance ( step , ( int , long ) ) : step = self . int ( step ) assert isinstance ( step , Expr ) if merge is None : merge = { } if while_loop : i , i_after , i_merge = self . loop_var ( \"\" , start ) merge . update ( i_merge ) cond = self . lt ( i , niters ) self . blocks . push ( ) loop_body ( i ) self . assign ( i_after , self . add ( i , step ) ) body = self . blocks . pop ( ) loop_stmt = While ( cond , body , merge ) else : var = self . fresh_var ( start . type , \"\" ) self . blocks . push ( ) loop_body ( var ) body = self . blocks . pop ( ) loop_stmt = ForLoop ( var , start , niters , step , body , merge ) if return_stmt : return loop_stmt else : self . blocks += loop_stmt class Accumulator : def __init__ ( self , acc_type , fresh_var , assign ) : self . acc_type = acc_type self . fresh_var = fresh_var self . assign = assign self . start_var = fresh_var ( acc_type , \"\" ) self . curr_var = self . start_var def get ( self ) : return self . curr_var def update ( self , new_value ) : new_var = self . fresh_var ( self . acc_type , \"\" ) self . assign ( new_var , new_value ) self . curr_var = new_var def mk_acc ( self , init ) : return self . Accumulator ( init . type , self . fresh_var , self . assign ) def accumulate_loop ( self , start , stop , loop_body , init , return_stmt = False ) : acc = self . mk_acc ( init ) def loop_body_with_acc ( i ) : loop_body ( acc , i ) loop_stmt = self . loop ( start , stop , loop_body_with_acc , return_stmt = True ) loop_stmt . merge [ acc . start_var . name ] = ( init , acc . curr_var ) if return_stmt : return loop_stmt , acc . start_var else : self . blocks += loop_stmt return acc . start_var def array_copy ( self , src , dest , return_stmt = False ) : assert self . is_array ( dest ) shape = self . shape ( dest ) dims = self . tuple_elts ( shape ) rank = len ( dims ) index_vars = [ ] def create_loops ( ) : i = len ( index_vars ) def loop_body ( index_var ) : index_vars . append ( index_var ) if i + == rank : index_tuple = self . tuple ( index_vars , \"\" ) lhs = self . index ( dest , index_tuple , temp = False ) rhs = self . index ( src , index_tuple , temp = True ) self . assign ( lhs , rhs ) else : self . blocks += create_loops ( ) start = syntax . zero_i64 stop = dims [ i ] if i > or return_stmt : return self . loop ( start , stop , loop_body , True ) else : return self . loop ( start , stop , loop_body , return_stmt ) return create_loops ( ) def _to_list ( self , bounds ) : if isinstance ( bounds , Expr ) : if isinstance ( bounds . type , ScalarT ) : return [ bounds ] else : assert isinstance ( bounds . type , TupleT ) , \"\" % ( bounds , bounds . type ) return self . tuple_elts ( bounds ) elif isinstance ( bounds , ( int , long ) ) : return [ bounds ] else : assert isinstance ( bounds , ( tuple , list ) ) return bounds def nested_loops ( self , upper_bounds , loop_body , lower_bounds = None , ", "answer": "step_sizes = None ,"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AddField ( ", "answer": "model_name = '' ,"}, {"prompt": " import sys import imp import errno import os from u2fval import default_settings import logging import logging . config __all__ = [ '' ] SETTINGS_FILE = os . getenv ( '' , os . path . join ( '' ) ) LOG_CONFIG_FILE = os . path . join ( os . path . dirname ( os . path . abspath ( SETTINGS_FILE ) ) , '' ) VALUES = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } ", "answer": "def parse ( conf , settings = { } ) :"}, {"prompt": " import abc from neutron_lib . api import converters from neutron_lib import constants from neutron_lib import exceptions import six from neutron . _i18n import _ from neutron . api import extensions DISTRIBUTED = '' EXTENDED_ATTRIBUTES_2_0 = { '' : { DISTRIBUTED : { '' : True , '' : True , '' : True , '' : constants . ATTR_NOT_SPECIFIED , '' : converters . convert_to_boolean_if_not_none , '' : True } , } } class DVRMacAddressNotFound ( exceptions . NotFound ) : message = _ ( \"\" \"\" ) class MacAddressGenerationFailure ( exceptions . ServiceUnavailable ) : message = _ ( \"\" ) class Dvr ( extensions . ExtensionDescriptor ) : \"\"\"\"\"\" @ classmethod def get_name ( cls ) : return \"\" @ classmethod def get_alias ( cls ) : return constants . L3_DISTRIBUTED_EXT_ALIAS @ classmethod def get_description ( cls ) : return \"\" @ classmethod def get_updated ( cls ) : return \"\" def get_required_extensions ( self ) : return [ \"\" ] @ classmethod def get_resources ( cls ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" __author__ = '' import csv import re import sys import GeoIP sys . path . append ( '' ) sys . path . append ( '' ) import third_party from libnamebench import nameserver_list from libnamebench import config from libnamebench import addr_util import check_nameserver_popularity gi = GeoIP . open ( '' , GeoIP . GEOIP_MEMORY_CACHE ) asn_lookup = GeoIP . open ( '' , GeoIP . GEOIP_MEMORY_CACHE ) existing_nameservers = config . GetLocalNameServerList ( ) check_ns = [ ] output = csv . writer ( open ( '' , '' ) ) for line in sys . stdin : ips = addr_util . ExtractIPsFromString ( line ) for ip in ips : print ip if '' in ip : continue if ip not in existing_nameservers : check_ns . append ( ( ip , ip ) ) if not check_ns : print \"\" sys . exit ( ) else : print \"\" % len ( check_ns ) print '' * nameserver_list . MAX_INITIAL_HEALTH_THREAD_COUNT = nameservers = nameserver_list . NameServers ( [ ] , global_servers = check_ns , timeout = , health_timeout = , threads = , num_servers = , skip_cache_collusion_checks = True , ) nameservers . min_healthy_percent = sanity_checks = config . GetLocalSanityChecks ( ) try : nameservers . CheckHealth ( sanity_checks [ '' ] , sanity_checks [ '' ] ) except nameserver_list . TooFewNameservers : pass print '' * for ns in nameservers : try : details = gi . record_by_addr ( ns . ip ) except : pass if not details : details = { } ", "answer": "city = details . get ( '' , '' )"}, {"prompt": " import unittest import sys from unit . test_utils import TestUtils from unit . test_upload import TestUpload def main ( ) : utils = unittest . TestLoader ( ) . loadTestsFromTestCase ( TestUtils ) unittest . TestSuite ( [ utils ] ) ", "answer": "unittest . main ( )"}, {"prompt": " \"\"\"\"\"\" from grr . endtoend_tests import base from grr . lib import action_mocks from grr . lib import aff4 from grr . lib import client_fixture from grr . lib import flags from grr . lib import flow from grr . lib import test_lib from grr . lib import utils from grr . lib . flows . cron import system from grr . lib . flows . general import endtoend as endtoend_flows from grr . lib . flows . general import endtoend_test from grr . lib . rdfvalues import client as client_rdf from grr . lib . rdfvalues import flows class SystemCronFlowTest ( test_lib . FlowTestsBaseclass ) : \"\"\"\"\"\" def setUp ( self ) : super ( SystemCronFlowTest , self ) . setUp ( ) fixture = test_lib . FilterFixture ( regex = \"\" ) for i in range ( , ) : test_lib . ClientFixture ( \"\" % i , token = self . token , fixture = fixture ) with aff4 . FACTORY . Open ( \"\" % i , mode = \"\" , token = self . token ) as client : client . AddLabels ( \"\" , \"\" , owner = \"\" ) client . AddLabels ( \"\" , owner = \"\" ) for i in range ( , ) : test_lib . ClientFixture ( \"\" % i , token = self . token , fixture = client_fixture . LINUX_FIXTURE ) def _CheckVersionStats ( self , label , attribute , counts ) : fd = aff4 . FACTORY . Open ( \"\" % label , token = self . token ) histogram = fd . Get ( attribute ) self . assertEqual ( histogram [ ] . title , \"\" % label ) self . assertEqual ( len ( histogram [ ] ) , counts [ ] ) self . assertEqual ( histogram [ ] . title , \"\" % label ) self . assertEqual ( len ( histogram [ ] ) , counts [ ] ) self . assertEqual ( histogram [ ] . title , \"\" % label ) self . assertEqual ( histogram [ ] [ ] . label , \"\" ) self . assertEqual ( histogram [ ] [ ] . y_value , counts [ ] ) self . assertEqual ( histogram [ ] . title , \"\" % label ) self . assertEqual ( histogram [ ] [ ] . label , \"\" ) self . assertEqual ( histogram [ ] [ ] . y_value , counts [ ] ) def testGRRVersionBreakDown ( self ) : \"\"\"\"\"\" for _ in test_lib . TestFlowHelper ( \"\" , token = self . token ) : pass histogram = aff4 . ClientFleetStats . SchemaCls . GRRVERSION_HISTOGRAM self . _CheckVersionStats ( \"\" , histogram , [ , , , ] ) self . _CheckVersionStats ( \"\" , histogram , [ , , , ] ) self . _CheckVersionStats ( \"\" , histogram , [ , , , ] ) aff4 . FACTORY . Open ( \"\" , \"\" , token = self . token ) def _CheckOSStats ( self , label , attribute , counts ) : fd = aff4 . FACTORY . Open ( \"\" % label , token = self . token ) histogram = fd . Get ( attribute ) self . assertEqual ( histogram [ ] . title , \"\" % label ) self . assertEqual ( len ( histogram [ ] ) , counts [ ] ) self . assertEqual ( histogram [ ] . title , \"\" % label ) self . assertEqual ( len ( histogram [ ] ) , counts [ ] ) self . assertEqual ( histogram [ ] . title , \"\" % label ) all_labels = [ ] for item in histogram [ ] : all_labels . append ( item . label ) self . assertEqual ( item . y_value , counts [ ] [ item . label ] ) self . assertItemsEqual ( all_labels , counts [ ] . keys ( ) ) self . assertEqual ( histogram [ ] . title , \"\" % label ) all_labels = [ ] for item in histogram [ ] : all_labels . append ( item . label ) self . assertEqual ( item . y_value , counts [ ] [ item . label ] ) self . assertItemsEqual ( all_labels , counts [ ] . keys ( ) ) def testOSBreakdown ( self ) : \"\"\"\"\"\" for _ in test_lib . TestFlowHelper ( \"\" , token = self . token ) : pass histogram = aff4 . ClientFleetStats . SchemaCls . OS_HISTOGRAM self . _CheckOSStats ( \"\" , histogram , [ , , { \"\" : , \"\" : } , { \"\" : , \"\" : } ] ) self . _CheckOSStats ( \"\" , histogram , [ , , { \"\" : } , { \"\" : } ] ) self . _CheckOSStats ( \"\" , histogram , [ , , { \"\" : } , { \"\" : } ] ) def _CheckAccessStats ( self , label , count ) : fd = aff4 . FACTORY . Open ( \"\" % label , token = self . token ) histogram = fd . Get ( fd . Schema . LAST_CONTACTED_HISTOGRAM ) data = [ ( x . x_value , x . y_value ) for x in histogram ] self . assertEqual ( data , [ ( L , L ) , ( L , L ) , ( L , L ) , ( L , L ) , ( L , count ) , ( L , count ) , ( L , count ) ] ) def testLastAccessStats ( self ) : \"\"\"\"\"\" for _ in test_lib . TestFlowHelper ( \"\" , token = self . token ) : pass self . _CheckAccessStats ( \"\" , count = L ) self . _CheckAccessStats ( \"\" , count = L ) self . _CheckAccessStats ( \"\" , count = L ) def testPurgeClientStats ( self ) : max_age = system . PurgeClientStats . MAX_AGE for t in [ * max_age , * max_age , * max_age ] : with test_lib . FakeTime ( t ) : urn = self . client_id . Add ( \"\" ) stats_fd = aff4 . FACTORY . Create ( urn , \"\" , token = self . token , mode = \"\" ) st = client_rdf . ClientStats ( RSS_size = int ( t ) ) stats_fd . AddAttribute ( stats_fd . Schema . STATS ( st ) ) stats_fd . Close ( ) stat_obj = aff4 . FACTORY . Open ( urn , age = aff4 . ALL_TIMES , token = self . token , ignore_cache = True ) stat_entries = list ( stat_obj . GetValuesForAttribute ( stat_obj . Schema . STATS ) ) self . assertEqual ( len ( stat_entries ) , ) self . assertTrue ( max_age in [ e . RSS_size for e in stat_entries ] ) with test_lib . FakeTime ( * max_age ) : for _ in test_lib . TestFlowHelper ( \"\" , None , client_id = self . client_id , token = self . token ) : pass stat_obj = aff4 . FACTORY . Open ( urn , age = aff4 . ALL_TIMES , token = self . token , ignore_cache = True ) stat_entries = list ( stat_obj . GetValuesForAttribute ( stat_obj . Schema . STATS ) ) self . assertEqual ( len ( stat_entries ) , ) self . assertTrue ( max_age not in [ e . RSS_size for e in stat_entries ] ) def _SetSummaries ( self , client_id ) : client = aff4 . FACTORY . Create ( client_id , \"\" , mode = \"\" , token = self . token ) client . Set ( client . Schema . HOSTNAME ( client_id ) ) client . Set ( client . Schema . SYSTEM ( \"\" ) ) client . Set ( client . Schema . OS_RELEASE ( \"\" ) ) client . Set ( client . Schema . OS_VERSION ( \"\" ) ) client . Set ( client . Schema . KERNEL ( \"\" ) ) client . Set ( client . Schema . FQDN ( \"\" % client_id ) ) client . Set ( client . Schema . ARCH ( \"\" ) ) client . Flush ( ) def testEndToEndTests ( self ) : self . client_ids = [ \"\" , \"\" , \"\" ] for clientid in self . client_ids : self . _SetSummaries ( clientid ) self . client_mock = action_mocks . ActionMock ( \"\" , \"\" ) with test_lib . ConfigOverrider ( { \"\" : self . client_ids } ) : with utils . MultiStubber ( ( base . AutomatedTest , \"\" , { \"\" : endtoend_test . MockEndToEndTest } ) , ( system . EndToEndTests , \"\" , ) ) : for _ in test_lib . TestFlowHelper ( \"\" , self . client_mock , client_id = self . client_id , check_flow_errors = False , token = self . token ) : pass test_lib . TestHuntHelperWithMultipleMocks ( { } , check_flow_errors = False , token = self . token ) hunt_ids = list ( aff4 . FACTORY . Open ( \"\" , token = self . token ) . ListChildren ( ) ) self . assertEqual ( len ( hunt_ids ) , ) hunt_obj = aff4 . FACTORY . Open ( hunt_ids [ ] , token = self . token , age = aff4 . ALL_TIMES ) self . assertItemsEqual ( sorted ( hunt_obj . GetClients ( ) ) , sorted ( self . client_ids ) ) def _CreateResult ( self , success , clientid ) : success = endtoend_flows . EndToEndTestResult ( success = success ) return flows . GrrMessage ( source = clientid , payload = success ) def testEndToEndTestsResultChecking ( self ) : self . client_ids = [ \"\" , \"\" , \"\" ] for clientid in self . client_ids : self . _SetSummaries ( clientid ) self . client_mock = action_mocks . ActionMock ( \"\" , \"\" ) endtoend = system . EndToEndTests ( None , token = self . token ) endtoend . state . Register ( \"\" , \"\" ) endtoend . state . Register ( \"\" , set ( self . client_ids ) ) endtoend . state . Register ( \"\" , set ( ) ) endtoend . state . Register ( \"\" , set ( ) ) self . assertRaises ( flow . FlowError , endtoend . _CheckForSuccess , [ ] ) endtoend . state . Register ( \"\" , set ( ) ) endtoend . state . Register ( \"\" , set ( ) ) self . assertRaises ( flow . FlowError , endtoend . _CheckForSuccess , [ self . _CreateResult ( True , \"\" ) ] ) endtoend . state . Register ( \"\" , set ( ) ) endtoend . state . Register ( \"\" , set ( ) ) endtoend . _CheckForSuccess ( [ self . _CreateResult ( True , \"\" ) , self . _CreateResult ( True , \"\" ) , self . _CreateResult ( True , \"\" ) ] ) endtoend . state . Register ( \"\" , set ( ) ) endtoend . state . Register ( \"\" , set ( ) ) self . assertRaises ( flow . FlowError , endtoend . _CheckForSuccess , ", "answer": "[ self . _CreateResult ( True , \"\" ) ,"}, {"prompt": " \"\"\"\"\"\" import sys from pycopia import clientserver class TestUDPClient ( clientserver . UDPClient ) : port = altport = def initialize ( self ) : fsm = self . fsm fsm . add_transition ( fsm . ANY , fsm . RESET , self . _greet , ) fsm . add_expression ( \"\" , , None , ) ", "answer": "fsm . add_transition ( \"\" , , self . _bye , fsm . RESET )"}, {"prompt": " \"\"\"\"\"\" from distutils . core import setup ", "answer": "from Cython . Build import cythonize"}, {"prompt": " import requests import yaml from lib . base import OpscenterAction class SetNodeConfAction ( OpscenterAction ) : def run ( self , node_ip , node_conf , cluster_id = None ) : if not cluster_id : cluster_id = self . cluster_id try : yaml . safe_load ( node_conf ) except : self . logger . error ( '' ) raise ", "answer": "url = self . _get_full_url ( [ cluster_id , '' , node_ip ] )"}, {"prompt": " \"\"\"\"\"\" __authors__ = \"\" __copyright__ = \"\" __credits__ = [ \"\" ] __license__ = \"\" __maintainer__ = \"\" __email__ = \"\" import numpy as np from theano . compat . six . moves import xrange from pylearn2 . datasets . dense_design_matrix import DenseDesignMatrix class ArangeDataset ( DenseDesignMatrix ) : \"\"\"\"\"\" def __init__ ( self , num_examples , * args , ** kwargs ) : X = np . zeros ( ( num_examples , ) ) X [ : , ] = np . arange ( num_examples ) super ( ArangeDataset , self ) . __init__ ( X , * args , ** kwargs ) def random_dense_design_matrix ( rng , num_examples , dim , num_classes ) : \"\"\"\"\"\" X = rng . randn ( num_examples , dim ) if num_classes : Y = rng . randint ( , num_classes , ( num_examples , ) ) y_labels = num_classes else : Y = None y_labels = None return DenseDesignMatrix ( X = X , y = Y , y_labels = y_labels ) def random_one_hot_dense_design_matrix ( rng , num_examples , dim , num_classes ) : X = rng . randn ( num_examples , dim ) idx = rng . randint ( , num_classes , ( num_examples , ) ) Y = np . zeros ( ( num_examples , num_classes ) ) for i in xrange ( num_examples ) : Y [ i , idx [ i ] ] = return DenseDesignMatrix ( X = X , y = Y ) def random_one_hot_topological_dense_design_matrix ( rng , num_examples , shape , channels , axes , num_classes ) : dims = { '' : num_examples , '' : channels } for i , dim in enumerate ( shape ) : dims [ i ] = dim shape = [ dims [ axis ] for axis in axes ] X = rng . randn ( * shape ) idx = rng . randint ( , num_classes , ( num_examples , ) ) Y = np . zeros ( ( num_examples , num_classes ) ) for i in xrange ( num_examples ) : Y [ i , idx [ i ] ] = return DenseDesignMatrix ( topo_view = X , axes = axes , y = Y ) def random_dense_design_matrix_for_regression ( rng , num_examples , dim , reg_min , reg_max ) : \"\"\"\"\"\" X = rng . randn ( num_examples , dim ) ", "answer": "Y = rng . randint ( reg_min , reg_max , ( num_examples , ) )"}, {"prompt": " \"\"\"\"\"\" import model_v8 as model class LineItem ( model . Entity ) : description = model . NonBlank ( ) ", "answer": "weight = model . Quantity ( )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division try : import unittest2 as unittest except ImportError : import unittest from neo . io import NeuroScopeIO from neo . test . iotest . common_io_test import BaseTestIO class TestNeuroScopeIO ( BaseTestIO , unittest . TestCase , ) : ioclass = NeuroScopeIO ", "answer": "files_to_test = [ '' ]"}, {"prompt": " from __future__ import unicode_literals import logging import sqlalchemy as sa from h . db import Base log = logging . getLogger ( __name__ ) FEATURES = { '' : \"\" , '' : \"\" , '' : '' } FEATURES_PENDING_REMOVAL = { '' : \"\" , '' : \"\" , ", "answer": "}"}, {"prompt": " from __future__ import unicode_literals \"\"\"\"\"\" import frappe , os , frappe . permissions class PatchError ( Exception ) : pass def run_all ( ) : \"\"\"\"\"\" executed = [ p [ ] for p in frappe . db . sql ( \"\"\"\"\"\" ) ] for patch in get_all_patches ( ) : if patch and ( patch not in executed ) : if not run_single ( patchmodule = patch ) : log ( patch + '' ) raise PatchError ( patch ) def get_all_patches ( ) : patches = [ ] for app in frappe . get_installed_apps ( ) : if app == \"\" : continue if app == \"\" : app = \"\" patches . extend ( frappe . get_file_items ( frappe . get_pymodule_path ( app , \"\" ) ) ) ", "answer": "return patches"}, {"prompt": " import decimal from django . conf import settings import stripe from . . import hooks from . . import models from . . import utils ", "answer": "def calculate_refund_amount ( charge , amount = None ) :"}, {"prompt": " from libcloud . compute . types import Provider from libcloud . compute . providers import get_driver RACKSPACE_USER = '' RACKSPACE_KEY = '' Driver = get_driver ( Provider . RACKSPACE ) conn = Driver ( RACKSPACE_USER , RACKSPACE_KEY ) ", "answer": "images = conn . list_images ( )"}, {"prompt": " def human_bytes ( bytes ) : bytes = float ( bytes ) if bytes >= : gigabytes = bytes / size = '' % gigabytes elif bytes >= : megabytes = bytes / size = '' % megabytes elif bytes >= : kilobytes = bytes / size = '' % kilobytes else : ", "answer": "size = '' % bytes"}, {"prompt": " from __future__ import unicode_literals import logging __all__ = ( '' , ", "answer": ")"}, {"prompt": " import abc import six @ six . add_metaclass ( abc . ABCMeta ) class Serializable ( object ) : @ abc . abstractmethod def to_dict ( self ) : pass @ classmethod def from_dict ( cls , data ) : ", "answer": "return cls ( ** data )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Tangible ( )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Creature ( )"}, {"prompt": " import pymel . core as pm def camera_film_offset_tool ( ) : \"\"\"\"\"\" sel_list = pm . ls ( sl = ) camera_shape = \"\" found_camera = for obj in sel_list : if isinstance ( obj , pm . nt . Transform ) : for shape in obj . listRelatives ( s = True ) : if isinstance ( shape , pm . nt . Camera ) : camera_shape = shape found_camera = break elif isinstance ( obj , pm . nt . Camera ) : camera_shape = obj found_camera = break if found_camera : pass else : raise RuntimeError ( \"\" ) temp = camera_shape . listRelatives ( p = True ) camera_transform = temp [ ] pm . getAttr ( \"\" ) pm . getAttr ( \"\" ) frame_curve = pm . curve ( d = , p = [ ( - , , ) , ", "answer": "( , , ) ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals import os , sys import pytz import xml . etree . ElementTree as ET import zipfile import logging from datetime import datetime from email import message_from_file from stat import S_ISREG from cStringIO import StringIO from time import timezone from django . db import Error from django . conf import settings from django . core . exceptions import ObjectDoesNotExist from django . core . management . base import BaseCommand , CommandError from dmarc . models import Reporter , Report , Record , Result class Command ( BaseCommand ) : \"\"\"\"\"\" args = '' help = '' def handle ( self , * args , ** options ) : \"\"\"\"\"\" logger = logging . getLogger ( __name__ ) logger . info ( \"\" ) supress_errors = False dmarc_iszipfile = False dmarc_xml = '' dmarc_file = '' if len ( args ) == : if args [ ] == '' : supress_errors = True email_msg = StringIO ( ) for line in sys . stdin : email_msg . write ( line ) email_msg . seek ( ) if email_msg : dmarcemail = message_from_file ( email_msg ) for mimepart in dmarcemail . walk ( ) : if mimepart . get_content_type ( ) == '' or mimepart . get_content_type ( ) == '' or mimepart . get_content_type ( ) == '' : dmarc_zip = StringIO ( ) dmarc_zip . write ( mimepart . get_payload ( decode = True ) ) dmarc_zip . seek ( ) ZipFile = zipfile . ZipFile ( dmarc_zip , '' ) files = ZipFile . infolist ( ) for f in files : dmarc_xml = ZipFile . read ( f ) ZipFile . close ( ) dmarc_iszipfile = True else : dmarc_file = args [ ] if os . path . exists ( dmarc_file ) : msg = \"\" % dmarc_file logger . debug ( msg ) else : msg = \"\" % dmarc_file logger . error ( msg ) raise CommandError ( msg ) mode = os . stat ( dmarc_file ) . st_mode if not S_ISREG ( mode ) : msg = \"\" % dmarc_file logger . error ( msg ) raise CommandError ( msg ) msg = \"\" % dmarc_file logger . debug ( msg ) if zipfile . is_zipfile ( dmarc_file ) : dmarc_iszipfile = True ZipFile = zipfile . ZipFile ( dmarc_file , '' ) files = ZipFile . infolist ( ) for f in files : dmarc_xml = ZipFile . read ( f ) ZipFile . close ( ) else : msg = \"\" logger . error ( msg ) raise CommandError ( msg ) tz_utc = pytz . timezone ( '' ) report_xml = '' if dmarc_iszipfile : report_xml = dmarc_xml root = ET . fromstring ( dmarc_xml ) else : tree = ET . parse ( dmarc_file ) report_xml_stringio = StringIO ( ) tree . write ( report_xml_stringio , encoding = \"\" , xml_declaration = True ) report_xml_stringio . seek ( ) report_xml = report_xml_stringio . readlines ( ) root = tree . getroot ( ) report_metadata = root . findall ( '' ) org_name = None email = None report_id = None report_begin = None report_end = None for node in report_metadata [ ] : if node . tag == '' : org_name = node . text if node . tag == '' : email = node . text if node . tag == '' : report_id = node . text if node . tag == '' : report_begin = node . find ( '' ) . text report_end = node . find ( '' ) . text if org_name is None : msg = \"\" logger . error ( msg ) if not supress_errors : raise CommandError ( msg ) if report_id is None : msg = \"\" % org_name logger . error ( msg ) if not supress_errors : raise CommandError ( msg ) try : reporter = Reporter . objects . get ( org_name = org_name ) except ObjectDoesNotExist : try : reporter = Reporter . objects . create ( org_name = org_name , email = email ) except Error as e : msg = \"\" % ( org_name , e ) logger . error ( msg ) if not supress_errors : raise CommandError ( msg ) policy_published = root . findall ( '' ) policy_domain = None policy_adkim = '' policy_aspf = '' policy_p = '' policy_sp = '' policy_pct = for node in policy_published [ ] : if node . tag == '' : policy_domain = node . text if node . tag == '' : policy_adkim = node . text if node . tag == '' : policy_aspf = node . text if node . tag == '' : policy_p = node . text if node . tag == '' : policy_sp = node . text if node . tag == '' : policy_pct = int ( node . text ) report = Report ( ) report . report_id = report_id report . reporter = reporter report_date_begin = datetime . fromtimestamp ( float ( report_begin ) ) . replace ( tzinfo = tz_utc ) try : report_date_begin = datetime . fromtimestamp ( float ( report_begin ) ) . replace ( tzinfo = tz_utc ) report_date_end = datetime . fromtimestamp ( float ( report_end ) ) . replace ( tzinfo = tz_utc ) except : msg = \"\" logger . error ( msg ) if not supress_errors : raise CommandError ( msg ) report . date_begin = report_date_begin report . date_end = report_date_end report . policy_domain = policy_domain report . policy_adkim = policy_adkim report . policy_aspf = policy_aspf report . policy_p = policy_p report . policy_sp = policy_sp report . policy_pct = policy_pct report . report_xml = report_xml try : report . save ( ) except Error as e : msg = \"\" % ( report_id , e ) ", "answer": "logger . error ( msg )"}, {"prompt": " from . . excel_comparsion_test import ExcelComparisonTest from ... workbook import Workbook class TestCompareXLSXFiles ( ExcelComparisonTest ) : \"\"\"\"\"\" def setUp ( self ) : self . maxDiff = None filename = '' test_dir = '' self . got_filename = test_dir + '' + filename self . exp_filename = test_dir + '' + filename self . ignore_files = [ '' , '' ] self . ignore_elements = { '' : [ '' ] , '' : [ '' , '' ] } def test_create_file ( self ) : \"\"\"\"\"\" workbook = Workbook ( self . got_filename ) worksheet = workbook . add_worksheet ( ) worksheet . hide_gridlines ( ) worksheet . center_horizontally ( ) ", "answer": "worksheet . center_vertically ( )"}, {"prompt": " from os . path import exists from setuptools import setup setup ( name = '' , version = '' , description = '' , url = '' , maintainer = '' , maintainer_email = '' , license = '' , keywords = '' , packages = [ '' ] , package_data = { '' : [ '' ] } , install_requires = list ( open ( '' ) . read ( ) . strip ( ) . split ( '' ) ) , ", "answer": "long_description = ( open ( '' ) . read ( ) if exists ( '' )"}, {"prompt": " from ... filters import sass from ... utils import get_media_dirs from django . conf import settings from django . core . management . base import NoArgsCommand from subprocess import Popen , PIPE import os import shutil import sys import __main__ _frameworks_dir = '' if hasattr ( __main__ , '' ) : ", "answer": "_root = os . path . dirname ( __main__ . __file__ )"}, {"prompt": " EDUPERSON_OID = '' NETSCAPE_LDAP = '' NOREDUPERSON_OID = '' PKCS_9 = '' UCL_DIR_PILOT = '' UMICH = '' X500ATTR = '' MAP = { \"\" : \"\" , '' : { EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , EDUPERSON_OID + '' : '' , NETSCAPE_LDAP + '' : '' , NETSCAPE_LDAP + '' : '' , NETSCAPE_LDAP + '' : '' , NETSCAPE_LDAP + '' : '' , NETSCAPE_LDAP + '' : '' , NETSCAPE_LDAP + '' : '' , NETSCAPE_LDAP + '' : '' , NETSCAPE_LDAP + '' : '' , NOREDUPERSON_OID + '' : '' , NOREDUPERSON_OID + '' : '' , NOREDUPERSON_OID + '' : '' , NOREDUPERSON_OID + '' : '' , NOREDUPERSON_OID + '' : '' , NOREDUPERSON_OID + '' : '' , NOREDUPERSON_OID + '' : '' , NOREDUPERSON_OID + '' : '' , NOREDUPERSON_OID + '' : '' , PKCS_9 + '' : '' , UCL_DIR_PILOT + '' : '' , UCL_DIR_PILOT + '' : '' , UCL_DIR_PILOT + '' : '' , UCL_DIR_PILOT + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , X500ATTR + '' : '' , } , '' : { '' : UCL_DIR_PILOT + '' , '' : X500ATTR + '' , '' : X500ATTR + '' , '' : X500ATTR + '' , '' : X500ATTR + '' , '' : NETSCAPE_LDAP + '' , '' : X500ATTR + '' , '' : X500ATTR + '' , '' : X500ATTR + '' , '' : UCL_DIR_PILOT + '' , '' : X500ATTR + '' , '' : NETSCAPE_LDAP + '' , '' : X500ATTR + '' , '' : NETSCAPE_LDAP + '' , '' : X500ATTR + '' , '' : X500ATTR + '' , '' : UCL_DIR_PILOT + '' , '' : EDUPERSON_OID + '' , '' : EDUPERSON_OID + '' , '' : EDUPERSON_OID + '' , '' : EDUPERSON_OID + '' , '' : EDUPERSON_OID + '' , '' : EDUPERSON_OID + '' , '' : EDUPERSON_OID + '' , ", "answer": "'' : EDUPERSON_OID + '' ,"}, {"prompt": " from . import util from okcupyd import User , photo @ util . use_cassette ( path = '' , match_on = util . match_on_no_body ) def test_photo_upload ( ) : uploader = photo . PhotoUploader ( ) upload_response_dict = uploader . upload_and_confirm ( '' ) assert int ( upload_response_dict [ '' ] ) > @ util . use_cassette ( path = '' , match_on = util . match_on_no_body ) def test_photo_delete ( ) : user = User ( ) response_dict = user . photo . upload_and_confirm ( user . quickmatch ( ) . photo_infos [ ] ) before_delete_photos = user . profile . photo_infos user . photo . delete ( response_dict [ '' ] ) user . profile . refresh ( ) assert len ( before_delete_photos ) - == len ( user . profile . photo_infos ) def test_make_photo_uri_from_https_link ( ) : photo_info = photo . Info . from_cdn_uri ( '' '' '' ", "answer": ")"}, {"prompt": " \"\"\"\"\"\" import doctest import os import sys from oslo_config import cfg import XenAPI possible_topdir = os . getcwd ( ) if os . path . exists ( os . path . join ( possible_topdir , \"\" , \"\" ) ) : sys . path . insert ( , possible_topdir ) from nova import config from nova import context import nova . conf from nova import db from nova import exception from oslo_utils import timeutils from nova . virt import virtapi from nova . virt . xenapi import driver as xenapi_driver cleaner_opts = [ cfg . IntOpt ( '' , default = , help = '' ) , ] cli_opt = cfg . StrOpt ( '' , help = '' ) CONF = nova . conf . CONF CONF . register_opts ( cleaner_opts ) CONF . register_cli_opt ( cli_opt ) ", "answer": "CONF . import_opt ( '' , '' )"}, {"prompt": " \"\"\"\"\"\" from social . p3 import urlsplit from social . backends . open_id import OpenIdAuth from social . exceptions import AuthMissingParameter class LiveJournalOpenId ( OpenIdAuth ) : \"\"\"\"\"\" name = '' def get_user_details ( self , response ) : \"\"\"\"\"\" values = super ( LiveJournalOpenId , self ) . get_user_details ( response ) values [ '' ] = values . get ( '' ) or urlsplit ( response . identity_url ) . netloc . split ( '' , ) [ ] return values def openid_url ( self ) : \"\"\"\"\"\" if not self . data . get ( '' ) : raise AuthMissingParameter ( self , '' ) ", "answer": "return '' . format ( self . data [ '' ] ) "}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Building ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " import unittest from openxc . sinks import UploaderSink class UploaderSinkTest ( unittest . TestCase ) : def test_create ( self ) : ", "answer": "UploaderSink ( \"\" ) "}, {"prompt": " \"\"\"\"\"\" import threading import socket import Queue import select import struct import logging from thrift . transport import TTransport from thrift . protocol . TBinaryProtocol import TBinaryProtocolFactory __all__ = [ '' ] class Worker ( threading . Thread ) : \"\"\"\"\"\" def __init__ ( self , queue ) : threading . Thread . __init__ ( self ) self . queue = queue def run ( self ) : \"\"\"\"\"\" while True : try : processor , iprot , oprot , otrans , callback = self . queue . get ( ) if processor is None : break processor . process ( iprot , oprot ) callback ( True , otrans . getvalue ( ) ) except Exception : logging . exception ( \"\" ) callback ( False , '' ) WAIT_LEN = WAIT_MESSAGE = WAIT_PROCESS = SEND_ANSWER = CLOSED = def locked ( func ) : \"\"\"\"\"\" def nested ( self , * args , ** kwargs ) : self . lock . acquire ( ) try : return func ( self , * args , ** kwargs ) finally : self . lock . release ( ) return nested def socket_exception ( func ) : \"\"\"\"\"\" def read ( self , * args , ** kwargs ) : try : return func ( self , * args , ** kwargs ) except socket . error : self . close ( ) return read class Connection : \"\"\"\"\"\" def __init__ ( self , new_socket , wake_up ) : self . socket = new_socket self . socket . setblocking ( False ) self . status = WAIT_LEN self . len = self . message = '' self . lock = threading . Lock ( ) self . wake_up = wake_up def _read_len ( self ) : \"\"\"\"\"\" read = self . socket . recv ( - len ( self . message ) ) if len ( read ) == : if len ( self . message ) != : logging . error ( \"\" ) self . close ( ) return self . message += read if len ( self . message ) == : self . len , = struct . unpack ( '' , self . message ) if self . len < : logging . error ( \"\" \"\" ) self . close ( ) elif self . len == : logging . error ( \"\" ) self . close ( ) else : self . message = '' self . status = WAIT_MESSAGE @ socket_exception def read ( self ) : \"\"\"\"\"\" assert self . status in ( WAIT_LEN , WAIT_MESSAGE ) if self . status == WAIT_LEN : self . _read_len ( ) elif self . status == WAIT_MESSAGE : read = self . socket . recv ( self . len - len ( self . message ) ) if len ( read ) == : logging . error ( \"\" \"\" % ( len ( self . message ) , self . len ) ) self . close ( ) return self . message += read if len ( self . message ) == self . len : self . status = WAIT_PROCESS @ socket_exception def write ( self ) : \"\"\"\"\"\" assert self . status == SEND_ANSWER sent = self . socket . send ( self . message ) if sent == len ( self . message ) : self . status = WAIT_LEN self . message = '' self . len = else : self . message = self . message [ sent : ] @ locked def ready ( self , all_ok , message ) : \"\"\"\"\"\" assert self . status == WAIT_PROCESS if not all_ok : self . close ( ) self . wake_up ( ) return self . len = '' if len ( message ) == : self . message = '' self . status = WAIT_LEN else : self . message = struct . pack ( '' , len ( message ) ) + message self . status = SEND_ANSWER self . wake_up ( ) @ locked def is_writeable ( self ) : \"\"\"\"\"\" return self . status == SEND_ANSWER @ locked def is_readable ( self ) : \"\"\"\"\"\" return self . status in ( WAIT_LEN , WAIT_MESSAGE ) @ locked ", "answer": "def is_closed ( self ) :"}, {"prompt": " from decimal import Decimal import logging import json from django . db import connection from django . db . models import Q from django . http import HttpResponse from annotation_server import utils logger = logging . getLogger ( __name__ ) def search_genes ( request , genome , search_string ) : \"\"\"\"\"\" logger . debug ( \"\" \"\" , genome , search_string ) if genome in utils . SUPPORTED_GENOMES : current_table = eval ( genome + \"\" ) curr_vals = current_table . objects . filter ( Q ( name__contains = search_string ) | Q ( name2__contains = search_string ) ) . values ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) data = ValuesQuerySetToDict ( curr_vals ) return HttpResponse ( data , '' ) else : return HttpResponse ( status = ) return HttpResponse ( status = ) def search_extended_genes ( request , genome , search_string ) : \"\"\"\"\"\" logger . debug ( \"\" \"\" , genome , search_string ) def get_sequence ( request , genome , chrom , start , end ) : \"\"\"\"\"\" logger . debug ( \"\" \"\" , genome , chrom ) offset = int ( end ) - int ( start ) if genome in utils . SUPPORTED_GENOMES : cursor = connection . cursor ( ) query = ( \"\" \"\" ) . format ( start , offset , genome , chrom ) cursor . execute ( query ) return HttpResponse ( cursor_to_json ( cursor ) , '' ) else : return HttpResponse ( status = ) def get_length ( request , genome ) : \"\"\"\"\"\" logger . debug ( \"\" , genome ) if genome in utils . SUPPORTED_GENOMES : current_table = eval ( genome + \"\" ) data = ValuesQuerySetToDict ( current_table . objects . values ( '' , '' ) ) return HttpResponse ( data , '' ) else : return HttpResponse ( status = ) def get_chrom_length ( request , genome , chrom ) : \"\"\"\"\"\" logger . debug ( \"\" \"\" , genome , chrom ) if genome in utils . SUPPORTED_GENOMES : current_table = eval ( genome + \"\" ) curr_vals = current_table . objects . filter ( chrom__iexact = chrom ) . values ( '' , '' ) data = ValuesQuerySetToDict ( curr_vals ) return HttpResponse ( data , '' ) else : return HttpResponse ( status = ) def get_cytoband ( request , genome , chrom ) : \"\"\"\"\"\" logger . debug ( \"\" \"\" , genome , chrom ) if genome in utils . SUPPORTED_GENOMES : current_table = eval ( genome + \"\" ) curr_vals = current_table . objects . filter ( chrom__iexact = chrom ) . values ( '' , '' , '' , '' , '' ) data = ValuesQuerySetToDict ( curr_vals ) return HttpResponse ( data , '' ) else : return HttpResponse ( status = ) def get_genes ( request , genome , chrom , start , end ) : \"\"\"\"\"\" logger . debug ( \"\" \"\" , genome , chrom ) if genome in utils . SUPPORTED_GENOMES : current_table = eval ( genome + \"\" ) curr_vals = current_table . objects . filter ( Q ( chrom__iexact = chrom ) , Q ( cdsStart__range = ( start , end ) ) | Q ( cdsEnd__range = ( start , end ) ) ) . values ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) ", "answer": "data = ValuesQuerySetToDict ( curr_vals )"}, {"prompt": " from __future__ import unicode_literals from django . contrib . gis . geos import ( GeometryCollection , LineString , MultiLineString , MultiPoint , MultiPolygon , Point , Polygon , ) from django . db import connection from django . test . utils import skipUnless from django . utils . module_loading import import_string from django . utils . translation import ugettext_lazy as _ from mutant . models import BaseDefinition from mutant . test . testcases import FieldDefinitionTestMixin from . utils import BaseModelDefinitionTestCase class GeometryFieldDefinitionTestMixin ( FieldDefinitionTestMixin ) : field_definition_category = _ ( '' ) @ property def field_definition_cls ( self ) : return import_string ( \"\" % self . field_definition_cls_name ) def setUp ( self ) : super ( GeometryFieldDefinitionTestMixin , self ) . setUp ( ) from mutant . contrib . geo . models import GeoModel BaseDefinition . objects . create ( model_def = self . model_def , base = GeoModel ) @ skipUnless ( connection . settings_dict [ '' ] == '' , '' ) class GeometryFieldDefinitionTest ( GeometryFieldDefinitionTestMixin , BaseModelDefinitionTestCase ) : field_definition_cls_name = '' field_values = ( LineString ( ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ) , Polygon ( ( ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ) ) ) @ skipUnless ( connection . settings_dict [ '' ] == '' , '' ) class PointFieldDefinitionTest ( GeometryFieldDefinitionTestMixin , BaseModelDefinitionTestCase ) : field_definition_cls_name = '' field_values = ( Point ( , ) , Point ( , ) ) @ skipUnless ( connection . settings_dict [ '' ] == '' , '' ) class LineStringFieldDefinitionTest ( GeometryFieldDefinitionTestMixin , BaseModelDefinitionTestCase ) : field_definition_cls_name = '' field_values = ( LineString ( ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ) , LineString ( ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ) ) @ skipUnless ( connection . settings_dict [ '' ] == '' , '' ) class PolygonFieldDefinitionTest ( GeometryFieldDefinitionTestMixin , BaseModelDefinitionTestCase ) : field_definition_cls_name = '' field_values = ( Polygon ( ( ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ) ) , Polygon ( ( ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ) ", "answer": ") ,"}, {"prompt": " from . _base import Config ", "answer": "class RatelimitConfig ( Config ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import try : from io import BytesIO except ImportError : from StringIO import StringIO as BytesIO import hashlib import pytest from zipfile import ZIP_DEFLATED , ZipFile from docx . opc . exceptions import PackageNotFoundError from docx . opc . packuri import PACKAGE_URI , PackURI from docx . opc . phys_pkg import ( _DirPkgReader , PhysPkgReader , PhysPkgWriter , _ZipPkgReader , _ZipPkgWriter ) from . . unitutil . file import absjoin , test_file_dir from . . unitutil . mock import class_mock , loose_mock , Mock test_docx_path = absjoin ( test_file_dir , '' ) dir_pkg_path = absjoin ( test_file_dir , '' ) zip_pkg_path = test_docx_path class DescribeDirPkgReader ( object ) : def it_is_used_by_PhysPkgReader_when_pkg_is_a_dir ( self ) : phys_reader = PhysPkgReader ( dir_pkg_path ) assert isinstance ( phys_reader , _DirPkgReader ) def it_doesnt_mind_being_closed_even_though_it_doesnt_need_it ( self , dir_reader ) : dir_reader . close ( ) def it_can_retrieve_the_blob_for_a_pack_uri ( self , dir_reader ) : pack_uri = PackURI ( '' ) blob = dir_reader . blob_for ( pack_uri ) sha1 = hashlib . sha1 ( blob ) . hexdigest ( ) assert sha1 == '' def it_can_get_the_content_types_xml ( self , dir_reader ) : sha1 = hashlib . sha1 ( dir_reader . content_types_xml ) . hexdigest ( ) assert sha1 == '' def it_can_retrieve_the_rels_xml_for_a_source_uri ( self , dir_reader ) : rels_xml = dir_reader . rels_xml_for ( PACKAGE_URI ) sha1 = hashlib . sha1 ( rels_xml ) . hexdigest ( ) assert sha1 == '' def it_returns_none_when_part_has_no_rels_xml ( self , dir_reader ) : partname = PackURI ( '' ) rels_xml = dir_reader . rels_xml_for ( partname ) assert rels_xml is None @ pytest . fixture def pkg_file_ ( self , request ) : return loose_mock ( request ) @ pytest . fixture ( scope = '' ) def dir_reader ( self ) : return _DirPkgReader ( dir_pkg_path ) class DescribePhysPkgReader ( object ) : def it_raises_when_pkg_path_is_not_a_package ( self ) : with pytest . raises ( PackageNotFoundError ) : PhysPkgReader ( '' ) class DescribeZipPkgReader ( object ) : def it_is_used_by_PhysPkgReader_when_pkg_is_a_zip ( self ) : phys_reader = PhysPkgReader ( zip_pkg_path ) assert isinstance ( phys_reader , _ZipPkgReader ) def it_is_used_by_PhysPkgReader_when_pkg_is_a_stream ( self ) : with open ( zip_pkg_path , '' ) as stream : phys_reader = PhysPkgReader ( stream ) assert isinstance ( phys_reader , _ZipPkgReader ) def it_opens_pkg_file_zip_on_construction ( self , ZipFile_ , pkg_file_ ) : _ZipPkgReader ( pkg_file_ ) ZipFile_ . assert_called_once_with ( pkg_file_ , '' ) def it_can_be_closed ( self , ZipFile_ ) : zipf = ZipFile_ . return_value zip_pkg_reader = _ZipPkgReader ( None ) zip_pkg_reader . close ( ) zipf . close . assert_called_once_with ( ) def it_can_retrieve_the_blob_for_a_pack_uri ( self , phys_reader ) : pack_uri = PackURI ( '' ) blob = phys_reader . blob_for ( pack_uri ) sha1 = hashlib . sha1 ( blob ) . hexdigest ( ) assert sha1 == '' def it_has_the_content_types_xml ( self , phys_reader ) : sha1 = hashlib . sha1 ( phys_reader . content_types_xml ) . hexdigest ( ) assert sha1 == '' def it_can_retrieve_rels_xml_for_source_uri ( self , phys_reader ) : rels_xml = phys_reader . rels_xml_for ( PACKAGE_URI ) sha1 = hashlib . sha1 ( rels_xml ) . hexdigest ( ) assert sha1 == '' def it_returns_none_when_part_has_no_rels_xml ( self , phys_reader ) : ", "answer": "partname = PackURI ( '' )"}, {"prompt": " import collections import copy import pprint import time from neutron_lib import constants ", "answer": "from oslo_log import log as logging"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , print_function , division from itertools import chain import numpy import theano from six . moves import xrange from theano . compat import izip from theano . gof import Op , Apply , local_optimizer , EquilibriumDB from theano . gof . utils import hash_from_dict from theano . sandbox . cuda import GpuElemwise , CudaNdarrayType , GpuOp from theano . sandbox . cuda . basic_ops import ( as_cuda_ndarray_variable , gpu_contiguous ) from theano . sandbox . cuda . opt import gpu_seqopt import pycuda from pycuda . compiler import SourceModule import pycuda . gpuarray from . import pycuda_init if not pycuda_init . pycuda_available : raise Exception ( \"\" ) def _replace_npy_types ( c_arg ) : c_arg = c_arg . replace ( '' , '' ) c_arg = c_arg . replace ( '' , '' ) c_arg = c_arg . replace ( '' , '' ) c_arg = c_arg . replace ( '' , '' ) c_arg = c_arg . replace ( '' , '' ) c_arg = c_arg . replace ( '' , '' ) c_arg = c_arg . replace ( '' , '' ) c_arg = c_arg . replace ( '' , '' ) return c_arg def theano_parse_c_arg ( c_arg ) : c_arg = _replace_npy_types ( c_arg ) return pycuda . tools . parse_c_arg ( c_arg ) \"\"\"\"\"\" class PycudaElemwiseSourceModuleOp ( GpuOp ) : nin = property ( lambda self : self . scalar_op . nin ) nout = property ( lambda self : self . scalar_op . nout ) def __init__ ( self , scalar_op , inplace_pattern = None , name = None ) : if inplace_pattern is None : inplace_pattern = { } self . name = name self . scalar_op = scalar_op self . inplace_pattern = inplace_pattern def __str__ ( self ) : if self . name is None : if self . inplace_pattern : items = list ( self . inplace_pattern . items ( ) ) items . sort ( ) return self . __class__ . __name__ + \"\" % ( self . scalar_op , str ( items ) ) else : return self . __class__ . __name__ + \"\" % ( self . scalar_op ) else : return self . name def __eq__ ( self , other ) : return ( type ( self ) == type ( other ) and self . scalar_op == other . scalar_op and self . inplace_pattern == other . inplace_pattern ) def __hash__ ( self ) : return ( hash ( type ( self ) ) ^ hash ( self . scalar_op ) ^ hash_from_dict ( self . inplace_pattern ) ) def make_node ( self , * inputs ) : _inputs = [ gpu_contiguous ( as_cuda_ndarray_variable ( i ) ) for i in inputs ] if self . nin > and len ( _inputs ) != self . nin : raise TypeError ( '' , ( self . nin , len ( _inputs ) ) ) for i in _inputs [ : ] : if i . type . ndim != inputs [ ] . type . ndim : raise TypeError ( '' ) if any ( [ any ( i . type . broadcastable ) for i in inputs ] ) : ", "answer": "raise Exception ( \"\" )"}, {"prompt": " \"\"\"\"\"\" import sys as _sys from operator import itemgetter as _itemgetter from keyword import iskeyword as _iskeyword from collections import OrderedDict class tagtuple ( tuple ) : \"\"\"\"\"\" __slots__ = ( ) def __new__ ( cls , * args ) : \"\"\"\"\"\" return super ( tagtuple , cls ) . __new__ ( cls , args ) def __repr__ ( self ) : \"\"\"\"\"\" return type ( self ) . __name__ + super ( tagtuple , self ) . __repr__ ( ) def __getnewargs__ ( self ) : \"\"\"\"\"\" return tuple ( self ) def __eq__ ( self , other ) : return type ( self ) is type ( other ) and super ( tagtuple , self ) . __eq__ ( other ) def __ne__ ( self , other ) : return not self . __eq__ ( other ) def __getslice__ ( self , i , j ) : return type ( self ) ( * super ( tagtuple , self ) . __getslice__ ( i , j ) ) __add__ = property ( ) __contains__ = property ( ) __mul__ = property ( ) __rmul__ = property ( ) count = property ( ) index = property ( ) _class_template = '''''' _repr_template = '' _field_template = '''''' def rectuple ( typename , field_names , verbose = False , rename = False ) : \"\"\"\"\"\" if isinstance ( field_names , basestring ) : field_names = field_names . replace ( '' , '' ) . split ( ) field_names = map ( str , field_names ) if rename : seen = set ( ) for index , name in enumerate ( field_names ) : if ( not all ( c . isalnum ( ) or c == '' for c in name ) or _iskeyword ( name ) or not name or name [ ] . isdigit ( ) or name . startswith ( '' ) or name in seen ) : field_names [ index ] = '' % index seen . add ( name ) for name in [ typename ] + field_names : if not all ( c . isalnum ( ) or c == '' for c in name ) : raise ValueError ( '' '' % name ) if _iskeyword ( name ) : raise ValueError ( '' '' % name ) if name [ ] . isdigit ( ) : raise ValueError ( '' '' % name ) seen = set ( ) for name in field_names : if name . startswith ( '' ) and not rename : raise ValueError ( '' '' % name ) if name in seen : raise ValueError ( '' % name ) seen . add ( name ) class_definition = _class_template . format ( typename = typename , field_names = tuple ( field_names ) , num_fields = len ( field_names ) , arg_list = repr ( tuple ( field_names ) ) . replace ( \"\" , \"\" ) [ : - ] , repr_fmt = '' . join ( _repr_template . format ( name = name ) for name in field_names ) , field_defs = '' . join ( _field_template . format ( index = index , name = name ) for index , name in enumerate ( field_names ) ) ) if verbose : print class_definition namespace = dict ( _itemgetter = _itemgetter , __name__ = '' % typename , OrderedDict = OrderedDict , _property = property , _tuple = tuple ) try : exec class_definition in namespace except SyntaxError as e : raise SyntaxError ( e . message + '' + class_definition ) result = namespace [ typename ] try : ", "answer": "result . __module__ = _sys . _getframe ( ) . f_globals . get ( '' , '' )"}, {"prompt": " \"\"\"\"\"\" revision = '' down_revision = '' from alembic import op import sqlalchemy as sa def upgrade ( ) : op . add_column ( '' , sa . Column ( '' , sa . Text ( ) , nullable = True ) ) def downgrade ( ) : ", "answer": "op . drop_column ( '' , '' ) "}, {"prompt": " from cvxopt import matrix , spmatrix , sparse , exp , uniform import numpy as np import math as math from so_interface import SOInterface class SOHMM ( SOInterface ) : \"\"\"\"\"\" ninf = - ** start_p = [ ] states = - hotstart_tradeoff = def __init__ ( self , X , y = [ ] , num_states = , hotstart_tradeoff = ) : SOInterface . __init__ ( self , X , y ) self . states = num_states self . start_p = matrix ( , ( self . states , ) ) self . hotstart_tradeoff = hotstart_tradeoff def get_hotstart_sol ( self ) : sol = uniform ( self . get_num_dims ( ) , , a = - , b = + ) sol [ : self . states * self . states ] = self . hotstart_tradeoff print ( '' . format ( self . hotstart_tradeoff ) ) return sol def calc_emission_matrix ( self , sol , idx , augment_loss = False , augment_prior = False ) : T = len ( self . X [ idx ] [ , : ] ) N = self . states F = self . dims em = matrix ( , ( N , T ) ) ; for t in xrange ( T ) : for s in xrange ( N ) : for f in xrange ( F ) : em [ s , t ] += sol [ N * N + s * F + f ] * self . X [ idx ] [ f , t ] if ( augment_loss == True ) : loss = matrix ( , ( N , T ) ) for t in xrange ( T ) : loss [ self . y [ idx ] [ t ] , t ] = em += loss if ( augment_prior == True ) : prior = matrix ( , ( N , T ) ) em += prior return em def get_transition_matrix ( self , sol ) : N = self . states A = matrix ( , ( N , N ) ) for i in xrange ( N ) : for j in xrange ( N ) : A [ i , j ] = sol [ i * N + j ] return A def argmax ( self , sol , idx , add_loss = False , add_prior = False , opt_type = '' ) : T = len ( self . X [ idx ] [ , : ] ) N = self . states F = self . dims A = self . get_transition_matrix ( sol ) em = self . calc_emission_matrix ( sol , idx , augment_loss = add_loss , augment_prior = add_prior ) delta = matrix ( , ( N , T ) ) ; psi = matrix ( , ( N , T ) ) ; for i in xrange ( N ) : delta [ i , ] = self . start_p [ i ] + em [ i , ] for t in xrange ( , T ) : for i in xrange ( N ) : ( delta [ i , t ] , psi [ i , t ] ) = max ( [ ( delta [ j , t - ] + A [ j , i ] + em [ i , t ] , j ) for j in xrange ( N ) ] ) ; states = matrix ( , ( , T ) ) ( prob , states [ T - ] ) = max ( [ delta [ i , T - ] , i ] for i in xrange ( N ) ) ; for t in reversed ( xrange ( , T ) ) : states [ t - ] = psi [ states [ t ] , t ] ; psi_idx = self . get_joint_feature_map ( idx , states ) val = sol . trans ( ) * psi_idx return ( val , states , psi_idx ) def get_jfm_norm2 ( self , idx , y = [ ] ) : y = np . array ( y ) if ( y . size == ) : y = np . array ( self . y [ idx ] ) jfm = self . get_joint_feature_map ( idx , y ) return jfm . trans ( ) * jfm def calc_loss ( self , idx , y ) : return float ( sum ( [ np . uint ( self . y [ idx ] [ i ] ) != np . uint ( y [ i ] ) for i in xrange ( len ( y ) ) ] ) ) def get_scores ( self , sol , idx , y = [ ] ) : y = np . array ( y ) if ( y . size == ) : y = np . array ( self . y [ idx ] ) ( foo , T ) = y . shape N = self . states F = self . dims scores = matrix ( , ( , T ) ) anom_score = sol . trans ( ) * self . get_joint_feature_map ( idx ) A = self . get_transition_matrix ( sol ) em = self . calc_emission_matrix ( sol , idx , augment_loss = False , augment_prior = False ) ; scores [ ] = self . start_p [ int ( y [ , ] ) ] + em [ int ( y [ , ] ) , ] for t in range ( , T ) : scores [ t ] = A [ int ( y [ , t - ] ) , int ( y [ , t ] ) ] + em [ int ( y [ , t ] ) , t ] if max ( abs ( scores ) ) > ** ( - ) : scores = exp ( - abs ( * scores / max ( abs ( scores ) ) ) ) else : scores = matrix ( , ( , T ) ) return ( float ( np . single ( anom_score ) ) , scores ) def get_joint_feature_map ( self , idx , y = [ ] ) : y = np . array ( y ) if ( y . size == ) : y = np . array ( self . y [ idx ] ) ( foo , T ) = y . shape N = self . states F = self . dims jfm = matrix ( , ( self . get_num_dims ( ) , ) ) for i in range ( N ) : ( foo , inds ) = np . where ( [ y [ , : T ] == i ] ) for j in range ( N ) : ( foo , indsj ) = np . where ( [ y [ , inds ] == j ] ) jfm [ j * N + i ] = len ( indsj ) for t in range ( T ) : for f in range ( F ) : jfm [ int ( y [ , t ] ) * F + f + N * N ] += self . X [ idx ] [ f , t ] return jfm def get_num_dims ( self ) : return self . dims * self . states + self . states * self . states def evaluate ( self , pred ) : \"\"\"\"\"\" N = self . samples if len ( pred ) != N : print len ( pred ) raise Exception ( '' ) all_tp = all_fp = all_tn = all_fn = err_exm = { } err_exm [ '' ] = [ ] err_exm [ '' ] = [ ] err_exm [ '' ] = [ ] err_exm [ '' ] = [ ] for i in xrange ( N ) : loss1 = self . calc_loss ( i , pred [ i ] ) loss2 = self . calc_loss ( i , - pred [ i ] + ) seq_true = np . uint ( np . sign ( self . y [ i ] ) ) seq_pred = np . uint ( np . sign ( pred [ i ] ) ) if loss2 < loss1 : seq_pred = np . uint ( np . sign ( - pred [ i ] + ) ) lens = len ( seq_pred [ , : ] ) tp = fp = tn = fn = isPosAvail = False for t in xrange ( lens ) : if ( seq_true [ , t ] == ) : isPosAvail = True fp += float ( seq_true [ , t ] == and seq_pred [ , t ] == ) fn += float ( seq_true [ , t ] == and seq_pred [ , t ] == ) tp += float ( seq_true [ , t ] == and seq_pred [ , t ] == ) ", "answer": "tn += float ( seq_true [ , t ] == and seq_pred [ , t ] == )"}, {"prompt": " '''''' ", "answer": "__all__ = ( '' , '' )"}, {"prompt": " from __pyjamas__ import get_main_frame , doc , JS sNextHashId = def getNextHashId ( ) : global sNextHashId sNextHashId += return sNextHashId def getHashCode ( o ) : JS ( \"\"\"\"\"\" ) def getModuleName ( ) : import os ", "answer": "import sys"}, {"prompt": " import json import re from django import http from django . db . models import Count from django . db . transaction import non_atomic_requests from django . shortcuts import redirect , render from django . views . decorators . csrf import csrf_exempt from olympia import amo from olympia . amo import utils as amo_utils from olympia . addons . decorators import owner_or_unlisted_reviewer from olympia . amo . decorators import post_required from olympia . addons . models import Addon from olympia . search . utils import floor_version from olympia . versions . compare import version_dict as vdict from . models import CompatReport from . forms import AppVerForm @ csrf_exempt @ post_required @ non_atomic_requests def incoming ( request ) : def snake_case ( s ) : ", "answer": "return re . sub ( '' , '' , s ) . lower ( )"}, {"prompt": " import unittest import os ", "answer": "import re"}, {"prompt": " from setuptools import setup , find_packages import codecs import os def read ( fname ) : \"\"\"\"\"\" return codecs . open ( os . path . join ( os . path . dirname ( __file__ ) , fname ) , encoding = '' ) . read ( ) setup ( name = '' , version = '' , description = '' , author = '' , author_email = '' , url = '' , packages = find_packages ( exclude = [ '' ] ) , install_requires = [ ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" import platform import warnings from ldacgsseq import * from ldacgsmulti import * from ldafunctions import load_lda __all__ = [ '' ] class LDA ( object ) : \"\"\"\"\"\" def __new__ ( cls , corpus = None , context_type = None , K = , V = , alpha = [ ] , beta = [ ] , multiprocessing = False , seed_or_seeds = None , n_proc = None ) : kwargs = dict ( corpus = corpus , context_type = context_type , ", "answer": "K = K , V = V , alpha = alpha , beta = beta )"}, {"prompt": " from . tokens_base import * class TokenEof ( Token ) : def __init__ ( self , * args , ** kwargs ) : super ( ) . __init__ ( TOKEN_EOF , '' , * args , ** kwargs ) class TokenOfSearch ( TokenOfRange ) : pass class TokenDollar ( TokenOfRange ) : def __init__ ( self , * args , ** kwargs ) : super ( ) . __init__ ( TOKEN_DOLLAR , '' , * args , ** kwargs ) class TokenComma ( TokenOfRange ) : ", "answer": "def __init__ ( self , * args , ** kwargs ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import models from djangobmf . models import BMFModel from djangobmf . workflow import Workflow from djangobmf . workflow import State from djangobmf . workflow import Transition class TestWorkflow ( Workflow ) : class States : start = State ( \"\" , default = True , delete = False ) end = State ( \"\" , update = False , delete = True ) class Transitions : go = Transition ( \"\" , \"\" , \"\" ) class TestView ( BMFModel ) : field = models . CharField ( max_length = ) field_b = models . CharField ( max_length = , blank = True , null = True ) class BMFMeta : has_files = True has_comments = True ", "answer": "observed_fields = [ '' , ]"}, {"prompt": " from os import system from os . path import join , abspath from pulsar . main import ArgumentParser , PulsarConfigBuilder from pulsar . core import DEFAULT_STAGING_DIRECTORY DESCRIPTION = \"\" FORCE_PRODUCTION = False def main ( argv = None ) : arg_parser = ArgumentParser ( description = DESCRIPTION ) arg_parser . add_argument ( \"\" , required = True ) arg_parser . add_argument ( \"\" ) arg_parser . add_argument ( \"\" ) ", "answer": "args = arg_parser . parse_args ( argv )"}, {"prompt": " from __future__ import unicode_literals from django . db import migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . RemoveField ( model_name = '' , name = '' , ) , ", "answer": "] "}, {"prompt": " \"\"\"\"\"\" from twisted . internet import defer from twisted . internet . defer import maybeDeferred from twisted . python import failure , reflect from twisted . cred import error from zope . interface import providedBy , Interface class IRealm ( Interface ) : \"\"\"\"\"\" def requestAvatar ( avatarId , mind , * interfaces ) : \"\"\"\"\"\" class Portal : \"\"\"\"\"\" def __init__ ( self , realm , checkers = ( ) ) : \"\"\"\"\"\" self . realm = realm self . checkers = { } for checker in checkers : self . registerChecker ( checker ) def listCredentialsInterfaces ( self ) : \"\"\"\"\"\" return self . checkers . keys ( ) def registerChecker ( self , checker , * credentialInterfaces ) : if not credentialInterfaces : credentialInterfaces = checker . credentialInterfaces for credentialInterface in credentialInterfaces : self . checkers [ credentialInterface ] = checker def login ( self , credentials , mind , * interfaces ) : \"\"\"\"\"\" for i in self . checkers : if i . providedBy ( credentials ) : return maybeDeferred ( self . checkers [ i ] . requestAvatarId , credentials ) . addCallback ( self . realm . requestAvatar , mind , * interfaces ) ifac = providedBy ( credentials ) ", "answer": "return defer . fail ( failure . Failure ( error . UnhandledCredentials ("}, {"prompt": " import unittest from test import support from itertools import * from weakref import proxy from decimal import Decimal from fractions import Fraction import sys import operator import random import copy import pickle from functools import reduce maxsize = support . MAX_Py_ssize_t minsize = - maxsize - def lzip ( * args ) : return list ( zip ( * args ) ) def onearg ( x ) : '' return * x def errfunc ( * args ) : '' raise ValueError def gen3 ( ) : '' for i in ( , , ) : yield i def isEven ( x ) : '' return x % == def isOdd ( x ) : '' return x % == def tupleize ( * args ) : return args def irange ( n ) : for i in range ( n ) : yield i class StopNow : '' def __iter__ ( self ) : return self def __next__ ( self ) : raise StopIteration def take ( n , seq ) : '' return list ( islice ( seq , n ) ) def prod ( iterable ) : return reduce ( operator . mul , iterable , ) def fact ( n ) : '' return prod ( range ( , n + ) ) def testR ( r ) : return r [ ] def testR2 ( r ) : return r [ ] def underten ( x ) : return x < class TestBasicOps ( unittest . TestCase ) : def pickletest ( self , it , stop = , take = , compare = None ) : \"\"\"\"\"\" def expand ( it , i = ) : if i > : raise RuntimeError ( \"\" ) if isinstance ( it , str ) : return it try : l = list ( islice ( it , stop ) ) except TypeError : return it return [ expand ( e , i + ) for e in l ] dump = pickle . dumps ( it ) i2 = pickle . loads ( dump ) self . assertEqual ( type ( it ) , type ( i2 ) ) a , b = expand ( it ) , expand ( i2 ) self . assertEqual ( a , b ) if compare : c = expand ( compare ) self . assertEqual ( a , c ) i3 = pickle . loads ( dump ) took = try : for i in range ( take ) : next ( i3 ) took += except StopIteration : pass dump = pickle . dumps ( i3 ) i4 = pickle . loads ( dump ) a , b = expand ( i3 ) , expand ( i4 ) self . assertEqual ( a , b ) if compare : c = expand ( compare [ took : ] ) self . assertEqual ( a , c ) ; def test_accumulate ( self ) : self . assertEqual ( list ( accumulate ( range ( ) ) ) , [ , , , , , , , , , ] ) self . assertEqual ( list ( accumulate ( iterable = range ( ) ) ) , [ , , , , , , , , , ] ) for typ in int , complex , Decimal , Fraction : self . assertEqual ( list ( accumulate ( map ( typ , range ( ) ) ) ) , list ( map ( typ , [ , , , , , , , , , ] ) ) ) self . assertEqual ( list ( accumulate ( '' ) ) , [ '' , '' , '' ] ) self . assertEqual ( list ( accumulate ( [ ] ) ) , [ ] ) self . assertEqual ( list ( accumulate ( [ ] ) ) , [ ] ) self . assertRaises ( TypeError , accumulate , range ( ) , , ) self . assertRaises ( TypeError , accumulate ) self . assertRaises ( TypeError , accumulate , x = range ( ) ) self . assertRaises ( TypeError , list , accumulate ( [ , [ ] ] ) ) s = [ , , , , , , , , , ] self . assertEqual ( list ( accumulate ( s , min ) ) , [ , , , , , , , , , ] ) self . assertEqual ( list ( accumulate ( s , max ) ) , [ , , , , , , , , , ] ) self . assertEqual ( list ( accumulate ( s , operator . mul ) ) , [ , , , , , , , , , ] ) with self . assertRaises ( TypeError ) : list ( accumulate ( s , chr ) ) self . pickletest ( accumulate ( range ( ) ) ) def test_chain ( self ) : def chain2 ( * iterables ) : '' for it in iterables : for element in it : yield element for c in ( chain , chain2 ) : self . assertEqual ( list ( c ( '' , '' ) ) , list ( '' ) ) self . assertEqual ( list ( c ( '' ) ) , list ( '' ) ) self . assertEqual ( list ( c ( '' ) ) , [ ] ) self . assertEqual ( take ( , c ( '' , '' ) ) , list ( '' ) ) self . assertRaises ( TypeError , list , c ( , ) ) def test_chain_from_iterable ( self ) : self . assertEqual ( list ( chain . from_iterable ( [ '' , '' ] ) ) , list ( '' ) ) self . assertEqual ( list ( chain . from_iterable ( [ '' ] ) ) , list ( '' ) ) self . assertEqual ( list ( chain . from_iterable ( [ '' ] ) ) , [ ] ) self . assertEqual ( take ( , chain . from_iterable ( [ '' , '' ] ) ) , list ( '' ) ) self . assertRaises ( TypeError , list , chain . from_iterable ( [ , ] ) ) def test_chain_reducible ( self ) : operators = [ copy . deepcopy , lambda s : pickle . loads ( pickle . dumps ( s ) ) ] for oper in operators : it = chain ( '' , '' ) self . assertEqual ( list ( oper ( it ) ) , list ( '' ) ) self . assertEqual ( next ( it ) , '' ) self . assertEqual ( list ( oper ( it ) ) , list ( '' ) ) self . assertEqual ( list ( oper ( chain ( '' ) ) ) , [ ] ) self . assertEqual ( take ( , oper ( chain ( '' , '' ) ) ) , list ( '' ) ) self . assertRaises ( TypeError , list , oper ( chain ( , ) ) ) self . pickletest ( chain ( '' , '' ) , compare = list ( '' ) ) def test_combinations ( self ) : self . assertRaises ( TypeError , combinations , '' ) self . assertRaises ( TypeError , combinations , '' , , ) self . assertRaises ( TypeError , combinations , None ) self . assertRaises ( ValueError , combinations , '' , - ) for op in ( lambda a : a , lambda a : pickle . loads ( pickle . dumps ( a ) ) ) : self . assertEqual ( list ( op ( combinations ( '' , ) ) ) , [ ] ) self . assertEqual ( list ( op ( combinations ( '' , ) ) ) , [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] ) testIntermediate = combinations ( '' , ) next ( testIntermediate ) self . assertEqual ( list ( op ( testIntermediate ) ) , [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] ) self . assertEqual ( list ( op ( combinations ( range ( ) , ) ) ) , [ ( , , ) , ( , , ) , ( , , ) , ( , , ) ] ) testIntermediate = combinations ( range ( ) , ) next ( testIntermediate ) self . assertEqual ( list ( op ( testIntermediate ) ) , [ ( , , ) , ( , , ) , ( , , ) ] ) def combinations1 ( iterable , r ) : '' pool = tuple ( iterable ) n = len ( pool ) if r > n : return indices = list ( range ( r ) ) yield tuple ( pool [ i ] for i in indices ) while : for i in reversed ( range ( r ) ) : if indices [ i ] != i + n - r : break else : return indices [ i ] += for j in range ( i + , r ) : indices [ j ] = indices [ j - ] + yield tuple ( pool [ i ] for i in indices ) def combinations2 ( iterable , r ) : '' pool = tuple ( iterable ) n = len ( pool ) for indices in permutations ( range ( n ) , r ) : if sorted ( indices ) == list ( indices ) : yield tuple ( pool [ i ] for i in indices ) def combinations3 ( iterable , r ) : '' pool = tuple ( iterable ) n = len ( pool ) for indices in combinations_with_replacement ( range ( n ) , r ) : if len ( set ( indices ) ) == r : yield tuple ( pool [ i ] for i in indices ) for n in range ( ) : values = [ * x - for x in range ( n ) ] for r in range ( n + ) : result = list ( combinations ( values , r ) ) self . assertEqual ( len ( result ) , if r > n else fact ( n ) / fact ( r ) / fact ( n - r ) ) self . assertEqual ( len ( result ) , len ( set ( result ) ) ) self . assertEqual ( result , sorted ( result ) ) for c in result : self . assertEqual ( len ( c ) , r ) self . assertEqual ( len ( set ( c ) ) , r ) self . assertEqual ( list ( c ) , sorted ( c ) ) self . assertTrue ( all ( e in values for e in c ) ) self . assertEqual ( list ( c ) , [ e for e in values if e in c ] ) self . assertEqual ( result , list ( combinations1 ( values , r ) ) ) self . assertEqual ( result , list ( combinations2 ( values , r ) ) ) self . assertEqual ( result , list ( combinations3 ( values , r ) ) ) self . pickletest ( combinations ( values , r ) ) @ support . impl_detail ( \"\" ) def test_combinations_tuple_reuse ( self ) : self . assertEqual ( len ( set ( map ( id , combinations ( '' , ) ) ) ) , ) self . assertNotEqual ( len ( set ( map ( id , list ( combinations ( '' , ) ) ) ) ) , ) def test_combinations_with_replacement ( self ) : cwr = combinations_with_replacement self . assertRaises ( TypeError , cwr , '' ) self . assertRaises ( TypeError , cwr , '' , , ) self . assertRaises ( TypeError , cwr , None ) self . assertRaises ( ValueError , cwr , '' , - ) for op in ( lambda a : a , lambda a : pickle . loads ( pickle . dumps ( a ) ) ) : self . assertEqual ( list ( op ( cwr ( '' , ) ) ) , [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] ) testIntermediate = cwr ( '' , ) next ( testIntermediate ) self . assertEqual ( list ( op ( testIntermediate ) ) , [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] ) def cwr1 ( iterable , r ) : '' pool = tuple ( iterable ) n = len ( pool ) if not n and r : return indices = [ ] * r yield tuple ( pool [ i ] for i in indices ) while : for i in reversed ( range ( r ) ) : if indices [ i ] != n - : break else : return indices [ i : ] = [ indices [ i ] + ] * ( r - i ) yield tuple ( pool [ i ] for i in indices ) def cwr2 ( iterable , r ) : '' pool = tuple ( iterable ) n = len ( pool ) for indices in product ( range ( n ) , repeat = r ) : if sorted ( indices ) == list ( indices ) : yield tuple ( pool [ i ] for i in indices ) def numcombs ( n , r ) : if not n : return if r else return fact ( n + r - ) / fact ( r ) / fact ( n - ) for n in range ( ) : values = [ * x - for x in range ( n ) ] for r in range ( n + ) : result = list ( cwr ( values , r ) ) self . assertEqual ( len ( result ) , numcombs ( n , r ) ) self . assertEqual ( len ( result ) , len ( set ( result ) ) ) self . assertEqual ( result , sorted ( result ) ) regular_combs = list ( combinations ( values , r ) ) if n == or r <= : self . assertEqual ( result , regular_combs ) else : self . assertTrue ( set ( result ) >= set ( regular_combs ) ) for c in result : self . assertEqual ( len ( c ) , r ) noruns = [ k for k , v in groupby ( c ) ] self . assertEqual ( len ( noruns ) , len ( set ( noruns ) ) ) self . assertEqual ( list ( c ) , sorted ( c ) ) self . assertTrue ( all ( e in values for e in c ) ) self . assertEqual ( noruns , [ e for e in values if e in c ] ) self . assertEqual ( result , list ( cwr1 ( values , r ) ) ) self . assertEqual ( result , list ( cwr2 ( values , r ) ) ) self . pickletest ( cwr ( values , r ) ) @ support . impl_detail ( \"\" ) def test_combinations_with_replacement_tuple_reuse ( self ) : cwr = combinations_with_replacement self . assertEqual ( len ( set ( map ( id , cwr ( '' , ) ) ) ) , ) self . assertNotEqual ( len ( set ( map ( id , list ( cwr ( '' , ) ) ) ) ) , ) def test_permutations ( self ) : self . assertRaises ( TypeError , permutations ) self . assertRaises ( TypeError , permutations , '' , , ) self . assertRaises ( TypeError , permutations , None ) self . assertRaises ( ValueError , permutations , '' , - ) self . assertEqual ( list ( permutations ( '' , ) ) , [ ] ) self . assertRaises ( TypeError , permutations , '' , '' ) self . assertEqual ( list ( permutations ( range ( ) , ) ) , [ ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ] ) def permutations1 ( iterable , r = None ) : '' pool = tuple ( iterable ) n = len ( pool ) r = n if r is None else r if r > n : return indices = list ( range ( n ) ) cycles = list ( range ( n - r + , n + ) ) [ : : - ] yield tuple ( pool [ i ] for i in indices [ : r ] ) while n : for i in reversed ( range ( r ) ) : cycles [ i ] -= if cycles [ i ] == : indices [ i : ] = indices [ i + : ] + indices [ i : i + ] cycles [ i ] = n - i else : j = cycles [ i ] indices [ i ] , indices [ - j ] = indices [ - j ] , indices [ i ] yield tuple ( pool [ i ] for i in indices [ : r ] ) break else : return def permutations2 ( iterable , r = None ) : '' pool = tuple ( iterable ) n = len ( pool ) r = n if r is None else r for indices in product ( range ( n ) , repeat = r ) : if len ( set ( indices ) ) == r : yield tuple ( pool [ i ] for i in indices ) for n in range ( ) : values = [ * x - for x in range ( n ) ] for r in range ( n + ) : result = list ( permutations ( values , r ) ) self . assertEqual ( len ( result ) , if r > n else fact ( n ) / fact ( n - r ) ) self . assertEqual ( len ( result ) , len ( set ( result ) ) ) self . assertEqual ( result , sorted ( result ) ) for p in result : self . assertEqual ( len ( p ) , r ) self . assertEqual ( len ( set ( p ) ) , r ) self . assertTrue ( all ( e in values for e in p ) ) self . assertEqual ( result , list ( permutations1 ( values , r ) ) ) self . assertEqual ( result , list ( permutations2 ( values , r ) ) ) if r == n : self . assertEqual ( result , list ( permutations ( values , None ) ) ) self . assertEqual ( result , list ( permutations ( values ) ) ) self . pickletest ( permutations ( values , r ) ) @ support . impl_detail ( \"\" ) def test_permutations_tuple_reuse ( self ) : self . assertEqual ( len ( set ( map ( id , permutations ( '' , ) ) ) ) , ) self . assertNotEqual ( len ( set ( map ( id , list ( permutations ( '' , ) ) ) ) ) , ) def test_combinatorics ( self ) : for n in range ( ) : s = '' [ : n ] for r in range ( ) : prod = list ( product ( s , repeat = r ) ) cwr = list ( combinations_with_replacement ( s , r ) ) perm = list ( permutations ( s , r ) ) comb = list ( combinations ( s , r ) ) self . assertEqual ( len ( prod ) , n ** r ) self . assertEqual ( len ( cwr ) , ( fact ( n + r - ) / fact ( r ) / fact ( n - ) ) if n else ( not r ) ) self . assertEqual ( len ( perm ) , if r > n else fact ( n ) / fact ( n - r ) ) self . assertEqual ( len ( comb ) , if r > n else fact ( n ) / fact ( r ) / fact ( n - r ) ) self . assertEqual ( prod , sorted ( set ( prod ) ) ) self . assertEqual ( cwr , sorted ( set ( cwr ) ) ) self . assertEqual ( perm , sorted ( set ( perm ) ) ) self . assertEqual ( comb , sorted ( set ( comb ) ) ) self . assertEqual ( cwr , [ t for t in prod if sorted ( t ) == list ( t ) ] ) self . assertEqual ( perm , [ t for t in prod if len ( set ( t ) ) == r ] ) self . assertEqual ( comb , [ t for t in perm if sorted ( t ) == list ( t ) ] ) self . assertEqual ( comb , [ t for t in cwr if len ( set ( t ) ) == r ] ) self . assertEqual ( comb , list ( filter ( set ( cwr ) . __contains__ , perm ) ) ) self . assertEqual ( comb , list ( filter ( set ( perm ) . __contains__ , cwr ) ) ) self . assertEqual ( comb , sorted ( set ( cwr ) & set ( perm ) ) ) def test_compress ( self ) : self . assertEqual ( list ( compress ( data = '' , selectors = [ , , , , , ] ) ) , list ( '' ) ) self . assertEqual ( list ( compress ( '' , [ , , , , , ] ) ) , list ( '' ) ) self . assertEqual ( list ( compress ( '' , [ , , , , , ] ) ) , list ( '' ) ) self . assertEqual ( list ( compress ( '' , [ , , , , , ] ) ) , list ( '' ) ) self . assertEqual ( list ( compress ( '' , [ , , ] ) ) , list ( '' ) ) self . assertEqual ( list ( compress ( '' , [ , , , , , ] ) ) , list ( '' ) ) n = data = chain . from_iterable ( repeat ( range ( ) , n ) ) selectors = chain . from_iterable ( repeat ( ( , ) ) ) self . assertEqual ( list ( compress ( data , selectors ) ) , [ , , ] * n ) self . assertRaises ( TypeError , compress , None , range ( ) ) self . assertRaises ( TypeError , compress , range ( ) , None ) self . assertRaises ( TypeError , compress , range ( ) ) self . assertRaises ( TypeError , compress , range ( ) , None ) for op in ( lambda a : copy . copy ( a ) , lambda a : copy . deepcopy ( a ) , lambda a : pickle . loads ( pickle . dumps ( a ) ) ) : for data , selectors , result1 , result2 in [ ( '' , [ , , , , , ] , '' , '' ) , ( '' , [ , , , , , ] , '' , '' ) , ( '' , [ , , , , , ] , '' , '' ) , ( '' , [ , , ] , '' , '' ) , ( '' , [ , , , , , ] , '' , '' ) , ] : self . assertEqual ( list ( op ( compress ( data = data , selectors = selectors ) ) ) , list ( result1 ) ) self . assertEqual ( list ( op ( compress ( data , selectors ) ) ) , list ( result1 ) ) testIntermediate = compress ( data , selectors ) if result1 : next ( testIntermediate ) self . assertEqual ( list ( op ( testIntermediate ) ) , list ( result2 ) ) def test_count ( self ) : self . assertEqual ( lzip ( '' , count ( ) ) , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( lzip ( '' , count ( ) ) , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( take ( , lzip ( '' , count ( ) ) ) , [ ( '' , ) , ( '' , ) ] ) self . assertEqual ( take ( , zip ( '' , count ( - ) ) ) , [ ( '' , - ) , ( '' , ) ] ) self . assertEqual ( take ( , zip ( '' , count ( - ) ) ) , [ ( '' , - ) , ( '' , - ) ] ) self . assertRaises ( TypeError , count , , , ) self . assertRaises ( TypeError , count , '' ) self . assertEqual ( list ( islice ( count ( maxsize - ) , ) ) , list ( range ( maxsize - , maxsize + ) ) ) self . assertEqual ( list ( islice ( count ( - maxsize - ) , ) ) , list ( range ( - maxsize - , - maxsize + ) ) ) self . assertEqual ( list ( islice ( count ( , maxsize + ) , ) ) , list ( range ( , + * ( maxsize + ) , maxsize + ) ) ) c = count ( ) self . assertEqual ( repr ( c ) , '' ) next ( c ) self . assertEqual ( repr ( c ) , '' ) c = count ( - ) self . assertEqual ( repr ( c ) , '' ) next ( c ) self . assertEqual ( repr ( count ( ) ) , '' ) self . assertEqual ( next ( c ) , - ) for i in ( - sys . maxsize - , - sys . maxsize + , - , - , , , sys . maxsize - , sys . maxsize + ) : r1 = repr ( count ( i ) ) r2 = '' . __mod__ ( i ) self . assertEqual ( r1 , r2 ) for value in - , , maxsize - , maxsize + : c = count ( value ) self . assertEqual ( next ( copy . copy ( c ) ) , value ) self . assertEqual ( next ( copy . deepcopy ( c ) ) , value ) self . pickletest ( count ( value ) ) count ( , maxsize + ) ; sys . exc_info ( ) def test_count_with_stride ( self ) : self . assertEqual ( lzip ( '' , count ( , ) ) , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( lzip ( '' , count ( start = , step = ) ) , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( lzip ( '' , count ( step = - ) ) , [ ( '' , ) , ( '' , - ) , ( '' , - ) ] ) self . assertEqual ( lzip ( '' , count ( , ) ) , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( lzip ( '' , count ( , ) ) , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( lzip ( '' , count ( , ) ) , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( take ( , count ( maxsize - , ) ) , take ( , range ( maxsize - , maxsize + , ) ) ) self . assertEqual ( take ( , count ( - maxsize - , ) ) , take ( , range ( - maxsize - , - maxsize + , ) ) ) self . assertEqual ( take ( , count ( , - ) ) , [ , - , - ] ) self . assertEqual ( take ( , count ( Decimal ( '' ) , Decimal ( '' ) ) ) , [ Decimal ( '' ) , Decimal ( '' ) , Decimal ( '' ) ] ) self . assertEqual ( take ( , count ( Fraction ( , ) , Fraction ( , ) ) ) , [ Fraction ( , ) , Fraction ( , ) , Fraction ( , ) ] ) self . assertEqual ( repr ( take ( , count ( , ) ) ) , repr ( [ , , ] ) ) c = count ( , ) self . assertEqual ( repr ( c ) , '' ) next ( c ) self . assertEqual ( repr ( c ) , '' ) c = count ( - , ) self . assertEqual ( repr ( c ) , '' ) next ( c ) self . assertEqual ( repr ( c ) , '' ) c = count ( - , - ) self . assertEqual ( repr ( c ) , '' ) next ( c ) self . assertEqual ( repr ( c ) , '' ) self . assertEqual ( repr ( c ) , '' ) self . assertEqual ( repr ( count ( , ) ) , '' ) self . assertEqual ( repr ( count ( , ) ) , '' ) self . assertEqual ( repr ( count ( , ) ) , '' ) for i in ( - sys . maxsize - , - sys . maxsize + , - , - , , , sys . maxsize - , sys . maxsize + ) : for j in ( - sys . maxsize - , - sys . maxsize + , - , - , , , , sys . maxsize - , sys . maxsize + ) : r1 = repr ( count ( i , j ) ) if j == : r2 = ( '' % i ) else : r2 = ( '' % ( i , j ) ) self . assertEqual ( r1 , r2 ) self . pickletest ( count ( i , j ) ) def test_cycle ( self ) : self . assertEqual ( take ( , cycle ( '' ) ) , list ( '' ) ) self . assertEqual ( list ( cycle ( '' ) ) , [ ] ) self . assertRaises ( TypeError , cycle ) self . assertRaises ( TypeError , cycle , ) self . assertEqual ( list ( islice ( cycle ( gen3 ( ) ) , ) ) , [ , , , , , , , , , ] ) c = cycle ( '' ) self . assertEqual ( next ( c ) , '' ) self . assertEqual ( take ( , copy . deepcopy ( c ) ) , list ( '' ) ) self . assertEqual ( take ( , pickle . loads ( pickle . dumps ( c ) ) ) , list ( '' ) ) next ( c ) self . assertEqual ( take ( , pickle . loads ( pickle . dumps ( c ) ) ) , list ( '' ) ) self . pickletest ( cycle ( '' ) ) def test_groupby ( self ) : self . assertEqual ( [ ] , list ( groupby ( [ ] ) ) ) self . assertEqual ( [ ] , list ( groupby ( [ ] , key = id ) ) ) self . assertRaises ( TypeError , list , groupby ( '' , [ ] ) ) self . assertRaises ( TypeError , groupby , None ) self . assertRaises ( TypeError , groupby , '' , lambda x : x , ) s = [ ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) ] dup = [ ] for k , g in groupby ( s , lambda r : r [ ] ) : for elem in g : self . assertEqual ( k , elem [ ] ) dup . append ( elem ) self . assertEqual ( s , dup ) dup = [ ] for k , g in pickle . loads ( pickle . dumps ( groupby ( s , testR ) ) ) : for elem in g : self . assertEqual ( k , elem [ ] ) dup . append ( elem ) self . assertEqual ( s , dup ) dup = [ ] for k , g in groupby ( s , testR ) : for ik , ig in groupby ( g , testR2 ) : for elem in ig : self . assertEqual ( k , elem [ ] ) self . assertEqual ( ik , elem [ ] ) dup . append ( elem ) self . assertEqual ( s , dup ) dup = [ ] for k , g in pickle . loads ( pickle . dumps ( groupby ( s , testR ) ) ) : for ik , ig in pickle . loads ( pickle . dumps ( groupby ( g , testR2 ) ) ) : for elem in ig : self . assertEqual ( k , elem [ ] ) self . assertEqual ( ik , elem [ ] ) dup . append ( elem ) self . assertEqual ( s , dup ) keys = [ k for k , g in groupby ( s , testR ) ] expectedkeys = set ( [ r [ ] for r in s ] ) self . assertEqual ( set ( keys ) , expectedkeys ) self . assertEqual ( len ( keys ) , len ( expectedkeys ) ) s = '' r = [ k for k , g in groupby ( sorted ( s ) ) ] self . assertEqual ( r , [ '' , '' , '' , '' , '' ] ) r = [ k for k , g in groupby ( sorted ( s ) ) if list ( islice ( g , , ) ) ] self . assertEqual ( r , [ '' , '' , '' ] ) r = [ ( len ( list ( g ) ) , k ) for k , g in groupby ( sorted ( s ) ) ] self . assertEqual ( r , [ ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) ] ) r = sorted ( [ ( len ( list ( g ) ) , k ) for k , g in groupby ( sorted ( s ) ) ] , reverse = True ) [ : ] self . assertEqual ( r , [ ( , '' ) , ( , '' ) , ( , '' ) ] ) class ExpectedError ( Exception ) : pass def delayed_raise ( n = ) : for i in range ( n ) : yield '' raise ExpectedError def gulp ( iterable , keyp = None , func = list ) : return [ func ( g ) for k , g in groupby ( iterable , keyp ) ] self . assertRaises ( ExpectedError , gulp , delayed_raise ( ) ) self . assertRaises ( ExpectedError , gulp , delayed_raise ( ) ) class DummyCmp : def __eq__ ( self , dst ) : raise ExpectedError s = [ DummyCmp ( ) , DummyCmp ( ) , None ] self . assertRaises ( ExpectedError , gulp , s , func = id ) self . assertRaises ( ExpectedError , gulp , s ) def keyfunc ( obj ) : if keyfunc . skip > : keyfunc . skip -= return obj else : raise ExpectedError keyfunc . skip = self . assertRaises ( ExpectedError , gulp , [ None ] , keyfunc ) keyfunc . skip = self . assertRaises ( ExpectedError , gulp , [ None , None ] , keyfunc ) def test_filter ( self ) : self . assertEqual ( list ( filter ( isEven , range ( ) ) ) , [ , , ] ) self . assertEqual ( list ( filter ( None , [ , , , , ] ) ) , [ , ] ) self . assertEqual ( list ( filter ( bool , [ , , , , ] ) ) , [ , ] ) self . assertEqual ( take ( , filter ( isEven , count ( ) ) ) , [ , , , ] ) self . assertRaises ( TypeError , filter ) self . assertRaises ( TypeError , filter , lambda x : x ) self . assertRaises ( TypeError , filter , lambda x : x , range ( ) , ) self . assertRaises ( TypeError , filter , isEven , ) self . assertRaises ( TypeError , next , filter ( range ( ) , range ( ) ) ) ans = [ , , ] c = filter ( isEven , range ( ) ) self . assertEqual ( list ( copy . copy ( c ) ) , ans ) c = filter ( isEven , range ( ) ) self . assertEqual ( list ( copy . deepcopy ( c ) ) , ans ) c = filter ( isEven , range ( ) ) self . assertEqual ( list ( pickle . loads ( pickle . dumps ( c ) ) ) , ans ) next ( c ) self . assertEqual ( list ( pickle . loads ( pickle . dumps ( c ) ) ) , ans [ : ] ) c = filter ( isEven , range ( ) ) self . pickletest ( c ) def test_filterfalse ( self ) : self . assertEqual ( list ( filterfalse ( isEven , range ( ) ) ) , [ , , ] ) self . assertEqual ( list ( filterfalse ( None , [ , , , , ] ) ) , [ , , ] ) self . assertEqual ( list ( filterfalse ( bool , [ , , , , ] ) ) , [ , , ] ) self . assertEqual ( take ( , filterfalse ( isEven , count ( ) ) ) , [ , , , ] ) self . assertRaises ( TypeError , filterfalse ) self . assertRaises ( TypeError , filterfalse , lambda x : x ) self . assertRaises ( TypeError , filterfalse , lambda x : x , range ( ) , ) self . assertRaises ( TypeError , filterfalse , isEven , ) self . assertRaises ( TypeError , next , filterfalse ( range ( ) , range ( ) ) ) self . pickletest ( filterfalse ( isEven , range ( ) ) ) def test_zip ( self ) : ans = [ ( x , y ) for x , y in zip ( '' , count ( ) ) ] self . assertEqual ( ans , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( list ( zip ( '' , range ( ) ) ) , lzip ( '' , range ( ) ) ) self . assertEqual ( list ( zip ( '' , range ( ) ) ) , lzip ( '' , range ( ) ) ) self . assertEqual ( take ( , zip ( '' , count ( ) ) ) , lzip ( '' , range ( ) ) ) self . assertEqual ( list ( zip ( '' ) ) , lzip ( '' ) ) self . assertEqual ( list ( zip ( ) ) , lzip ( ) ) self . assertRaises ( TypeError , zip , ) self . assertRaises ( TypeError , zip , range ( ) , ) self . assertEqual ( [ tuple ( list ( pair ) ) for pair in zip ( '' , '' ) ] , lzip ( '' , '' ) ) self . assertEqual ( [ pair for pair in zip ( '' , '' ) ] , lzip ( '' , '' ) ) @ support . impl_detail ( \"\" ) def test_zip_tuple_reuse ( self ) : ids = list ( map ( id , zip ( '' , '' ) ) ) self . assertEqual ( min ( ids ) , max ( ids ) ) ids = list ( map ( id , list ( zip ( '' , '' ) ) ) ) self . assertEqual ( len ( dict . fromkeys ( ids ) ) , len ( ids ) ) ans = [ ( x , y ) for x , y in copy . copy ( zip ( '' , count ( ) ) ) ] self . assertEqual ( ans , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) ans = [ ( x , y ) for x , y in copy . deepcopy ( zip ( '' , count ( ) ) ) ] self . assertEqual ( ans , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) ans = [ ( x , y ) for x , y in pickle . loads ( pickle . dumps ( zip ( '' , count ( ) ) ) ) ] self . assertEqual ( ans , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) testIntermediate = zip ( '' , count ( ) ) next ( testIntermediate ) ans = [ ( x , y ) for x , y in pickle . loads ( pickle . dumps ( testIntermediate ) ) ] self . assertEqual ( ans , [ ( '' , ) , ( '' , ) ] ) self . pickletest ( zip ( '' , count ( ) ) ) def test_ziplongest ( self ) : for args in [ [ '' , range ( ) ] , [ range ( ) , '' ] , [ range ( ) , range ( , ) , range ( , ) ] , [ range ( ) , range ( ) , range ( , ) , range ( ) , range ( ) ] , [ range ( ) , range ( ) , range ( , ) , range ( ) , range ( ) , range ( ) ] , ] : target = [ tuple ( [ arg [ i ] if i < len ( arg ) else None for arg in args ] ) for i in range ( max ( map ( len , args ) ) ) ] self . assertEqual ( list ( zip_longest ( * args ) ) , target ) self . assertEqual ( list ( zip_longest ( * args , ** { } ) ) , target ) target = [ tuple ( ( e is None and '' or e ) for e in t ) for t in target ] self . assertEqual ( list ( zip_longest ( * args , ** dict ( fillvalue = '' ) ) ) , target ) self . assertEqual ( take ( , zip_longest ( '' , count ( ) ) ) , list ( zip ( '' , range ( ) ) ) ) self . assertEqual ( list ( zip_longest ( ) ) , list ( zip ( ) ) ) self . assertEqual ( list ( zip_longest ( [ ] ) ) , list ( zip ( [ ] ) ) ) self . assertEqual ( list ( zip_longest ( '' ) ) , list ( zip ( '' ) ) ) self . assertEqual ( list ( zip_longest ( '' , '' , ** { } ) ) , list ( zip ( list ( '' ) + [ None ] , '' ) ) ) self . assertRaises ( TypeError , zip_longest , ) self . assertRaises ( TypeError , zip_longest , range ( ) , ) for stmt in [ \"\" , \"\" , ] : try : eval ( stmt , globals ( ) , locals ( ) ) except TypeError : pass else : self . fail ( '' + stmt ) self . assertEqual ( [ tuple ( list ( pair ) ) for pair in zip_longest ( '' , '' ) ] , list ( zip ( '' , '' ) ) ) self . assertEqual ( [ pair for pair in zip_longest ( '' , '' ) ] , list ( zip ( '' , '' ) ) ) @ support . impl_detail ( \"\" ) def test_zip_longest_tuple_reuse ( self ) : ids = list ( map ( id , zip_longest ( '' , '' ) ) ) self . assertEqual ( min ( ids ) , max ( ids ) ) ids = list ( map ( id , list ( zip_longest ( '' , '' ) ) ) ) self . assertEqual ( len ( dict . fromkeys ( ids ) ) , len ( ids ) ) def test_zip_longest_pickling ( self ) : self . pickletest ( zip_longest ( \"\" , \"\" ) ) self . pickletest ( zip_longest ( \"\" , \"\" ) ) self . pickletest ( zip_longest ( \"\" , \"\" , fillvalue = ) ) self . pickletest ( zip_longest ( \"\" , \"\" ) ) def test_bug_7244 ( self ) : class Repeater : def __init__ ( self , o , t , e ) : self . o = o self . t = int ( t ) self . e = e def __iter__ ( self ) : return self def __next__ ( self ) : if self . t > : self . t -= return self . o else : raise self . e r1 = Repeater ( , , StopIteration ) r2 = Repeater ( , , StopIteration ) def run ( r1 , r2 ) : result = [ ] for i , j in zip_longest ( r1 , r2 , fillvalue = ) : with support . captured_output ( '' ) : print ( ( i , j ) ) result . append ( ( i , j ) ) return result self . assertEqual ( run ( r1 , r2 ) , [ ( , ) , ( , ) , ( , ) , ( , ) ] ) r1 = Repeater ( , , RuntimeError ) r2 = Repeater ( , , StopIteration ) it = zip_longest ( r1 , r2 , fillvalue = ) self . assertEqual ( next ( it ) , ( , ) ) self . assertEqual ( next ( it ) , ( , ) ) self . assertEqual ( next ( it ) , ( , ) ) self . assertRaises ( RuntimeError , next , it ) def test_product ( self ) : for args , result in [ ( [ ] , [ ( ) ] ) , ( [ '' ] , [ ( '' , ) , ( '' , ) ] ) , ( [ range ( ) , range ( ) ] , [ ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ] ) , ( [ range ( ) , range ( ) , range ( ) ] , [ ] ) , ( [ range ( ) , range ( ) , range ( ) ] , [ ] ) , ( [ range ( ) , range ( ) , range ( ) ] , [ ] ) , ] : self . assertEqual ( list ( product ( * args ) ) , result ) for r in range ( ) : self . assertEqual ( list ( product ( * ( args * r ) ) ) , list ( product ( * args , ** dict ( repeat = r ) ) ) ) self . assertEqual ( len ( list ( product ( * [ range ( ) ] * ) ) ) , ** ) self . assertRaises ( TypeError , product , range ( ) , None ) def product1 ( * args , ** kwds ) : pools = list ( map ( tuple , args ) ) * kwds . get ( '' , ) n = len ( pools ) if n == : yield ( ) return if any ( len ( pool ) == for pool in pools ) : return indices = [ ] * n yield tuple ( pool [ i ] for pool , i in zip ( pools , indices ) ) while : for i in reversed ( range ( n ) ) : if indices [ i ] == len ( pools [ i ] ) - : continue indices [ i ] += for j in range ( i + , n ) : indices [ j ] = yield tuple ( pool [ i ] for pool , i in zip ( pools , indices ) ) break else : return def product2 ( * args , ** kwds ) : '' pools = list ( map ( tuple , args ) ) * kwds . get ( '' , ) result = [ [ ] ] for pool in pools : result = [ x + [ y ] for x in result for y in pool ] for prod in result : yield tuple ( prod ) argtypes = [ '' , '' , '' , range ( ) , range ( ) , dict ( a = , b = , c = ) , set ( '' ) , range ( ) , tuple ( range ( ) ) ] for i in range ( ) : args = [ random . choice ( argtypes ) for j in range ( random . randrange ( ) ) ] expected_len = prod ( map ( len , args ) ) self . assertEqual ( len ( list ( product ( * args ) ) ) , expected_len ) self . assertEqual ( list ( product ( * args ) ) , list ( product1 ( * args ) ) ) self . assertEqual ( list ( product ( * args ) ) , list ( product2 ( * args ) ) ) args = map ( iter , args ) self . assertEqual ( len ( list ( product ( * args ) ) ) , expected_len ) @ support . impl_detail ( \"\" ) def test_product_tuple_reuse ( self ) : self . assertEqual ( len ( set ( map ( id , product ( '' , '' ) ) ) ) , ) self . assertNotEqual ( len ( set ( map ( id , list ( product ( '' , '' ) ) ) ) ) , ) def test_product_pickling ( self ) : for args , result in [ ( [ ] , [ ( ) ] ) , ( [ '' ] , [ ( '' , ) , ( '' , ) ] ) , ( [ range ( ) , range ( ) ] , [ ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ] ) , ( [ range ( ) , range ( ) , range ( ) ] , [ ] ) , ( [ range ( ) , range ( ) , range ( ) ] , [ ] ) , ( [ range ( ) , range ( ) , range ( ) ] , [ ] ) , ] : self . assertEqual ( list ( copy . copy ( product ( * args ) ) ) , result ) self . assertEqual ( list ( copy . deepcopy ( product ( * args ) ) ) , result ) self . pickletest ( product ( * args ) ) def test_repeat ( self ) : self . assertEqual ( list ( repeat ( object = '' , times = ) ) , [ '' , '' , '' ] ) self . assertEqual ( lzip ( range ( ) , repeat ( '' ) ) , [ ( , '' ) , ( , '' ) , ( , '' ) ] ) self . assertEqual ( list ( repeat ( '' , ) ) , [ '' , '' , '' ] ) self . assertEqual ( take ( , repeat ( '' ) ) , [ '' , '' , '' ] ) self . assertEqual ( list ( repeat ( '' , ) ) , [ ] ) self . assertEqual ( list ( repeat ( '' , - ) ) , [ ] ) self . assertRaises ( TypeError , repeat ) self . assertRaises ( TypeError , repeat , None , , ) self . assertRaises ( TypeError , repeat , None , '' ) r = repeat ( + ) self . assertEqual ( repr ( r ) , '' ) r = repeat ( + , ) self . assertEqual ( repr ( r ) , '' ) list ( r ) self . assertEqual ( repr ( r ) , '' ) c = repeat ( object = '' , times = ) self . assertEqual ( next ( c ) , '' ) self . assertEqual ( take ( , copy . copy ( c ) ) , list ( '' * ) ) self . assertEqual ( take ( , copy . deepcopy ( c ) ) , list ( '' * ) ) self . pickletest ( repeat ( object = '' , times = ) ) def test_map ( self ) : self . assertEqual ( list ( map ( operator . pow , range ( ) , range ( , ) ) ) , [ ** , ** , ** ] ) self . assertEqual ( list ( map ( tupleize , '' , range ( ) ) ) , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( list ( map ( tupleize , '' , count ( ) ) ) , [ ( '' , ) , ( '' , ) , ( '' , ) ] ) self . assertEqual ( take ( , map ( tupleize , '' , count ( ) ) ) , [ ( '' , ) , ( '' , ) ] ) self . assertEqual ( list ( map ( operator . pow , [ ] ) ) , [ ] ) self . assertRaises ( TypeError , map ) self . assertRaises ( TypeError , list , map ( None , range ( ) , range ( ) ) ) self . assertRaises ( TypeError , map , operator . neg ) self . assertRaises ( TypeError , next , map ( , range ( ) ) ) self . assertRaises ( ValueError , next , map ( errfunc , [ ] , [ ] ) ) self . assertRaises ( TypeError , next , map ( onearg , [ ] , [ ] ) ) ans = [ ( '' , ) , ( '' , ) , ( '' , ) ] c = map ( tupleize , '' , count ( ) ) self . assertEqual ( list ( copy . copy ( c ) ) , ans ) c = map ( tupleize , '' , count ( ) ) self . assertEqual ( list ( copy . deepcopy ( c ) ) , ans ) c = map ( tupleize , '' , count ( ) ) self . pickletest ( c ) def test_starmap ( self ) : self . assertEqual ( list ( starmap ( operator . pow , zip ( range ( ) , range ( , ) ) ) ) , [ ** , ** , ** ] ) self . assertEqual ( take ( , starmap ( operator . pow , zip ( count ( ) , count ( ) ) ) ) , [ ** , ** , ** ] ) self . assertEqual ( list ( starmap ( operator . pow , [ ] ) ) , [ ] ) self . assertEqual ( list ( starmap ( operator . pow , [ iter ( [ , ] ) ] ) ) , [ ** ] ) self . assertRaises ( TypeError , list , starmap ( operator . pow , [ None ] ) ) self . assertRaises ( TypeError , starmap ) self . assertRaises ( TypeError , starmap , operator . pow , [ ( , ) ] , '' ) self . assertRaises ( TypeError , next , starmap ( , [ ( , ) ] ) ) self . assertRaises ( ValueError , next , starmap ( errfunc , [ ( , ) ] ) ) self . assertRaises ( TypeError , next , starmap ( onearg , [ ( , ) ] ) ) ans = [ ** , ** , ** ] c = starmap ( operator . pow , zip ( range ( ) , range ( , ) ) ) self . assertEqual ( list ( copy . copy ( c ) ) , ans ) c = starmap ( operator . pow , zip ( range ( ) , range ( , ) ) ) self . assertEqual ( list ( copy . deepcopy ( c ) ) , ans ) c = starmap ( operator . pow , zip ( range ( ) , range ( , ) ) ) self . pickletest ( c ) def test_islice ( self ) : for args in [ ( , , ) , ( , , ) , ( , ) , ( , ) , ( , ) ] : self . assertEqual ( list ( islice ( range ( ) , * args ) ) , list ( range ( * args ) ) ) for args , tgtargs in [ ( ( , , ) , ( ( , , ) ) ) , ( ( , ) , ( ( , ) ) ) , ( ( , ) , ( , ) ) ] : self . assertEqual ( list ( islice ( range ( ) , * args ) ) , list ( range ( * tgtargs ) ) ) self . assertEqual ( list ( islice ( range ( ) , None ) ) , list ( range ( ) ) ) self . assertEqual ( list ( islice ( range ( ) , None , None ) ) , list ( range ( ) ) ) self . assertEqual ( list ( islice ( range ( ) , None , None , None ) ) , list ( range ( ) ) ) self . assertEqual ( list ( islice ( range ( ) , , None ) ) , list ( range ( , ) ) ) self . assertEqual ( list ( islice ( range ( ) , , None , ) ) , list ( range ( , , ) ) ) it = iter ( range ( ) ) self . assertEqual ( list ( islice ( it , ) ) , list ( range ( ) ) ) self . assertEqual ( list ( it ) , list ( range ( , ) ) ) ra = range ( ) self . assertRaises ( TypeError , islice , ra ) self . assertRaises ( TypeError , islice , ra , , , , ) self . assertRaises ( ValueError , islice , ra , - , , ) self . assertRaises ( ValueError , islice , ra , , - , - ) self . assertRaises ( ValueError , islice , ra , , , - ) self . assertRaises ( ValueError , islice , ra , , , ) self . assertRaises ( ValueError , islice , ra , '' ) self . assertRaises ( ValueError , islice , ra , '' , ) self . assertRaises ( ValueError , islice , ra , , '' ) self . assertRaises ( ValueError , islice , ra , '' , , ) self . assertRaises ( ValueError , islice , ra , , '' , ) self . assertEqual ( len ( list ( islice ( count ( ) , , , maxsize ) ) ) , ) c = count ( ) self . assertEqual ( list ( islice ( c , , , ) ) , [ ] ) self . assertEqual ( next ( c ) , ) for args in [ ( , , ) , ( , , ) , ( , ) , ( , ) , ( , ) ] : self . assertEqual ( list ( copy . copy ( islice ( range ( ) , * args ) ) ) , list ( range ( * args ) ) ) self . assertEqual ( list ( copy . deepcopy ( islice ( range ( ) , * args ) ) ) , list ( range ( * args ) ) ) self . pickletest ( islice ( range ( ) , * args ) ) def test_takewhile ( self ) : data = [ , , , , , , , ] self . assertEqual ( list ( takewhile ( underten , data ) ) , [ , , ] ) self . assertEqual ( list ( takewhile ( underten , [ ] ) ) , [ ] ) self . assertRaises ( TypeError , takewhile ) self . assertRaises ( TypeError , takewhile , operator . pow ) self . assertRaises ( TypeError , takewhile , operator . pow , [ ( , ) ] , '' ) self . assertRaises ( TypeError , next , takewhile ( , [ ( , ) ] ) ) self . assertRaises ( ValueError , next , takewhile ( errfunc , [ ( , ) ] ) ) t = takewhile ( bool , [ , , , , , ] ) self . assertEqual ( list ( t ) , [ , , ] ) self . assertRaises ( StopIteration , next , t ) self . assertEqual ( list ( copy . copy ( takewhile ( underten , data ) ) ) , [ , , ] ) self . assertEqual ( list ( copy . deepcopy ( takewhile ( underten , data ) ) ) , [ , , ] ) self . pickletest ( takewhile ( underten , data ) ) def test_dropwhile ( self ) : data = [ , , , , , , , ] self . assertEqual ( list ( dropwhile ( underten , data ) ) , [ , , , , ] ) self . assertEqual ( list ( dropwhile ( underten , [ ] ) ) , [ ] ) self . assertRaises ( TypeError , dropwhile ) self . assertRaises ( TypeError , dropwhile , operator . pow ) self . assertRaises ( TypeError , dropwhile , operator . pow , [ ( , ) ] , '' ) self . assertRaises ( TypeError , next , dropwhile ( , [ ( , ) ] ) ) self . assertRaises ( ValueError , next , dropwhile ( errfunc , [ ( , ) ] ) ) self . assertEqual ( list ( copy . copy ( dropwhile ( underten , data ) ) ) , [ , , , , ] ) self . assertEqual ( list ( copy . deepcopy ( dropwhile ( underten , data ) ) ) , [ , , , , ] ) self . pickletest ( dropwhile ( underten , data ) ) def test_tee ( self ) : n = a , b = tee ( [ ] ) self . assertEqual ( list ( a ) , [ ] ) self . assertEqual ( list ( b ) , [ ] ) a , b = tee ( irange ( n ) ) self . assertEqual ( lzip ( a , b ) , lzip ( range ( n ) , range ( n ) ) ) a , b = tee ( irange ( n ) ) self . assertEqual ( list ( a ) , list ( range ( n ) ) ) self . assertEqual ( list ( b ) , list ( range ( n ) ) ) a , b = tee ( irange ( n ) ) ", "answer": "for i in range ( ) :"}, {"prompt": " \"\"\"\"\"\" try : import unittest2 as unittest except ImportError : import unittest import mock from pamqp import specification from rabbitpy import PYPY from rabbitpy import amqp_queue from rabbitpy import channel from rabbitpy import exceptions from rabbitpy import utils class QueueInitializationTests ( unittest . TestCase ) : def setUp ( self ) : self . chan = channel . Channel ( , { } , None , None , None , None , , None ) def test_empty_queue_name ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertEqual ( queue . name , '' ) def test_invalid_queue_name ( self ) : self . assertRaises ( ValueError , amqp_queue . Queue , self . chan , None ) def test_auto_delete_default ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertFalse ( queue . auto_delete ) def test_auto_delete_true ( self ) : queue = amqp_queue . Queue ( self . chan , auto_delete = True ) self . assertTrue ( queue . auto_delete ) def test_auto_delete_false ( self ) : queue = amqp_queue . Queue ( self . chan , auto_delete = False ) self . assertFalse ( queue . auto_delete ) def test_auto_delete_validation ( self ) : self . assertRaises ( ValueError , amqp_queue . Queue , self . chan , None , None , None , ) def test_durable_default ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertFalse ( queue . durable ) def test_durable_true ( self ) : queue = amqp_queue . Queue ( self . chan , durable = True ) self . assertTrue ( queue . durable ) def test_durable_false ( self ) : queue = amqp_queue . Queue ( self . chan , durable = False ) self . assertFalse ( queue . durable ) def test_durable_validation ( self ) : self . assertRaises ( ValueError , amqp_queue . Queue , self . chan , None , '' ) def test_exclusive_default ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertFalse ( queue . exclusive ) def test_exclusive_true ( self ) : queue = amqp_queue . Queue ( self . chan , exclusive = True ) self . assertTrue ( queue . exclusive ) def test_exclusive_false ( self ) : queue = amqp_queue . Queue ( self . chan , exclusive = False ) self . assertFalse ( queue . exclusive ) def test_exclusive_validation ( self ) : self . assertRaises ( ValueError , amqp_queue . Queue , self . chan , None , None , '' ) def test_expires_default ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertIsNone ( queue . expires ) def test_expires_named_value ( self ) : queue = amqp_queue . Queue ( self . chan , expires = ) self . assertEqual ( queue . expires , ) self . assertIsInstance ( queue . expires , int ) def test_expires_positional_value ( self ) : queue = amqp_queue . Queue ( self . chan , '' , True , False , True , None , None , ) self . assertEqual ( queue . expires , ) self . assertIsInstance ( queue . expires , int ) def test_expires_validation ( self ) : self . assertRaises ( ValueError , amqp_queue . Queue , self . chan , '' , True , False , True , None , None , '' ) def test_max_length_default ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertIsNone ( queue . max_length ) def test_max_length_named_value ( self ) : queue = amqp_queue . Queue ( self . chan , max_length = ) self . assertEqual ( queue . max_length , ) self . assertIsInstance ( queue . max_length , int ) def test_max_length_positional_value ( self ) : queue = amqp_queue . Queue ( self . chan , '' , True , False , True , ) self . assertEqual ( queue . max_length , ) self . assertIsInstance ( queue . max_length , int ) def test_max_length_validation ( self ) : self . assertRaises ( ValueError , amqp_queue . Queue , self . chan , '' , True , False , True , '' ) def test_message_ttl_default ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertIsNone ( queue . message_ttl ) def test_message_ttl_value ( self ) : queue = amqp_queue . Queue ( self . chan , message_ttl = ) self . assertEqual ( queue . message_ttl , ) self . assertIsInstance ( queue . message_ttl , int ) def test_message_ttl_positional_value ( self ) : queue = amqp_queue . Queue ( self . chan , '' , True , False , True , None , ) self . assertEqual ( queue . message_ttl , ) self . assertIsInstance ( queue . message_ttl , int ) def test_message_ttl_validation ( self ) : self . assertRaises ( ValueError , amqp_queue . Queue , self . chan , '' , True , False , True , None , '' ) def test_dlx_default ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertIsNone ( queue . dead_letter_exchange ) def test_dlx_value ( self ) : queue = amqp_queue . Queue ( self . chan , dead_letter_exchange = '' ) self . assertEqual ( queue . dead_letter_exchange , '' ) def test_dlx_bytes ( self ) : queue = amqp_queue . Queue ( self . chan , dead_letter_exchange = b'' ) self . assertIsInstance ( queue . dead_letter_exchange , bytes ) def test_dlx_str ( self ) : queue = amqp_queue . Queue ( self . chan , dead_letter_exchange = '' ) self . assertIsInstance ( queue . dead_letter_exchange , str ) @ unittest . skipIf ( utils . PYTHON3 , '' ) def test_dlx_unicode ( self ) : queue = amqp_queue . Queue ( self . chan , dead_letter_exchange = unicode ( '' ) ) self . assertIsInstance ( queue . dead_letter_exchange , unicode ) def test_message_dlx_validation ( self ) : self . assertRaises ( ValueError , amqp_queue . Queue , self . chan , '' , True , False , True , None , None , None , True ) def test_dlr_default ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertIsNone ( queue . dead_letter_routing_key ) def test_dlr_value ( self ) : queue = amqp_queue . Queue ( self . chan , dead_letter_routing_key = '' ) self . assertEqual ( queue . dead_letter_routing_key , '' ) def test_dlr_bytes ( self ) : queue = amqp_queue . Queue ( self . chan , dead_letter_routing_key = b'' ) self . assertIsInstance ( queue . dead_letter_routing_key , bytes ) def test_dlr_str ( self ) : queue = amqp_queue . Queue ( self . chan , dead_letter_routing_key = '' ) self . assertIsInstance ( queue . dead_letter_routing_key , str ) @ unittest . skipIf ( utils . PYTHON3 , '' ) def test_dlr_unicode ( self ) : routing_key = unicode ( '' ) queue = amqp_queue . Queue ( self . chan , dead_letter_routing_key = routing_key ) self . assertIsInstance ( queue . dead_letter_routing_key , unicode ) def test_dlr_validation ( self ) : self . assertRaises ( ValueError , amqp_queue . Queue , self . chan , '' , True , False , True , None , None , None , None , True ) @ unittest . skipIf ( PYPY , '' ) def test_stop_consuming_raises_exception ( self ) : queue = amqp_queue . Queue ( self . chan ) self . assertRaises ( exceptions . NotConsumingError , queue . stop_consuming ) class QueueDeclareTests ( unittest . TestCase ) : def setUp ( self ) : self . chan = channel . Channel ( , { } , None , None , None , None , , None ) def test_default_declare ( self ) : obj = amqp_queue . Queue ( self . chan ) expectation = { '' : { } , '' : False , '' : False , '' : False , '' : False , '' : False , '' : '' , '' : } self . assertDictEqual ( dict ( obj . _declare ( False ) ) , expectation ) ", "answer": "def test_default_declare_passive ( self ) :"}, {"prompt": " from django . contrib . auth . models import AbstractBaseUser , PermissionsMixin from django . contrib . auth . models import UserManager from django . contrib . flatpages . models import FlatPage from django . core . urlresolvers import reverse from django . db . models import signals from django . templatetags . static import static from django . utils import timezone from django . db import models from allauth . account . models import EmailAddress from django_countries . fields import CountryField from skills . models import Skill , TrainingBit class CustomUserManager ( UserManager ) : def create_superuser ( self , username , password , ** kwargs ) : user = self . model ( username = username , is_staff = True , is_superuser = True , ** kwargs ) user . set_password ( password ) user . save ( ) return user class User ( AbstractBaseUser , PermissionsMixin ) : USERNAME_FIELD = '' datetime_joined = models . DateTimeField ( default = timezone . now ) username = models . CharField ( max_length = , unique = True , error_messages = { '' : '' } ) email = models . CharField ( max_length = , blank = True ) image = models . ImageField ( upload_to = '' , null = True , blank = True ) description = models . TextField ( blank = True ) skills_in_progress = models . ManyToManyField ( Skill , blank = True , related_name = '' ) skills_completed = models . ManyToManyField ( Skill , blank = True , related_name = '' ) trainingbits_in_progress = models . ManyToManyField ( TrainingBit , blank = True , related_name = '' ) trainingbits_completed = models . ManyToManyField ( TrainingBit , blank = True , related_name = '' ) is_active = models . BooleanField ( default = True ) has_been_welcomed = models . BooleanField ( default = False ) def is_taking_skill ( self , skill ) : return skill in self . skills_in_progress . all ( ) def complete_skill ( self , completed_skill ) : skills = self . complete_skills ( [ complete_skill ] ) return skills [ ] def complete_skills ( self , completed_skills ) : self . skills_in_progress . remove ( * completed_skills ) self . skills_completed . add ( * completed_skills ) return completed_skills def has_completed_skill ( self , skill ) : return skill in self . skills_completed . all ( ) def is_taking_trainingbit ( self , trainingbit ) : return trainingbit in self . trainingbits_in_progress . all ( ) def complete_trainingbit ( self , completed_trainingbit ) : tbs = self . complete_trainingbits ( [ completed_trainingbit ] ) return tbs [ ] def complete_trainingbits ( self , completed_trainingbits ) : self . trainingbits_in_progress . remove ( * completed_trainingbits ) self . trainingbits_completed . add ( * completed_trainingbits ) return completed_trainingbits def has_completed_trainingbit ( self , trainingbit ) : return trainingbit in self . trainingbits_completed . all ( ) def get_full_name ( self ) : return self . email def get_short_name ( self ) : return self . email objects = CustomUserManager ( ) def account_verified ( self ) : if self . user . is_authenticated : result = EmailAddress . objects . get_primary ( self . user ) if len ( result ) : return result [ ] . verified return False @ property def is_trainer ( self ) : if self . is_admin : return True return self . groups . filter ( name = '' ) @ property def is_admin ( self ) : return self . groups . filter ( name = '' ) or self . is_superuser @ property def is_staff ( self ) : \"\" return self . is_admin or self . is_trainer def get_absolute_url ( self ) : return reverse ( '' , args = [ self . id ] ) def getImage ( self ) : if self . image : return self . image . url else : return static ( '' ) class UserInfo ( models . Model ) : SEXES = [ ( '' , '' ) , ( '' , '' ) , ] ORGANISATION_TYPES = [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ] sex = models . CharField ( max_length = , choices = SEXES , blank = False ) country = CountryField ( null = True ) birthdate = models . DateField ( null = True ) organization = models . CharField ( max_length = , choices = ORGANISATION_TYPES , blank = False ) user = models . OneToOneField ( User , null = True , blank = True ) def get_or_create_userinfo ( user ) : \"\"\"\"\"\" userinfo , c = UserInfo . objects . get_or_create ( user = user ) return userinfo User . userinfo = property ( get_or_create_userinfo ) class GCLFlatPage ( FlatPage ) : show_in_footer = models . BooleanField ( default = False ) ", "answer": "class Meta :"}, {"prompt": " \"\"\"\"\"\" from cloudcafe . auth . config import UserAuthConfig as _UserAuthConfig from cloudcafe . common . models . configuration import ConfigSectionInterface class BlockstorageAltUserConfig ( _UserAuthConfig ) : SECTION_NAME = '' class BlockStorageConfig ( ConfigSectionInterface ) : SECTION_NAME = '' @ property def identity_service_name ( self ) : return self . get ( '' ) @ property def region ( self ) : return self . get ( '' ) @ property def availability_zone ( self ) : return self . get ( '' ) @ property def service_endpoint_override ( self ) : ", "answer": "return self . get ( '' ) "}, {"prompt": " from ga import send_request_to_google_analytics , get_random_number , get_visitor_id , get_ip , VERSION , COOKIE_NAME , COOKIE_PATH , COOKIE_USER_PERSISTENCE , GIF_DATA import httplib2 ", "answer": "import time"}, {"prompt": " class ObjectDict ( dict ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import base64 import binascii import os from Crypto . PublicKey import RSA from cryptography import exceptions from cryptography . hazmat import backends from cryptography . hazmat . primitives . asymmetric import padding from cryptography . hazmat . primitives import hashes from cryptography . hazmat . primitives import serialization from cryptography import x509 from oslo_concurrency import processutils from oslo_log import log as logging from oslo_utils import excutils from oslo_utils import fileutils import paramiko import six import nova . conf from nova import context from nova import db from nova import exception from nova . i18n import _ , _LE from nova import utils LOG = logging . getLogger ( __name__ ) CONF = nova . conf . CONF def ca_folder ( project_id = None ) : if CONF . crypto . use_project_ca and project_id : return os . path . join ( CONF . crypto . ca_path , '' , project_id ) return CONF . crypto . ca_path def ca_path ( project_id = None ) : return os . path . join ( ca_folder ( project_id ) , CONF . crypto . ca_file ) def key_path ( project_id = None ) : return os . path . join ( ca_folder ( project_id ) , CONF . crypto . key_file ) def crl_path ( project_id = None ) : return os . path . join ( ca_folder ( project_id ) , CONF . crypto . crl_file ) def fetch_ca ( project_id = None ) : if not CONF . crypto . use_project_ca : project_id = None ca_file_path = ca_path ( project_id ) if not os . path . exists ( ca_file_path ) : raise exception . CryptoCAFileNotFound ( project = project_id ) with open ( ca_file_path , '' ) as cafile : return cafile . read ( ) def ensure_ca_filesystem ( ) : \"\"\"\"\"\" ca_dir = ca_folder ( ) if not os . path . exists ( ca_path ( ) ) : genrootca_sh_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '' , '' ) ) fileutils . ensure_tree ( ca_dir ) utils . execute ( \"\" , genrootca_sh_path , cwd = ca_dir ) def generate_fingerprint ( public_key ) : try : pub_bytes = public_key . encode ( '' ) serialization . load_ssh_public_key ( pub_bytes , backends . default_backend ( ) ) pub_data = base64 . b64decode ( public_key . split ( '' ) [ ] ) digest = hashes . Hash ( hashes . MD5 ( ) , backends . default_backend ( ) ) digest . update ( pub_data ) md5hash = digest . finalize ( ) raw_fp = binascii . hexlify ( md5hash ) if six . PY3 : raw_fp = raw_fp . decode ( '' ) return '' . join ( a + b for a , b in zip ( raw_fp [ : : ] , raw_fp [ : : ] ) ) except Exception : raise exception . InvalidKeypair ( reason = _ ( '' ) ) def generate_x509_fingerprint ( pem_key ) : try : if isinstance ( pem_key , six . text_type ) : pem_key = pem_key . encode ( '' ) cert = x509 . load_pem_x509_certificate ( pem_key , backends . default_backend ( ) ) raw_fp = binascii . hexlify ( cert . fingerprint ( hashes . SHA1 ( ) ) ) if six . PY3 : raw_fp = raw_fp . decode ( '' ) return '' . join ( a + b for a , b in zip ( raw_fp [ : : ] , raw_fp [ : : ] ) ) except ( ValueError , TypeError , binascii . Error ) as ex : raise exception . InvalidKeypair ( reason = _ ( '' '' ) % ex ) def generate_key ( bits ) : \"\"\"\"\"\" rsa = RSA . generate ( bits ) key = paramiko . RSAKey ( vals = ( rsa . e , rsa . n ) ) key . d = rsa . d key . p = rsa . p key . q = rsa . q return key def generate_key_pair ( bits = ) : key = generate_key ( bits ) keyout = six . StringIO ( ) key . write_private_key ( keyout ) private_key = keyout . getvalue ( ) public_key = '' % ( key . get_name ( ) , key . get_base64 ( ) ) fingerprint = generate_fingerprint ( public_key ) return ( private_key , public_key , fingerprint ) def fetch_crl ( project_id ) : \"\"\"\"\"\" if not CONF . crypto . use_project_ca : project_id = None crl_file_path = crl_path ( project_id ) if not os . path . exists ( crl_file_path ) : raise exception . CryptoCRLFileNotFound ( project = project_id ) with open ( crl_file_path , '' ) as crlfile : return crlfile . read ( ) def decrypt_text ( project_id , text ) : private_key_file = key_path ( project_id ) if not os . path . exists ( private_key_file ) : ", "answer": "raise exception . ProjectNotFound ( project_id = project_id )"}, {"prompt": " from unittest import TestSuite class DeferrableTestSuite ( TestSuite ) : def run ( self , result ) : for test in self . _tests : if result . shouldStop : break deferred = test ( result ) if deferred is not None and hasattr ( deferred , '' ) : for x in deferred : yield x ", "answer": "yield "}, {"prompt": " from django . contrib . sites . models import Site from django . conf import settings class DynamicSiteMiddleware ( object ) : def hosting_parse ( self , hosting ) : \"\"\"\"\"\" if '' in hosting : return hosting . rsplit ( '' , ) return hosting , None def get_hosting ( self , hosting ) : domain , port = self . hosting_parse ( hosting ) if domain in settings . OPPS_DEFAULT_URLS : domain = '' try : return Site . objects . get ( domain = domain ) except Site . DoesNotExist : return Site . objects . order_by ( '' ) [ ] ", "answer": "def process_request ( self , request ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) ", "answer": "result . template = \"\""}, {"prompt": " def f1 ( ) : x = \"\" y = \"\" z = \"\" x += y + z def f2 ( ) : x = \"\" y = \"\" z = \"\" x = x + y + z def f3 ( ) : x = \"\" y = \"\" z = \"\" x = \"\" . join ( ( x , y , z ) ) ", "answer": "def f4 ( ) :"}, {"prompt": " from bcc import BPF import time from unittest import main , TestCase class TestCallchain ( TestCase ) : def test_callchain1 ( self ) : hist = { } def cb ( pid , callchain ) : counter = hist . get ( callchain , ) counter += hist [ callchain ] = counter b = BPF ( text = \"\"\"\"\"\" , cb = cb ) ", "answer": "start = time . time ( )"}, {"prompt": " import os import sys import sqlalchemy as sql import compression as Z from collections import defaultdict from gemini . config import read_gemini_config import gemini_utils as util from gemini_constants import * def get_pathways ( args ) : version_dic = defaultdict ( ) version_dic = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } config = read_gemini_config ( args = args ) path_dirname = config [ \"\" ] if args . version in version_dic : path_file = os . path . join ( path_dirname , version_dic [ args . version ] ) else : sys . exit ( \"\" ) agn_paths = defaultdict ( list ) hgnc_paths = defaultdict ( list ) ensembl_paths = defaultdict ( list ) for line in open ( path_file , '' ) : fields = line . strip ( ) . split ( \"\" ) uniprot = fields [ ] agn = fields [ ] hgnc = fields [ ] ensid = fields [ ] ens_transcript = fields [ ] hsa = fields [ ] path = fields [ ] if fields [ ] != '' else None if path is not None and path . startswith ( \"\" ) : path = path [ : ] path = path . replace ( \"\" , \"\" ) agn_paths [ ( agn , ens_transcript ) ] . append ( path ) hgnc_paths [ ( hgnc , ens_transcript ) ] . append ( path ) ensembl_paths [ ( ensid , ens_transcript ) ] . append ( path ) return agn_paths , hgnc_paths , ensembl_paths def _get_pathways ( gene , transcript , pathways , allow_none = True ) : pathways = set ( pathways ) if None in pathways : if len ( pathways ) > or allow_none is False : pathways . remove ( None ) return pathways def _report_variant_pathways ( res , args , idx_to_sample ) : ( agn_paths , hgnc_paths , ensembl_paths ) = get_pathways ( args ) unpack = Z . unpack_genotype_blob for r in res : try : gt_types = unpack ( r [ '' ] ) gts = unpack ( r [ '' ] ) except : unpack = Z . snappy_unpack_blob gt_types = unpack ( r [ '' ] ) gts = unpack ( r [ '' ] ) gene = str ( r [ '' ] ) trans = str ( r [ '' ] ) pathways = [ ] if ( gene , trans ) in agn_paths : pathways = _get_pathways ( gene , trans , agn_paths [ ( gene , trans ) ] , allow_none = False ) elif ( gene , trans ) in hgnc_paths : pathways = _get_pathways ( gene , trans , hgnc_paths [ ( gene , trans ) ] , allow_none = False ) elif ( gene , trans ) in ensembl_paths : pathways = _get_pathways ( gene , trans , ensembl_paths [ ( gene , trans ) ] , allow_none = False ) pathlist = \"\" . join ( pathways ) for idx , gt_type in enumerate ( gt_types ) : if ( gt_type == HET or gt_type == HOM_ALT ) and len ( pathways ) > : print \"\" . join ( [ r [ '' ] , str ( r [ '' ] ) , str ( r [ '' ] ) , r [ '' ] , r [ '' ] , r [ '' ] , idx_to_sample [ idx ] , gts [ idx ] , gene , trans , pathlist ] ) def get_ind_pathways ( conn , metadata , args ) : idx_to_sample = util . map_indices_to_samples ( metadata ) query = \"\" res = conn . execute ( sql . text ( query ) ) print '' . join ( [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) _report_variant_pathways ( res , args , idx_to_sample ) def get_ind_lof_pathways ( conn , metadata , args ) : idx_to_sample = util . map_indices_to_samples ( metadata ) query = \"\" res = conn . execute ( sql . text ( query ) ) print '' . join ( [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) _report_variant_pathways ( res , args , idx_to_sample ) def pathways ( parser , args ) : import database ", "answer": "conn , metadata = database . get_session_metadata ( args . db )"}, {"prompt": " \"\"\"\"\"\" from google . appengine . ext import db ", "answer": "from cache import Cache"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import weakref import collections import types from . . import exc , util _key_to_collection = collections . defaultdict ( dict ) \"\"\"\"\"\" _collection_to_key = collections . defaultdict ( dict ) \"\"\"\"\"\" def _collection_gced ( ref ) : if not _collection_to_key or ref not in _collection_to_key : return listener_to_key = _collection_to_key . pop ( ref ) for key in listener_to_key . values ( ) : if key in _key_to_collection : dispatch_reg = _key_to_collection [ key ] dispatch_reg . pop ( ref ) if not dispatch_reg : _key_to_collection . pop ( key ) def _stored_in_collection ( event_key , owner ) : key = event_key . _key dispatch_reg = _key_to_collection [ key ] owner_ref = owner . ref listen_ref = weakref . ref ( event_key . _listen_fn ) if owner_ref in dispatch_reg : return False dispatch_reg [ owner_ref ] = listen_ref listener_to_key = _collection_to_key [ owner_ref ] listener_to_key [ listen_ref ] = key return True def _removed_from_collection ( event_key , owner ) : key = event_key . _key dispatch_reg = _key_to_collection [ key ] listen_ref = weakref . ref ( event_key . _listen_fn ) owner_ref = owner . ref dispatch_reg . pop ( owner_ref , None ) if not dispatch_reg : del _key_to_collection [ key ] if owner_ref in _collection_to_key : listener_to_key = _collection_to_key [ owner_ref ] listener_to_key . pop ( listen_ref ) def _stored_in_collection_multi ( newowner , oldowner , elements ) : if not elements : return oldowner = oldowner . ref newowner = newowner . ref old_listener_to_key = _collection_to_key [ oldowner ] new_listener_to_key = _collection_to_key [ newowner ] for listen_fn in elements : listen_ref = weakref . ref ( listen_fn ) key = old_listener_to_key [ listen_ref ] dispatch_reg = _key_to_collection [ key ] if newowner in dispatch_reg : assert dispatch_reg [ newowner ] == listen_ref else : dispatch_reg [ newowner ] = listen_ref new_listener_to_key [ listen_ref ] = key def _clear ( owner , elements ) : if not elements : return owner = owner . ref listener_to_key = _collection_to_key [ owner ] for listen_fn in elements : listen_ref = weakref . ref ( listen_fn ) key = listener_to_key [ listen_ref ] dispatch_reg = _key_to_collection [ key ] dispatch_reg . pop ( owner , None ) if not dispatch_reg : del _key_to_collection [ key ] class _EventKey ( object ) : \"\"\"\"\"\" def __init__ ( self , target , identifier , fn , dispatch_target , _fn_wrap = None ) : self . target = target self . identifier = identifier self . fn = fn if isinstance ( fn , types . MethodType ) : self . fn_key = id ( fn . __func__ ) , id ( fn . __self__ ) else : self . fn_key = id ( fn ) self . fn_wrap = _fn_wrap self . dispatch_target = dispatch_target @ property def _key ( self ) : return ( id ( self . target ) , self . identifier , self . fn_key ) def with_wrapper ( self , fn_wrap ) : if fn_wrap is self . _listen_fn : return self else : return _EventKey ( self . target , self . identifier , self . fn , self . dispatch_target , _fn_wrap = fn_wrap ) def with_dispatch_target ( self , dispatch_target ) : if dispatch_target is self . dispatch_target : return self else : return _EventKey ( self . target , self . identifier , self . fn , dispatch_target , _fn_wrap = self . fn_wrap ) def listen ( self , * args , ** kw ) : once = kw . pop ( \"\" , False ) named = kw . pop ( \"\" , False ) target , identifier , fn = self . dispatch_target , self . identifier , self . _listen_fn dispatch_descriptor = getattr ( target . dispatch , identifier ) adjusted_fn = dispatch_descriptor . _adjust_fn_spec ( fn , named ) self = self . with_wrapper ( adjusted_fn ) if once : self . with_wrapper ( util . only_once ( self . _listen_fn ) ) . listen ( * args , ** kw ) else : self . dispatch_target . dispatch . _listen ( self , * args , ** kw ) def remove ( self ) : key = self . _key if key not in _key_to_collection : raise exc . InvalidRequestError ( \"\" % ( self . target , self . identifier , self . fn ) ) dispatch_reg = _key_to_collection . pop ( key ) for collection_ref , listener_ref in dispatch_reg . items ( ) : collection = collection_ref ( ) listener_fn = listener_ref ( ) if collection is not None and listener_fn is not None : collection . remove ( self . with_wrapper ( listener_fn ) ) def contains ( self ) : \"\"\"\"\"\" return self . _key in _key_to_collection def base_listen ( self , propagate = False , insert = False , named = False ) : target , identifier , fn = self . dispatch_target , self . identifier , self . _listen_fn dispatch_descriptor = getattr ( target . dispatch , identifier ) if insert : dispatch_descriptor . for_modify ( target . dispatch ) . insert ( self , propagate ) else : dispatch_descriptor . for_modify ( target . dispatch ) . append ( self , propagate ) @ property def _listen_fn ( self ) : return self . fn_wrap or self . fn def append_to_list ( self , owner , list_ ) : if _stored_in_collection ( self , owner ) : list_ . append ( self . _listen_fn ) return True ", "answer": "else :"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " def valid ( x , y , kernel , stride ) : return ( ( x - kernel ) / stride + , ( y - kernel ) / stride + ) def full ( x , y , kernel , stride ) : return ( ( x + kernel ) / stride - , ( y + kernel ) / stride - ) ", "answer": "def spp_outdim ( input_channels , levels ) :"}, {"prompt": " from . AddConstant import AddConstant from . BatchNormalization import BatchNormalization from . Dropout import Dropout from . Identity import Identity from . Linear import Linear from . Bias import Bias from . Log import Log from . ReLU import ReLU from . ELU import ELU from . Reshape import Reshape from . Flatten import Flatten from . Permute import Permute from . PoolingCUDNN import PoolingCUDNN ", "answer": "from . Sigmoid import Sigmoid"}, {"prompt": " from twisted . internet import defer def got_results ( res ) : print '' , res print '' d = defer . DeferredList ( [ ] ) ", "answer": "print ''"}, {"prompt": " from django . db import models from django . utils . encoding import smart_str class Post ( models . Model ) : title = models . CharField ( max_length = , null = False ) ", "answer": "content = models . TextField ( max_length = , null = False )"}, {"prompt": " import logging from urllib2 import urlopen from lxml import etree from datetime import datetime , timedelta , date , time import socket socket . setdefaulttimeout ( ) from django . conf import settings from django . utils . translation import ugettext_lazy as _ from molly . conf . provider import Provider , task from molly . apps . weather . models import ( Weather , PTYPE_OBSERVATION , PTYPE_FORECAST ) logger = logging . getLogger ( __name__ ) METOFFICE_OUTLOOK_CHOICES = ( ( '' , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ( , '' ) , ", "answer": "( , '' ) ,"}, {"prompt": " import datetime import django from django . utils . translation import ugettext as _ register = django . template . Library ( ) @ register . filter ( name = '' ) def unix_ms_to_datetime ( unixtime ) : \"\"\"\"\"\" if unixtime : return datetime . datetime . fromtimestamp ( unixtime / ) return _ ( \"\" ) ", "answer": "unix_ms_to_datetime . is_safe = True "}, {"prompt": " import base64 import bz2 import contextlib import itertools import json import mimetypes import optparse import os import re import tarfile def list_files ( fn ) : ", "answer": "if os . path . isdir ( fn ) :"}, {"prompt": " import django from django . db . backends . postgresql_psycopg2 . introspection import DatabaseIntrospection if django . VERSION >= ( , , ) : from django . db . backends . base . introspection import TableInfo class DatabaseSchemaIntrospection ( DatabaseIntrospection ) : def get_table_list ( self , cursor ) : \"\" cursor . execute ( \"\"\"\"\"\" % self . connection . schema_name ) if django . VERSION >= ( , , ) : return [ TableInfo ( row [ ] , { '' : '' , '' : '' } . get ( row [ ] ) ) for row in cursor . fetchall ( ) if row [ ] not in self . ignored_tables ] ", "answer": "else :"}, {"prompt": " from setuptools import setup setup ( name = '' , version = '' , description = '' , author = '' , author_email = '' , url = '' , download_url = '' , keywords = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] , packages = [ '' , '' , '' , '' ] , license = '' , install_requires = [ '' ] , classifiers = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , ] , ", "answer": "entry_points = {"}, {"prompt": " import urllib import codecs import re from datetime import datetime from BeautifulSoup import BeautifulSoup PRESENT_KNESET_URL = r\"\" LAST_UPDATE_TIME_ID = \"\" LAST_UPDATE_TIME_REGEX = re . compile ( '' ) LAST_UPDATE_DATETIME_FORMAT = \"\" ID_LINK_REGEX = re . compile ( r'' ) MK_IMG_ID = re . compile ( '' ) class KnessetPresenceParser ( object ) : '''''' __check_time = None __last_update_time = None __soup = None __MK_NOT_PRESENT_IMG_CLASS_STR = '' __MK_PRESENT_IMG_CLASS_STR = '' def __init__ ( self ) : '''''' self . __soup = self . _get_presence_html_page ( ) self . __last_update_time = self . _get_lastupdate_time ( ) def _is_mk_present ( self , tag ) : '''''' if tag is None or tag . attrMap is None : return False if '' in tag . attrMap and tag [ '' ] == self . __MK_PRESENT_IMG_CLASS_STR : return True ", "answer": "return False"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Ship ( ) ", "answer": "result . template = \"\""}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import six from twitter . common . collections import OrderedSet from pants . backend . jvm . targets . jar_dependency import JarDependency from pants . base . exceptions import TargetDefinitionException from pants . base . payload import Payload from pants . base . payload_field import ExcludesField , JarsField , PrimitiveField from pants . build_graph . address import Address from pants . build_graph . target import Target class JarLibrary ( Target ) : \"\"\"\"\"\" class WrongTargetTypeError ( Exception ) : \"\"\"\"\"\" pass class ExpectedAddressError ( Exception ) : \"\"\"\"\"\" pass def __init__ ( self , payload = None , jars = None , managed_dependencies = None , ** kwargs ) : \"\"\"\"\"\" jars = self . assert_list ( jars , expected_type = JarDependency , key_arg = '' ) payload = payload or Payload ( ) payload . add_fields ( { '' : JarsField ( jars ) , '' : ExcludesField ( [ ] ) , '' : PrimitiveField ( managed_dependencies ) , } ) super ( JarLibrary , self ) . __init__ ( payload = payload , ** kwargs ) if not jars : raise TargetDefinitionException ( self , '' ) self . add_labels ( '' , '' ) @ property def managed_dependencies ( self ) : \"\"\"\"\"\" if self . payload . managed_dependencies : address = Address . parse ( self . payload . managed_dependencies , relative_to = self . address . spec_path ) self . _build_graph . inject_address_closure ( address ) return self . _build_graph . get_target ( address ) return None @ property def jar_dependencies ( self ) : \"\"\"\"\"\" return self . payload . jars @ property def excludes ( self ) : \"\"\"\"\"\" return self . payload . excludes @ staticmethod def to_jar_dependencies ( relative_to , jar_library_specs , build_graph ) : \"\"\"\"\"\" jar_deps = OrderedSet ( ) ", "answer": "for spec in jar_library_specs :"}, {"prompt": " class C ( object ) : pass class D : pass for l in [ type , set , int , list , tuple , C , D ] : print l , l . __module__ ", "answer": "print type . __dict__ [ '' ] . __get__ ( set , None )"}, {"prompt": " \"\"\"\"\"\" import boto from boto . ec2 . ec2object import EC2Object , TaggedEC2Object from boto . resultset import ResultSet from boto . ec2 . address import Address from boto . ec2 . blockdevicemapping import BlockDeviceMapping from boto . ec2 . image import ProductCodes from boto . ec2 . networkinterface import NetworkInterface from boto . ec2 . group import Group import base64 class Reservation ( EC2Object ) : \"\"\"\"\"\" def __init__ ( self , connection = None ) : EC2Object . __init__ ( self , connection ) self . id = None self . owner_id = None self . groups = [ ] self . instances = [ ] def __repr__ ( self ) : return '' % self . id def startElement ( self , name , attrs , connection ) : if name == '' : self . instances = ResultSet ( [ ( '' , Instance ) ] ) return self . instances elif name == '' : self . groups = ResultSet ( [ ( '' , Group ) ] ) return self . groups else : return None def endElement ( self , name , value , connection ) : if name == '' : self . id = value elif name == '' : self . owner_id = value else : setattr ( self , name , value ) def stop_all ( self ) : for instance in self . instances : instance . stop ( ) class Instance ( TaggedEC2Object ) : \"\"\"\"\"\" def __init__ ( self , connection = None ) : TaggedEC2Object . __init__ ( self , connection ) self . id = None self . dns_name = None self . public_dns_name = None self . private_dns_name = None self . state = None self . state_code = None self . key_name = None self . shutdown_state = None self . previous_state = None self . instance_type = None self . launch_time = None self . image_id = None self . placement = None self . kernel = None self . ramdisk = None self . product_codes = ProductCodes ( ) self . ami_launch_index = None self . monitored = False self . spot_instance_request_id = None self . subnet_id = None self . vpc_id = None self . private_ip_address = None self . ip_address = None self . requester_id = None self . _in_monitoring_element = False self . persistent = False self . root_device_name = None self . root_device_type = None self . block_device_mapping = None self . state_reason = None self . group_name = None self . client_token = None self . eventsSet = None self . groups = [ ] self . platform = None self . interfaces = [ ] self . hypervisor = None self . virtualization_type = None self . architecture = None def __repr__ ( self ) : return '' % self . id def startElement ( self , name , attrs , connection ) : retval = TaggedEC2Object . startElement ( self , name , attrs , connection ) if retval is not None : return retval if name == '' : self . _in_monitoring_element = True elif name == '' : self . block_device_mapping = BlockDeviceMapping ( ) return self . block_device_mapping elif name == '' : return self . product_codes elif name == '' : self . state_reason = SubParse ( '' ) return self . state_reason elif name == '' : self . groups = ResultSet ( [ ( '' , Group ) ] ) return self . groups elif name == \"\" : self . eventsSet = SubParse ( '' ) return self . eventsSet elif name == '' : self . interfaces = ResultSet ( [ ( '' , NetworkInterface ) ] ) return None def endElement ( self , name , value , connection ) : if name == '' : self . id = value elif name == '' : self . image_id = value elif name == '' or name == '' : self . dns_name = value self . public_dns_name = value elif name == '' : self . private_dns_name = value elif name == '' : self . key_name = value elif name == '' : self . ami_launch_index = value elif name == '' : self . shutdown_state = value elif name == '' : self . previous_state = value elif name == '' : self . state = value elif name == '' : try : self . state_code = int ( value ) except ValueError : boto . log . warning ( '' % value ) self . state_code = value elif name == '' : self . instance_type = value elif name == '' : self . root_device_name = value elif name == '' : self . root_device_type = value elif name == '' : self . launch_time = value elif name == '' : self . placement = value elif name == '' : self . platform = value elif name == '' : pass elif name == '' : self . kernel = value elif name == '' : self . ramdisk = value elif name == '' : if self . _in_monitoring_element : if value == '' : self . monitored = True self . _in_monitoring_element = False elif name == '' : self . spot_instance_request_id = value elif name == '' : self . subnet_id = value elif name == '' : ", "answer": "self . vpc_id = value"}, {"prompt": " __author__ = '' HTTP_OK = HTTP_CREATED = HTTP_ACCEPTED = HTTP_NON_AUTH_INFO = HTTP_NO_CONTENT = HTTP_RESET = HTTP_PARTIAL_CONTENT = HTTP_BAD_REQUEST = HTTP_UNAUTHORIZED = HTTP_PAYMENT_REQUIRED = HTTP_FORBIDDEN = HTTP_NOT_FOUND = HTTP_METHOD_NOT_ALLOWED = HTTP_NOT_ACCEPTABLE = HTTP_PROXY_AUTH_REQUIRED = HTTP_REQUEST_TIMEOUT = HTTP_CONFLICT = HTTP_GONE = HTTP_REQ_TO_LARGE = HTTP_REQ_TO_LONG = HTTP_UNSUPPORTED_MEDIA_TYPE = HTTP_TOO_MANY_REQUESTS = ", "answer": "HTTP_INTERNAL_ERROR = "}, {"prompt": " \"\"\"\"\"\" import codecs import zlib def zlib_encode ( input , errors = '' ) : \"\"\"\"\"\" assert errors == '' output = zlib . compress ( input ) return ( output , len ( input ) ) def zlib_decode ( input , errors = '' ) : \"\"\"\"\"\" assert errors == '' output = zlib . decompress ( input ) ", "answer": "return ( output , len ( input ) )"}, {"prompt": " import urllib import sys import time from shippo import api_requestor , error , util , rates_req_timeout , transaction_req_timeout def convert_to_shippo_object ( resp , api_key ) : if isinstance ( resp , list ) : return [ convert_to_shippo_object ( i , api_key ) for i in resp ] elif isinstance ( resp , dict ) and not isinstance ( resp , ShippoObject ) : resp = resp . copy ( ) return ShippoObject . construct_from ( resp , api_key ) else : return resp class ShippoObject ( dict ) : def __init__ ( self , id = None , api_key = None , ** params ) : super ( ShippoObject , self ) . __init__ ( ) self . _unsaved_values = set ( ) self . _transient_values = set ( ) self . _retrieve_params = params self . _previous_metadata = None object . __setattr__ ( self , '' , api_key ) if id : self [ '' ] = id def __setattr__ ( self , k , v ) : if k [ ] == '' or k in self . __dict__ : return super ( ShippoObject , self ) . __setattr__ ( k , v ) else : self [ k ] = v def __getattr__ ( self , k ) : if k [ ] == '' : raise AttributeError ( k ) try : return self [ k ] except KeyError , err : raise AttributeError ( * err . args ) def __setitem__ ( self , k , v ) : if v == \"\" : raise ValueError ( \"\" \"\" \"\" % ( k , str ( self ) , k ) ) super ( ShippoObject , self ) . __setitem__ ( k , v ) if not hasattr ( self , '' ) : self . _unsaved_values = set ( ) self . _unsaved_values . add ( k ) def __getitem__ ( self , k ) : try : return super ( ShippoObject , self ) . __getitem__ ( k ) except KeyError , err : if k in self . _transient_values : raise KeyError ( \"\" \"\" \"\" \"\" \"\" % ( k , k , '' . join ( self . keys ( ) ) ) ) else : raise err def __delitem__ ( self , k ) : raise TypeError ( \"\" \"\" ) @ classmethod def construct_from ( cls , values , api_key ) : instance = cls ( values . get ( '' ) , api_key ) instance . refresh_from ( values , api_key ) return instance def refresh_from ( self , values , api_key = None , partial = False ) : self . api_key = api_key or getattr ( values , '' , None ) if partial : self . _unsaved_values = ( self . _unsaved_values - set ( values ) ) else : removed = set ( self . keys ( ) ) - set ( values ) self . _transient_values = self . _transient_values | removed self . _unsaved_values = set ( ) self . clear ( ) self . _transient_values = self . _transient_values - set ( values ) for k , v in values . iteritems ( ) : super ( ShippoObject , self ) . __setitem__ ( k , convert_to_shippo_object ( v , api_key ) ) self . _previous_metadata = values . get ( '' ) def request ( self , method , url , params = None ) : if params is None : params = self . _retrieve_params requestor = api_requestor . APIRequestor ( self . api_key ) response , api_key = requestor . request ( method , url , params ) return convert_to_shippo_object ( response , api_key ) def __repr__ ( self ) : ident_parts = [ type ( self ) . __name__ ] if isinstance ( self . get ( '' ) , basestring ) : ident_parts . append ( self . get ( '' ) ) if isinstance ( self . get ( '' ) , basestring ) : ident_parts . append ( '' % ( self . get ( '' ) , ) ) unicode_repr = '' % ( '' . join ( ident_parts ) , hex ( id ( self ) ) , str ( self ) ) if sys . version_info [ ] < : return unicode_repr . encode ( '' ) else : return unicode_repr def __str__ ( self ) : return util . json . dumps ( self , sort_keys = True , indent = ) @ property def shippo_id ( self ) : return self . id class APIResource ( ShippoObject ) : def refresh ( self ) : self . refresh_from ( self . request ( '' , self . instance_url ( ) ) ) return self @ classmethod def class_name ( cls ) : ", "answer": "if cls == APIResource :"}, {"prompt": " import random import unittest import time import threading try : import BaseHTTPServer as HTTPServer except ImportError : import http . server as HTTPServer import sys , os , os . path rootDirectory = os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , '' , '' ) if rootDirectory not in sys . path : sys . path . append ( rootDirectory ) from applicationinsights import channel class TestSenderBase ( unittest . TestCase ) : def test_construct ( self ) : actual = channel . SenderBase ( '' ) self . assertIsNotNone ( actual ) self . assertEqual ( '' , actual . service_endpoint_uri ) self . assertIsNone ( actual . queue ) self . assertEqual ( , actual . send_buffer_size ) def test_service_endpoint_uri_works_as_expected ( self ) : actual = channel . SenderBase ( '' ) self . assertEqual ( '' , actual . service_endpoint_uri ) actual . service_endpoint_uri = '' self . assertEqual ( '' , actual . service_endpoint_uri ) def test_queue_works_as_expected ( self ) : actual = channel . SenderBase ( '' ) self . assertIsNone ( actual . queue ) expected = object ( ) actual . queue = expected ", "answer": "self . assertEqual ( expected , actual . queue )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from . . phonemetadata import NumberFormat"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Weapon ( ) ", "answer": "result . template = \"\""}, {"prompt": " from setuptools import setup , find_packages setup ( name = '' , version = '' , description = '' , author = '' , author_email = '' , license = '' , packages = find_packages ( ) , package_data = { '' : [ '' , '' ] , ", "answer": "} ,"}, {"prompt": " \"\"\"\"\"\" import datetime import logging import os import pickle import struct import sys import tempfile import threading import types import warnings from google . appengine . api import api_base_pb from google . appengine . api import datastore from google . appengine . api import datastore_admin from google . appengine . api import datastore_errors from google . appengine . api import datastore_types from google . appengine . api import users from google . appengine . datastore import datastore_pb from google . appengine . datastore import datastore_index from google . appengine . runtime import apiproxy_errors from google . net . proto import ProtocolBuffer from google . appengine . datastore import entity_pb warnings . filterwarnings ( '' , '' ) entity_pb . Reference . __hash__ = lambda self : hash ( self . Encode ( ) ) datastore_pb . Query . __hash__ = lambda self : hash ( self . Encode ( ) ) class DatastoreFileStub ( object ) : \"\"\"\"\"\" def __init__ ( self , app_id , datastore_file , history_file , require_indexes = False ) : \"\"\"\"\"\" assert isinstance ( app_id , types . StringTypes ) and app_id != '' self . __app_id = app_id self . __datastore_file = datastore_file self . __history_file = history_file self . __entities = { } self . __tx_snapshot = { } self . __queries = { } self . __transactions = { } self . __indexes = { } self . __require_indexes = require_indexes self . __query_history = { } self . __next_id = self . __next_cursor = self . __next_tx_handle = self . __next_index_id = self . __id_lock = threading . Lock ( ) self . __cursor_lock = threading . Lock ( ) self . __tx_handle_lock = threading . Lock ( ) self . __index_id_lock = threading . Lock ( ) self . __tx_lock = threading . Lock ( ) self . __entities_lock = threading . Lock ( ) self . __file_lock = threading . Lock ( ) self . __indexes_lock = threading . Lock ( ) self . Read ( ) def Clear ( self ) : \"\"\"\"\"\" self . __entities = { } self . __queries = { } self . __transactions = { } self . __query_history = { } def Read ( self ) : \"\"\"\"\"\" pb_exceptions = ( ProtocolBuffer . ProtocolBufferDecodeError , LookupError , TypeError , ValueError ) error_msg = ( '' '' ) if self . __datastore_file and self . __datastore_file != '' : for encoded_entity in self . __ReadPickled ( self . __datastore_file ) : try : entity = entity_pb . EntityProto ( encoded_entity ) except pb_exceptions , e : raise datastore_errors . InternalError ( error_msg % ( self . __datastore_file , e ) ) last_path = entity . key ( ) . path ( ) . element_list ( ) [ - ] app_kind = ( entity . key ( ) . app ( ) , last_path . type ( ) ) kind_dict = self . __entities . setdefault ( app_kind , { } ) kind_dict [ entity . key ( ) ] = entity if last_path . has_id ( ) and last_path . id ( ) >= self . __next_id : self . __next_id = last_path . id ( ) + self . __query_history = { } for encoded_query , count in self . __ReadPickled ( self . __history_file ) : try : query_pb = datastore_pb . Query ( encoded_query ) except pb_exceptions , e : raise datastore_errors . InternalError ( error_msg % ( self . __history_file , e ) ) if query_pb in self . __query_history : self . __query_history [ query_pb ] += count else : self . __query_history [ query_pb ] = count def Write ( self ) : \"\"\"\"\"\" self . __WriteDatastore ( ) self . __WriteHistory ( ) ", "answer": "def __WriteDatastore ( self ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import unittest class Assertions ( unittest . TestCase ) : ", "answer": "pass "}, {"prompt": " \"\"\"\"\"\" import re import sys import unittest import param from param . ipython import ParamPager test1_repr = \"\"\"\"\"\" test2_repr = \"\"\"\"\"\" class TestParamPager ( unittest . TestCase ) : def setUp ( self ) : self . maxDiff = None class TestClass ( param . Parameterized ) : u = param . Number ( ) v = param . Number ( , constant = True ) w = param . Number ( , readonly = True ) x = param . String ( None , allow_None = True ) y = param . Number ( , bounds = ( - , None ) ) z = param . Number ( , bounds = ( - , ) , softbounds = ( - , - ) ) self . TestClass = TestClass self . pager = ParamPager ( ) def test_parameterized_class ( self ) : page_string = self . pager ( self . TestClass ) page_string = re . sub ( '' , '' , page_string ) ", "answer": "ref_string = re . sub ( '' , '' , test1_repr )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Building ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " from jinja2 import nodes , TemplateAssertionError , Markup as mark_safe from jinja2 . ext import Extension from mediagenerator . generators . bundles . utils import _render_include_media class MediaExtension ( Extension ) : tags = set ( [ '' ] ) def __init__ ( self , environment ) : self . environment = environment def parse ( self , parser ) : token = parser . stream . next ( ) args = [ parser . parse_expression ( ) ] kwargs = [ ] while parser . stream . current . type != '' : if kwargs : parser . stream . expect ( '' ) if parser . stream . skip_if ( '' ) : ", "answer": "break"}, {"prompt": " from django . db import models class ExampleModel ( models . Model ) : name = models . CharField ( max_length = ) value = models . BooleanField ( default = False ) date_created = models . DateTimeField ( auto_now_add = True ) related = models . ForeignKey ( '' , blank = True , null = True ) relateds = models . ManyToManyField ( '' , blank = True ) def __unicode__ ( self ) : return \"\" % ( self . pk , ) def __str__ ( self ) : return \"\" % ( self . pk , ) def __repr__ ( self ) : return \"\" % ( self . pk , self . name , ) def get_absolute_url ( self ) : return \"\" . format ( pk = self . pk ) def get_negative_pk ( self ) : return - * self . pk class RelatedModel ( models . Model ) : ", "answer": "name = models . CharField ( max_length = )"}, {"prompt": " from functools import partial import inspect import logging import sys import re from silk . utils import six from silk . profiling . profiler import silk_profile Logger = logging . getLogger ( '' ) def _get_module ( module_name ) : \"\"\"\"\"\" if '' in module_name : splt = module_name . split ( '' ) imp = '' . join ( splt [ : - ] ) frm = splt [ - ] module = __import__ ( imp , globals ( ) , locals ( ) , [ frm ] , ) module = getattr ( module , frm ) else : module = __import__ ( module_name , globals ( ) , locals ( ) , [ ] , ) return module def _get_func ( module , func_name ) : \"\"\"\"\"\" cls_name = None cls = None if '' in func_name : cls_name , func_name = func_name . split ( '' ) if cls_name : cls = getattr ( module , cls_name ) func = getattr ( cls , func_name ) else : func = getattr ( module , func_name ) return cls , func def profile_function_or_method ( module , func , name = None ) : \"\"\"\"\"\" if type ( module ) is str or type ( module ) is unicode : module = _get_module ( module ) decorator = silk_profile ( name , _dynamic = True ) func_name = func cls , func = _get_func ( module , func_name ) ", "answer": "wrapped_target = decorator ( func )"}, {"prompt": " \"\"\"\"\"\" from googleads import adwords AD_GROUP_ID = '' def main ( client , ad_group_id ) : ad_group_service = client . GetService ( '' , version = '' ) operations = [ { '' : '' , '' : { '' : ad_group_id , '' : '' } } ] result = ad_group_service . mutate ( operations ) ", "answer": "for ad_group in result [ '' ] :"}, {"prompt": " import csv from operator import add from datetime import datetime from StringIO import StringIO from collections import namedtuple from pyspark import SparkConf , SparkContext DATE_FMT = \"\" Order = namedtuple ( '' , ( '' , '' , '' , '' ) ) def parse ( row ) : \"\"\"\"\"\" row [ ] = int ( row [ ] ) row [ ] = int ( row [ ] ) row [ ] = datetime . strptime ( row [ ] , DATE_FMT ) return Order ( * row ) def split ( line ) : \"\"\"\"\"\" reader = csv . reader ( StringIO ( line ) ) return reader . next ( ) ", "answer": "if __name__ == '' :"}, {"prompt": " import hashlib import urllib import base64 import json import ast from django . test import TestCase from django . conf import settings from django . core . urlresolvers import reverse from adl_lrs . views import register class AgentProfileTests ( TestCase ) : testagent = '' otheragent = '' content_type = \"\" testprofileId1 = \"\" testprofileId2 = \"\" testprofileId3 = \"\" otherprofileId1 = \"\" @ classmethod def setUpClass ( cls ) : print \"\" % __name__ super ( AgentProfileTests , cls ) . setUpClass ( ) def setUp ( self ) : self . username = \"\" self . email = \"\" self . password = \"\" self . auth = \"\" % base64 . b64encode ( \"\" % ( self . username , self . password ) ) form = { '' : self . username , '' : self . email , '' : self . password , '' : self . password } self . client . post ( reverse ( register ) , form , X_Experience_API_Version = settings . XAPI_VERSION ) self . testparams1 = { \"\" : self . testprofileId1 , \"\" : self . testagent } path = '' % ( reverse ( '' ) , urllib . urlencode ( self . testparams1 ) ) self . testprofile1 = { \"\" : \"\" , \"\" : { \"\" : \"\" } } self . put1 = self . client . put ( path , self . testprofile1 , content_type = self . content_type , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . testparams2 = { \"\" : self . testprofileId2 , \"\" : self . testagent } path = '' % ( reverse ( '' ) , urllib . urlencode ( self . testparams2 ) ) self . testprofile2 = { \"\" : \"\" , \"\" : { \"\" : \"\" } } self . put2 = self . client . put ( path , self . testprofile2 , content_type = self . content_type , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . testparams3 = { \"\" : self . testprofileId3 , \"\" : self . testagent } path = '' % ( reverse ( '' ) , urllib . urlencode ( self . testparams3 ) ) self . testprofile3 = { \"\" : \"\" , \"\" : { \"\" : \"\" } } self . put3 = self . client . put ( path , self . testprofile3 , content_type = self . content_type , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . testparams4 = { \"\" : self . otherprofileId1 , \"\" : self . otheragent } path = '' % ( reverse ( '' ) , urllib . urlencode ( self . testparams4 ) ) self . otherprofile1 = { \"\" : \"\" , \"\" : { \"\" : \"\" } } self . put4 = self . client . put ( path , self . otherprofile1 , content_type = self . content_type , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) def tearDown ( self ) : self . client . delete ( reverse ( '' ) , self . testparams1 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . client . delete ( reverse ( '' ) , self . testparams2 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . client . delete ( reverse ( '' ) , self . testparams3 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . client . delete ( reverse ( '' ) , self . testparams4 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) def test_get_agent_not_found ( self ) : a = '' p = '' param = { \"\" : p , \"\" : a } r = self . client . get ( reverse ( '' ) , param , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) def test_put ( self ) : self . assertEqual ( self . put1 . status_code , ) self . assertEqual ( self . put1 . content , '' ) self . assertEqual ( self . put2 . status_code , ) self . assertEqual ( self . put2 . content , '' ) self . assertEqual ( self . put3 . status_code , ) self . assertEqual ( self . put3 . content , '' ) self . assertEqual ( self . put4 . status_code , ) self . assertEqual ( self . put4 . content , '' ) def test_put_etag_missing_on_change ( self ) : path = '' % ( reverse ( '' ) , urllib . urlencode ( self . testparams1 ) ) profile = { \"\" : \"\" , \"\" : { \"\" : \"\" } } response = self . client . put ( path , profile , content_type = self . content_type , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( response . status_code , ) self . assertIn ( '' , response . content ) r = self . client . get ( reverse ( '' ) , self . testparams1 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) robj = ast . literal_eval ( r . content ) self . assertEqual ( robj [ '' ] , self . testprofile1 [ '' ] ) self . assertEqual ( robj [ '' ] [ '' ] , self . testprofile1 [ '' ] [ '' ] ) def test_put_etag_right_on_change ( self ) : path = '' % ( reverse ( '' ) , urllib . urlencode ( self . testparams1 ) ) profile = { \"\" : \"\" , \"\" : { \"\" : \"\" } } thehash = '' % hashlib . sha1 ( '' % self . testprofile1 ) . hexdigest ( ) response = self . client . put ( path , profile , content_type = self . content_type , If_Match = thehash , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( response . status_code , ) self . assertEqual ( response . content , '' ) r = self . client . get ( reverse ( '' ) , self . testparams1 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) robj = ast . literal_eval ( r . content ) self . assertEqual ( robj [ '' ] , profile [ '' ] ) self . assertEqual ( robj [ '' ] [ '' ] , profile [ '' ] [ '' ] ) def test_put_etag_wrong_on_change ( self ) : path = '' % ( reverse ( '' ) , urllib . urlencode ( self . testparams1 ) ) profile = { \"\" : \"\" , \"\" : { \"\" : \"\" } } thehash = '' % hashlib . sha1 ( '' % '' ) . hexdigest ( ) response = self . client . put ( path , profile , content_type = self . content_type , If_Match = thehash , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( response . status_code , ) self . assertIn ( '' , response . content ) r = self . client . get ( reverse ( '' ) , self . testparams1 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) robj = ast . literal_eval ( r . content ) self . assertEqual ( robj [ '' ] , self . testprofile1 [ '' ] ) self . assertEqual ( robj [ '' ] [ '' ] , self . testprofile1 [ '' ] [ '' ] ) def test_put_etag_if_none_match_good ( self ) : params = { \"\" : '' , \"\" : self . testagent } path = '' % ( reverse ( '' ) , urllib . urlencode ( params ) ) profile = { \"\" : \"\" , \"\" : { \"\" : \"\" } } response = self . client . put ( path , profile , content_type = self . content_type , If_None_Match = '' , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( response . status_code , ) self . assertEqual ( response . content , '' ) r = self . client . get ( reverse ( '' ) , params , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) robj = ast . literal_eval ( r . content ) self . assertEqual ( robj [ '' ] , profile [ '' ] ) self . assertEqual ( robj [ '' ] [ '' ] , profile [ '' ] [ '' ] ) r = self . client . delete ( reverse ( '' ) , params , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) def test_put_etag_if_none_match_bad ( self ) : path = '' % ( reverse ( '' ) , urllib . urlencode ( self . testparams1 ) ) profile = { \"\" : \"\" , \"\" : { \"\" : \"\" } } response = self . client . put ( path , profile , content_type = self . content_type , If_None_Match = '' , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( response . status_code , ) self . assertEqual ( response . content , '' ) r = self . client . get ( reverse ( '' ) , self . testparams1 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) robj = ast . literal_eval ( r . content ) self . assertEqual ( robj [ '' ] , self . testprofile1 [ '' ] ) self . assertEqual ( robj [ '' ] [ '' ] , self . testprofile1 [ '' ] [ '' ] ) def test_get_invalid_agent_structure ( self ) : r = self . client . get ( reverse ( '' ) , { \"\" : self . testprofileId1 , \"\" : \"\" } , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) self . assertEqual ( r . content , \"\" ) def test_get_invalid_agent ( self ) : r = self . client . get ( reverse ( '' ) , { \"\" : self . testprofileId1 , \"\" : { \"\" : \"\" } } , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) self . assertEqual ( r . content , \"\" ) def test_get ( self ) : r = self . client . get ( reverse ( '' ) , self . testparams1 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) robj = ast . literal_eval ( r . content ) self . assertEqual ( robj [ '' ] , self . testprofile1 [ '' ] ) self . assertEqual ( robj [ '' ] [ '' ] , self . testprofile1 [ '' ] [ '' ] ) self . assertEqual ( r [ '' ] , '' % hashlib . sha1 ( '' % self . testprofile1 ) . hexdigest ( ) ) r2 = self . client . get ( reverse ( '' ) , self . testparams2 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r2 . status_code , ) robj2 = ast . literal_eval ( r2 . content ) self . assertEqual ( robj2 [ '' ] , self . testprofile2 [ '' ] ) self . assertEqual ( robj2 [ '' ] [ '' ] , self . testprofile2 [ '' ] [ '' ] ) self . assertEqual ( r2 [ '' ] , '' % hashlib . sha1 ( '' % self . testprofile2 ) . hexdigest ( ) ) r3 = self . client . get ( reverse ( '' ) , self . testparams3 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r3 . status_code , ) robj3 = ast . literal_eval ( r3 . content ) self . assertEqual ( robj3 [ '' ] , self . testprofile3 [ '' ] ) self . assertEqual ( robj3 [ '' ] [ '' ] , self . testprofile3 [ '' ] [ '' ] ) self . assertEqual ( r3 [ '' ] , '' % hashlib . sha1 ( '' % self . testprofile3 ) . hexdigest ( ) ) r4 = self . client . get ( reverse ( '' ) , self . testparams4 , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r4 . status_code , ) robj4 = ast . literal_eval ( r4 . content ) self . assertEqual ( robj4 [ '' ] , self . otherprofile1 [ '' ] ) self . assertEqual ( robj4 [ '' ] [ '' ] , self . otherprofile1 [ '' ] [ '' ] ) self . assertEqual ( r4 [ '' ] , '' % hashlib . sha1 ( '' % self . otherprofile1 ) . hexdigest ( ) ) def test_get_no_params ( self ) : r = self . client . get ( reverse ( '' ) , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) self . assertIn ( '' , r . content ) def test_get_no_agent ( self ) : params = { \"\" : self . testprofileId1 } r = self . client . get ( reverse ( '' ) , params , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) self . assertIn ( '' , r . content ) def test_get_no_profileId ( self ) : params = { \"\" : self . testagent } r = self . client . get ( reverse ( '' ) , params , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) def test_delete ( self ) : prof_id = \"\" params = { \"\" : prof_id , \"\" : self . testagent } path = '' % ( reverse ( '' ) , urllib . urlencode ( params ) ) profile = { \"\" : \"\" , \"\" : { \"\" : \"\" } } response = self . client . put ( path , profile , content_type = self . content_type , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( response . status_code , ) r = self . client . get ( reverse ( '' ) , params , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) robj = ast . literal_eval ( r . content ) self . assertEqual ( robj [ '' ] , profile [ '' ] ) self . assertEqual ( robj [ '' ] [ '' ] , profile [ '' ] [ '' ] ) r = self . client . delete ( reverse ( '' ) , params , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) self . assertEqual ( r . status_code , ) r = self . client . get ( reverse ( '' ) , params , Authorization = self . auth , X_Experience_API_Version = settings . XAPI_VERSION ) ", "answer": "self . assertEqual ( r . status_code , )"}, {"prompt": " import requests import json import sys import conn import os import extra_functions os . system ( '' ) headers = conn . headers auth = conn . auth payload = { \"\" : , \"\" : \"\" } url = conn . url + '' def get ( ) : print '' r = requests . get ( url , auth = auth ) if r . status_code == : result = json . loads ( r . text ) for items in result : print items , '' , result [ items ] print '' else : print '' def put ( ) : if extra_functions . volume_check ( ) == False : import storage_volume storage_volume . post ( ) r = requests . put ( url , auth = auth , data = json . dumps ( payload ) , headers = headers ) if r . status_code == : print '' else : print '' def post ( ) : print '' ", "answer": "def delete ( ) :"}, {"prompt": " import collections from oslo_concurrency import lockutils from oslo_utils import timeutils from neutron . openstack . common . cache import backends class MemoryBackend ( backends . BaseCache ) : def __init__ ( self , parsed_url , options = None ) : super ( MemoryBackend , self ) . __init__ ( parsed_url , options ) self . _clear ( ) def _set_unlocked ( self , key , value , ttl = ) : expires_at = if ttl != : expires_at = timeutils . utcnow_ts ( ) + ttl self . _cache [ key ] = ( expires_at , value ) if expires_at : self . _keys_expires [ expires_at ] . add ( key ) def _set ( self , key , value , ttl = , not_exists = False ) : with lockutils . lock ( key ) : if not_exists and self . _exists_unlocked ( key ) : return False self . _set_unlocked ( key , value , ttl ) return True def _get_unlocked ( self , key , default = None ) : now = timeutils . utcnow_ts ( ) try : timeout , value = self . _cache [ key ] except KeyError : return ( , default ) if timeout and now >= timeout : try : del self . _cache [ key ] except KeyError : pass try : self . _keys_expires [ timeout ] . remove ( key ) except ( KeyError , ValueError ) : pass return ( , default ) return ( timeout , value ) def _get ( self , key , default = None ) : with lockutils . lock ( key ) : return self . _get_unlocked ( key , default ) [ ] def _exists_unlocked ( self , key ) : now = timeutils . utcnow_ts ( ) try : timeout = self . _cache [ key ] [ ] return not timeout or now <= timeout except KeyError : return False def __contains__ ( self , key ) : with lockutils . lock ( key ) : return self . _exists_unlocked ( key ) def _incr_append ( self , key , other ) : with lockutils . lock ( key ) : timeout , value = self . _get_unlocked ( key ) ", "answer": "if value is None :"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals AUTHOR = '' APP = '' TITLE = APP + '' VERSION = '' extensions = [ ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = APP copyright = '' + AUTHOR ", "answer": "version = release = VERSION"}, {"prompt": " \"\"\"\"\"\" ", "answer": "import redis"}, {"prompt": " from unittest . mock import Mock , call from gitman import common from gitman . common import _Config class TestShowConsole : def setup_method ( self , _ ) : _Config . indent_level = _Config . verbosity = self . file = Mock ( ) def test_show ( self ) : common . show ( \"\" , file = self . file ) assert [ call . write ( \"\" ) , call . write ( \"\" ) , ] == self . file . mock_calls def test_show_after_indent ( self ) : common . indent ( ) common . show ( \"\" , file = self . file ) assert [ call . write ( \"\" ) , call . write ( \"\" ) , ] == self . file . mock_calls def test_show_after_1_indent_2_dedent ( self ) : common . indent ( ) common . dedent ( ) common . dedent ( ) ", "answer": "common . show ( \"\" , file = self . file )"}, {"prompt": " from traits . api import HasTraits , Str , Int from traitsui . api import View , Item , Group import traitsui class SimpleEmployee2 ( HasTraits ) : first_name = Str last_name = Str department = Str employee_number = Str salary = Int traits_view = View ( Group ( Item ( name = '' ) , ", "answer": "Item ( name = '' ) ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Weapon ( ) result . template = \"\" result . attribute_template_id = ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " from nose . tools import * from tests import ( prepare_database , with_database , TEST_1_FP_RAW , TEST_1_LENGTH , TEST_1A_FP_RAW , TEST_1A_LENGTH , TEST_1B_FP_RAW , TEST_1B_LENGTH , TEST_1C_FP_RAW , TEST_1C_LENGTH , TEST_1D_FP_RAW , TEST_1D_LENGTH , TEST_2_FP_RAW , TEST_2_LENGTH , ) from acoustid import tables , const from acoustid . data . meta import insert_meta from acoustid . data . submission import insert_submission , import_submission , import_queued_submissions @ with_database def test_insert_submission ( conn ) : id = insert_submission ( conn , { '' : [ , , , , , ] , '' : , '' : , '' : , '' : , } ) assert_equals ( , id ) rows = conn . execute ( \"\"\"\"\"\" , ( id , ) ) . fetchall ( ) expected_rows = [ ( [ , , , , , ] , , , ) , ] assert_equals ( expected_rows , rows ) @ with_database def test_import_submission_with_foreignid ( conn ) : prepare_database ( conn , \"\"\"\"\"\" ) id = insert_submission ( conn , { '' : TEST_1_FP_RAW , '' : TEST_1_LENGTH , '' : , '' : , '' : , '' : , } ) query = tables . submission . select ( tables . submission . c . id == id ) submission = conn . execute ( query ) . fetchone ( ) fingerprint = import_submission ( conn , submission ) query = tables . track_foreignid . select ( tables . track_foreignid . c . track_id == fingerprint [ '' ] ) track_foreignid = conn . execute ( query ) . fetchone ( ) assert_equals ( , track_foreignid [ '' ] ) @ with_database def test_import_submission ( conn ) : id = insert_submission ( conn , { '' : TEST_1_FP_RAW , '' : TEST_1_LENGTH , '' : , '' : , '' : , '' : '' , '' : '' , } ) query = tables . submission . select ( tables . submission . c . id == id ) submission = conn . execute ( query ) . fetchone ( ) assert_false ( submission [ '' ] ) fingerprint = import_submission ( conn , submission ) assert_equals ( , fingerprint [ '' ] ) assert_equals ( , fingerprint [ '' ] ) query = tables . submission . select ( tables . submission . c . id == id ) submission = conn . execute ( query ) . fetchone ( ) assert_true ( submission [ '' ] ) query = tables . track_mbid . select ( tables . track_mbid . c . track_id == fingerprint [ '' ] ) track_mbid = conn . execute ( query ) . fetchone ( ) assert_equals ( , track_mbid [ '' ] ) query = tables . track_puid . select ( tables . track_puid . c . track_id == fingerprint [ '' ] ) track_puid = conn . execute ( query ) . fetchone ( ) assert_equals ( , track_puid [ '' ] ) query = tables . fingerprint . select ( tables . fingerprint . c . id == fingerprint [ '' ] ) fingerprint = conn . execute ( query ) . fetchone ( ) assert_equals ( , fingerprint [ '' ] ) id = insert_submission ( conn , { '' : TEST_2_FP_RAW , '' : TEST_2_LENGTH , '' : , '' : , '' : , } ) query = tables . submission . select ( tables . submission . c . id == id ) submission = conn . execute ( query ) . fetchone ( ) assert_false ( submission [ '' ] ) fingerprint = import_submission ( conn , submission ) assert_equals ( , fingerprint [ '' ] ) assert_equals ( , fingerprint [ '' ] ) query = tables . submission . select ( tables . submission . c . id == id ) submission = conn . execute ( query ) . fetchone ( ) assert_true ( submission [ '' ] ) id = insert_submission ( conn , { '' : TEST_1_FP_RAW , '' : TEST_1_LENGTH , '' : , '' : , '' : , '' : '' , '' : '' , } ) query = tables . submission . select ( tables . submission . c . id == id ) submission = conn . execute ( query ) . fetchone ( ) assert_false ( submission [ '' ] ) fingerprint = import_submission ( conn , submission ) assert_equals ( , fingerprint [ '' ] ) assert_equals ( , fingerprint [ '' ] ) query = tables . submission . select ( tables . submission . c . id == id ) submission = conn . execute ( query ) . fetchone ( ) assert_true ( submission [ '' ] ) query = tables . track_mbid . select ( tables . track_mbid . c . track_id == fingerprint [ '' ] ) track_mbid = conn . execute ( query ) . fetchone ( ) assert_equals ( , track_mbid [ '' ] ) query = tables . track_puid . select ( tables . track_puid . c . track_id == fingerprint [ '' ] ) track_puid = conn . execute ( query ) . fetchone ( ) assert_equals ( , track_puid [ '' ] ) query = tables . fingerprint . select ( tables . fingerprint . c . id == fingerprint [ '' ] ) fingerprint = conn . execute ( query ) . fetchone ( ) assert_equals ( , fingerprint [ '' ] ) @ with_database def test_import_submission_reuse_fingerprint_97 ( conn ) : prepare_database ( conn , \"\"\"\"\"\" , dict ( fp = TEST_1A_FP_RAW , len = TEST_1A_LENGTH ) ) id = insert_submission ( conn , { '' : TEST_1B_FP_RAW , '' : TEST_1B_LENGTH , '' : , '' : '' , '' : '' , } ) query = tables . submission . select ( tables . submission . c . id == id ) submission = conn . execute ( query ) . fetchone ( ) ", "answer": "assert_false ( submission [ '' ] )"}, {"prompt": " import requests import time def test_resolve_service_with_path ( wc_host ) : \"\"\"\"\"\" load_watson_with_config ( wc_host , \"\" ) time . sleep ( ) assert requests . get ( \"\" , params = dict ( name = \"\" ) ) . text == \"\" def test_resolve_service_without_path ( wc_host ) : \"\"\"\"\"\" load_watson_with_config ( wc_host , \"\" ) ", "answer": "time . sleep ( )"}, {"prompt": " import numpy as np import theano import theano . tensor as T import collections as C import anglepy as ap import anglepy . ndict as ndict from anglepy . misc import lazytheanofunc import math , inspect def shared32 ( x , name = None , borrow = False ) : return theano . shared ( np . asarray ( x , dtype = '' ) , name = name , borrow = borrow ) '''''' class GPUVAE_YZ_X ( ap . GPUVAEModel ) : def __init__ ( self , get_optimizer , n_x , n_y , n_hidden_q , n_z , n_hidden_p , nonlinear_q = '' , nonlinear_p = '' , type_px = '' , type_qz = '' , type_pz = '' , prior_sd = , init_sd = , var_smoothing = , n_mixture = , uniform_y = False ) : self . constr = ( __name__ , inspect . stack ( ) [ ] [ ] , locals ( ) ) self . n_x = n_x self . n_y = n_y self . n_hidden_q = n_hidden_q self . n_z = n_z self . n_hidden_p = n_hidden_p self . dropout = False self . nonlinear_q = nonlinear_q self . nonlinear_p = nonlinear_p self . type_px = type_px self . type_qz = type_qz self . type_pz = type_pz self . prior_sd = prior_sd self . var_smoothing = var_smoothing self . n_mixture = n_mixture self . uniform_y = uniform_y v , w = self . init_w ( ) for i in v : v [ i ] = shared32 ( v [ i ] ) for i in w : w [ i ] = shared32 ( w [ i ] ) self . v = v self . w = w super ( GPUVAE_YZ_X , self ) . __init__ ( get_optimizer ) def factors ( self , x , z , A ) : v = self . v w = self . w '''''' def f_softplus ( x ) : return T . log ( T . exp ( x ) + ) def f_rectlin ( x ) : return x * ( x > ) def f_rectlin2 ( x ) : return x * ( x > ) + * x nonlinear = { '' : T . tanh , '' : T . nnet . sigmoid , '' : f_softplus , '' : f_rectlin , '' : f_rectlin2 } nonlinear_q = nonlinear [ self . nonlinear_q ] nonlinear_p = nonlinear [ self . nonlinear_p ] import theano . tensor . shared_randomstreams rng = theano . tensor . shared_randomstreams . RandomStreams ( ) hidden_q = [ nonlinear_q ( T . dot ( v [ '' ] , x [ '' ] ) + T . dot ( v [ '' ] , x [ '' ] ) + T . dot ( v [ '' ] , A ) ) ] for i in range ( , len ( self . n_hidden_q ) ) : hidden_q . append ( nonlinear_q ( T . dot ( v [ '' + str ( i ) ] , hidden_q [ - ] ) + T . dot ( v [ '' + str ( i ) ] , A ) ) ) q_mean = T . dot ( v [ '' ] , hidden_q [ - ] ) + T . dot ( v [ '' ] , A ) if self . type_qz == '' or self . type_qz == '' : q_logvar = T . dot ( v [ '' ] , hidden_q [ - ] ) + T . dot ( v [ '' ] , A ) else : raise Exception ( ) theanofunc = lazytheanofunc ( '' , mode = '' ) self . dist_qz [ '' ] = theanofunc ( [ x [ '' ] , x [ '' ] ] + [ A ] , [ q_mean , q_logvar ] ) eps = rng . normal ( size = q_mean . shape , dtype = '' ) _z = q_mean + T . exp ( * q_logvar ) * eps hidden_p = [ nonlinear_p ( T . dot ( w [ '' ] , x [ '' ] ) + T . dot ( w [ '' ] , _z ) + T . dot ( w [ '' ] , A ) ) ] for i in range ( , len ( self . n_hidden_p ) ) : hidden_p . append ( nonlinear_p ( T . dot ( w [ '' + str ( i ) ] , hidden_p [ - ] ) + T . dot ( w [ '' + str ( i ) ] , A ) ) ) if self . dropout : hidden_p [ - ] *= * ( rng . uniform ( size = hidden_p [ - ] . shape , dtype = '' ) > ) if self . type_px == '' : p = T . nnet . sigmoid ( T . dot ( w [ '' ] , hidden_p [ - ] ) + T . dot ( w [ '' ] , A ) ) _logpx = - T . nnet . binary_crossentropy ( p , x [ '' ] ) self . dist_px [ '' ] = theanofunc ( [ x [ '' ] , _z ] + [ A ] , p ) elif self . type_px == '' : x_mean = T . dot ( w [ '' ] , hidden_p [ - ] ) + T . dot ( w [ '' ] , A ) x_logvar = T . dot ( w [ '' ] , hidden_p [ - ] ) + T . dot ( w [ '' ] , A ) _logpx = ap . logpdfs . normal2 ( x [ '' ] , x_mean , x_logvar ) self . dist_px [ '' ] = theanofunc ( [ x [ '' ] , _z ] + [ A ] , [ x_mean , x_logvar ] ) elif self . type_px == '' : x_mean = T . dot ( w [ '' ] , hidden_p [ - ] ) + T . dot ( w [ '' ] , A ) x_logvar = T . dot ( w [ '' ] , hidden_p [ - ] ) + T . dot ( w [ '' ] , A ) _logpx = ap . logpdfs . laplace ( x [ '' ] , x_mean , x_logvar ) self . dist_px [ '' ] = theanofunc ( [ x [ '' ] , _z ] + [ A ] , [ x_mean , x_logvar ] ) else : raise Exception ( \"\" ) logpx = T . dot ( shared32 ( np . ones ( ( , self . n_x ) ) ) , _logpx ) if self . type_pz == '' : logpz = - * ( np . log ( * np . pi ) + ( q_mean ** + T . exp ( q_logvar ) ) ) . sum ( axis = , keepdims = True ) elif self . type_pz == '' : logpz = ap . logpdfs . standard_normal ( _z ) . sum ( axis = , keepdims = True ) elif self . type_pz == '' : pz = ", "answer": "for i in range ( self . n_mixture ) :"}, {"prompt": " \"\"\"\"\"\" class LineItem : def __init__ ( self , description , weight , price ) : self . description = description self . weight = weight self . price = price def subtotal ( self ) : return self . weight * self . price def get_weight ( self ) : return self . __weight ", "answer": "def set_weight ( self , value ) :"}, {"prompt": " import sys srfile = file ( sys . argv [ ] ) table = { } for line in srfile . xreadlines ( ) : clas , repl = line . split ( ) ", "answer": "if repl [ - ] not in '' :"}, {"prompt": " \"\"\"\"\"\" from django . test import TestCase ", "answer": "from . . widgets import ColorPickerWidget"}, {"prompt": " import matplotlib . delaunay as md from scipy import ndimage from pylab import * from numpy import * from PCV . geometry import homography def image_in_image ( im1 , im2 , tp ) : \"\"\"\"\"\" ", "answer": "m , n = im1 . shape [ : ]"}, {"prompt": " __version__ = '' ", "answer": "version = __version__"}, {"prompt": " from aliyunsdkcore . request import RpcRequest class DescribeServerCertificateRequest ( RpcRequest ) : def __init__ ( self ) : RpcRequest . __init__ ( self , '' , '' , '' ) ", "answer": "def get_OwnerId ( self ) :"}, {"prompt": " from less import LessException from less . settings import LESS_EXECUTABLE , LESS_ROOT , LESS_OUTPUT_DIR , LESS_OPTIONS from django . conf import settings import logging import urlparse import re import os import subprocess logger = logging . getLogger ( \"\" ) STATIC_URL = getattr ( settings , \"\" , getattr ( settings , \"\" ) ) class URLConverter ( object ) : URL_PATTERN = re . compile ( r'' ) def __init__ ( self , content , source_path ) : self . content = content self . source_dir = os . path . dirname ( source_path ) if not self . source_dir . endswith ( '' ) : self . source_dir = self . source_dir + '' def convert_url ( self , matchobj ) : url = matchobj . group ( ) url = url . strip ( '' ) if url . startswith ( ( '' , '' , '' , '' ) ) : return \"\" % url return \"\" % urlparse . urljoin ( self . source_dir , url ) def convert ( self ) : return self . URL_PATTERN . sub ( self . convert_url , self . content ) def compile_less ( input , output , less_path ) : less_root = os . path . join ( LESS_ROOT , LESS_OUTPUT_DIR ) if not os . path . exists ( less_root ) : os . makedirs ( less_root ) args = [ LESS_EXECUTABLE ] + LESS_OPTIONS + [ input ] popen_kwargs = dict ( stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) if os . name == \"\" : popen_kwargs [ \"\" ] = True p = subprocess . Popen ( args , ** popen_kwargs ) out , errors = p . communicate ( ) if errors : logger . error ( errors ) raise LessException ( errors ) output_directory = os . path . dirname ( output ) ", "answer": "if not os . path . exists ( output_directory ) :"}, {"prompt": " \"\"\"\"\"\" import argparse import collections import functools import logging import os import sys from six . moves import BaseHTTPServer from six . moves import http_client from six . moves import socketserver import OpenSSL from acme import challenges from acme import crypto_util logger = logging . getLogger ( __name__ ) class TLSServer ( socketserver . TCPServer ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : self . certs = kwargs . pop ( \"\" , { } ) self . method = kwargs . pop ( \"\" , crypto_util . _DEFAULT_TLSSNI01_SSL_METHOD ) self . allow_reuse_address = kwargs . pop ( \"\" , 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 ) : self . _wrap_sock ( ) return socketserver . TCPServer . server_bind ( self ) class ACMEServerMixin : \"\"\"\"\"\" server_version = \"\" allow_reuse_address = True class TLSSNI01Server ( TLSServer , ACMEServerMixin ) : \"\"\"\"\"\" def __init__ ( self , server_address , certs ) : TLSServer . __init__ ( self , server_address , BaseRequestHandlerWithLogging , certs = certs ) class BaseRequestHandlerWithLogging ( socketserver . BaseRequestHandler ) : \"\"\"\"\"\" def log_message ( self , format , * args ) : \"\"\"\"\"\" logger . debug ( \"\" , self . client_address [ ] , format % args ) def handle ( self ) : \"\"\"\"\"\" self . log_message ( \"\" ) socketserver . BaseRequestHandler . handle ( self ) class HTTP01Server ( BaseHTTPServer . HTTPServer , ACMEServerMixin ) : \"\"\"\"\"\" def __init__ ( self , server_address , resources ) : BaseHTTPServer . HTTPServer . __init__ ( self , server_address , HTTP01RequestHandler . partial_init ( simple_http_resources = resources ) ) class HTTP01RequestHandler ( BaseHTTPServer . BaseHTTPRequestHandler ) : \"\"\"\"\"\" HTTP01Resource = collections . namedtuple ( \"\" , \"\" ) def __init__ ( self , * args , ** kwargs ) : self . simple_http_resources = kwargs . pop ( \"\" , set ( ) ) socketserver . BaseRequestHandler . __init__ ( self , * args , ** kwargs ) def log_message ( self , format , * args ) : \"\"\"\"\"\" logger . debug ( \"\" , self . client_address [ ] , format % args ) def handle ( self ) : \"\"\"\"\"\" self . log_message ( \"\" ) BaseHTTPServer . BaseHTTPRequestHandler . handle ( self ) def do_GET ( self ) : if self . path == \"\" : self . handle_index ( ) elif self . path . startswith ( \"\" + challenges . HTTP01 . URI_ROOT_PATH ) : self . handle_simple_http_resource ( ) else : self . handle_404 ( ) def handle_index ( self ) : \"\"\"\"\"\" self . send_response ( ) self . send_header ( \"\" , \"\" ) self . end_headers ( ) self . wfile . write ( self . server . server_version . encode ( ) ) def handle_404 ( self ) : \"\"\"\"\"\" self . send_response ( http_client . NOT_FOUND , message = \"\" ) self . send_header ( \"\" , \"\" ) self . end_headers ( ) self . wfile . write ( b\"\" ) def handle_simple_http_resource ( self ) : \"\"\"\"\"\" for resource in self . simple_http_resources : if resource . chall . path == self . path : self . log_message ( \"\" , resource . chall . encode ( \"\" ) ) self . send_response ( http_client . OK ) self . end_headers ( ) self . wfile . write ( resource . validation . encode ( ) ) return else : self . log_message ( \"\" ) self . log_message ( \"\" , self . path ) @ classmethod def partial_init ( cls , simple_http_resources ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from crispy_forms . bootstrap import ( Accordion , AccordionGroup , FieldWithButtons , StrictButton , Tab ) from crispy_forms . layout import Field , HTML , Layout from crispy_forms . helper import FormHelper from django . utils . translation import ugettext_lazy as _ from haystack . forms import ModelSearchForm class SearchForm ( ModelSearchForm ) : def _wrap_all ( self ) : self . helper . filter ( str , max_level = ) . wrap ( Field , css_class = \"\" ) def __init__ ( self , * args , ** kwargs ) : super ( SearchForm , self ) . __init__ ( * args , ** kwargs ) self . helper = FormHelper ( self ) self . helper . form_tag = False self . helper . layout = Layout ( ", "answer": "Accordion ("}, {"prompt": " \"\"\"\"\"\" import logging import sys from mistralclient . api import client import mistralclient . commands . v2 . action_executions import mistralclient . commands . v2 . actions import mistralclient . commands . v2 . cron_triggers import mistralclient . commands . v2 . environments import mistralclient . commands . v2 . executions import mistralclient . commands . v2 . members import mistralclient . commands . v2 . services import mistralclient . commands . v2 . tasks import mistralclient . commands . v2 . workbooks import mistralclient . commands . v2 . workflows from mistralclient . openstack . common import cliutils as c from cliff import app from cliff import command from cliff import commandmanager import argparse LOG = logging . getLogger ( __name__ ) class OpenStackHelpFormatter ( argparse . HelpFormatter ) : def __init__ ( self , prog , indent_increment = , max_help_position = , width = None ) : super ( OpenStackHelpFormatter , self ) . __init__ ( prog , indent_increment , max_help_position , width ) def start_section ( self , heading ) : heading = '' % ( heading [ ] . upper ( ) , heading [ : ] ) super ( OpenStackHelpFormatter , self ) . start_section ( heading ) class HelpAction ( argparse . Action ) : \"\"\"\"\"\" def __call__ ( self , parser , namespace , values , option_string = None ) : outputs = [ ] max_len = app = self . default parser . print_help ( app . stdout ) app . stdout . write ( '' ) for name , ep in sorted ( app . command_manager ) : factory = ep . load ( ) cmd = factory ( self , None ) one_liner = cmd . get_description ( ) . split ( '' ) [ ] outputs . append ( ( name , one_liner ) ) max_len = max ( len ( name ) , max_len ) for ( name , one_liner ) in outputs : app . stdout . write ( '' % ( name . ljust ( max_len ) , one_liner ) ) sys . exit ( ) class BashCompletionCommand ( command . Command ) : \"\"\"\"\"\" def take_action ( self , parsed_args ) : commands = set ( ) options = set ( ) for option , _action in self . app . parser . _option_string_actions . items ( ) : options . add ( option ) for command_name , _cmd in self . app . command_manager : commands . add ( command_name ) print ( '' . join ( commands | options ) ) class MistralShell ( app . App ) : def __init__ ( self ) : super ( MistralShell , self ) . __init__ ( description = __doc__ . strip ( ) , version = mistralclient . __version__ , command_manager = commandmanager . CommandManager ( '' ) , ) self . _set_shell_commands ( self . _get_commands_v2 ( ) ) def configure_logging ( self ) : log_lvl = logging . DEBUG if self . options . debug else logging . WARNING logging . basicConfig ( format = \"\" , level = log_lvl ) logging . getLogger ( '' ) . setLevel ( logging . WARNING ) if self . options . verbose_level <= : logging . getLogger ( '' ) . setLevel ( logging . WARNING ) def build_option_parser ( self , description , version , argparse_kwargs = None ) : \"\"\"\"\"\" argparse_kwargs = argparse_kwargs or { } parser = argparse . ArgumentParser ( description = description , add_help = False , formatter_class = OpenStackHelpFormatter , ** argparse_kwargs ) parser . add_argument ( '' , action = '' , version = '' . format ( version ) , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , default = self . DEFAULT_VERBOSE_LEVEL , help = '' , ) parser . add_argument ( '' , action = '' , default = None , help = '' , ) parser . add_argument ( '' , '' , action = '' , dest = '' , const = , help = '' , ) parser . add_argument ( '' , '' , action = HelpAction , nargs = , default = self , help = \"\" , ) parser . add_argument ( '' , default = False , action = '' , help = '' , ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' ) , help = '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' , default = '' ) , help = '' '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' , default = '' ) , help = '' '' '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' , default = '' ) , help = '' '' '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' , default = '' ) , help = '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' ) , help = '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' ) , help = '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' , '' ) , help = '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' ) , help = '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' ) , help = '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' ) , help = '' ) parser . add_argument ( '' , action = '' , dest = '' , default = c . env ( '' , default = False ) , help = '' '' ) return parser def initialize_app ( self , argv ) : self . _clear_shell_commands ( ) ver = client . determine_client_version ( self . options . mistral_version ) self . _set_shell_commands ( self . _get_commands ( ver ) ) do_help = ( '' in argv ) or ( '' in argv ) or not argv if not self . options . auth_url : if self . options . password or self . options . token : self . options . auth_url = '' if do_help or ( '' in argv ) : self . options . auth_url = None self . client = client . client ( mistral_url = self . options . mistral_url , username = self . options . username , api_key = self . options . password , project_name = self . options . tenant_name , auth_url = self . options . auth_url , project_id = self . options . tenant_id , endpoint_type = self . options . endpoint_type , service_type = self . options . service_type , auth_token = self . options . token , cacert = self . options . cacert , insecure = self . options . insecure ) ClientManager = type ( '' , ( object , ) , dict ( workflow_engine = self . client ) ) self . client_manager = ClientManager ( ) def _set_shell_commands ( self , cmds_dict ) : for k , v in cmds_dict . items ( ) : self . command_manager . add_command ( k , v ) def _clear_shell_commands ( self ) : exclude_cmds = [ '' , '' ] cmds = self . command_manager . commands . copy ( ) for k , v in cmds . items ( ) : if k not in exclude_cmds : self . command_manager . commands . pop ( k ) def _get_commands ( self , version ) : if version == : return self . _get_commands_v2 ( ) return { } @ staticmethod def _get_commands_v2 ( ) : return { '' : BashCompletionCommand , '' : mistralclient . commands . v2 . workbooks . List , '' : mistralclient . commands . v2 . workbooks . Get , '' : mistralclient . commands . v2 . workbooks . Create , '' : mistralclient . commands . v2 . workbooks . Delete , ", "answer": "'' : mistralclient . commands . v2 . workbooks . Update ,"}, {"prompt": " from __future__ import unicode_literals ", "answer": "from django . utils . encoding import python_2_unicode_compatible"}, {"prompt": " \"\"\"\"\"\" from ironic . common import exception from ironic . tests . unit . db import base from ironic . tests . unit . db import utils as db_utils class DbNodeTagTestCase ( base . DbTestCase ) : def setUp ( self ) : super ( DbNodeTagTestCase , self ) . setUp ( ) self . node = db_utils . create_test_node ( ) def test_set_node_tags ( self ) : tags = self . dbapi . set_node_tags ( self . node . id , [ '' , '' ] ) self . assertEqual ( self . node . id , tags [ ] . node_id ) self . assertItemsEqual ( [ '' , '' ] , [ tag . tag for tag in tags ] ) tags = self . dbapi . set_node_tags ( self . node . id , [ ] ) self . assertEqual ( [ ] , tags ) def test_set_node_tags_duplicate ( self ) : tags = self . dbapi . set_node_tags ( self . node . id , [ '' , '' , '' ] ) self . assertEqual ( self . node . id , tags [ ] . node_id ) self . assertItemsEqual ( [ '' , '' ] , [ tag . tag for tag in tags ] ) def test_set_node_tags_node_not_exist ( self ) : self . assertRaises ( exception . NodeNotFound , self . dbapi . set_node_tags , '' , [ '' , '' ] ) def test_get_node_tags_by_node_id ( self ) : self . dbapi . set_node_tags ( self . node . id , [ '' , '' ] ) tags = self . dbapi . get_node_tags_by_node_id ( self . node . id ) self . assertEqual ( self . node . id , tags [ ] . node_id ) self . assertItemsEqual ( [ '' , '' ] , [ tag . tag for tag in tags ] ) def test_get_node_tags_empty ( self ) : tags = self . dbapi . get_node_tags_by_node_id ( self . node . id ) self . assertEqual ( [ ] , tags ) def test_get_node_tags_node_not_exist ( self ) : self . assertRaises ( exception . NodeNotFound , self . dbapi . get_node_tags_by_node_id , '' ) def test_unset_node_tags ( self ) : self . dbapi . set_node_tags ( self . node . id , [ '' , '' ] ) self . dbapi . unset_node_tags ( self . node . id ) tags = self . dbapi . get_node_tags_by_node_id ( self . node . id ) self . assertEqual ( [ ] , tags ) def test_unset_empty_node_tags ( self ) : self . dbapi . unset_node_tags ( self . node . id ) tags = self . dbapi . get_node_tags_by_node_id ( self . node . id ) self . assertEqual ( [ ] , tags ) def test_unset_node_tags_node_not_exist ( self ) : self . assertRaises ( exception . NodeNotFound , self . dbapi . unset_node_tags , '' ) def test_add_node_tag ( self ) : tag = self . dbapi . add_node_tag ( self . node . id , '' ) self . assertEqual ( self . node . id , tag . node_id ) self . assertEqual ( '' , tag . tag ) def test_add_node_tag_duplicate ( self ) : tag = self . dbapi . add_node_tag ( self . node . id , '' ) tag = self . dbapi . add_node_tag ( self . node . id , '' ) self . assertEqual ( self . node . id , tag . node_id ) self . assertEqual ( '' , tag . tag ) def test_add_node_tag_node_not_exist ( self ) : self . assertRaises ( exception . NodeNotFound , self . dbapi . add_node_tag , '' , '' ) def test_delete_node_tag ( self ) : self . dbapi . set_node_tags ( self . node . id , [ '' , '' ] ) self . dbapi . delete_node_tag ( self . node . id , '' ) tags = self . dbapi . get_node_tags_by_node_id ( self . node . id ) self . assertEqual ( , len ( tags ) ) self . assertEqual ( '' , tags [ ] . tag ) ", "answer": "def test_delete_node_tag_not_found ( self ) :"}, {"prompt": " \"\"\"\"\"\" from googleads import dfp def main ( client ) : premium_rate_service = client . GetService ( '' , version = '' ) statement = dfp . FilterStatement ( '' ) while True : response = premium_rate_service . getPremiumRatesByStatement ( ", "answer": "statement . ToStatement ( ) )"}, {"prompt": " import os import re import socket import sys import time from optparse import make_option from django . conf import settings from django . core . management . base import BaseCommand , CommandError from django_extensions . management . utils import setup_logger , RedirectHandler , signalcommand from django_extensions . management . technical_response import null_technical_500_response try : if '' in settings . INSTALLED_APPS : from django . contrib . staticfiles . handlers import StaticFilesHandler USE_STATICFILES = True elif '' in settings . INSTALLED_APPS : from staticfiles . handlers import StaticFilesHandler USE_STATICFILES = True else : USE_STATICFILES = False except ImportError : USE_STATICFILES = False naiveip_re = re . compile ( r\"\"\"\"\"\" , re . X ) DEFAULT_PORT = \"\" import logging logger = logging . getLogger ( __name__ ) class Command ( BaseCommand ) : option_list = BaseCommand . option_list + ( make_option ( '' , '' , action = '' , dest = '' , default = False , help = '' ) , make_option ( '' , action = '' , dest = '' , default = True , help = '' ) , make_option ( '' , action = '' , dest = '' , help = '' ) , make_option ( '' , dest = '' , default = '' , help = '' ) , make_option ( '' , action = '' , dest = '' , help = '' ) , make_option ( '' , action = '' , dest = '' , help = '' ) , make_option ( '' , dest = '' , default = None , help = '' ) , make_option ( '' , action = '' , default = False , help = \"\" ) , make_option ( '' , dest = '' , action = \"\" , type = \"\" , help = '' ) , ) if USE_STATICFILES : option_list += ( make_option ( '' , action = \"\" , dest = '' , default = True , help = '' ) , make_option ( '' , action = \"\" , dest = '' , default = False , help = '' ) , ) help = \"\" args = '' requires_model_validation = False @ signalcommand def handle ( self , addrport = '' , * args , ** options ) : import django if hasattr ( self . stderr , '' ) : self . stderr . ending = None setup_logger ( logger , self . stderr , filename = options . get ( '' , None ) ) logredirect = RedirectHandler ( __name__ ) werklogger = logging . getLogger ( '' ) werklogger . setLevel ( logging . INFO ) werklogger . addHandler ( logredirect ) werklogger . propagate = False if options . get ( \"\" , False ) : try : from django . db . backends import utils except ImportError : from django . db . backends import util as utils try : import sqlparse except ImportError : sqlparse = None class PrintQueryWrapper ( utils . CursorDebugWrapper ) : def execute ( self , sql , params = ( ) ) : starttime = time . time ( ) try : return self . cursor . execute ( sql , params ) finally : raw_sql = self . db . ops . last_executed_query ( self . cursor , sql , params ) execution_time = time . time ( ) - starttime therest = '' % ( execution_time , self . db . alias ) if sqlparse : logger . info ( sqlparse . format ( raw_sql , reindent = True ) + therest ) else : logger . info ( raw_sql + therest ) utils . CursorDebugWrapper = PrintQueryWrapper try : from django . core . servers . basehttp import AdminMediaHandler USE_ADMINMEDIAHANDLER = True except ImportError : USE_ADMINMEDIAHANDLER = False try : from django . core . servers . basehttp import get_internal_wsgi_application as WSGIHandler except ImportError : from django . core . handlers . wsgi import WSGIHandler try : from werkzeug import run_simple , DebuggedApplication if settings . DEBUG : try : set_werkzeug_log_color ( ) except : print ( \"\" ) pass except ImportError : raise CommandError ( \"\" ) from django . views import debug debug . technical_500_response = null_technical_500_response self . use_ipv6 = options . get ( '' ) if self . use_ipv6 and not socket . has_ipv6 : raise CommandError ( '' ) self . _raw_ipv6 = False if not addrport : try : addrport = settings . RUNSERVERPLUS_SERVER_ADDRESS_PORT except AttributeError : pass if not addrport : self . addr = '' self . port = DEFAULT_PORT else : m = re . match ( naiveip_re , addrport ) if m is None : raise CommandError ( '' '' % addrport ) self . addr , _ipv4 , _ipv6 , _fqdn , self . port = m . groups ( ) if not self . port . isdigit ( ) : raise CommandError ( \"\" % self . port ) if self . addr : if _ipv6 : self . addr = self . addr [ : - ] self . use_ipv6 = True self . _raw_ipv6 = True elif self . use_ipv6 and not _fqdn : raise CommandError ( '' % self . addr ) if not self . addr : self . addr = '' if self . use_ipv6 else '' threaded = options . get ( '' , True ) use_reloader = options . get ( '' , True ) open_browser = options . get ( '' , False ) cert_path = options . get ( \"\" ) quit_command = ( sys . platform == '' ) and '' or '' bind_url = \"\" % ( self . addr if not self . _raw_ipv6 else '' % self . addr , self . port ) def inner_run ( ) : print ( \"\" ) self . validate ( display_num_errors = True ) print ( \"\" % ( django . get_version ( ) , settings . SETTINGS_MODULE ) ) print ( \"\" % ( bind_url , ) ) print ( \"\" ) print ( \"\" % quit_command ) path = options . get ( '' , '' ) if not path : admin_media_path = os . path . join ( django . __path__ [ ] , '' ) if os . path . isdir ( admin_media_path ) : path = admin_media_path else : path = os . path . join ( django . __path__ [ ] , '' ) handler = WSGIHandler ( ) if USE_ADMINMEDIAHANDLER : handler = AdminMediaHandler ( handler , path ) if USE_STATICFILES : use_static_handler = options . get ( '' , True ) insecure_serving = options . get ( '' , False ) if use_static_handler and ( settings . DEBUG or insecure_serving ) : handler = StaticFilesHandler ( handler ) if open_browser : import webbrowser webbrowser . open ( bind_url ) if cert_path : \"\"\"\"\"\" try : import OpenSSL except ImportError : raise CommandError ( \"\" \"\" \"\" ) dir_path , cert_file = os . path . split ( cert_path ) if not dir_path : dir_path = os . getcwd ( ) root , ext = os . path . splitext ( cert_file ) certfile = os . path . join ( dir_path , root + \"\" ) keyfile = os . path . join ( dir_path , root + \"\" ) try : from werkzeug . serving import make_ssl_devcert if os . path . exists ( certfile ) and os . path . exists ( keyfile ) : ssl_context = ( certfile , keyfile ) else : ssl_context = make_ssl_devcert ( os . path . join ( dir_path , root ) , host = '' ) except ImportError : print ( \"\" ) ssl_context = \"\" else : ssl_context = None run_simple ( self . addr , int ( self . port ) , DebuggedApplication ( handler , True ) , use_reloader = use_reloader , use_debugger = True , threaded = threaded , ssl_context = ssl_context ) inner_run ( ) def set_werkzeug_log_color ( ) : \"\"\"\"\"\" from django . core . management . color import color_style from werkzeug . serving import WSGIRequestHandler from werkzeug . _internal import _log _style = color_style ( ) _orig_log = WSGIRequestHandler . log def werk_log ( self , type , message , * args ) : try : msg = '' % ( self . address_string ( ) , self . log_date_time_string ( ) , message % args , ) http_code = str ( args [ ] ) except : return _orig_log ( type , message , * args ) if http_code [ ] == '' : msg = _style . HTTP_SUCCESS ( msg ) elif http_code [ ] == '' : msg = _style . HTTP_INFO ( msg ) elif http_code == '' : ", "answer": "msg = _style . HTTP_NOT_MODIFIED ( msg )"}, {"prompt": " \"\"\"\"\"\" import io import os import shutil from freezer . storage import fslike from freezer . utils import utils class LocalStorage ( fslike . FsLikeStorage ) : def get_file ( self , from_path , to_path ) : shutil . copyfile ( from_path , to_path ) def put_file ( self , from_path , to_path ) : shutil . copyfile ( from_path , to_path ) def listdir ( self , directory ) : return os . listdir ( directory ) ", "answer": "def create_dirs ( self , path ) :"}, {"prompt": " import vstruct from vstruct . primitives import * DEVICE_RELATION_TYPE = v_enum ( ) DEVICE_RELATION_TYPE . BusRelations = DEVICE_RELATION_TYPE . EjectionRelations = DEVICE_RELATION_TYPE . PowerRelations = DEVICE_RELATION_TYPE . RemovalRelations = DEVICE_RELATION_TYPE . TargetDeviceRelation = DEVICE_RELATION_TYPE . SingleBusRelations = IO_ALLOCATION_ACTION = v_enum ( ) IO_ALLOCATION_ACTION . KeepObject = IO_ALLOCATION_ACTION . DeallocateObject = IO_ALLOCATION_ACTION . DeallocateObjectKeepRegisters = BUS_QUERY_ID_TYPE = v_enum ( ) BUS_QUERY_ID_TYPE . BusQueryDeviceID = BUS_QUERY_ID_TYPE . BusQueryHardwareIDs = BUS_QUERY_ID_TYPE . BusQueryCompatibleIDs = BUS_QUERY_ID_TYPE . BusQueryInstanceID = BUS_QUERY_ID_TYPE . BusQueryDeviceSerialNumber = NT_PRODUCT_TYPE = v_enum ( ) NT_PRODUCT_TYPE . NtProductWinNt = NT_PRODUCT_TYPE . NtProductLanManNt = NT_PRODUCT_TYPE . NtProductServer = DEVICE_POWER_STATE = v_enum ( ) DEVICE_POWER_STATE . PowerDeviceUnspecified = DEVICE_POWER_STATE . PowerDeviceD0 = DEVICE_POWER_STATE . PowerDeviceD1 = DEVICE_POWER_STATE . PowerDeviceD2 = DEVICE_POWER_STATE . PowerDeviceD3 = DEVICE_POWER_STATE . PowerDeviceMaximum = KSPIN_LOCK_QUEUE_NUMBER = v_enum ( ) KSPIN_LOCK_QUEUE_NUMBER . LockQueueDispatcherLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueContextSwapLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueuePfnLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueSystemSpaceLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueVacbLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueMasterLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueNonPagedPoolLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueIoCancelLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueWorkQueueLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueIoVpbLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueIoDatabaseLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueIoCompletionLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueNtfsStructLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueAfdWorkQueueLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueBcbLock = KSPIN_LOCK_QUEUE_NUMBER . LockQueueMaximumLock = FSINFOCLASS = v_enum ( ) FSINFOCLASS . FileFsVolumeInformation = FSINFOCLASS . FileFsLabelInformation = FSINFOCLASS . FileFsSizeInformation = FSINFOCLASS . FileFsDeviceInformation = FSINFOCLASS . FileFsAttributeInformation = FSINFOCLASS . FileFsControlInformation = FSINFOCLASS . FileFsFullSizeInformation = FSINFOCLASS . FileFsObjectIdInformation = FSINFOCLASS . FileFsDriverPathInformation = FSINFOCLASS . FileFsMaximumInformation = POOL_TYPE = v_enum ( ) POOL_TYPE . NonPagedPool = POOL_TYPE . PagedPool = POOL_TYPE . NonPagedPoolMustSucceed = POOL_TYPE . DontUseThisType = POOL_TYPE . NonPagedPoolCacheAligned = POOL_TYPE . PagedPoolCacheAligned = POOL_TYPE . NonPagedPoolCacheAlignedMustS = POOL_TYPE . MaxPoolType = POOL_TYPE . NonPagedPoolSession = POOL_TYPE . PagedPoolSession = POOL_TYPE . NonPagedPoolMustSucceedSession = POOL_TYPE . DontUseThisTypeSession = POOL_TYPE . NonPagedPoolCacheAlignedSession = POOL_TYPE . PagedPoolCacheAlignedSession = POOL_TYPE . NonPagedPoolCacheAlignedMustSSession = MODE = v_enum ( ) MODE . KernelMode = MODE . UserMode = MODE . MaximumMode = FS_FILTER_SECTION_SYNC_TYPE = v_enum ( ) FS_FILTER_SECTION_SYNC_TYPE . SyncTypeOther = FS_FILTER_SECTION_SYNC_TYPE . SyncTypeCreateSection = OB_OPEN_REASON = v_enum ( ) OB_OPEN_REASON . ObCreateHandle = OB_OPEN_REASON . ObOpenHandle = OB_OPEN_REASON . ObDuplicateHandle = OB_OPEN_REASON . ObInheritHandle = OB_OPEN_REASON . ObMaxOpenReason = DEVICE_TEXT_TYPE = v_enum ( ) DEVICE_TEXT_TYPE . DeviceTextDescription = DEVICE_TEXT_TYPE . DeviceTextLocationInformation = POWER_STATE_TYPE = v_enum ( ) POWER_STATE_TYPE . SystemPowerState = POWER_STATE_TYPE . DevicePowerState = FILE_INFORMATION_CLASS = v_enum ( ) FILE_INFORMATION_CLASS . FileDirectoryInformation = FILE_INFORMATION_CLASS . FileFullDirectoryInformation = FILE_INFORMATION_CLASS . FileBothDirectoryInformation = FILE_INFORMATION_CLASS . FileBasicInformation = FILE_INFORMATION_CLASS . FileStandardInformation = FILE_INFORMATION_CLASS . FileInternalInformation = FILE_INFORMATION_CLASS . FileEaInformation = FILE_INFORMATION_CLASS . FileAccessInformation = FILE_INFORMATION_CLASS . FileNameInformation = FILE_INFORMATION_CLASS . FileRenameInformation = FILE_INFORMATION_CLASS . FileLinkInformation = FILE_INFORMATION_CLASS . FileNamesInformation = FILE_INFORMATION_CLASS . FileDispositionInformation = FILE_INFORMATION_CLASS . FilePositionInformation = FILE_INFORMATION_CLASS . FileFullEaInformation = FILE_INFORMATION_CLASS . FileModeInformation = FILE_INFORMATION_CLASS . FileAlignmentInformation = FILE_INFORMATION_CLASS . FileAllInformation = FILE_INFORMATION_CLASS . FileAllocationInformation = FILE_INFORMATION_CLASS . FileEndOfFileInformation = FILE_INFORMATION_CLASS . FileAlternateNameInformation = FILE_INFORMATION_CLASS . FileStreamInformation = FILE_INFORMATION_CLASS . FilePipeInformation = FILE_INFORMATION_CLASS . FilePipeLocalInformation = FILE_INFORMATION_CLASS . FilePipeRemoteInformation = FILE_INFORMATION_CLASS . FileMailslotQueryInformation = FILE_INFORMATION_CLASS . FileMailslotSetInformation = FILE_INFORMATION_CLASS . FileCompressionInformation = FILE_INFORMATION_CLASS . FileObjectIdInformation = FILE_INFORMATION_CLASS . FileCompletionInformation = FILE_INFORMATION_CLASS . FileMoveClusterInformation = FILE_INFORMATION_CLASS . FileQuotaInformation = FILE_INFORMATION_CLASS . FileReparsePointInformation = FILE_INFORMATION_CLASS . FileNetworkOpenInformation = FILE_INFORMATION_CLASS . FileAttributeTagInformation = FILE_INFORMATION_CLASS . FileTrackingInformation = FILE_INFORMATION_CLASS . FileIdBothDirectoryInformation = FILE_INFORMATION_CLASS . FileIdFullDirectoryInformation = FILE_INFORMATION_CLASS . FileValidDataLengthInformation = FILE_INFORMATION_CLASS . FileShortNameInformation = FILE_INFORMATION_CLASS . FileMaximumInformation = EXCEPTION_DISPOSITION = v_enum ( ) EXCEPTION_DISPOSITION . ExceptionContinueExecution = EXCEPTION_DISPOSITION . ExceptionContinueSearch = EXCEPTION_DISPOSITION . ExceptionNestedException = EXCEPTION_DISPOSITION . ExceptionCollidedUnwind = PF_SCENARIO_TYPE = v_enum ( ) PF_SCENARIO_TYPE . PfApplicationLaunchScenarioType = PF_SCENARIO_TYPE . PfSystemBootScenarioType = PF_SCENARIO_TYPE . PfMaxScenarioType = SECURITY_OPERATION_CODE = v_enum ( ) SECURITY_OPERATION_CODE . SetSecurityDescriptor = SECURITY_OPERATION_CODE . QuerySecurityDescriptor = SECURITY_OPERATION_CODE . DeleteSecurityDescriptor = SECURITY_OPERATION_CODE . AssignSecurityDescriptor = PP_NPAGED_LOOKASIDE_NUMBER = v_enum ( ) PP_NPAGED_LOOKASIDE_NUMBER . LookasideSmallIrpList = PP_NPAGED_LOOKASIDE_NUMBER . LookasideLargeIrpList = PP_NPAGED_LOOKASIDE_NUMBER . LookasideMdlList = PP_NPAGED_LOOKASIDE_NUMBER . LookasideCreateInfoList = PP_NPAGED_LOOKASIDE_NUMBER . LookasideNameBufferList = PP_NPAGED_LOOKASIDE_NUMBER . LookasideTwilightList = PP_NPAGED_LOOKASIDE_NUMBER . LookasideCompletionList = PP_NPAGED_LOOKASIDE_NUMBER . LookasideMaximumList = SECURITY_IMPERSONATION_LEVEL = v_enum ( ) SECURITY_IMPERSONATION_LEVEL . SecurityAnonymous = SECURITY_IMPERSONATION_LEVEL . SecurityIdentification = SECURITY_IMPERSONATION_LEVEL . SecurityImpersonation = SECURITY_IMPERSONATION_LEVEL . SecurityDelegation = DEVICE_USAGE_NOTIFICATION_TYPE = v_enum ( ) DEVICE_USAGE_NOTIFICATION_TYPE . DeviceUsageTypeUndefined = DEVICE_USAGE_NOTIFICATION_TYPE . DeviceUsageTypePaging = DEVICE_USAGE_NOTIFICATION_TYPE . DeviceUsageTypeHibernation = DEVICE_USAGE_NOTIFICATION_TYPE . DeviceUsageTypeDumpFile = INTERFACE_TYPE = v_enum ( ) INTERFACE_TYPE . InterfaceTypeUndefined = - INTERFACE_TYPE . Internal = INTERFACE_TYPE . Isa = INTERFACE_TYPE . Eisa = INTERFACE_TYPE . MicroChannel = INTERFACE_TYPE . TurboChannel = INTERFACE_TYPE . PCIBus = INTERFACE_TYPE . VMEBus = INTERFACE_TYPE . NuBus = INTERFACE_TYPE . PCMCIABus = INTERFACE_TYPE . CBus = INTERFACE_TYPE . MPIBus = INTERFACE_TYPE . MPSABus = INTERFACE_TYPE . ProcessorInternal = INTERFACE_TYPE . InternalPowerBus = INTERFACE_TYPE . PNPISABus = INTERFACE_TYPE . PNPBus = INTERFACE_TYPE . MaximumInterfaceType = KWAIT_REASON = v_enum ( ) KWAIT_REASON . Executive = KWAIT_REASON . FreePage = KWAIT_REASON . PageIn = KWAIT_REASON . PoolAllocation = KWAIT_REASON . DelayExecution = KWAIT_REASON . Suspended = KWAIT_REASON . UserRequest = KWAIT_REASON . WrExecutive = KWAIT_REASON . WrFreePage = KWAIT_REASON . WrPageIn = KWAIT_REASON . WrPoolAllocation = KWAIT_REASON . WrDelayExecution = KWAIT_REASON . WrSuspended = KWAIT_REASON . WrUserRequest = KWAIT_REASON . WrEventPair = KWAIT_REASON . WrQueue = KWAIT_REASON . WrLpcReceive = KWAIT_REASON . WrLpcReply = KWAIT_REASON . WrVirtualMemory = KWAIT_REASON . WrPageOut = KWAIT_REASON . WrRendezvous = KWAIT_REASON . Spare2 = KWAIT_REASON . Spare3 = KWAIT_REASON . Spare4 = KWAIT_REASON . Spare5 = KWAIT_REASON . Spare6 = KWAIT_REASON . WrKernel = KWAIT_REASON . MaximumWaitReason = ALTERNATIVE_ARCHITECTURE_TYPE = v_enum ( ) ALTERNATIVE_ARCHITECTURE_TYPE . StandardDesign = ALTERNATIVE_ARCHITECTURE_TYPE . NEC98x86 = ALTERNATIVE_ARCHITECTURE_TYPE . EndAlternatives = MEMORY_TYPE = v_enum ( ) MEMORY_TYPE . MemoryExceptionBlock = MEMORY_TYPE . MemorySystemBlock = MEMORY_TYPE . MemoryFree = MEMORY_TYPE . MemoryBad = MEMORY_TYPE . MemoryLoadedProgram = MEMORY_TYPE . MemoryFirmwareTemporary = MEMORY_TYPE . MemoryFirmwarePermanent = MEMORY_TYPE . MemoryFreeContiguous = MEMORY_TYPE . MemorySpecialMemory = MEMORY_TYPE . MemoryMaximum = PS_QUOTA_TYPE = v_enum ( ) PS_QUOTA_TYPE . PsNonPagedPool = PS_QUOTA_TYPE . PsPagedPool = PS_QUOTA_TYPE . PsPageFile = PS_QUOTA_TYPE . PsQuotaTypes = ReplacesCorHdrNumericDefines = v_enum ( ) ReplacesCorHdrNumericDefines . COMIMAGE_FLAGS_ILONLY = ReplacesCorHdrNumericDefines . COMIMAGE_FLAGS_32BITREQUIRED = ReplacesCorHdrNumericDefines . COMIMAGE_FLAGS_IL_LIBRARY = ReplacesCorHdrNumericDefines . COMIMAGE_FLAGS_STRONGNAMESIGNED = ReplacesCorHdrNumericDefines . COMIMAGE_FLAGS_TRACKDEBUGDATA = ReplacesCorHdrNumericDefines . COR_VERSION_MAJOR_V2 = ReplacesCorHdrNumericDefines . COR_VERSION_MAJOR = ReplacesCorHdrNumericDefines . COR_VERSION_MINOR = ReplacesCorHdrNumericDefines . COR_DELETED_NAME_LENGTH = ReplacesCorHdrNumericDefines . COR_VTABLEGAP_NAME_LENGTH = ReplacesCorHdrNumericDefines . NATIVE_TYPE_MAX_CB = ReplacesCorHdrNumericDefines . COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = ReplacesCorHdrNumericDefines . IMAGE_COR_MIH_METHODRVA = ReplacesCorHdrNumericDefines . IMAGE_COR_MIH_EHRVA = ReplacesCorHdrNumericDefines . IMAGE_COR_MIH_BASICBLOCK = ReplacesCorHdrNumericDefines . COR_VTABLE_32BIT = ReplacesCorHdrNumericDefines . COR_VTABLE_64BIT = ReplacesCorHdrNumericDefines . COR_VTABLE_FROM_UNMANAGED = ReplacesCorHdrNumericDefines . COR_VTABLE_CALL_MOST_DERIVED = ReplacesCorHdrNumericDefines . IMAGE_COR_EATJ_THUNK_SIZE = ReplacesCorHdrNumericDefines . MAX_CLASS_NAME = ReplacesCorHdrNumericDefines . MAX_PACKAGE_NAME = SYSTEM_POWER_STATE = v_enum ( ) SYSTEM_POWER_STATE . PowerSystemUnspecified = SYSTEM_POWER_STATE . PowerSystemWorking = SYSTEM_POWER_STATE . PowerSystemSleeping1 = SYSTEM_POWER_STATE . PowerSystemSleeping2 = SYSTEM_POWER_STATE . PowerSystemSleeping3 = SYSTEM_POWER_STATE . PowerSystemHibernate = SYSTEM_POWER_STATE . PowerSystemShutdown = SYSTEM_POWER_STATE . PowerSystemMaximum = MEMORY_CACHING_TYPE_ORIG = v_enum ( ) MEMORY_CACHING_TYPE_ORIG . MmFrameBufferCached = POWER_ACTION = v_enum ( ) POWER_ACTION . PowerActionNone = POWER_ACTION . PowerActionReserved = POWER_ACTION . PowerActionSleep = POWER_ACTION . PowerActionHibernate = POWER_ACTION . PowerActionShutdown = POWER_ACTION . PowerActionShutdownReset = POWER_ACTION . PowerActionShutdownOff = POWER_ACTION . PowerActionWarmEject = class _unnamed_5821 ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . MinimumChannel = v_uint32 ( ) self . MaximumChannel = v_uint32 ( ) class KEXECUTE_OPTIONS ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . ExecuteDisable = v_uint8 ( ) class _unnamed_5824 ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . Data = vstruct . VArray ( [ v_uint32 ( ) for i in xrange ( ) ] ) class _unnamed_5826 ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . Length = v_uint32 ( ) self . MinBusNumber = v_uint32 ( ) self . MaxBusNumber = v_uint32 ( ) self . Reserved = v_uint32 ( ) class KPRCB ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . MinorVersion = v_uint16 ( ) self . MajorVersion = v_uint16 ( ) self . CurrentThread = v_ptr32 ( ) self . NextThread = v_ptr32 ( ) self . IdleThread = v_ptr32 ( ) self . Number = v_uint8 ( ) self . Reserved = v_uint8 ( ) self . BuildType = v_uint16 ( ) self . SetMember = v_uint32 ( ) self . CpuType = v_uint8 ( ) self . CpuID = v_uint8 ( ) self . CpuStep = v_uint16 ( ) self . ProcessorState = KPROCESSOR_STATE ( ) self . KernelReserved = vstruct . VArray ( [ v_uint32 ( ) for i in xrange ( ) ] ) self . HalReserved = vstruct . VArray ( [ v_uint32 ( ) for i in xrange ( ) ] ) self . PrcbPad0 = vstruct . VArray ( [ v_uint8 ( ) for i in xrange ( ) ] ) self . LockQueue = vstruct . VArray ( [ KSPIN_LOCK_QUEUE ( ) for i in xrange ( ) ] ) self . PrcbPad1 = vstruct . VArray ( [ v_uint8 ( ) for i in xrange ( ) ] ) self . NpxThread = v_ptr32 ( ) self . InterruptCount = v_uint32 ( ) self . KernelTime = v_uint32 ( ) self . UserTime = v_uint32 ( ) self . DpcTime = v_uint32 ( ) self . DebugDpcTime = v_uint32 ( ) self . InterruptTime = v_uint32 ( ) self . AdjustDpcThreshold = v_uint32 ( ) self . PageColor = v_uint32 ( ) self . SkipTick = v_uint32 ( ) self . MultiThreadSetBusy = v_uint8 ( ) self . Spare2 = vstruct . VArray ( [ v_uint8 ( ) for i in xrange ( ) ] ) self . ParentNode = v_ptr32 ( ) self . MultiThreadProcessorSet = v_uint32 ( ) self . MultiThreadSetMaster = v_ptr32 ( ) self . ThreadStartCount = vstruct . VArray ( [ v_uint32 ( ) for i in xrange ( ) ] ) self . CcFastReadNoWait = v_uint32 ( ) self . CcFastReadWait = v_uint32 ( ) self . CcFastReadNotPossible = v_uint32 ( ) self . CcCopyReadNoWait = v_uint32 ( ) self . CcCopyReadWait = v_uint32 ( ) self . CcCopyReadNoWaitMiss = v_uint32 ( ) self . KeAlignmentFixupCount = v_uint32 ( ) self . KeContextSwitches = v_uint32 ( ) self . KeDcacheFlushCount = v_uint32 ( ) self . KeExceptionDispatchCount = v_uint32 ( ) self . KeFirstLevelTbFills = v_uint32 ( ) self . KeFloatingEmulationCount = v_uint32 ( ) self . KeIcacheFlushCount = v_uint32 ( ) self . KeSecondLevelTbFills = v_uint32 ( ) self . KeSystemCalls = v_uint32 ( ) self . SpareCounter0 = vstruct . VArray ( [ v_uint32 ( ) for i in xrange ( ) ] ) self . PPLookasideList = vstruct . VArray ( [ PP_LOOKASIDE_LIST ( ) for i in xrange ( ) ] ) self . PPNPagedLookasideList = vstruct . VArray ( [ PP_LOOKASIDE_LIST ( ) for i in xrange ( ) ] ) self . PPPagedLookasideList = vstruct . VArray ( [ PP_LOOKASIDE_LIST ( ) for i in xrange ( ) ] ) self . PacketBarrier = v_uint32 ( ) self . ReverseStall = v_uint32 ( ) self . IpiFrame = v_ptr32 ( ) self . PrcbPad2 = vstruct . VArray ( [ v_uint8 ( ) for i in xrange ( ) ] ) self . CurrentPacket = vstruct . VArray ( [ v_ptr32 ( ) for i in xrange ( ) ] ) self . TargetSet = v_uint32 ( ) self . WorkerRoutine = v_ptr32 ( ) self . IpiFrozen = v_uint32 ( ) self . PrcbPad3 = vstruct . VArray ( [ v_uint8 ( ) for i in xrange ( ) ] ) self . RequestSummary = v_uint32 ( ) self . SignalDone = v_ptr32 ( ) self . PrcbPad4 = vstruct . VArray ( [ v_uint8 ( ) for i in xrange ( ) ] ) self . DpcListHead = LIST_ENTRY ( ) self . DpcStack = v_ptr32 ( ) self . DpcCount = v_uint32 ( ) self . DpcQueueDepth = v_uint32 ( ) self . DpcRoutineActive = v_uint32 ( ) self . DpcInterruptRequested = v_uint32 ( ) self . DpcLastCount = v_uint32 ( ) self . DpcRequestRate = v_uint32 ( ) self . MaximumDpcQueueDepth = v_uint32 ( ) self . MinimumDpcRate = v_uint32 ( ) self . QuantumEnd = v_uint32 ( ) self . PrcbPad5 = vstruct . VArray ( [ v_uint8 ( ) for i in xrange ( ) ] ) self . DpcLock = v_uint32 ( ) self . PrcbPad6 = vstruct . VArray ( [ v_uint8 ( ) for i in xrange ( ) ] ) self . CallDpc = KDPC ( ) self . ChainedInterruptList = v_ptr32 ( ) self . LookasideIrpFloat = v_uint32 ( ) self . SpareFields0 = vstruct . VArray ( [ v_uint32 ( ) for i in xrange ( ) ] ) self . VendorString = vstruct . VArray ( [ v_uint8 ( ) for i in xrange ( ) ] ) self . InitialApicId = v_uint8 ( ) self . LogicalProcessorsPerPhysicalProcessor = v_uint8 ( ) self . _pad0910 = v_bytes ( size = ) self . MHz = v_uint32 ( ) self . FeatureBits = v_uint32 ( ) self . UpdateSignature = LARGE_INTEGER ( ) self . NpxSaveArea = FX_SAVE_AREA ( ) self . PowerState = PROCESSOR_POWER_STATE ( ) class _unnamed_5494 ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . Type = v_uint32 ( ) class OBJECT_ATTRIBUTES ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . Length = v_uint32 ( ) self . RootDirectory = v_ptr32 ( ) self . ObjectName = v_ptr32 ( ) self . Attributes = v_uint32 ( ) self . SecurityDescriptor = v_ptr32 ( ) self . SecurityQualityOfService = v_ptr32 ( ) class IO_COUNTERS ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . ReadOperationCount = v_uint64 ( ) self . WriteOperationCount = v_uint64 ( ) self . OtherOperationCount = v_uint64 ( ) self . ReadTransferCount = v_uint64 ( ) self . WriteTransferCount = v_uint64 ( ) self . OtherTransferCount = v_uint64 ( ) class KSYSTEM_TIME ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . LowPart = v_uint32 ( ) self . High1Time = v_uint32 ( ) self . High2Time = v_uint32 ( ) class CM_FULL_RESOURCE_DESCRIPTOR ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . InterfaceType = v_uint32 ( ) self . BusNumber = v_uint32 ( ) self . PartialResourceList = CM_PARTIAL_RESOURCE_LIST ( ) class EXCEPTION_RECORD ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . ExceptionCode = v_uint32 ( ) self . ExceptionFlags = v_uint32 ( ) self . ExceptionRecord = v_ptr32 ( ) self . ExceptionAddress = v_ptr32 ( ) self . NumberParameters = v_uint32 ( ) self . ExceptionInformation = vstruct . VArray ( [ v_uint32 ( ) for i in xrange ( ) ] ) class SID ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . Revision = v_uint8 ( ) self . SubAuthorityCount = v_uint8 ( ) self . IdentifierAuthority = SID_IDENTIFIER_AUTHORITY ( ) self . SubAuthority = vstruct . VArray ( [ v_uint32 ( ) for i in xrange ( ) ] ) class PS_JOB_TOKEN_FILTER ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . CapturedSidCount = v_uint32 ( ) self . CapturedSids = v_ptr32 ( ) self . CapturedSidsLength = v_uint32 ( ) self . CapturedGroupCount = v_uint32 ( ) self . CapturedGroups = v_ptr32 ( ) self . CapturedGroupsLength = v_uint32 ( ) self . CapturedPrivilegeCount = v_uint32 ( ) self . CapturedPrivileges = v_ptr32 ( ) self . CapturedPrivilegesLength = v_uint32 ( ) class KSPIN_LOCK_QUEUE ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . Next = v_ptr32 ( ) self . Lock = v_ptr32 ( ) class FAST_IO_DISPATCH ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . SizeOfFastIoDispatch = v_uint32 ( ) self . FastIoCheckIfPossible = v_ptr32 ( ) self . FastIoRead = v_ptr32 ( ) self . FastIoWrite = v_ptr32 ( ) self . FastIoQueryBasicInfo = v_ptr32 ( ) self . FastIoQueryStandardInfo = v_ptr32 ( ) self . FastIoLock = v_ptr32 ( ) self . FastIoUnlockSingle = v_ptr32 ( ) self . FastIoUnlockAll = v_ptr32 ( ) self . FastIoUnlockAllByKey = v_ptr32 ( ) self . FastIoDeviceControl = v_ptr32 ( ) self . AcquireFileForNtCreateSection = v_ptr32 ( ) self . ReleaseFileForNtCreateSection = v_ptr32 ( ) self . FastIoDetachDevice = v_ptr32 ( ) self . FastIoQueryNetworkOpenInfo = v_ptr32 ( ) self . AcquireForModWrite = v_ptr32 ( ) self . MdlRead = v_ptr32 ( ) self . MdlReadComplete = v_ptr32 ( ) self . PrepareMdlWrite = v_ptr32 ( ) self . MdlWriteComplete = v_ptr32 ( ) self . FastIoReadCompressed = v_ptr32 ( ) self . FastIoWriteCompressed = v_ptr32 ( ) self . MdlReadCompleteCompressed = v_ptr32 ( ) self . MdlWriteCompleteCompressed = v_ptr32 ( ) self . FastIoQueryOpen = v_ptr32 ( ) self . ReleaseForModWrite = v_ptr32 ( ) self . AcquireForCcFlush = v_ptr32 ( ) self . ReleaseForCcFlush = v_ptr32 ( ) class _unnamed_5463 ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . SecurityInformation = v_uint32 ( ) self . Length = v_uint32 ( ) class FS_FILTER_CALLBACKS ( vstruct . VStruct ) : def __init__ ( self ) : vstruct . VStruct . __init__ ( self ) self . SizeOfFsFilterCallbacks = v_uint32 ( ) self . Reserved = v_uint32 ( ) self . PreAcquireForSectionSynchronization = v_ptr32 ( ) self . PostAcquireForSectionSynchronization = v_ptr32 ( ) self . PreReleaseForSectionSynchronization = v_ptr32 ( ) self . PostReleaseForSectionSynchronization = v_ptr32 ( ) self . PreAcquireForCcFlush = v_ptr32 ( ) self . PostAcquireForCcFlush = v_ptr32 ( ) ", "answer": "self . PreReleaseForCcFlush = v_ptr32 ( )"}, {"prompt": " from __future__ import absolute_import from django . core . exceptions import ImproperlyConfigured from django . test import TestCase from django . views . generic . base import View from . models import Artist , Author , Page class DetailViewTest ( TestCase ) : fixtures = [ '' ] urls = '' def test_simple_object ( self ) : res = self . client . get ( '' ) self . assertEqual ( res . status_code , ) self . assertEqual ( res . context [ '' ] , { '' : '' } ) self . assertIsInstance ( res . context [ '' ] , View ) self . assertTemplateUsed ( res , '' ) def test_detail_by_pk ( self ) : res = self . client . get ( '' ) self . assertEqual ( res . status_code , ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( pk = ) ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( pk = ) ) self . assertTemplateUsed ( res , '' ) def test_detail_by_custom_pk ( self ) : res = self . client . get ( '' ) self . assertEqual ( res . status_code , ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( pk = ) ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( pk = ) ) self . assertTemplateUsed ( res , '' ) def test_detail_by_slug ( self ) : res = self . client . get ( '' ) self . assertEqual ( res . status_code , ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( slug = '' ) ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( slug = '' ) ) self . assertTemplateUsed ( res , '' ) def test_detail_by_custom_slug ( self ) : res = self . client . get ( '' ) self . assertEqual ( res . status_code , ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( slug = '' ) ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( slug = '' ) ) self . assertTemplateUsed ( res , '' ) def test_verbose_name ( self ) : res = self . client . get ( '' ) self . assertEqual ( res . status_code , ) self . assertEqual ( res . context [ '' ] , Artist . objects . get ( pk = ) ) self . assertEqual ( res . context [ '' ] , Artist . objects . get ( pk = ) ) self . assertTemplateUsed ( res , '' ) def test_template_name ( self ) : res = self . client . get ( '' ) self . assertEqual ( res . status_code , ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( pk = ) ) self . assertEqual ( res . context [ '' ] , Author . objects . get ( pk = ) ) self . assertTemplateUsed ( res , '' ) ", "answer": "def test_template_name_suffix ( self ) :"}, {"prompt": " import unittest from ctypes import PyDLL , py_object , c_void_p , byref , POINTER from ctypes . wintypes import BOOL from comtypes import IUnknown from comtypes . client import CreateObject from comtypes . automation import IDispatch from comtypes . test import requires requires ( \"\" ) import pythoncom import win32com . client _PyCom_PyObjectFromIUnknown = PyDLL ( pythoncom . __file__ ) . PyCom_PyObjectFromIUnknown _PyCom_PyObjectFromIUnknown . restype = py_object _PyCom_PyObjectFromIUnknown . argtypes = ( POINTER ( IUnknown ) , c_void_p , BOOL ) def comtypes2pywin ( ptr , interface = None ) : \"\"\"\"\"\" if interface is None : interface = IUnknown return _PyCom_PyObjectFromIUnknown ( ptr , byref ( interface . _iid_ ) , True ) def comtypes_get_refcount ( ptr ) : \"\"\"\"\"\" ptr . AddRef ( ) return ptr . Release ( ) from comtypes import COMObject class MyComObject ( COMObject ) : \"\"\"\"\"\" _com_interfaces_ = [ IDispatch ] class Test ( unittest . TestCase ) : def tearDown ( self ) : if hasattr ( self , \"\" ) : self . ie . Quit ( ) del self . ie def test_mycomobject ( self ) : o = MyComObject ( ) p = comtypes2pywin ( o , IDispatch ) disp = win32com . client . Dispatch ( p ) self . failUnlessEqual ( repr ( disp ) , \"\" ) def test_ie ( self ) : ie = self . ie = CreateObject ( \"\" ) self . failUnlessEqual ( comtypes_get_refcount ( ie ) , ) self . failUnlessEqual ( ie . Visible , False ) p = comtypes2pywin ( ie , interface = IDispatch ) self . failUnlessEqual ( comtypes_get_refcount ( ie ) , ) ", "answer": "disp = win32com . client . Dispatch ( p )"}, {"prompt": " from __future__ import division import numpy as np import mahotas as mh from . . labeled import bwperim from . . internal import _make_binary __all__ = [ '' , '' , ", "answer": "'' ,"}, {"prompt": " from apgl . graph . VertexList import VertexList from apgl . graph . GeneralVertexList import GeneralVertexList from apgl . generator . BarabasiAlbertGenerator import BarabasiAlbertGenerator from apgl . util . PathDefaults import PathDefaults import numpy import os import logging import pickle import numpy . testing as nptst \"\"\"\"\"\" class MatrixGraphTest ( ) : def initialise ( self ) : numpy . set_printoptions ( suppress = True ) numpy . random . seed ( ) self . numVertices = self . numFeatures = self . vList = VertexList ( self . numVertices , self . numFeatures ) self . graph = self . GraphType ( self . vList ) self . graph . addEdge ( , , ) self . graph . addEdge ( , , ) self . graph . addEdge ( , , ) self . graph . addEdge ( , , ) self . graph . addEdge ( , , ) self . graph . addEdge ( , , ) self . graph2 = self . GraphType ( self . vList , False ) self . graph2 . addEdge ( , , ) self . graph2 . addEdge ( , , ) self . graph2 . addEdge ( , , ) self . graph2 . addEdge ( , , ) self . graph2 . addEdge ( , , ) self . graph2 . addEdge ( , , ) def testAddEdge ( self ) : self . graph . addEdge ( , , ) self . assertEquals ( self . graph . getEdge ( , ) , ) self . assertEquals ( self . graph . getEdge ( , ) , ) self . assertEquals ( self . graph . getEdge ( , ) , None ) self . assertRaises ( ValueError , self . graph . addEdge , , , ) def testAddEdges ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) vList . setVertices ( numpy . random . rand ( numVertices , numFeatures ) ) graph = self . GraphType ( vList ) edgeIndexArray = numpy . array ( [ [ , ] , [ , ] ] ) graph . addEdges ( edgeIndexArray ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getNumEdges ( ) , ) graph = self . GraphType ( vList , False ) graph . addEdges ( edgeIndexArray ) self . assertEquals ( graph . getNumEdges ( ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) edgeValues = numpy . array ( [ , ] ) graph . addEdges ( edgeIndexArray , edgeValues ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) graph = self . GraphType ( vList ) graph . addEdges ( edgeIndexArray , edgeValues ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) edgeValues = numpy . array ( [ , ] ) self . assertRaises ( ValueError , graph . addEdges , edgeIndexArray , edgeValues ) def testRemoveEdge ( self ) : self . graph . addEdge ( , , ) self . assertEquals ( self . graph . getEdge ( , ) , ) self . assertEquals ( self . graph . getEdge ( , ) , ) self . graph . removeEdge ( , ) self . assertEquals ( self . graph . getEdge ( , ) , None ) self . assertEquals ( self . graph . getEdge ( , ) , None ) def testNeighbours ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertTrue ( ( numpy . sort ( graph . neighbours ( ) ) == numpy . array ( [ , , ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbours ( ) == numpy . array ( [ ] ) ) . all ( ) ) self . assertTrue ( ( numpy . sort ( graph . neighbours ( ) ) == numpy . array ( [ , ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbours ( ) == numpy . array ( [ ] ) ) . all ( ) ) graph = self . GraphType ( vList , False ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertTrue ( ( numpy . sort ( graph . neighbours ( ) ) == numpy . array ( [ , ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbours ( ) == numpy . array ( [ ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbours ( ) == numpy . array ( [ ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbours ( ) == numpy . array ( [ ] ) ) . all ( ) ) def testNeighbourOf ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertTrue ( ( graph . neighbourOf ( ) == numpy . array ( [ , , ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbourOf ( ) == numpy . array ( [ ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbourOf ( ) == numpy . array ( [ , ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbourOf ( ) == numpy . array ( [ ] ) ) . all ( ) ) graph = self . GraphType ( vList , False ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertTrue ( ( graph . neighbourOf ( ) == numpy . array ( [ ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbourOf ( ) == numpy . array ( [ ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbourOf ( ) == numpy . array ( [ , ] ) ) . all ( ) ) self . assertTrue ( ( graph . neighbourOf ( ) == numpy . array ( [ ] ) ) . all ( ) ) def testClusteringCoefficient ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertEqual ( graph . clusteringCoefficient ( ) , ) graph . addEdge ( , , ) self . assertEqual ( graph . clusteringCoefficient ( ) , ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertEqual ( graph . clusteringCoefficient ( ) , float ( ) / ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) self . assertEqual ( graph . clusteringCoefficient ( ) , ) def testDegreeDistribution ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) self . assertTrue ( ( graph . degreeDistribution ( ) == numpy . array ( [ ] ) ) . all ( ) ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertTrue ( ( graph . degreeDistribution ( ) == numpy . array ( [ , , , , ] ) ) . all ( ) ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) self . assertTrue ( ( graph . degreeDistribution ( ) == numpy . array ( [ ] ) ) . all ( ) ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertTrue ( ( graph . degreeDistribution ( ) == numpy . array ( [ , , , , , ] ) ) . all ( ) ) subGraph = graph . subgraph ( [ , , , ] ) def testDijkstrasAlgorithm ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertTrue ( ( graph . dijkstrasAlgorithm ( ) == numpy . array ( [ , , , , ] ) ) . all ( ) ) self . assertTrue ( ( graph . dijkstrasAlgorithm ( ) == numpy . array ( [ , , , , ] ) ) . all ( ) ) self . assertTrue ( ( graph . dijkstrasAlgorithm ( ) == numpy . array ( [ , , , , ] ) ) . all ( ) ) self . assertTrue ( ( graph . dijkstrasAlgorithm ( ) == numpy . array ( [ , , , , ] ) ) . all ( ) ) self . assertTrue ( ( graph . dijkstrasAlgorithm ( ) == numpy . array ( [ , , , , ] ) ) . all ( ) ) self . assertTrue ( ( self . graph . dijkstrasAlgorithm ( , self . graph . adjacencyList ( ) ) == numpy . array ( [ , , , , , float ( '' ) ] ) ) . all ( ) ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertTrue ( ( graph . dijkstrasAlgorithm ( ) == numpy . array ( [ , , , , numpy . inf ] ) ) . all ( ) ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertTrue ( ( graph . dijkstrasAlgorithm ( ) == numpy . array ( [ , , , , ] ) ) . all ( ) ) def testGeodesicDistance ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) P = graph . floydWarshall ( ) self . assertEquals ( graph . geodesicDistance ( ) , / ) self . assertEquals ( graph . geodesicDistance ( P ) , / ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) P = graph . floydWarshall ( ) self . assertEquals ( graph . geodesicDistance ( ) , / ) self . assertEquals ( graph . geodesicDistance ( P ) , / ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) P = graph . floydWarshall ( ) self . assertEquals ( graph . geodesicDistance ( ) , / ) self . assertEquals ( graph . geodesicDistance ( P ) , / ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList , False ) graph . addEdge ( , , ) graph . addEdge ( , , ) P = graph . floydWarshall ( ) self . assertEquals ( graph . geodesicDistance ( ) , / ) self . assertEquals ( graph . geodesicDistance ( P ) , / ) def testHopCount ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) self . assertTrue ( ( graph . hopCount ( ) == numpy . array ( [ , , ] ) ) . all ( ) ) graph . addEdge ( , ) self . assertTrue ( ( graph . hopCount ( ) == numpy . array ( [ , , ] ) ) . all ( ) ) graph . addEdge ( , ) self . assertTrue ( ( graph . hopCount ( ) == numpy . array ( [ , , , ] ) ) . all ( ) ) P = graph . floydWarshall ( ) self . assertTrue ( ( graph . hopCount ( P ) == numpy . array ( [ , , , ] ) ) . all ( ) ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList , False ) graph . addEdge ( , ) graph . addEdge ( , , ) graph . addEdge ( , ) self . assertTrue ( ( graph . hopCount ( ) == numpy . array ( [ , ] ) ) . all ( ) ) P = graph . floydWarshall ( False ) self . assertTrue ( ( graph . hopCount ( P ) == numpy . array ( [ , ] ) ) . all ( ) ) graph = self . GraphType ( vList , True ) self . assertTrue ( ( graph . hopCount ( ) == numpy . array ( [ numVertices ] ) ) . all ( ) ) vList = VertexList ( , ) graph = self . GraphType ( vList , True ) self . assertTrue ( ( graph . hopCount ( ) == numpy . array ( [ ] ) ) . all ( ) ) def testHarmonicGeodesicDistance ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertEquals ( graph . harmonicGeodesicDistance ( ) , ) P = graph . floydWarshall ( True ) self . assertEquals ( graph . harmonicGeodesicDistance ( P ) , ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertAlmostEquals ( graph . harmonicGeodesicDistance ( ) , / , places = ) P = graph . floydWarshall ( True ) self . assertAlmostEquals ( graph . harmonicGeodesicDistance ( P ) , / , places = ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertAlmostEquals ( graph . harmonicGeodesicDistance ( ) , / , places = ) P = graph . floydWarshall ( True ) self . assertAlmostEquals ( graph . harmonicGeodesicDistance ( P ) , / , places = ) graph = self . GraphType ( vList ) self . assertEquals ( graph . harmonicGeodesicDistance ( ) , float ( '' ) ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) P = graph . floydWarshall ( True ) inds = [ , ] self . assertEquals ( graph . harmonicGeodesicDistance ( vertexInds = inds ) , ) graph = self . GraphType ( vList , False ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) P = graph . floydWarshall ( True ) self . assertAlmostEquals ( graph . harmonicGeodesicDistance ( P ) , / , places = ) def testGetAllEdges ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) edges = graph . getAllEdges ( ) self . assertEquals ( edges . shape [ ] , ) self . assertTrue ( ( edges [ , : ] == numpy . array ( [ , ] ) ) . all ( ) ) self . assertTrue ( ( edges [ , : ] == numpy . array ( [ , ] ) ) . all ( ) ) self . assertTrue ( ( edges [ , : ] == numpy . array ( [ , ] ) ) . all ( ) ) self . assertTrue ( ( edges [ , : ] == numpy . array ( [ , ] ) ) . all ( ) ) graph = self . GraphType ( vList , False ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) edges = graph . getAllEdges ( ) edgeSet = set ( [ ( x , y ) for x , y in edges ] ) edgeSet2 = set ( [ ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ] ) self . assertEquals ( edges . shape [ ] , ) self . assertEquals ( edgeSet , edgeSet2 ) graph = self . GraphType ( vList ) edges = graph . getAllEdges ( ) self . assertEquals ( edges . shape , ( , ) ) def testGetNumEdges ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) self . assertEquals ( graph . getNumEdges ( ) , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertEquals ( graph . getNumEdges ( ) , ) graph . addEdge ( , , ) self . assertEquals ( graph . getNumEdges ( ) , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertEquals ( graph . getNumEdges ( ) , ) graph = self . GraphType ( vList , False ) graph . addEdge ( , , ) self . assertEquals ( graph . getNumEdges ( ) , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertEquals ( graph . getNumEdges ( ) , ) graph . addEdge ( , , ) self . assertEquals ( graph . getNumEdges ( ) , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertEquals ( graph . getNumEdges ( ) , ) def testGetNumVertices ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) self . assertEquals ( graph . getNumVertices ( ) , numVertices ) def testGetEdge ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , None ) def testGetVertex ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . setVertex ( , numpy . array ( [ , , ] ) ) self . assertRaises ( ValueError , graph . setVertex , - , numpy . array ( [ , , ] ) ) self . assertRaises ( ValueError , graph . setVertex , , numpy . array ( [ , , ] ) ) self . assertRaises ( ValueError , graph . setVertex , , numpy . array ( [ , , , ] ) ) self . assertRaises ( ValueError , graph . setVertex , , numpy . array ( [ , ] ) ) self . assertTrue ( ( graph . getVertex ( ) == numpy . array ( [ , , ] ) ) . all ( ) ) self . assertTrue ( ( graph . getVertex ( ) == numpy . array ( [ , , ] ) ) . all ( ) ) def testSetVertex ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . setVertex ( , numpy . array ( [ , , ] ) ) self . assertTrue ( ( graph . getVertex ( ) == numpy . array ( [ , , ] ) ) . all ( ) ) self . assertTrue ( ( graph . getVertex ( ) == numpy . array ( [ , , ] ) ) . all ( ) ) graph . setVertex ( , numpy . array ( [ , , ] ) ) self . assertTrue ( ( graph . getVertex ( ) == numpy . array ( [ , , ] ) ) . all ( ) ) def testIsUndirected ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList , True ) self . assertEquals ( graph . isUndirected ( ) , True ) graph = self . GraphType ( vList , False ) self . assertEquals ( graph . isUndirected ( ) , False ) def testGetAllVertexIds ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) self . assertTrue ( ( graph . getAllVertexIds ( ) == numpy . array ( list ( range ( , numVertices ) ) ) ) . all ( ) ) def testSubgraph ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) vertices = numpy . random . rand ( numVertices , numFeatures ) vList . setVertices ( vertices ) graph = self . GraphType ( vList ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) subgraph = graph . subgraph ( [ , , , ] ) self . assertEquals ( subgraph . getNumVertices ( ) , ) self . assertEquals ( subgraph . getVertexList ( ) . getNumFeatures ( ) , numFeatures ) self . assertTrue ( ( subgraph . getVertexList ( ) . getVertices ( list ( range ( , ) ) ) == vertices [ list ( range ( , ) ) , : ] ) . all ( ) ) self . assertEquals ( subgraph . getNumEdges ( ) , ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) subgraph = graph . subgraph ( [ , , , ] ) self . assertEquals ( subgraph . getNumVertices ( ) , ) self . assertEquals ( subgraph . getVertexList ( ) . getNumFeatures ( ) , numFeatures ) self . assertEquals ( subgraph . getNumEdges ( ) , ) self . assertTrue ( ( subgraph . getVertexList ( ) . getVertices ( [ , , , ] ) == vertices [ [ , , , ] , : ] ) . all ( ) ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) vertices = numpy . random . rand ( numVertices , numFeatures ) vList . setVertices ( vertices ) graph = self . GraphType ( vList , False ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) subgraph = graph . subgraph ( [ , , , ] ) self . assertEquals ( subgraph . isUndirected ( ) , False ) self . assertEquals ( subgraph . getNumVertices ( ) , ) self . assertEquals ( subgraph . getVertexList ( ) . getNumFeatures ( ) , numFeatures ) self . assertTrue ( ( subgraph . getVertexList ( ) . getVertices ( list ( range ( , ) ) ) == vertices [ list ( range ( , ) ) , : ] ) . all ( ) ) self . assertEquals ( subgraph . getNumEdges ( ) , ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) subgraph = graph . subgraph ( [ , , , ] ) self . assertEquals ( subgraph . getNumVertices ( ) , ) self . assertEquals ( subgraph . getVertexList ( ) . getNumFeatures ( ) , numFeatures ) self . assertEquals ( subgraph . getNumEdges ( ) , ) self . assertTrue ( ( subgraph . getVertexList ( ) . getVertices ( [ , , , ] ) == vertices [ [ , , , ] , : ] ) . all ( ) ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) self . assertTrue ( subgraph . getEdge ( , ) == ) subgraph = graph . subgraph ( [ ] ) def testAdd ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList , False ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph2 = self . GraphType ( vList , False ) graph2 . addEdge ( , ) graph2 . addEdge ( , ) graph2 . addEdge ( , ) graph2 . addEdge ( , ) newGraph = graph . add ( graph2 ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( newGraph . getEdge ( , ) , ) self . assertEquals ( newGraph . getEdge ( , ) , ) self . assertEquals ( newGraph . getEdge ( , ) , ) self . assertEquals ( newGraph . getEdge ( , ) , ) vList2 = VertexList ( numVertices - , numFeatures ) graph2 = self . GraphType ( vList2 , False ) graph2 . addEdge ( , ) self . assertRaises ( ValueError , graph . add , graph2 ) def testMultiply ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList , False ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , , ) graph2 = self . GraphType ( vList , False ) graph2 . addEdge ( , ) graph2 . addEdge ( , ) graph2 . addEdge ( , ) graph2 . addEdge ( , , ) newGraph = graph . multiply ( graph2 ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , ) self . assertEquals ( newGraph . getNumEdges ( ) , ) self . assertEquals ( newGraph . getEdge ( , ) , None ) self . assertEquals ( newGraph . getEdge ( , ) , None ) self . assertEquals ( newGraph . getEdge ( , ) , None ) self . assertEquals ( newGraph . getEdge ( , ) , ) vList2 = VertexList ( numVertices - , numFeatures ) graph2 = self . GraphType ( vList2 , False ) graph2 . addEdge ( , ) self . assertRaises ( ValueError , graph . multiply , graph2 ) def testCopy ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList , False ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph2 = graph . copy ( ) graph2 . addEdge ( , ) self . assertEquals ( graph2 . getEdge ( , ) , ) self . assertEquals ( graph . getEdge ( , ) , None ) def testDensity ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList , False ) self . assertEquals ( graph . density ( ) , ) graph . addEdge ( , ) self . assertEquals ( graph . density ( ) , float ( ) / ) graph = self . GraphType ( vList , True ) self . assertEquals ( graph . density ( ) , ) graph . addEdge ( , ) self . assertEquals ( graph . density ( ) , float ( ) / ) def testDepthFirstSearch ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) self . assertEquals ( graph . depthFirstSearch ( ) , [ , , , , ] ) self . assertEquals ( graph . depthFirstSearch ( ) , [ , , , , ] ) self . assertEquals ( graph . depthFirstSearch ( ) , [ , , , , ] ) self . assertEquals ( graph . depthFirstSearch ( ) , [ , ] ) self . assertEquals ( graph . depthFirstSearch ( ) , [ , ] ) self . assertEquals ( graph . depthFirstSearch ( ) , [ ] ) def testBreadthFirstSearch ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) self . assertEquals ( graph . breadthFirstSearch ( ) , [ , , , , , , , ] ) self . assertEquals ( graph . breadthFirstSearch ( ) , [ , , , , , , , ] ) self . assertEquals ( graph . breadthFirstSearch ( ) , [ , , , , , , , ] ) self . assertEquals ( graph . breadthFirstSearch ( ) , [ , ] ) self . assertEquals ( graph . breadthFirstSearch ( ) , [ , ] ) self . assertEquals ( graph . breadthFirstSearch ( ) , [ , , , , , , , ] ) def testDiameter ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList , True ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) P = graph . floydWarshall ( False ) self . assertEquals ( graph . diameter ( P = P ) , ) graph = self . GraphType ( vList , False ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) graph . addEdge ( , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) P = graph . floydWarshall ( False ) self . assertEquals ( graph . diameter ( P = P ) , ) graph = self . GraphType ( vList , False ) self . assertEquals ( graph . diameter ( ) , ) graph = self . GraphType ( vList , True ) graph . addEdge ( , , ) graph . addEdge ( , , ) graph . addEdge ( , , ) self . assertAlmostEqual ( graph . diameter ( True ) , , places = ) P = graph . floydWarshall ( True ) self . assertAlmostEquals ( graph . diameter ( True , P = P ) , , places = ) def testEffectiveDiameter ( self ) : numVertices = numFeatures = vList = VertexList ( numVertices , numFeatures ) graph = self . GraphType ( vList , True ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) self . assertEquals ( graph . diameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) P = graph . floydWarshall ( False ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) graph = self . GraphType ( vList , False ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) graph . addEdge ( , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) P = graph . floydWarshall ( False ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) graph = self . GraphType ( vList , True ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) P = graph . floydWarshall ( False ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) graph = self . GraphType ( vList , False ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) P = graph . floydWarshall ( False ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) self . assertEquals ( graph . effectiveDiameter ( , P = P ) , ) graph = self . GraphType ( vList , True ) graph . addEdge ( , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) self . assertEquals ( graph . effectiveDiameter ( ) , ) ", "answer": "self . assertEquals ( graph . effectiveDiameter ( ) , )"}, {"prompt": " from django . http import HttpResponse from django . utils . feedgenerator import SyndicationFeed import vobject FEED_ICAL_MAP = { '' : '' , '' : '' , '' : '' , '' : '' } ITEM_ICAL_MAP = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } class ICalendarFeed ( SyndicationFeed ) : mime_type = '' def add_item ( self , * args , ** kwargs ) : for kwarg in [ '' , '' , '' , '' ] : kwargs . setdefault ( kwarg , None ) super ( ICalendarFeed , self ) . add_item ( * args , ** kwargs ) def write ( self , outfile , encoding ) : cal = vobject . iCalendar ( ) cal . add ( '' ) . value = '' for key , val in self . feed . items ( ) : if key in FEED_ICAL_MAP and val : cal . add ( FEED_ICAL_MAP [ key ] ) . value = val for item in self . items : event = cal . add ( '' ) for key , val in item . items ( ) : if key in ITEM_ICAL_MAP and val : ", "answer": "event . add ( ITEM_ICAL_MAP [ key ] ) . value = val"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Creature ( )"}, {"prompt": " import hashlib import urllib from django . conf import settings from django . utils . encoding import force_str from django . utils . translation import ugettext as _ from django_jinja import library from jinja2 import escape , Markup from kitsune . sumo . templatetags . jinja_helpers import urlparams from kitsune . sumo . urlresolvers import reverse from kitsune . users . models import Profile ", "answer": "@ library . global_function"}, {"prompt": " from thrift . Thrift import * from thrift . protocol import TBinaryProtocol from thrift . transport import TTransport try : from thrift . protocol import fastbinary except : fastbinary = None class TBase ( object ) : __slots__ = [ ] def __repr__ ( self ) : L = [ '' % ( key , getattr ( self , key ) ) ", "answer": "for key in self . __slots__ ]"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import datetime class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ( '' , '' ) , ] operations = [ migrations . CreateModel ( name = '' , fields = [ ", "answer": "( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) ,"}, {"prompt": " from __future__ import print_function from __future__ import division from __future__ import absolute_import import unittest from jnius import autoclass , JavaException class Interface ( unittest . TestCase ) : def test_reflect_interface ( self ) : Interface = autoclass ( '' ) self . assertTrue ( Interface ) def test_reflect_enum_in_interface ( self ) : ATTITUDE = autoclass ( '' ) self . assertTrue ( ATTITUDE ) ", "answer": "self . assertTrue ( ATTITUDE . GOOD )"}, {"prompt": " from ooi . occi . core import attribute from ooi . occi . core import entity from ooi . occi . core import kind from ooi . occi . core import link from ooi . occi import helpers class Resource ( entity . Entity ) : \"\"\"\"\"\" ", "answer": "attributes = attribute . AttributeCollection ( [ \"\" ] )"}, {"prompt": " __all__ = [ '' ] def wiggle ( count ) : for i in range ( , count ) : print ( '' ) ", "answer": "def waggle ( count ) :"}, {"prompt": " \"\"\"\"\"\" from google_voice . main import GoogleVoice from africa_talking . main import AfricaTalking import config '''''' class VoiceXTransport : ", "answer": "def __init__ ( self , auth ) :"}, {"prompt": " import unittest from ... compatibility import StringIO from ... format import Format class TestInitialisation ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . fh = StringIO ( ) self . format = Format ( ) self . format . _set_filehandle ( self . fh ) def test_xml_declaration ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import hTools2 . dialogs . glyphs . anchors_create ", "answer": "reload ( hTools2 . dialogs . glyphs . anchors_create ) "}, {"prompt": " from __future__ import unicode_literals from django . db import migrations , models import django . db . models . deletion class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( auto_created = True , primary_key = True , serialize = False , verbose_name = '' ) ) , ( '' , models . ForeignKey ( on_delete = django . db . models . deletion . CASCADE , to = '' ) ) , ] , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( auto_created = True , primary_key = True , serialize = False , verbose_name = '' ) ) , ( '' , models . BooleanField ( default = False ) ) , ( '' , models . ForeignKey ( on_delete = django . db . models . deletion . CASCADE , related_name = '' , to = '' ) ) , ] , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( auto_created = True , primary_key = True , serialize = False , verbose_name = '' ) ) , ] , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . AlterUniqueTogether ( name = '' , unique_together = set ( [ ] ) , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . AlterUniqueTogether ( name = '' , unique_together = set ( [ ] ) , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . AlterUniqueTogether ( name = '' , unique_together = set ( [ ] ) , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . AlterUniqueTogether ( name = '' , unique_together = set ( [ ] ) , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . AlterUniqueTogether ( name = '' , unique_together = set ( [ ] ) , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . AlterUniqueTogether ( name = '' , unique_together = set ( [ ] ) , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . AddField ( model_name = '' , name = '' , field = models . BooleanField ( default = True ) , ) , migrations . AddField ( model_name = '' , name = '' , field = models . CharField ( blank = True , max_length = , null = True ) , ) , migrations . AddField ( model_name = '' , name = '' , field = models . IntegerField ( choices = [ ( , b'' ) , ( , b'' ) , ( , b'' ) , ( , b'' ) ] , default = ) , ) , migrations . AddField ( model_name = '' , ", "answer": "name = '' ,"}, {"prompt": " \"\"\"\"\"\" __author__ = '' class Solution : def findPeak ( self , A ) : \"\"\"\"\"\" n = len ( A ) l = h = n while l < h : m = ( l + h ) / if A [ m - ] < A [ m ] > A [ m + ] : ", "answer": "return m"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " import glob import os import shutil class PCLReferenceAssembliesPackage ( Package ) : def __init__ ( self ) : Package . __init__ ( self , name = '' , version = '' , sources = [ '' ] ) def build ( self ) : pass def install ( self ) : dest = os . path . join ( self . staged_prefix , \"\" , \"\" , \"\" , \"\" ) if not os . path . exists ( dest ) : os . makedirs ( dest ) shutil . rmtree ( dest , ignore_errors = True ) self . sh ( \"\" % ( self . workspace , dest ) ) for f in glob . glob ( \"\" % dest ) : self . write_xml ( f ) def write_xml ( self , directory ) : data = { os . path . join ( directory , \"\" ) : ", "answer": "\"\"\"\"\"\" ,"}, {"prompt": " from django import template register = template . Library ( ) @ register . inclusion_tag ( '' ) def video_list_item ( video ) : return { '' : video } @ register . inclusion_tag ( '' ) def pagination ( page_obj , paginator , request ) : \"\"\"\"\"\" base_link = '' . join ( [ \"\" % ( k , v ) for ( k , v ) in request . GET . items ( ) if k != '' ] ) if paginator . num_pages <= : show_pages = [ [ x , \"\" % ( base_link , x ) , False ] for x in range ( , paginator . num_pages + ) ] show_pages [ page_obj . number - ] [ ] = True else : if page_obj . number <= : ", "answer": "show_pages = [ [ x , \"\" % ( base_link , x ) , False ] for x in range ( , page_obj . number + ) ]"}, {"prompt": " import sys import os import unittest sys . path . append ( os . path . join ( os . path . dirname ( __file__ ) , '' ) ) from testlib import get_fixture , function from testlib import EapiConfigUnitTest import pyeapi . api . bgp class TestApiBgp ( EapiConfigUnitTest ) : def __init__ ( self , * args , ** kwargs ) : super ( TestApiBgp , self ) . __init__ ( * args , ** kwargs ) self . instance = pyeapi . api . bgp . instance ( None ) self . config = open ( get_fixture ( '' ) ) . read ( ) def test_get ( self ) : result = self . instance . get ( ) keys = [ '' , '' , '' , '' , '' , '' , '' ] self . assertEqual ( sorted ( keys ) , sorted ( result . keys ( ) ) ) def test_create ( self ) : for bgpas in [ '' , ] : func = function ( '' , bgpas ) cmds = '' . format ( bgpas ) self . eapi_positive_config_test ( func , cmds ) def test_create_invalid_as ( self ) : for bgpas in [ '' , ] : with self . assertRaises ( ValueError ) : self . instance . create ( bgpas ) def test_delete ( self ) : func = function ( '' ) cmds = '' self . eapi_positive_config_test ( func , cmds ) def test_default ( self ) : func = function ( '' ) cmds = '' self . eapi_positive_config_test ( func , cmds ) def test_add_network ( self ) : func = function ( '' , '' , '' , '' ) cmds = [ '' , '' ] self . eapi_positive_config_test ( func , cmds ) func = function ( '' , '' , '' , '' ) self . eapi_exception_config_test ( func , ValueError ) func = function ( '' , '' , '' , '' ) self . eapi_exception_config_test ( func , ValueError ) def test_remove_network ( self ) : func = function ( '' , '' , '' , '' ) cmds = [ '' , '' ] self . eapi_positive_config_test ( func , cmds ) func = function ( '' , '' , '' , '' ) self . eapi_exception_config_test ( func , ValueError ) func = function ( '' , '' , '' , '' ) self . eapi_exception_config_test ( func , ValueError ) def test_set_router_id ( self ) : for state in [ '' , '' , '' ] : rid = '' if state == '' : cmds = [ '' , '' ] func = function ( '' , rid ) elif state == '' : cmds = [ '' , '' ] func = function ( '' , None , False , True ) elif state == '' : cmds = [ '' , '' ] func = function ( '' , rid , True ) self . eapi_positive_config_test ( func , cmds ) cmds = [ '' , '' ] func = function ( '' , None ) self . eapi_positive_config_test ( func , cmds ) def test_maximum_paths_just_max_path ( self ) : for state in [ '' , '' , '' ] : max_paths = if state == '' : cmds = [ '' , '' ] func = function ( '' , max_paths ) elif state == '' : cmds = [ '' , '' ] func = function ( '' , disable = True ) elif state == '' : cmds = [ '' , '' ] func = function ( '' , default = True ) self . eapi_positive_config_test ( func , cmds ) cmds = [ '' , '' ] func = function ( '' , None ) self . eapi_positive_config_test ( func , cmds ) def test_maximum_paths_max_path_and_ecmp ( self ) : for state in [ '' , '' , '' ] : ", "answer": "max_paths = "}, {"prompt": " \"\"\"\"\"\" from redis import Redis __all__ = [ '' ] class Connection ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . _redis = None @ property def redis ( self ) : ", "answer": "if not self . _redis :"}, {"prompt": " \"\"\"\"\"\" from testtools import content from shade . tests . functional import base class TestZone ( base . BaseFunctionalTestCase ) : def setUp ( self ) : super ( TestZone , self ) . setUp ( ) if not self . demo_cloud . has_service ( '' ) : self . skipTest ( '' ) def test_zones ( self ) : '''''' name = '' zone_type = '' email = '' description = '' ttl = masters = None self . addDetail ( '' , content . text_content ( name ) ) self . addCleanup ( self . cleanup , name ) zone = self . demo_cloud . create_zone ( name = name , zone_type = zone_type , email = email , description = description , ttl = ttl , masters = masters ) self . assertEquals ( zone [ '' ] , name ) self . assertEquals ( zone [ '' ] , zone_type . upper ( ) ) self . assertEquals ( zone [ '' ] , email ) self . assertEquals ( zone [ '' ] , description ) self . assertEquals ( zone [ '' ] , ttl ) self . assertEquals ( zone [ '' ] , [ ] ) zones = self . demo_cloud . list_zones ( ) self . assertIsNotNone ( zones ) zone_get = self . demo_cloud . get_zone ( zone [ '' ] ) self . assertEquals ( zone_get [ '' ] , zone [ '' ] ) zone_get = self . demo_cloud . get_zone ( name ) self . assertEquals ( zone_get [ '' ] , zone [ '' ] ) zone_update = self . demo_cloud . update_zone ( zone [ '' ] , ttl = ) self . assertEquals ( zone_update [ '' ] , zone [ '' ] ) ", "answer": "self . assertEquals ( zone_update [ '' ] , zone [ '' ] )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) result . setStringAttribute ( \"\" , \"\" ) result . setStringAttribute ( \"\" , \"\" ) result . setStringAttribute ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import sys import commands import getopt import os import time from msct_parser import Parser import sct_utils as sct from sct_extract_metric import read_label_file path_script = os . path . dirname ( __file__ ) path_sct = os . path . dirname ( path_script ) class Param : def __init__ ( self ) : self . debug = self . folder_out = '' self . path_template = path_sct + '' self . folder_template = '' self . folder_atlas = '' self . folder_spinal_levels = '' self . file_info_label = '' self . warp_atlas = self . warp_spinal_levels = self . list_labels_nn = [ '' , '' , '' ] self . list_labels_spline = [ '' ] self . verbose = self . qc = class WarpTemplate : def __init__ ( self , fname_src , fname_transfo , warp_atlas , warp_spinal_levels , folder_out , path_template , verbose , qc ) : self . fname_src = fname_src self . fname_transfo = fname_transfo self . warp_atlas = warp_atlas self . warp_spinal_levels = warp_spinal_levels self . folder_out = folder_out self . path_template = path_template self . folder_template = param . folder_template self . folder_atlas = param . folder_atlas self . folder_spinal_levels = param . folder_spinal_levels self . verbose = verbose self . qc = qc start_time = time . time ( ) sct . printv ( '' , self . verbose ) sct . check_file_exist ( self . fname_src ) sct . check_file_exist ( self . fname_transfo ) self . path_template = sct . slash_at_the_end ( self . path_template , ) self . folder_out = sct . slash_at_the_end ( self . folder_out , ) self . folder_template = sct . slash_at_the_end ( self . folder_template , ) self . folder_atlas = sct . slash_at_the_end ( self . folder_atlas , ) self . folder_spinal_levels = sct . slash_at_the_end ( self . folder_spinal_levels , ) print '' print '' + self . fname_src print '' + self . fname_transfo print '' + self . path_template print '' + self . folder_out + '' path_src , file_src , ext_src = sct . extract_fname ( self . fname_src ) if os . path . exists ( self . folder_out ) : sct . printv ( '' , self . verbose , '' ) sct . run ( '' + self . folder_out ) sct . run ( '' + self . folder_out ) sct . printv ( '' , self . verbose ) warp_label ( self . path_template , self . folder_template , param . file_info_label , self . fname_src , self . fname_transfo , self . folder_out ) if self . warp_atlas == : sct . printv ( '' , self . verbose ) warp_label ( self . path_template , self . folder_atlas , param . file_info_label , self . fname_src , self . fname_transfo , self . folder_out ) if self . warp_spinal_levels == : sct . printv ( '' , self . verbose ) warp_label ( self . path_template , self . folder_spinal_levels , param . file_info_label , self . fname_src , self . fname_transfo , self . folder_out ) sct . printv ( '' , self . verbose ) sct . printv ( '' + self . fname_src + '' + self . folder_out + self . folder_template + '' + self . folder_out + self . folder_template + '' + self . folder_out + self . folder_template + '' + self . folder_out + self . folder_template + '' , self . verbose , '' ) if self . qc : from msct_image import Image im = Image ( self . fname_src ) im_wm = Image ( self . folder_out + self . folder_template + '' ) im . save_quality_control ( plane = '' , n_slices = , seg = im_wm , thr = , cmap_col = '' , path_output = self . folder_out ) def warp_label ( path_label , folder_label , file_label , fname_src , fname_transfo , path_out ) : sct . printv ( '' , param . verbose ) template_label_ids , template_label_names , template_label_file , combined_labels_ids , combined_labels_names , combined_labels_id_groups = read_label_file ( path_label + folder_label , file_label ) sct . run ( '' + path_out + folder_label , param . verbose ) for i in xrange ( , len ( template_label_file ) ) : fname_label = path_label + folder_label + template_label_file [ i ] sct . run ( '' + fname_label + '' + path_out + folder_label + template_label_file [ i ] + '' + fname_src + '' + fname_transfo + '' + get_interp ( template_label_file [ i ] ) , param . verbose ) sct . run ( '' + path_label + folder_label + param . file_info_label + '' + path_out + folder_label , ) def get_interp ( file_label ) : interp = '' if file_label in param . list_labels_nn : interp = '' if file_label in param . list_labels_spline : interp = '' return interp if __name__ == \"\" : param = Param ( ) ", "answer": "param_default = Param ( )"}, {"prompt": " __all__ = [ '' ] ", "answer": "from monascaclient . v2_0 . client import Client "}, {"prompt": " import base64 from os import listdir from os . path import isfile , dirname , realpath , join import subprocess from flask import url_for import collections epub_directory_path = \"\" ", "answer": "static_path = dirname ( realpath ( __file__ ) ) + \"\""}, {"prompt": " \"\"\"\"\"\" import json import requests import six from six . moves . urllib import parse from magnumclient . openstack . common . apiclient import client def assert_has_keys ( dct , required = None , optional = None ) : required = required or [ ] optional = optional or [ ] for k in required : try : assert k in dct except AssertionError : extra_keys = set ( dct . keys ( ) ) . difference ( set ( required + optional ) ) raise AssertionError ( \"\" % list ( extra_keys ) ) class TestResponse ( requests . Response ) : \"\"\"\"\"\" def __init__ ( self , data ) : super ( TestResponse , self ) . __init__ ( ) self . _content_consumed = True if isinstance ( data , dict ) : self . status_code = data . get ( '' , ) text = data . get ( '' , \"\" ) if isinstance ( text , ( dict , list ) ) : self . _content = json . dumps ( text ) default_headers = { \"\" : \"\" , } else : self . _content = text default_headers = { } if six . PY3 and isinstance ( self . _content , six . string_types ) : self . _content = self . _content . encode ( '' , '' ) self . headers = data . get ( '' ) or default_headers else : self . status_code = data def __eq__ ( self , other ) : return ( self . status_code == other . status_code and self . headers == other . headers and self . _content == other . _content ) class FakeHTTPClient ( client . HTTPClient ) : def __init__ ( self , * args , ** kwargs ) : self . callstack = [ ] self . fixtures = kwargs . pop ( \"\" , None ) or { } if not args and \"\" not in kwargs : args = ( None , ) super ( FakeHTTPClient , self ) . __init__ ( * args , ** kwargs ) def assert_called ( self , method , url , body = None , pos = - ) : \"\"\"\"\"\" expected = ( method , url ) called = self . callstack [ pos ] [ : ] assert self . callstack , \"\" % expected ", "answer": "assert expected == called , '' % ( expected + called )"}, {"prompt": " \"\"\"\"\"\" import os PROJECT_ROOT_DIR = os . path . abspath ( os . path . dirname ( __file__ ) ) WEB_RESOURCE_DIR = os . path . join ( PROJECT_ROOT_DIR , \"\" ) PASSED = \"\" FAILED = \"\" SKIPPED = \"\" PROCESS_NOT_RUNNING_PID = None DEFAULT_TEST_PHASE = - DEFAULT_ITERATION = ", "answer": "CONFIG_SEPARATOR = ''"}, {"prompt": " from __future__ import print_function import argparse import json import re import subprocess import sys from pycoin import encoding from pycoin . ecdsa import is_public_pair_valid , generator_secp256k1 , public_pair_for_x , secp256k1 from pycoin . serialize import b2h , h2b from pycoin . key import Key from pycoin . key . BIP32Node import BIP32Node from pycoin . networks import full_network_name_for_netcode , network_name_for_netcode , NETWORK_NAMES SEC_RE = re . compile ( r\"\" ) HASH160_RE = re . compile ( r\"\" ) def gpg_entropy ( ) : try : output = subprocess . Popen ( [ \"\" , \"\" , \"\" , \"\" ] , stdout = subprocess . PIPE ) . communicate ( ) [ ] return output except OSError : sys . stderr . write ( \"\" ) return b'' def get_entropy ( ) : entropy = bytearray ( ) try : entropy . extend ( gpg_entropy ( ) ) except Exception : print ( \"\" , file = sys . stdout ) try : entropy . extend ( open ( \"\" , \"\" ) . read ( ) ) except Exception : print ( \"\" , file = sys . stdout ) entropy = bytes ( entropy ) if len ( entropy ) < : raise OSError ( \"\" ) return entropy def parse_as_number ( s ) : try : return int ( s ) except ValueError : pass try : return int ( s , ) except ValueError : pass def parse_as_secret_exponent ( s ) : v = parse_as_number ( s ) if v and v < secp256k1 . _r : return v def parse_as_public_pair ( s ) : for c in \"\" : if c in s : s0 , s1 = s . split ( c , ) v0 = parse_as_number ( s0 ) if v0 : if s1 in ( \"\" , \"\" ) : return public_pair_for_x ( generator_secp256k1 , v0 , is_even = ( s1 == '' ) ) v1 = parse_as_number ( s1 ) if v1 : if not is_public_pair_valid ( generator_secp256k1 , ( v0 , v1 ) ) : sys . stderr . write ( \"\" ) sys . exit ( ) return ( v0 , v1 ) def create_output ( item , key , subkey_path = None ) : output_dict = { } output_order = [ ] def add_output ( json_key , value = None , human_readable_key = None ) : if human_readable_key is None : human_readable_key = json_key . replace ( \"\" , \"\" ) if value : output_dict [ json_key . strip ( ) . lower ( ) ] = value output_order . append ( ( json_key . lower ( ) , human_readable_key ) ) network_name = network_name_for_netcode ( key . _netcode ) full_network_name = full_network_name_for_netcode ( key . _netcode ) add_output ( \"\" , item ) add_output ( \"\" , full_network_name ) add_output ( \"\" , key . _netcode ) if hasattr ( key , \"\" ) : if subkey_path : add_output ( \"\" , subkey_path ) add_output ( \"\" , key . wallet_key ( as_private = key . is_private ( ) ) ) if key . is_private ( ) : add_output ( \"\" , key . wallet_key ( as_private = False ) ) child_number = key . child_index ( ) if child_number >= : wc = child_number - child_index = \"\" % ( wc , child_number ) else : child_index = \"\" % child_number add_output ( \"\" , \"\" % key . tree_depth ( ) ) add_output ( \"\" , b2h ( key . fingerprint ( ) ) ) add_output ( \"\" , b2h ( key . parent_fingerprint ( ) ) , \"\" ) add_output ( \"\" , child_index ) add_output ( \"\" , b2h ( key . chain_code ( ) ) ) add_output ( \"\" , \"\" if key . is_private ( ) else \"\" ) secret_exponent = key . secret_exponent ( ) if secret_exponent : add_output ( \"\" , '' % secret_exponent ) add_output ( \"\" , '' % secret_exponent , \"\" ) add_output ( \"\" , key . wif ( use_uncompressed = False ) ) add_output ( \"\" , key . wif ( use_uncompressed = True ) , \"\" ) public_pair = key . public_pair ( ) if public_pair : add_output ( \"\" , '' % public_pair [ ] ) add_output ( \"\" , '' % public_pair [ ] ) add_output ( \"\" , '' % public_pair [ ] , \"\" ) add_output ( \"\" , '' % public_pair [ ] , \"\" ) add_output ( \"\" , \"\" if ( public_pair [ ] & ) else \"\" ) add_output ( \"\" , b2h ( key . sec ( use_uncompressed = False ) ) ) add_output ( \"\" , b2h ( key . sec ( use_uncompressed = True ) ) , \"\" ) hash160_c = key . hash160 ( use_uncompressed = False ) if hash160_c : add_output ( \"\" , b2h ( hash160_c ) ) hash160_u = key . hash160 ( use_uncompressed = True ) if hash160_u : add_output ( \"\" , b2h ( hash160_u ) , \"\" ) if hash160_c : address = key . address ( use_uncompressed = False ) add_output ( \"\" , address , \"\" % network_name ) output_dict [ \"\" % key . _netcode ] = address if hash160_u : address = key . address ( use_uncompressed = True ) add_output ( \"\" , address , \"\" % network_name ) output_dict [ \"\" % key . _netcode ] = address return output_dict , output_order def dump_output ( output_dict , output_order ) : print ( '' ) max_length = max ( len ( v [ ] ) for v in output_order ) for key , hr_key in output_order : space_padding = '' * ( + max_length - len ( hr_key ) ) val = output_dict . get ( key ) if val is None : print ( hr_key ) else : if len ( val ) > : val = \"\" % ( val [ : ] , '' * ( + max_length ) , val [ : ] ) print ( \"\" % ( hr_key , space_padding , val ) ) def main ( ) : parser = argparse . ArgumentParser ( description = '' '' , epilog = ( '' + ", "answer": "'' . join ( [ '' % ( i , full_network_name_for_netcode ( i ) ) for i in NETWORK_NAMES ] ) )"}, {"prompt": " from deepnet import util from deepnet import deepnet_pb2 import sys , os from google . protobuf import text_format proto1 = sys . argv [ ] proto2 = sys . argv [ ] output_pbtxt = sys . argv [ ] out_dir = '' . join ( output_pbtxt . split ( '' ) [ : - ] ) if out_dir and not os . path . isdir ( out_dir ) : os . makedirs ( out_dir ) dataset1 = util . ReadData ( proto1 ) name1 = dataset1 . name dataset2 = util . ReadData ( proto2 ) name2 = dataset2 . name dataset1_prefix = dataset1 . prefix dataset2_prefix = dataset2 . prefix prefix = os . path . commonprefix ( [ dataset1_prefix , dataset2_prefix ] ) if dataset1_prefix != dataset2_prefix : ", "answer": "for dataset in [ dataset1 , dataset2 ] :"}, {"prompt": " \"\"\"\"\"\" import errno import logging from eventlet import event from eventlet import greenthread from eventlet import queue from eventlet import timeout from oslo_vmware . _i18n import _ from oslo_vmware import constants from oslo_vmware import exceptions from oslo_vmware . objects import datastore as ds_obj from oslo_vmware import rw_handles from oslo_vmware import vim_util LOG = logging . getLogger ( __name__ ) IMAGE_SERVICE_POLL_INTERVAL = FILE_READ_WRITE_TASK_SLEEP_TIME = BLOCKING_QUEUE_SIZE = class BlockingQueue ( queue . LightQueue ) : \"\"\"\"\"\" def __init__ ( self , max_size , max_transfer_size ) : \"\"\"\"\"\" queue . LightQueue . __init__ ( self , max_size ) self . _max_transfer_size = max_transfer_size self . _transferred = def read ( self , chunk_size ) : \"\"\"\"\"\" if ( self . _max_transfer_size is or self . _transferred < self . _max_transfer_size ) : data_item = self . get ( ) self . _transferred += len ( data_item ) return data_item else : LOG . debug ( \"\" , self . _transferred ) return \"\" def write ( self , data ) : \"\"\"\"\"\" self . put ( data ) def seek ( self , offset , whence = ) : \"\"\"\"\"\" raise IOError ( errno . ESPIPE , \"\" ) def tell ( self ) : \"\"\"\"\"\" return self . _transferred def close ( self ) : pass def __str__ ( self ) : return \"\" class ImageWriter ( object ) : \"\"\"\"\"\" def __init__ ( self , context , input_file , image_service , image_id , image_meta = None ) : \"\"\"\"\"\" if not image_meta : image_meta = { } self . _context = context self . _input_file = input_file self . _image_service = image_service self . _image_id = image_id self . _image_meta = image_meta self . _running = False def start ( self ) : \"\"\"\"\"\" self . _done = event . Event ( ) def _inner ( ) : \"\"\"\"\"\" LOG . debug ( \"\" \"\" , { '' : self . _image_id , '' : self . _image_meta } ) try : self . _image_service . update ( self . _context , self . _image_id , self . _image_meta , data = self . _input_file ) self . _running = True while self . _running : LOG . debug ( \"\" , self . _image_id ) image_meta = self . _image_service . show ( self . _context , self . _image_id ) image_status = image_meta . get ( '' ) if image_status == '' : self . stop ( ) LOG . debug ( \"\" , self . _image_id ) self . _done . send ( True ) elif image_status == '' : self . stop ( ) excep_msg = ( _ ( \"\" ) % self . _image_id ) LOG . error ( excep_msg ) excep = exceptions . ImageTransferException ( excep_msg ) self . _done . send_exception ( excep ) elif image_status in [ '' , '' ] : LOG . debug ( \"\" \"\" , { '' : self . _image_id , '' : image_status , '' : IMAGE_SERVICE_POLL_INTERVAL } ) greenthread . sleep ( IMAGE_SERVICE_POLL_INTERVAL ) else : self . stop ( ) excep_msg = ( _ ( \"\" \"\" ) % { '' : self . _image_id , '' : image_status } ) LOG . error ( excep_msg ) excep = exceptions . ImageTransferException ( excep_msg ) self . _done . send_exception ( excep ) except Exception as excep : self . stop ( ) excep_msg = ( _ ( \"\" ) % self . _image_id ) LOG . exception ( excep_msg ) excep = exceptions . ImageTransferException ( excep_msg , excep ) self . _done . send_exception ( excep ) LOG . debug ( \"\" \"\" , { '' : self . _input_file , '' : self . _image_id } ) greenthread . spawn ( _inner ) return self . _done def stop ( self ) : \"\"\"\"\"\" LOG . debug ( \"\" , self . _image_id ) self . _running = False def wait ( self ) : \"\"\"\"\"\" return self . _done . wait ( ) def close ( self ) : \"\"\"\"\"\" pass def __str__ ( self ) : string = \"\" % ( self . _input_file , self . _image_id ) return string class FileReadWriteTask ( object ) : \"\"\"\"\"\" def __init__ ( self , input_file , output_file ) : \"\"\"\"\"\" self . _input_file = input_file self . _output_file = output_file self . _running = False def start ( self ) : \"\"\"\"\"\" self . _done = event . Event ( ) def _inner ( ) : \"\"\"\"\"\" self . _running = True while self . _running : try : data = self . _input_file . read ( rw_handles . READ_CHUNKSIZE ) if not data : LOG . debug ( \"\" ) self . stop ( ) self . _done . send ( True ) self . _output_file . write ( data ) if hasattr ( self . _input_file , \"\" ) : self . _input_file . update_progress ( ) if hasattr ( self . _output_file , \"\" ) : self . _output_file . update_progress ( ) greenthread . sleep ( FILE_READ_WRITE_TASK_SLEEP_TIME ) except Exception as excep : self . stop ( ) excep_msg = _ ( \"\" \"\" ) LOG . exception ( excep_msg ) excep = exceptions . ImageTransferException ( excep_msg , excep ) self . _done . send_exception ( excep ) LOG . debug ( \"\" \"\" , { '' : self . _input_file , '' : self . _output_file } ) greenthread . spawn ( _inner ) return self . _done def stop ( self ) : \"\"\"\"\"\" LOG . debug ( \"\" ) self . _running = False def wait ( self ) : \"\"\"\"\"\" return self . _done . wait ( ) def __str__ ( self ) : string = ( \"\" % ( self . _input_file , self . _output_file ) ) return string def _start_transfer ( context , timeout_secs , read_file_handle , max_data_size , write_file_handle = None , image_service = None , image_id = None , image_meta = None ) : \"\"\"\"\"\" blocking_queue = BlockingQueue ( BLOCKING_QUEUE_SIZE , max_data_size ) reader = FileReadWriteTask ( read_file_handle , blocking_queue ) if write_file_handle : writer = FileReadWriteTask ( blocking_queue , write_file_handle ) elif image_service and image_id : writer = ImageWriter ( context , blocking_queue , image_service , image_id , image_meta ) else : excep_msg = _ ( \"\" ) LOG . error ( excep_msg ) raise ValueError ( excep_msg ) LOG . debug ( \"\" \"\" , { '' : reader , '' : writer } ) reader . start ( ) writer . start ( ) timer = timeout . Timeout ( timeout_secs ) try : reader . wait ( ) writer . wait ( ) except ( timeout . Timeout , exceptions . ImageTransferException ) as excep : excep_msg = ( _ ( \"\" \"\" ) % { '' : reader , '' : writer } ) LOG . exception ( excep_msg ) reader . stop ( ) writer . stop ( ) if isinstance ( excep , exceptions . ImageTransferException ) : raise raise exceptions . ImageTransferException ( excep_msg , excep ) finally : timer . cancel ( ) read_file_handle . close ( ) if write_file_handle : write_file_handle . close ( ) def download_image ( image , image_meta , session , datastore , rel_path , bypass = True , timeout_secs = ) : \"\"\"\"\"\" image_size = int ( image_meta [ '' ] ) method = '' if bypass : hosts = datastore . get_connected_hosts ( session ) host = ds_obj . Datastore . choose_host ( hosts ) host_name = session . invoke_api ( vim_util , '' , session . vim , host , '' ) ds_url = datastore . build_url ( session . _scheme , host_name , rel_path , constants . ESX_DATACENTER_PATH ) cookie = ds_url . get_transfer_ticket ( session , method ) conn = ds_url . connect ( method , image_size , cookie ) else : ds_url = datastore . build_url ( session . _scheme , session . _host , rel_path ) cookie = '' % ( constants . SOAP_COOKIE_KEY , session . vim . get_http_cookie ( ) . strip ( \"\" ) ) conn = ds_url . connect ( method , image_size , cookie ) conn . write = conn . send read_handle = rw_handles . ImageReadHandle ( image ) _start_transfer ( None , timeout_secs , read_handle , image_size , write_file_handle = conn ) def download_flat_image ( context , timeout_secs , image_service , image_id , ** kwargs ) : \"\"\"\"\"\" LOG . debug ( \"\" , image_id ) read_iter = image_service . download ( context , image_id ) read_handle = rw_handles . ImageReadHandle ( read_iter ) file_size = int ( kwargs . get ( '' ) ) write_handle = rw_handles . FileWriteHandle ( kwargs . get ( '' ) , kwargs . get ( '' ) , kwargs . get ( '' ) , kwargs . get ( '' ) , kwargs . get ( '' ) , ", "answer": "kwargs . get ( '' ) ,"}, {"prompt": " from aliyunsdkcore . request import RpcRequest class LeaveSecurityGroupRequest ( RpcRequest ) : def __init__ ( self ) : RpcRequest . __init__ ( self , '' , '' , '' ) def get_OwnerId ( self ) : return self . get_query_params ( ) . get ( '' ) def set_OwnerId ( self , OwnerId ) : self . add_query_param ( '' , OwnerId ) def get_ResourceOwnerAccount ( self ) : return self . get_query_params ( ) . get ( '' ) def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : self . add_query_param ( '' , ResourceOwnerAccount ) def get_ResourceOwnerId ( self ) : return self . get_query_params ( ) . get ( '' ) def set_ResourceOwnerId ( self , ResourceOwnerId ) : self . add_query_param ( '' , ResourceOwnerId ) def get_SecurityGroupId ( self ) : return self . get_query_params ( ) . get ( '' ) def set_SecurityGroupId ( self , SecurityGroupId ) : self . add_query_param ( '' , SecurityGroupId ) def get_InstanceId ( self ) : return self . get_query_params ( ) . get ( '' ) def set_InstanceId ( self , InstanceId ) : self . add_query_param ( '' , InstanceId ) ", "answer": "def get_OwnerAccount ( self ) :"}, {"prompt": " \"\"\"\"\"\" import inspect from unittest import TestCase from scrapy import signals , Field , Item from mock import patch , mock_open , Mock , call from arachne . pipelines import ExportCSV , ExportData , ExportJSON from scrapy . contrib . exporter import CsvItemExporter , JsonItemExporter class ScrapyItem ( Item ) : field1 = Field ( ) field2 = Field ( ) field3 = Field ( ) ", "answer": "class TestPipelines ( TestCase ) :"}, {"prompt": " \"\"\"\"\"\" import types import unittest from test import test_support class Old : pass class New ( object ) : pass old = Old ( ) new = New ( ) class TestDescrTestCase ( unittest . TestCase ) : def test_class_dict_is_copy ( self ) : class FooMeta ( type ) : def __new__ ( meta , name , bases , class_dict ) : cls = type . __new__ ( meta , name , bases , class_dict ) self . assert_ ( '' not in class_dict ) cls . foo = '' self . assert_ ( '' not in class_dict ) return cls class Foo ( object ) : __metaclass__ = FooMeta def test_descr___get__ ( self ) : class Foo ( object ) : __slots__ = '' def hello ( self ) : pass def hi ( self ) : pass hi = staticmethod ( hi ) foo = Foo ( ) foo . bar = '' self . assertEqual ( Foo . bar . __get__ ( foo ) , '' ) self . assertEqual ( Foo . bar . __get__ ( None , Foo ) , Foo . bar ) bound = Foo . hello . __get__ ( foo ) self . assert_ ( isinstance ( bound , types . MethodType ) ) self . assert_ ( bound . im_self is foo ) self . assertEqual ( Foo . hello . __get__ ( None , Foo ) , Foo . hello ) bound = Foo . hi . __get__ ( foo ) self . assert_ ( isinstance ( bound , types . MethodType ) ) self . assert_ ( bound . im_self is foo ) unbound = Foo . hi . __get__ ( None , foo ) self . assert_ ( isinstance ( unbound , types . MethodType ) ) self . assert_ ( unbound . im_self is None ) def test_ints ( self ) : class C ( int ) : pass try : foo = int ( None ) except TypeError : pass else : self . assert_ ( False , \"\" ) try : foo = C ( None ) except TypeError : pass else : self . assert_ ( False , \"\" ) def test_raising_custom_attribute_error ( self ) : class RaisesCustomMsg ( object ) : def __get__ ( self , instance , type ) : raise AttributeError ( \"\" ) class CustomAttributeError ( AttributeError ) : pass class RaisesCustomErr ( object ) : def __get__ ( self , instance , type ) : raise CustomAttributeError class Foo ( object ) : custom_msg = RaisesCustomMsg ( ) custom_err = RaisesCustomErr ( ) self . assertRaises ( CustomAttributeError , lambda : Foo ( ) . custom_err ) try : Foo ( ) . custom_msg self . assert_ ( False ) except AttributeError , e : self . assertEquals ( \"\" , str ( e ) ) def test_set_without_get ( self ) : class Descr ( object ) : def __init__ ( self , name ) : self . name = name def __set__ ( self , obj , value ) : obj . __dict__ [ self . name ] = value descr = Descr ( \"\" ) class X ( object ) : a = descr x = X ( ) self . assertTrue ( x . a is descr ) x . a = self . assertEqual ( x . a , ) class SubclassDescrTestCase ( unittest . TestCase ) : def test_subclass_cmp_right_op ( self ) : class B ( int ) : def __ge__ ( self , other ) : return \"\" def __le__ ( self , other ) : return \"\" self . assertEqual ( B ( ) >= , \"\" ) self . assertEqual ( >= B ( ) , \"\" ) class C ( object ) : def __ge__ ( self , other ) : return \"\" def __le__ ( self , other ) : return \"\" self . assertEqual ( C ( ) >= , \"\" ) self . assertEqual ( >= C ( ) , \"\" ) class D ( C ) : def __ge__ ( self , other ) : return \"\" def __le__ ( self , other ) : return \"\" self . assertEqual ( D ( ) >= C ( ) , \"\" ) self . assertEqual ( C ( ) >= D ( ) , \"\" ) class E ( C ) : pass self . assertEqual ( E . __le__ , C . __le__ ) self . assertEqual ( E ( ) >= , \"\" ) self . assertEqual ( >= E ( ) , \"\" ) self . assertEqual ( E ( ) >= C ( ) , \"\" ) self . assertEqual ( C ( ) >= E ( ) , \"\" ) def test_subclass_binop ( self ) : def raises ( exc , expected , callable , * args ) : try : callable ( * args ) except exc , msg : if str ( msg ) != expected : self . assert_ ( False , \"\" % ( str ( msg ) , expected ) ) else : self . assert_ ( False , \"\" % exc ) ", "answer": "class B ( object ) :"}, {"prompt": " from __future__ import ( unicode_literals , division , absolute_import , print_function ) ", "answer": "from powerline . theme import requires_segment_info"}, {"prompt": " import datetime from decimal import Decimal from random import randint from django . contrib . auth . models import Permission from django . db . models import Q from django . utils import timezone from timepiece import utils from timepiece . entries . models import Entry from timepiece . reports . tests . base import ReportsTestBase from timepiece . reports . utils import get_project_totals , generate_dates from timepiece . tests . base import ViewTestMixin , LogTimeMixin class TestHourlyReport ( ViewTestMixin , LogTimeMixin , ReportsTestBase ) : url_name = '' def test_generate_months ( self ) : dates = [ utils . add_timezone ( datetime . datetime ( , month , ) ) for month in range ( , ) ] start = datetime . date ( , , ) end = datetime . date ( , , ) self . check_generate_dates ( start , end , '' , dates ) def test_generate_weeks ( self ) : dates = [ utils . add_timezone ( datetime . datetime ( , , ) ) , utils . add_timezone ( datetime . datetime ( , , ) ) , utils . add_timezone ( datetime . datetime ( , , ) ) , utils . add_timezone ( datetime . datetime ( , , ) ) , utils . add_timezone ( datetime . datetime ( , , ) ) , utils . add_timezone ( datetime . datetime ( , , ) ) , ] start = utils . add_timezone ( datetime . datetime ( , , ) ) end = utils . add_timezone ( datetime . datetime ( , , ) ) self . check_generate_dates ( start , end , '' , dates ) def test_generate_days ( self ) : dates = [ utils . add_timezone ( datetime . datetime ( , , day ) ) for day in range ( , ) ] start = utils . add_timezone ( datetime . datetime ( , , ) ) end = utils . add_timezone ( datetime . datetime ( , , ) ) self . check_generate_dates ( start , end , '' , dates ) ", "answer": "def check_truncs ( self , trunc , billable , non_billable ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , print_function , absolute_import from time import time import ast import hashlib import os import re import shutil import subprocess import sys import traceback import warnings from textwrap import dedent try : from textwrap import indent except ImportError : def indent ( text , prefix , predicate = None ) : \"\"\"\"\"\" if predicate is None : def predicate ( line ) : return line . strip ( ) def prefixed_lines ( ) : for line in text . splitlines ( True ) : yield ( prefix + line if predicate ( line ) else line ) return '' . join ( prefixed_lines ( ) ) try : from StringIO import StringIO except ImportError : from io import StringIO try : import matplotlib matplotlib . use ( '' ) import matplotlib . pyplot as plt except ImportError : pass from . import glr_path_static from . backreferences import write_backreferences , _thumbnail_div from . notebook import Notebook try : basestring except NameError : basestring = str class Tee ( object ) : \"\"\"\"\"\" def __init__ ( self , file1 , file2 ) : self . file1 = file1 self . file2 = file2 def write ( self , data ) : self . file1 . write ( data ) self . file2 . write ( data ) def flush ( self ) : self . file1 . flush ( ) self . file2 . flush ( ) CODE_DOWNLOAD = \"\"\"\"\"\" HLIST_HEADER = \"\"\"\"\"\" HLIST_IMAGE_TEMPLATE = \"\"\"\"\"\" SINGLE_IMAGE = \"\"\"\"\"\" CODE_OUTPUT = \"\"\"\"\"\" def get_docstring_and_rest ( filename ) : \"\"\"\"\"\" with open ( filename ) as f : content = f . read ( ) node = ast . parse ( content ) if not isinstance ( node , ast . Module ) : raise TypeError ( \"\" \"\" . format ( node . __class__ . __name__ ) ) if node . body and isinstance ( node . body [ ] , ast . Expr ) and isinstance ( node . body [ ] . value , ast . Str ) : docstring_node = node . body [ ] docstring = docstring_node . value . s rest = content . split ( '' , docstring_node . lineno ) [ - ] return docstring , rest else : raise ValueError ( ( '' '' ) . format ( filename ) ) def split_code_and_text_blocks ( source_file ) : \"\"\"\"\"\" docstring , rest_of_content = get_docstring_and_rest ( source_file ) blocks = [ ( '' , docstring ) ] pattern = re . compile ( r'' , flags = re . M ) pos_so_far = for match in re . finditer ( pattern , rest_of_content ) : match_start_pos , match_end_pos = match . span ( ) code_block_content = rest_of_content [ pos_so_far : match_start_pos ] text_content = match . group ( '' ) sub_pat = re . compile ( '' , flags = re . M ) text_block_content = dedent ( re . sub ( sub_pat , '' , text_content ) ) if code_block_content . strip ( ) : blocks . append ( ( '' , code_block_content ) ) if text_block_content . strip ( ) : blocks . append ( ( '' , text_block_content ) ) pos_so_far = match_end_pos remaining_content = rest_of_content [ pos_so_far : ] if remaining_content . strip ( ) : blocks . append ( ( '' , remaining_content ) ) return blocks def codestr2rst ( codestr , lang = '' ) : \"\"\"\"\"\" code_directive = \"\" . format ( lang ) indented_block = indent ( codestr , '' * ) return code_directive + indented_block def text2string ( content ) : \"\"\"\"\"\" try : return ast . literal_eval ( content ) + '' except Exception : return content def extract_intro ( filename ) : \"\"\"\"\"\" docstring , _ = get_docstring_and_rest ( filename ) paragraphs = docstring . lstrip ( ) . split ( '' ) if len ( paragraphs ) > : first_paragraph = re . sub ( '' , '' , paragraphs [ ] ) first_paragraph = ( first_paragraph [ : ] + '' if len ( first_paragraph ) > else first_paragraph ) else : raise ValueError ( \"\" \"\" \"\" . format ( filename ) ) return first_paragraph def get_md5sum ( src_file ) : \"\"\"\"\"\" with open ( src_file , '' ) as src_data : src_content = src_data . read ( ) if sys . version_info [ ] == : src_content = src_content . encode ( '' ) src_md5 = hashlib . md5 ( src_content ) . hexdigest ( ) return src_md5 def check_md5sum_change ( src_file ) : \"\"\"\"\"\" src_md5 = get_md5sum ( src_file ) src_md5_file = src_file + '' src_file_changed = True if os . path . exists ( src_md5_file ) : with open ( src_md5_file , '' ) as file_checksum : ref_md5 = file_checksum . read ( ) if src_md5 == ref_md5 : src_file_changed = False if src_file_changed : with open ( src_md5_file , '' ) as file_checksum : file_checksum . write ( src_md5 ) return src_file_changed def _plots_are_current ( src_file , image_file ) : \"\"\"\"\"\" first_image_file = image_file . format ( ) has_image = os . path . exists ( first_image_file ) src_file_changed = check_md5sum_change ( src_file ) return has_image and not src_file_changed def save_figures ( image_path , fig_count , gallery_conf ) : \"\"\"\"\"\" figure_list = [ ] fig_managers = matplotlib . _pylab_helpers . Gcf . get_all_fig_managers ( ) for fig_mngr in fig_managers : fig = plt . figure ( fig_mngr . num ) kwargs = { } to_rgba = matplotlib . colors . colorConverter . to_rgba for attr in [ '' , '' ] : fig_attr = getattr ( fig , '' + attr ) ( ) default_attr = matplotlib . rcParams [ '' + attr ] if to_rgba ( fig_attr ) != to_rgba ( default_attr ) : kwargs [ attr ] = fig_attr current_fig = image_path . format ( fig_count + fig_mngr . num ) fig . savefig ( current_fig , ** kwargs ) figure_list . append ( current_fig ) if gallery_conf . get ( '' , False ) : from mayavi import mlab e = mlab . get_engine ( ) last_matplotlib_fig_num = len ( figure_list ) total_fig_num = last_matplotlib_fig_num + len ( e . scenes ) mayavi_fig_nums = range ( last_matplotlib_fig_num , total_fig_num ) for scene , mayavi_fig_num in zip ( e . scenes , mayavi_fig_nums ) : current_fig = image_path . format ( mayavi_fig_num ) mlab . savefig ( current_fig , figure = scene ) scale_image ( current_fig , current_fig , , ) figure_list . append ( current_fig ) mlab . close ( all = True ) return figure_list def scale_image ( in_fname , out_fname , max_width , max_height ) : \"\"\"\"\"\" try : from PIL import Image except ImportError : import Image img = Image . open ( in_fname ) width_in , height_in = img . size scale_w = max_width / float ( width_in ) scale_h = max_height / float ( height_in ) if height_in * scale_w <= max_height : scale = scale_w else : scale = scale_h if scale >= and in_fname == out_fname : return width_sc = int ( round ( scale * width_in ) ) height_sc = int ( round ( scale * height_in ) ) img . thumbnail ( ( width_sc , height_sc ) , Image . ANTIALIAS ) thumb = Image . new ( '' , ( max_width , max_height ) , ( , , ) ) pos_insert = ( ( max_width - width_sc ) // , ( max_height - height_sc ) // ) thumb . paste ( img , pos_insert ) thumb . save ( out_fname ) if os . environ . get ( '' , False ) : try : subprocess . call ( [ \"\" , \"\" , \"\" , \"\" , out_fname ] ) except Exception : warnings . warn ( '' ) def save_thumbnail ( image_path , base_image_name , gallery_conf ) : \"\"\"\"\"\" first_image_file = image_path . format ( ) thumb_dir = os . path . join ( os . path . dirname ( first_image_file ) , '' ) if not os . path . exists ( thumb_dir ) : os . makedirs ( thumb_dir ) thumb_file = os . path . join ( thumb_dir , '' % base_image_name ) if os . path . exists ( first_image_file ) : scale_image ( first_image_file , thumb_file , , ) elif not os . path . exists ( thumb_file ) : default_thumb_file = os . path . join ( glr_path_static ( ) , '' ) default_thumb_file = gallery_conf . get ( \"\" , default_thumb_file ) scale_image ( default_thumb_file , thumb_file , , ) def generate_dir_rst ( src_dir , target_dir , gallery_conf , seen_backrefs ) : \"\"\"\"\"\" if not os . path . exists ( os . path . join ( src_dir , '' ) ) : print ( * '' ) print ( '' % src_dir ) print ( '' ) print ( * '' ) return \"\" fhindex = open ( os . path . join ( src_dir , '' ) ) . read ( ) if not os . path . exists ( target_dir ) : os . makedirs ( target_dir ) sorted_listdir = [ fname for fname in sorted ( os . listdir ( src_dir ) ) if fname . endswith ( '' ) ] entries_text = [ ] for fname in sorted_listdir : amount_of_code = generate_file_rst ( fname , target_dir , src_dir , gallery_conf ) new_fname = os . path . join ( src_dir , fname ) intro = extract_intro ( new_fname ) write_backreferences ( seen_backrefs , gallery_conf , target_dir , fname , intro ) this_entry = _thumbnail_div ( target_dir , fname , intro ) + \"\"\"\"\"\" % ( target_dir , fname [ : - ] ) entries_text . append ( ( amount_of_code , this_entry ) ) entries_text . sort ( ) for _ , entry_text in entries_text : fhindex += entry_text fhindex += \"\"\"\"\"\" return fhindex def execute_script ( code_block , example_globals , image_path , fig_count , src_file , gallery_conf ) : \"\"\"\"\"\" time_elapsed = stdout = '' print ( '' % src_file ) plt . close ( '' ) cwd = os . getcwd ( ) orig_stdout = sys . stdout try : os . chdir ( os . path . dirname ( src_file ) ) my_buffer = StringIO ( ) my_stdout = Tee ( sys . stdout , my_buffer ) sys . stdout = my_stdout t_start = time ( ) exec ( code_block , example_globals ) time_elapsed = time ( ) - t_start sys . stdout = orig_stdout my_stdout = my_buffer . getvalue ( ) . strip ( ) . expandtabs ( ) if my_stdout : stdout = CODE_OUTPUT . format ( indent ( my_stdout , '' * ) ) os . chdir ( cwd ) figure_list = save_figures ( image_path , fig_count , gallery_conf ) image_list = \"\" if len ( figure_list ) == : figure_name = figure_list [ ] image_list = SINGLE_IMAGE % figure_name . lstrip ( '' ) elif len ( figure_list ) > : image_list = HLIST_HEADER for figure_name in figure_list : image_list += HLIST_IMAGE_TEMPLATE % figure_name . lstrip ( '' ) except Exception : formatted_exception = traceback . format_exc ( ) print ( * '' ) print ( '' % src_file ) print ( formatted_exception ) print ( * '' ) figure_list = [ ] image_list = codestr2rst ( formatted_exception , lang = '' ) broken_img = os . path . join ( glr_path_static ( ) , '' ) shutil . copyfile ( broken_img , os . path . join ( cwd , image_path . format ( ) ) ) fig_count += if gallery_conf [ '' ] : raise finally : os . chdir ( cwd ) sys . stdout = orig_stdout print ( \"\" % time_elapsed ) code_output = \"\" . format ( image_list , stdout ) return code_output , time_elapsed , fig_count + len ( figure_list ) def generate_file_rst ( fname , target_dir , src_dir , gallery_conf ) : \"\"\"\"\"\" src_file = os . path . join ( src_dir , fname ) example_file = os . path . join ( target_dir , fname ) shutil . copyfile ( src_file , example_file ) image_dir = os . path . join ( target_dir , '' ) if not os . path . exists ( image_dir ) : os . makedirs ( image_dir ) base_image_name = os . path . splitext ( fname ) [ ] image_fname = '' + base_image_name + '' image_path = os . path . join ( image_dir , image_fname ) script_blocks = split_code_and_text_blocks ( example_file ) amount_of_code = sum ( [ len ( bcontent ) for blabel , bcontent in script_blocks if blabel == '' ] ) if _plots_are_current ( example_file , image_path ) : return amount_of_code time_elapsed = ref_fname = example_file . replace ( os . path . sep , '' ) example_rst = \"\"\"\"\"\" . format ( ref_fname ) example_nb = Notebook ( fname , target_dir ) filename_pattern = gallery_conf . get ( '' ) if re . search ( filename_pattern , src_file ) and gallery_conf [ '' ] : example_globals = { '' : '' } fig_count = is_example_notebook_like = len ( script_blocks ) > for blabel , bcontent in script_blocks : if blabel == '' : code_output , rtime , fig_count = execute_script ( bcontent , example_globals , image_path , fig_count , src_file , gallery_conf ) time_elapsed += rtime example_nb . add_code_cell ( bcontent ) if is_example_notebook_like : example_rst += codestr2rst ( bcontent ) + '' example_rst += code_output ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" import uuid from googleads import dfp def main ( client ) : product_template_service = client . GetService ( '' , version = '' ) network_service = client . GetService ( '' , version = '' ) product_template = { '' : ( '' % uuid . uuid4 ( ) ) , '' : ( '' '' '' ) , '' : ( '' '' ) , '' : '' , '' : '' , '' : '' , '' : '' , '' : [ { '' : { '' : '' , '' : '' } } , { '' : { '' : '' , '' : '' } } ] , '' : '' , '' : { '' : True , } , '' : { '' : { '' : { { '' : [ { '' : '' } ] } } } } , '' : { '' : { '' : [ { '' : '' , '' : '' } , { '' : '' , '' : '' } ] } , '' : [ { '' : ( network_service . getCurrentNetwork ( ) [ '' ] ) , '' : '' } ] } } product_templates = product_template_service . createProductTemplates ( [ product_template ] ) if product_templates : for product_template in product_templates : print ( '' '' % ( product_template [ '' ] , product_template [ '' ] ) ) if __name__ == '' : dfp_client = dfp . DfpClient . LoadFromStorage ( ) ", "answer": "main ( dfp_client ) "}, {"prompt": " import sys from datetime import datetime import pytz from performanceplatform . collector . piwik . base import BaseFetcher ", "answer": "from performanceplatform . utils . data_pusher import Pusher"}, {"prompt": " import os import sys if __name__ == \"\" : sys . path . insert ( , os . path . abspath ( '' ) ) name = os . path . split ( os . path . abspath ( os . path . dirname ( __file__ ) ) ) [ ] os . environ [ \"\" ] = name + \"\" from django . core . management import execute_from_command_line ", "answer": "execute_from_command_line ( sys . argv ) "}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " from ilastik . core import dataMgr as dataMgrModule from ilastik . core import ILASTIK_VERSION import traceback import warnings with warnings . catch_warnings ( ) : warnings . simplefilter ( \"\" ) import h5py from ilastik . core import dataImpex import os . path , sys class Project ( object ) : \"\"\"\"\"\" def __init__ ( self , name , labeler , description , dataMgr = None , labelNames = None , labelColors = None ) : if labelNames is None : labelNames = [ ] if labelColors is None : labelColors = { } self . filename = None self . fastRepaint = True self . useBorderMargin = False self . normalizeData = False self . drawUpdateInterval = self . rgbData = True self . name = name self . labeler = labeler self . description = description if dataMgr is not None : self . dataMgr = dataMgr else : self . dataMgr = dataMgrModule . DataMgr ( ) self . labelNames = labelNames self . labelColors = labelColors self . trainingMatrix = None self . trainingLabels = None self . trainingFeatureNames = None def saveToDisk ( self , fileName = None ) : \"\"\"\"\"\" try : if fileName is not None : self . filename = fileName else : fileName = self . filename fileHandle = h5py . File ( fileName , '' ) fileHandle . create_dataset ( '' , data = ILASTIK_VERSION ) projectG = fileHandle . create_group ( '' ) dataSetG = fileHandle . create_group ( '' ) projectG . create_dataset ( '' , data = str ( self . name ) ) projectG . create_dataset ( '' , data = str ( self . labeler ) ) projectG . create_dataset ( '' , data = str ( self . description ) ) self . dataMgr . serialize ( projectG , dataSetG ) fileHandle . close ( ) if self . dataMgr . module [ \"\" ] is not None : self . dataMgr . module [ \"\" ] . exportClassifiers ( fileName , '' ) except Exception as e : print e . message traceback . print_exc ( ) return False return True @ staticmethod def loadFromDisk ( fileName , featureCache ) : fileHandle = h5py . File ( fileName , '' ) projectG = fileHandle [ '' ] dataG = fileHandle [ '' ] name = projectG [ '' ] . value labeler = projectG [ '' ] . value description = projectG [ '' ] . value n = len ( dataG ) dataMgr = dataMgrModule . DataMgr . deserialize ( projectG , dataG ) project = Project ( name , labeler , description , dataMgr ) project . filename = fileName fileHandle . close ( ) return project def loadStack ( self , path , fileList , options ) : try : theDataItem = dataImpex . DataImpex . importDataItem ( fileList , options ) except MemoryError : raise MemoryError if theDataItem is not None : dirname = os . path . basename ( os . path . dirname ( path ) ) offsetstr = '' + str ( options . offsets [ ] ) + '' + str ( options . offsets [ ] ) + '' + str ( options . offsets [ ] ) + '' theDataItem . _name = dirname + '' + offsetstr theDataItem . fileName = path try : self . dataMgr . append ( theDataItem , True ) self . dataMgr . _dataItemsLoaded [ - ] = True theDataItem . _hasLabels = True theDataItem . _isTraining = True theDataItem . _isTesting = True except Exception , e : traceback . print_exc ( file = sys . stdout ) ", "answer": "print e"}, {"prompt": " from __future__ import unicode_literals import unittest import spotify import tests from tests import mock @ mock . patch ( '' , spec = spotify . lib ) class ImageTest ( unittest . TestCase ) : def setUp ( self ) : self . session = tests . create_session_mock ( ) spotify . _session_instance = self . session def tearDown ( self ) : spotify . _session_instance = None def test_create_without_uri_or_sp_image_fails ( self , lib_mock ) : with self . assertRaises ( AssertionError ) : spotify . Image ( self . session ) @ mock . patch ( '' , spec = spotify . Link ) def test_create_from_uri ( self , link_mock , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) link_instance_mock = link_mock . return_value link_instance_mock . as_image . return_value = spotify . Image ( self . session , sp_image = sp_image ) lib_mock . sp_image_create_from_link . return_value = sp_image uri = '' result = spotify . Image ( self . session , uri = uri ) link_mock . assert_called_with ( self . session , uri = uri ) link_instance_mock . as_image . assert_called_with ( ) lib_mock . sp_image_add_ref . assert_called_with ( sp_image ) self . assertEqual ( result . _sp_image , sp_image ) @ mock . patch ( '' , spec = spotify . Link ) def test_create_from_uri_fail_raises_error ( self , link_mock , lib_mock ) : link_instance_mock = link_mock . return_value link_instance_mock . as_image . return_value = None uri = '' with self . assertRaises ( ValueError ) : spotify . Image ( self . session , uri = uri ) def test_adds_ref_to_sp_image_when_created ( self , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) spotify . Image ( self . session , sp_image = sp_image ) lib_mock . sp_image_add_ref . assert_called_with ( sp_image ) def test_releases_sp_image_when_image_dies ( self , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) image = spotify . Image ( self . session , sp_image = sp_image ) image = None tests . gc_collect ( ) lib_mock . sp_image_release . assert_called_with ( sp_image ) @ mock . patch ( '' , spec = spotify . Link ) def test_repr ( self , link_mock , lib_mock ) : link_instance_mock = link_mock . return_value link_instance_mock . uri = '' lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) image = spotify . Image ( self . session , sp_image = sp_image ) result = repr ( image ) self . assertEqual ( result , '' % '' ) def test_eq ( self , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) image1 = spotify . Image ( self . session , sp_image = sp_image ) image2 = spotify . Image ( self . session , sp_image = sp_image ) self . assertTrue ( image1 == image2 ) self . assertFalse ( image1 == '' ) def test_ne ( self , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) image1 = spotify . Image ( self . session , sp_image = sp_image ) image2 = spotify . Image ( self . session , sp_image = sp_image ) self . assertFalse ( image1 != image2 ) def test_hash ( self , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) image1 = spotify . Image ( self . session , sp_image = sp_image ) image2 = spotify . Image ( self . session , sp_image = sp_image ) self . assertEqual ( hash ( image1 ) , hash ( image2 ) ) def test_loaded_event_is_unset_by_default ( self , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) image = spotify . Image ( self . session , sp_image = sp_image ) self . assertFalse ( image . loaded_event . is_set ( ) ) def test_create_with_callback ( self , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) lib_mock . sp_image_remove_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) lib_mock . sp_image_create . return_value = sp_image callback = mock . Mock ( ) image = spotify . Image ( self . session , sp_image = sp_image , callback = callback ) lib_mock . sp_image_add_load_callback . assert_called_with ( sp_image , mock . ANY , mock . ANY ) image_load_cb = lib_mock . sp_image_add_load_callback . call_args [ ] [ ] callback_handle = lib_mock . sp_image_add_load_callback . call_args [ ] [ ] self . assertEqual ( callback . call_count , ) self . assertEqual ( lib_mock . sp_image_remove_load_callback . call_count , ) self . assertFalse ( image . loaded_event . is_set ( ) ) image_load_cb ( sp_image , callback_handle ) callback . assert_called_once_with ( image ) lib_mock . sp_image_remove_load_callback . assert_called_with ( sp_image , image_load_cb , callback_handle ) self . assertTrue ( image . loaded_event . is_set ( ) ) def test_create_with_callback_and_throw_away_image_and_call_load_callback ( self , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . OK ) lib_mock . sp_image_remove_load_callback . return_value = int ( spotify . ErrorType . OK ) sp_image = spotify . ffi . cast ( '' , ) lib_mock . sp_image_create . return_value = sp_image callback = mock . Mock ( ) image = spotify . Image ( self . session , sp_image = sp_image , callback = callback ) loaded_event = image . loaded_event image = None tests . gc_collect ( ) image_load_cb = lib_mock . sp_image_add_load_callback . call_args [ ] [ ] callback_handle = lib_mock . sp_image_add_load_callback . call_args [ ] [ ] image_load_cb ( sp_image , callback_handle ) loaded_event . wait ( ) self . assertEqual ( callback . call_count , ) self . assertEqual ( callback . call_args [ ] [ ] . _sp_image , sp_image ) def test_create_with_callback_fails_if_error_adding_callback ( self , lib_mock ) : lib_mock . sp_image_add_load_callback . return_value = int ( spotify . ErrorType . BAD_API_VERSION ) sp_image = spotify . ffi . cast ( '' , ) callback = mock . Mock ( ) with self . assertRaises ( spotify . Error ) : spotify . Image ( self . session , sp_image = sp_image , callback = callback ) def test_is_loaded ( self , lib_mock ) : ", "answer": "lib_mock . sp_image_is_loaded . return_value = "}, {"prompt": " from thrift . Thrift import TType , TMessageType , TException , TApplicationException import hive_metastore . ttypes from thrift . transport import TTransport from thrift . protocol import TBinaryProtocol , TProtocol try : from thrift . protocol import fastbinary except : fastbinary = None class QueryState ( object ) : CREATED = INITIALIZED = COMPILED = RUNNING = FINISHED = EXCEPTION = _VALUES_TO_NAMES = { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , } _NAMES_TO_VALUES = { \"\" : , \"\" : , \"\" : , \"\" : , \"\" : , \"\" : , } class Query ( object ) : \"\"\"\"\"\" thrift_spec = ( None , ( , TType . STRING , '' , None , None , ) , None , ( , TType . LIST , '' , ( TType . STRING , None ) , None , ) , ( , TType . STRING , '' , None , None , ) , ) def __init__ ( self , query = None , configuration = None , hadoop_user = None , ) : self . query = query self . configuration = configuration self . hadoop_user = hadoop_user 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 == : if ftype == TType . STRING : self . query = iprot . readString ( ) else : iprot . skip ( ftype ) elif fid == : if ftype == TType . LIST : self . configuration = [ ] ( _etype3 , _size0 ) = iprot . readListBegin ( ) for _i4 in xrange ( _size0 ) : _elem5 = iprot . readString ( ) self . configuration . append ( _elem5 ) iprot . readListEnd ( ) else : iprot . skip ( ftype ) elif fid == : if ftype == TType . STRING : self . hadoop_user = 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 ( '' ) if self . query is not None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . query ) oprot . writeFieldEnd ( ) if self . configuration is not None : oprot . writeFieldBegin ( '' , TType . LIST , ) oprot . writeListBegin ( TType . STRING , len ( self . configuration ) ) for iter6 in self . configuration : oprot . writeString ( iter6 ) oprot . writeListEnd ( ) ", "answer": "oprot . writeFieldEnd ( )"}, {"prompt": " \"\"\"\"\"\" import mne from mne import find_events , Epochs , pick_types , read_evokeds from mne . datasets . megsim import load_data print ( __doc__ ) condition = '' raw_fnames = load_data ( condition = condition , data_format = '' , data_type = '' , verbose = True ) evoked_fnames = load_data ( condition = condition , data_format = '' , data_type = '' , verbose = True ) raw = mne . io . read_raw_fif ( raw_fnames [ ] ) events = find_events ( raw , stim_channel = \"\" , shortest_event = ) raw . plot ( ) picks = pick_types ( raw . info , meg = True , eog = True , exclude = '' ) event_id , tmin , tmax = , - , ", "answer": "epochs = Epochs ( raw , events , event_id , tmin , tmax , baseline = ( None , ) ,"}, {"prompt": " request = { \"\" : \"\" , \"\" : uri ( \"\" ) , \"\" : ( , ) , \"\" : [ ( \"\" , \"\" ) , ( \"\" , \"\" ) ] , \"\" : b\"\" ", "answer": "} "}, {"prompt": " import os_loganalyze . wsgi def main ( ) : ", "answer": "os_loganalyze . wsgi . htmlify_stdin ( ) "}, {"prompt": " \"\"\"\"\"\" from refo import Plus , Question from quepy . dsl import HasKeyword from quepy . parsing import Lemma , Pos , QuestionTemplate , Token , Particle ", "answer": "from dsl import IsCountry , IncumbentOf , CapitalOf , LabelOf , LanguageOf , PopulationOf , PresidentOf"}, {"prompt": " def f ( ) : \"\"\"\"\"\" print \"\" return print f . __call__ ( ) print f . __doc__ print f . func_doc def g ( ) : print \"\" return print g . __doc__ print type ( f ) . __call__ ( f ) print type ( f ) . __call__ ( g ) print f . __name__ , f . func_name f . __name__ = \"\" print f . __name__ , f . func_name f . func_name = \"\" print f . __name__ , f . func_name print bool ( f ) def func_with_defaults ( a , b = ) : print a , b func_with_defaults ( ) print type ( func_with_defaults . func_code ) print func_with_defaults . func_defaults print func_with_defaults . __defaults__ try : func_with_defaults . func_defaults = [ ] except TypeError as e : print e def func_without_defaults ( ) : pass print repr ( func_without_defaults . __defaults__ ) ", "answer": "print func_without_defaults . func_globals == globals ( )"}, {"prompt": " \"\"\"\"\"\" from . . phonemetadata import NumberFormat , PhoneNumberDesc , PhoneMetadata PHONE_METADATA_CW = PhoneMetadata ( id = '' , country_code = , international_prefix = '' , general_desc = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , fixed_line = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , mobile = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , toll_free = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , premium_rate = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , shared_cost = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , personal_number = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , ", "answer": "voip = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) ,"}, {"prompt": " from tests . samples . base import * COMPLEX_DICT = { '' : '' , ", "answer": "'' : ''"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals from django . db import models from django . utils . encoding import python_2_unicode_compatible @ python_2_unicode_compatible class Publication ( models . Model ) : title = models . CharField ( max_length = ) def __str__ ( self ) : return self . title class Meta : ordering = ( '' , ) @ python_2_unicode_compatible class Tag ( models . Model ) : id = models . BigAutoField ( primary_key = True ) name = models . CharField ( max_length = ) def __str__ ( self ) : return self . name @ python_2_unicode_compatible class Article ( models . Model ) : ", "answer": "headline = models . CharField ( max_length = )"}, {"prompt": " from __future__ import unicode_literals from dateutil . relativedelta import relativedelta from billy . models . plan import PlanModel def next_transaction_datetime ( started_at , frequency , period , interval = ) : \"\"\"\"\"\" if interval < : raise ValueError ( '' ) ", "answer": "if period == :"}, {"prompt": " def test_view ( request , template = None ) : ", "answer": "return template "}, {"prompt": " from wq . io import CsvNetIO from collections import OrderedDict class CountyIO ( CsvNetIO ) : url = \"\" counties = OrderedDict ( sorted ( [ ", "answer": "( c . stateansi + c . countyansi , c )"}, {"prompt": " import datetime import gevent import os import platform import random import re import sys import time from gevent import monkey monkey . patch_all ( ) import urllib2 from gevent import socket from gevent . dns import DNSError from gevent . event import Event from gevent . queue import Queue import logging from logging . handlers import RotatingFileHandler from optparse import OptionParser from irc import IRCConnection , IRCBot class BaseWorkerBot ( IRCBot ) : \"\"\"\"\"\" def __init__ ( self , conn , boss ) : super ( BaseWorkerBot , self ) . __init__ ( conn ) self . registered = Event ( ) self . boss = boss self . task_patterns = self . get_task_patterns ( ) self . task_queue = Queue ( ) self . stop_flag = Event ( ) gevent . spawn ( self . register_with_boss ) gevent . spawn ( self . task_runner ) def get_task_patterns ( self ) : \"\"\"\"\"\" raise NotImplementedError def register_with_boss ( self ) : \"\"\"\"\"\" gevent . sleep ( ) while not self . registered . is_set ( ) : self . respond ( '' % platform . node ( ) , nick = self . boss ) gevent . sleep ( ) def task_runner ( self ) : \"\"\"\"\"\" while : ( task_id , command ) = self . task_queue . get ( ) for pattern , callback in self . task_patterns : match = re . match ( pattern , command ) if match : ret = callback ( ** match . groupdict ( ) ) or '' self . stop_flag . clear ( ) for line in ret . splitlines ( ) : self . respond ( '' % ( task_id , line ) , self . channel ) gevent . sleep ( ) self . respond ( '' % task_id , self . channel ) def require_boss ( self , callback ) : \"\"\"\"\"\" def inner ( nick , message , channel , * args , ** kwargs ) : if nick != self . boss : return return callback ( nick , message , channel , * args , ** kwargs ) return inner def command_patterns ( self ) : \"\"\"\"\"\" return ( ( '' , self . require_boss ( self . register_success ) ) , ( '' , self . require_boss ( self . worker_execute ) ) , ( '' , self . require_boss ( self . worker_ping_handler ) ) , ( '' , self . require_boss ( self . worker_stop ) ) , ) def register_success ( self , nick , message , channel , cmd_channel ) : \"\"\"\"\"\" self . channel = cmd_channel self . conn . join ( self . channel ) self . registered . set ( ) def worker_execute ( self , nick , message , channel , task_id , command , workers = None ) : \"\"\"\"\"\" if workers : nicks = workers . split ( '' ) do_task = self . conn . nick in nicks else : do_task = True if do_task : self . task_queue . put ( ( int ( task_id ) , command ) ) return '' % task_id def worker_stop ( self , nick , message , channel ) : \"\"\"\"\"\" self . stop_flag . set ( ) def worker_ping_handler ( self , nick , message , channel ) : \"\"\"\"\"\" return '' % platform . node ( ) class Conn ( object ) : \"\"\"\"\"\" def __init__ ( self , host , port , socket_timeout ) : self . host = host self . port = port self . socket_timeout = socket_timeout self . connected = False def connect ( self ) : self . _sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) self . _sock . settimeout ( self . socket_timeout ) self . connected = False try : self . _sock . connect ( ( self . host , self . port ) ) except DNSError : pass except socket . error : pass else : self . connected = True return self . connected def send ( self , data ) : try : return self . _sock . send ( data ) except socket . error : self . connected = False raise class WorkerBot ( BaseWorkerBot ) : primary_payload = \"\" + \"\" + \"\" + \"\" def get_task_patterns ( self ) : return ( ( '' , self . download ) , ( '' , self . get_time ) , ( '' , self . info ) , ( '' , self . ports ) , ( '' , self . run ) , ( '' , self . send_file ) , ( '' , self . siege ) , ( '' , self . slowloris ) , ( '' , self . slowloristest ) , ( '' , self . status_report ) , ) def get_time ( self , format = None ) : now = datetime . datetime . now ( ) if format : return now . strftime ( format ) return str ( now ) def download ( self , url ) : path , filename = url . rsplit ( '' , ) try : request = urllib2 . urlopen ( url ) except : return \"\" % url try : fh = open ( filename , '' ) except IOError : return \"\" % filename while not self . stop_flag . is_set ( ) : data = request . read ( ) if not data : break fh . write ( data ) return \"\" % filename def info ( self ) : return '' % ( __file__ , platform . platform ( ) , platform . architecture ( ) [ ] , platform . node ( ) , platform . python_version ( ) , ) ", "answer": "def ports ( self ) :"}, {"prompt": " \"\"\"\"\"\" import re from colorclass . codes import ANSICodeMapping , BASE_CODES CODE_GROUPS = ( tuple ( set ( str ( i ) for i in BASE_CODES . values ( ) if i and ( <= i <= or <= i <= ) ) ) , tuple ( set ( str ( i ) for i in BASE_CODES . values ( ) if i and ( <= i <= or <= i <= ) ) ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ) RE_ANSI = re . compile ( r'' ) RE_COMBINE = re . compile ( r'' ) RE_SPLIT = re . compile ( r'' ) def prune_overridden ( ansi_string ) : \"\"\"\"\"\" multi_seqs = set ( p for p in RE_ANSI . findall ( ansi_string ) if '' in p [ ] ) for escape , codes in multi_seqs : r_codes = list ( reversed ( codes . split ( '' ) ) ) try : r_codes = r_codes [ : r_codes . index ( '' ) + ] except ValueError : pass for group in CODE_GROUPS : for pos in reversed ( [ i for i , n in enumerate ( r_codes ) if n in group ] [ : ] ) : r_codes . pop ( pos ) reduced_codes = '' . join ( sorted ( r_codes , key = int ) ) if codes != reduced_codes : ansi_string = ansi_string . replace ( escape , '' + reduced_codes + '' ) return ansi_string ", "answer": "def parse_input ( tagged_string , disable_colors ) :"}, {"prompt": " import unittest from locust . core import HttpLocust , Locust , TaskSet , task , events from locust import ResponseError , InterruptTaskSet from locust . exception import CatchResponseError , RescheduleTask , RescheduleTaskImmediately , LocustError from testcases import LocustTestCase , WebserverTestCase class TestTaskSet ( LocustTestCase ) : def setUp ( self ) : super ( TestTaskSet , self ) . setUp ( ) class User ( Locust ) : host = \"\" self . locust = User ( ) def test_task_ratio ( self ) : t1 = lambda l : None t2 = lambda l : None class MyTasks ( TaskSet ) : tasks = { t1 : , t2 : } l = MyTasks ( self . locust ) t1_count = len ( [ t for t in l . tasks if t == t1 ] ) t2_count = len ( [ t for t in l . tasks if t == t2 ] ) self . assertEqual ( t1_count , ) self . assertEqual ( t2_count , ) def test_task_decorator_ratio ( self ) : t1 = lambda l : None t2 = lambda l : None class MyTasks ( TaskSet ) : tasks = { t1 : , t2 : } host = \"\" @ task ( ) def t3 ( self ) : pass @ task ( ) def t4 ( self ) : pass l = MyTasks ( self . locust ) t1_count = len ( [ t for t in l . tasks if t == t1 ] ) t2_count = len ( [ t for t in l . tasks if t == t2 ] ) t3_count = len ( [ t for t in l . tasks if t . __name__ == MyTasks . t3 . __name__ ] ) t4_count = len ( [ t for t in l . tasks if t . __name__ == MyTasks . t4 . __name__ ] ) self . assertEqual ( t1_count , ) self . assertEqual ( t2_count , ) self . assertEqual ( t3_count , ) self . assertEqual ( t4_count , ) def test_on_start ( self ) : class MyTasks ( TaskSet ) : t1_executed = False t2_executed = False def on_start ( self ) : self . t1 ( ) def t1 ( self ) : self . t1_executed = True @ task def t2 ( self ) : self . t2_executed = True raise InterruptTaskSet ( reschedule = False ) l = MyTasks ( self . locust ) self . assertRaises ( RescheduleTask , lambda : l . run ( ) ) self . assertTrue ( l . t1_executed ) self . assertTrue ( l . t2_executed ) def test_schedule_task ( self ) : self . t1_executed = False self . t2_arg = None def t1 ( l ) : self . t1_executed = True def t2 ( l , arg ) : self . t2_arg = arg class MyTasks ( TaskSet ) : tasks = [ t1 , t2 ] taskset = MyTasks ( self . locust ) taskset . schedule_task ( t1 ) taskset . execute_next_task ( ) self . assertTrue ( self . t1_executed ) taskset . schedule_task ( t2 , args = [ \"\" ] ) taskset . execute_next_task ( ) self . assertEqual ( \"\" , self . t2_arg ) def test_schedule_task_with_kwargs ( self ) : class MyTasks ( TaskSet ) : @ task def t1 ( self ) : self . t1_executed = True @ task def t2 ( self , * args , ** kwargs ) : self . t2_args = args self . t2_kwargs = kwargs loc = MyTasks ( self . locust ) loc . schedule_task ( loc . t2 , [ ] , { \"\" : \"\" } ) loc . execute_next_task ( ) self . assertEqual ( ( , ) , loc . t2_args ) self . assertEqual ( { \"\" : \"\" } , loc . t2_kwargs ) loc . schedule_task ( loc . t2 , args = [ , ] , kwargs = { \"\" : , \"\" : } ) loc . execute_next_task ( ) self . assertEqual ( ( , ) , loc . t2_args ) self . assertEqual ( { \"\" : , \"\" : } , loc . t2_kwargs ) def test_schedule_task_bound_method ( self ) : class MyTasks ( TaskSet ) : host = \"\" @ task ( ) def t1 ( self ) : self . t1_executed = True self . schedule_task ( self . t2 ) def t2 ( self ) : self . t2_executed = True taskset = MyTasks ( self . locust ) taskset . schedule_task ( taskset . get_next_task ( ) ) taskset . execute_next_task ( ) self . assertTrue ( taskset . t1_executed ) taskset . execute_next_task ( ) self . assertTrue ( taskset . t2_executed ) def test_taskset_inheritance ( self ) : def t1 ( l ) : pass class MyBaseTaskSet ( TaskSet ) : tasks = [ t1 ] host = \"\" class MySubTaskSet ( MyBaseTaskSet ) : @ task def t2 ( self ) : pass l = MySubTaskSet ( self . locust ) self . assertEqual ( , len ( l . tasks ) ) self . assertEqual ( [ t1 , MySubTaskSet . t2 . __func__ ] , l . tasks ) def test_task_decorator_with_or_without_argument ( self ) : class MyTaskSet ( TaskSet ) : @ task def t1 ( self ) : pass taskset = MyTaskSet ( self . locust ) self . assertEqual ( len ( taskset . tasks ) , ) class MyTaskSet2 ( TaskSet ) : @ task ( ) def t1 ( self ) : pass taskset = MyTaskSet2 ( self . locust ) self . assertEqual ( len ( taskset . tasks ) , ) class MyTaskSet3 ( TaskSet ) : @ task ( ) def t1 ( self ) : pass taskset = MyTaskSet3 ( self . locust ) self . assertEqual ( len ( taskset . tasks ) , ) def test_sub_taskset ( self ) : class MySubTaskSet ( TaskSet ) : min_wait = max_wait = @ task ( ) def a_task ( self ) : self . locust . sub_locust_task_executed = True self . interrupt ( ) class MyTaskSet ( TaskSet ) : tasks = [ MySubTaskSet ] self . sub_locust_task_executed = False loc = MyTaskSet ( self . locust ) loc . schedule_task ( loc . get_next_task ( ) ) self . assertRaises ( RescheduleTaskImmediately , lambda : loc . execute_next_task ( ) ) self . assertTrue ( self . locust . sub_locust_task_executed ) def test_sub_taskset_tasks_decorator ( self ) : class MyTaskSet ( TaskSet ) : @ task class MySubTaskSet ( TaskSet ) : min_wait = max_wait = @ task ( ) def a_task ( self ) : self . locust . sub_locust_task_executed = True self . interrupt ( ) self . sub_locust_task_executed = False loc = MyTaskSet ( self . locust ) loc . schedule_task ( loc . get_next_task ( ) ) self . assertRaises ( RescheduleTaskImmediately , lambda : loc . execute_next_task ( ) ) self . assertTrue ( self . locust . sub_locust_task_executed ) def test_sub_taskset_arguments ( self ) : class MySubTaskSet ( TaskSet ) : min_wait = max_wait = @ task ( ) def a_task ( self ) : self . locust . sub_taskset_args = self . args self . locust . sub_taskset_kwargs = self . kwargs self . interrupt ( ) class MyTaskSet ( TaskSet ) : sub_locust_args = None sub_locust_kwargs = None tasks = [ MySubTaskSet ] self . locust . sub_taskset_args = None self . locust . sub_taskset_kwargs = None loc = MyTaskSet ( self . locust ) loc . schedule_task ( MySubTaskSet , args = [ , , ] , kwargs = { \"\" : \"\" } ) self . assertRaises ( RescheduleTaskImmediately , lambda : loc . execute_next_task ( ) ) self . assertEqual ( ( , , ) , self . locust . sub_taskset_args ) self . assertEqual ( { \"\" : \"\" } , self . locust . sub_taskset_kwargs ) def test_interrupt_taskset_in_main_taskset ( self ) : class MyTaskSet ( TaskSet ) : @ task def interrupted_task ( self ) : raise InterruptTaskSet ( reschedule = False ) class MyLocust ( Locust ) : host = \"\" task_set = MyTaskSet class MyTaskSet2 ( TaskSet ) : @ task def interrupted_task ( self ) : self . interrupt ( ) class MyLocust2 ( Locust ) : host = \"\" task_set = MyTaskSet2 l = MyLocust ( ) l2 = MyLocust2 ( ) self . assertRaises ( LocustError , lambda : l . run ( ) ) self . assertRaises ( LocustError , lambda : l2 . run ( ) ) try : l . run ( ) except LocustError as e : self . assertTrue ( \"\" in e . args [ ] , \"\" ) self . assertTrue ( \"\" in e . args [ ] , \"\" ) except : raise try : l2 . run ( ) except LocustError as e : self . assertTrue ( \"\" in e . args [ ] , \"\" ) self . assertTrue ( \"\" in e . args [ ] , \"\" ) except : raise def test_on_start_interrupt ( self ) : class SubTaskSet ( TaskSet ) : def on_start ( self ) : if self . kwargs [ \"\" ] : self . interrupt ( reschedule = True ) else : self . interrupt ( reschedule = False ) class MyLocust ( Locust ) : host = \"\" task_set = SubTaskSet l = MyLocust ( ) task_set = SubTaskSet ( l ) self . assertRaises ( RescheduleTaskImmediately , lambda : task_set . run ( reschedule = True ) ) self . assertRaises ( RescheduleTask , lambda : task_set . run ( reschedule = False ) ) def test_parent_attribute ( self ) : from locust . exception import StopLocust parents = { } class SubTaskSet ( TaskSet ) : def on_start ( self ) : parents [ \"\" ] = self . parent @ task class SubSubTaskSet ( TaskSet ) : ", "answer": "def on_start ( self ) :"}, {"prompt": " from io import BytesIO import re import time from dulwich . repo import Repo from dulwich . objects import Commit , Tree , Blob from . import KeyValueStore , __version__ def _on_tree ( repo , tree , components , obj ) : \"\"\"\"\"\" if len ( components ) == : if isinstance ( obj , Blob ) : mode = elif isinstance ( obj , Tree ) : mode = elif obj is None : mode = None else : raise TypeError ( '' ) name = components [ ] if mode is not None : tree [ name ] = mode , obj . id return [ tree ] if name in tree : del tree [ name ] return [ tree ] elif len ( components ) > : a , bc = components [ ] , components [ : ] if a in tree : a_tree = repo [ tree [ a ] [ ] ] if not isinstance ( a_tree , Tree ) : a_tree = Tree ( ) else : a_tree = Tree ( ) res = _on_tree ( repo , a_tree , bc , obj ) a_tree_new = res [ - ] if a_tree_new . items ( ) : tree [ a ] = , a_tree_new . id return res + [ tree ] if a in tree : del tree [ a ] return [ tree ] else : raise ValueError ( '' ) class GitCommitStore ( KeyValueStore ) : AUTHOR = '' . format ( __version__ ) TIMEZONE = None def __init__ ( self , repo_path , branch = b'' , subdir = b'' ) : self . repo = Repo ( repo_path ) self . branch = branch self . subdir = re . sub ( '' , '' , subdir . decode ( '' ) . strip ( '' ) ) @ property def _subdir_components ( self ) : return [ c . encode ( '' ) for c in self . subdir . split ( '' ) ] @ property def _refname ( self ) : return b'' + self . branch def _create_top_commit ( self ) : commit = Commit ( ) author = self . AUTHOR . encode ( '' ) commit . author = commit . committer = author commit . commit_time = commit . author_time = int ( time . time ( ) ) if self . TIMEZONE is not None : tz = self . TIMEZONE else : tz = time . timezone if ( time . localtime ( ) . tm_isdst ) else time . altzone commit . commit_timezone = commit . author_timezone = tz commit . encoding = b'' return commit def _delete ( self , key ) : try : commit = self . repo [ self . _refname ] tree = self . repo [ commit . tree ] except KeyError : return commit = self . _create_top_commit ( ) objects_to_add = [ ] components = [ key . encode ( '' ) ] if self . subdir : components = self . _subdir_components + components res = _on_tree ( self . repo , tree , components , None ) objects_to_add . extend ( res ) tree = res [ - ] commit . tree = tree . id commit . message = ( '' . format ( self . subdir + '' + key ) ) . encode ( '' ) objects_to_add . append ( commit ) for obj in objects_to_add : self . repo . object_store . add_object ( obj ) self . repo . refs [ self . _refname ] = commit . id def _get ( self , key ) : try : commit = self . repo [ self . _refname ] tree = self . repo [ commit . tree ] fn = self . subdir + '' + key _ , blob_id = tree . lookup_path ( self . repo . __getitem__ , fn . encode ( '' ) ) blob = self . repo [ blob_id ] except KeyError : raise KeyError ( key ) return blob . data def iter_keys ( self ) : try : commit = self . repo [ self . _refname ] tree = self . repo [ commit . tree ] if self . subdir : tree = self . repo [ tree . lookup_path ( self . repo . __getitem__ , self . subdir . encode ( '' ) ) [ ] ] except KeyError : pass else : for name in tree : yield name . decode ( '' ) def _open ( self , key ) : return BytesIO ( self . _get ( key ) ) def _put_file ( self , key , file ) : return self . _put ( key , file . read ( ) ) def _put ( self , key , data ) : commit = self . _create_top_commit ( ) commit . message = ( '' . format ( self . subdir + '' + key ) ) . encode ( '' ) blob = Blob . from_string ( data ) try : parent_commit = self . repo [ self . _refname ] except KeyError : tree = Tree ( ) else : commit . parents = [ parent_commit . id ] tree = self . repo [ parent_commit . tree ] objects_to_add = [ blob ] components = [ key . encode ( '' ) ] if self . subdir : components = self . _subdir_components + components ", "answer": "res = _on_tree ( self . repo , tree , components , blob )"}, {"prompt": " from functools import wraps import six import pyrax from pyrax . client import BaseClient import pyrax . exceptions as exc from pyrax . manager import BaseManager from pyrax . resource import BaseResource import pyrax . utils as utils def assure_parent ( fnc ) : @ wraps ( fnc ) def wrapped ( self , * args , ** kwargs ) : lb = self . parent if not lb : exc_class = { Node : exc . UnattachedNode , VirtualIP : exc . UnattachedVirtualIP } [ self . __class__ ] raise exc_class ( \"\" \"\" ) return fnc ( self , * args , ** kwargs ) return wrapped def assure_loadbalancer ( fnc ) : @ wraps ( fnc ) def _wrapped ( self , loadbalancer , * args , ** kwargs ) : if not isinstance ( loadbalancer , CloudLoadBalancer ) : loadbalancer = self . _manager . get ( loadbalancer ) return fnc ( self , loadbalancer , * args , ** kwargs ) return _wrapped class CloudLoadBalancer ( BaseResource ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : self . _connection_logging = None self . _content_caching = None self . _session_persistence = None self . _non_display = [ \"\" , \"\" ] super ( CloudLoadBalancer , self ) . __init__ ( * args , ** kwargs ) def add_nodes ( self , nodes ) : \"\"\"\"\"\" return self . manager . add_nodes ( self , nodes ) def add_virtualip ( self , vip ) : \"\"\"\"\"\" return self . manager . add_virtualip ( self , vip ) def get_usage ( self , start = None , end = None ) : \"\"\"\"\"\" return self . manager . get_usage ( self , start = start , end = end ) def get_stats ( self ) : \"\"\"\"\"\" return self . manager . get_stats ( self ) def _add_details ( self , info ) : \"\"\"\"\"\" for ( key , val ) in six . iteritems ( info ) : if key == \"\" : val = [ Node ( parent = self , ** nd ) for nd in val ] elif key == \"\" : val = val [ '' ] elif key == \"\" : val = val [ '' ] elif key == \"\" : key = \"\" val = [ VirtualIP ( parent = self , ** vip ) for vip in val ] setattr ( self , key , val ) def update ( self , name = None , algorithm = None , protocol = None , halfClosed = None , port = None , timeout = None , httpsRedirect = None ) : \"\"\"\"\"\" return self . manager . update ( self , name = name , algorithm = algorithm , protocol = protocol , halfClosed = halfClosed , port = port , timeout = timeout , httpsRedirect = httpsRedirect ) def delete_node ( self , node ) : \"\"\"\"\"\" return self . manager . delete_node ( self , node ) def update_node ( self , node , diff = None ) : \"\"\"\"\"\" return self . manager . update_node ( node , diff = diff ) def delete_virtualip ( self , vip ) : \"\"\"\"\"\" return self . manager . delete_virtualip ( self , vip ) def get_access_list ( self ) : \"\"\"\"\"\" return self . manager . get_access_list ( self ) def add_access_list ( self , access_list ) : \"\"\"\"\"\" return self . manager . add_access_list ( self , access_list ) def delete_access_list ( self ) : \"\"\"\"\"\" return self . manager . delete_access_list ( self ) def delete_access_list_items ( self , item_ids ) : \"\"\"\"\"\" return self . manager . delete_access_list_items ( self , item_ids ) def get_health_monitor ( self ) : \"\"\"\"\"\" return self . manager . get_health_monitor ( self ) def add_health_monitor ( self , type , delay = , timeout = , attemptsBeforeDeactivation = , path = \"\" , statusRegex = None , bodyRegex = None , hostHeader = None ) : \"\"\"\"\"\" abd = attemptsBeforeDeactivation return self . manager . add_health_monitor ( self , type = type , delay = delay , timeout = timeout , attemptsBeforeDeactivation = abd , path = path , statusRegex = statusRegex , bodyRegex = bodyRegex , hostHeader = hostHeader ) def delete_health_monitor ( self ) : \"\"\"\"\"\" return self . manager . delete_health_monitor ( self ) def get_connection_throttle ( self ) : \"\"\"\"\"\" return self . manager . get_connection_throttle ( self ) def add_connection_throttle ( self , maxConnectionRate = None , maxConnections = None , minConnections = None , rateInterval = None ) : \"\"\"\"\"\" if not any ( ( maxConnectionRate , maxConnections , minConnections , rateInterval ) ) : return return self . manager . add_connection_throttle ( self , maxConnectionRate = maxConnectionRate , maxConnections = maxConnections , minConnections = minConnections , rateInterval = rateInterval ) def delete_connection_throttle ( self ) : \"\"\"\"\"\" return self . manager . delete_connection_throttle ( self ) def get_ssl_termination ( self ) : \"\"\"\"\"\" return self . manager . get_ssl_termination ( self ) def add_ssl_termination ( self , securePort , privatekey , certificate , intermediateCertificate = None , enabled = True , secureTrafficOnly = False ) : \"\"\"\"\"\" return self . manager . add_ssl_termination ( self , securePort = securePort , privatekey = privatekey , certificate = certificate , intermediateCertificate = intermediateCertificate , enabled = enabled , secureTrafficOnly = secureTrafficOnly ) def update_ssl_termination ( self , securePort = None , enabled = None , secureTrafficOnly = None ) : \"\"\"\"\"\" return self . manager . update_ssl_termination ( self , securePort = securePort , enabled = enabled , secureTrafficOnly = secureTrafficOnly ) def delete_ssl_termination ( self ) : \"\"\"\"\"\" return self . manager . delete_ssl_termination ( self ) def get_metadata ( self ) : \"\"\"\"\"\" return self . manager . get_metadata ( self ) def set_metadata ( self , metadata ) : \"\"\"\"\"\" return self . manager . set_metadata ( self , metadata ) def update_metadata ( self , metadata ) : \"\"\"\"\"\" return self . manager . update_metadata ( self , metadata ) def delete_metadata ( self , keys = None ) : \"\"\"\"\"\" return self . manager . delete_metadata ( self , keys = keys ) def get_metadata_for_node ( self , node ) : \"\"\"\"\"\" return self . manager . get_metadata ( self , node = node ) def set_metadata_for_node ( self , node , metadata ) : \"\"\"\"\"\" return self . manager . set_metadata ( self , metadata , node = node ) def update_metadata_for_node ( self , node , metadata ) : \"\"\"\"\"\" return self . manager . update_metadata ( self , metadata , node = node ) def delete_metadata_for_node ( self , node , keys = None ) : \"\"\"\"\"\" return self . manager . delete_metadata ( self , keys = keys , node = node ) def get_error_page ( self ) : \"\"\"\"\"\" return self . manager . get_error_page ( self ) def set_error_page ( self , html ) : \"\"\"\"\"\" return self . manager . set_error_page ( self , html ) def clear_error_page ( self ) : \"\"\"\"\"\" return self . manager . clear_error_page ( self ) def _get_connection_logging ( self ) : if self . _connection_logging is None : self . _connection_logging = self . manager . get_connection_logging ( self ) return self . _connection_logging def _set_connection_logging ( self , val ) : self . manager . set_connection_logging ( self , val ) self . _connection_logging = val def _get_content_caching ( self ) : if self . _content_caching is None : self . _content_caching = self . manager . get_content_caching ( self ) return self . _content_caching def _set_content_caching ( self , val ) : self . manager . set_content_caching ( self , val ) self . _content_caching = val def _get_session_persistence ( self ) : if self . _session_persistence is None : self . _session_persistence = self . manager . get_session_persistence ( self ) return self . _session_persistence def _set_session_persistence ( self , val ) : if val : if not isinstance ( val , six . string_types ) or ( val . upper ( ) not in ( \"\" , \"\" ) ) : raise exc . InvalidSessionPersistenceType ( \"\" \"\" \"\" % val ) self . manager . set_session_persistence ( self , val ) self . _session_persistence = val . upper ( ) else : self . manager . delete_session_persistence ( self ) self . _session_persistence = \"\" connection_logging = property ( _get_connection_logging , _set_connection_logging , None , \"\" \"\" ) content_caching = property ( _get_content_caching , _set_content_caching , None , \"\" \"\" ) session_persistence = property ( _get_session_persistence , _set_session_persistence , None , \"\" \"\" \"\" ) class CloudLoadBalancerManager ( BaseManager ) : def update ( self , lb , name = None , algorithm = None , protocol = None , halfClosed = None , port = None , timeout = None , httpsRedirect = None ) : \"\"\"\"\"\" body = { } if name is not None : body [ \"\" ] = name if algorithm is not None : body [ \"\" ] = algorithm if protocol is not None : body [ \"\" ] = protocol if halfClosed is not None : body [ \"\" ] = halfClosed if port is not None : body [ \"\" ] = port if timeout is not None : body [ \"\" ] = timeout if httpsRedirect is not None : body [ \"\" ] = httpsRedirect if not body : return body = { \"\" : body } uri = \"\" % utils . get_id ( lb ) try : resp , resp_body = self . api . method_put ( uri , body = body ) except exc . ClientException as e : message = e . message details = e . details if message and details : errmsg = \"\" % ( message , details ) else : errmsg = message raise exc . InvalidLoadBalancerParameters ( errmsg ) return resp , resp_body def _create_body ( self , name , port = None , protocol = None , nodes = None , virtual_ips = None , algorithm = None , halfClosed = None , accessList = None , connectionLogging = None , connectionThrottle = None , healthMonitor = None , metadata = None , timeout = None , sessionPersistence = None , httpsRedirect = None ) : \"\"\"\"\"\" required = ( virtual_ips , port , protocol ) if not all ( required ) : raise exc . MissingLoadBalancerParameters ( \"\" \"\" ) nodes = utils . coerce_to_list ( nodes ) virtual_ips = utils . coerce_to_list ( virtual_ips ) bad_conditions = [ node . condition for node in nodes if node . condition . upper ( ) not in ( \"\" , \"\" ) ] if bad_conditions : raise exc . InvalidNodeCondition ( \"\" \"\" \"\" % \"\" . join ( set ( bad_conditions ) ) ) node_dicts = [ nd . to_dict ( ) for nd in nodes ] vip_dicts = [ vip . to_dict ( ) for vip in virtual_ips ] body = { \"\" : { \"\" : name , \"\" : port , \"\" : protocol , \"\" : node_dicts , \"\" : vip_dicts , \"\" : algorithm or \"\" , \"\" : halfClosed , \"\" : accessList , \"\" : connectionLogging , \"\" : connectionThrottle , \"\" : healthMonitor , \"\" : metadata , \"\" : timeout , \"\" : sessionPersistence , \"\" : httpsRedirect , } } return body def add_nodes ( self , lb , nodes ) : \"\"\"\"\"\" if not isinstance ( nodes , ( list , tuple ) ) : nodes = [ nodes ] node_dicts = [ nd . to_dict ( ) for nd in nodes ] resp , body = self . api . method_post ( \"\" % lb . id , body = { \"\" : node_dicts } ) return resp , body def delete_node ( self , loadbalancer , node ) : \"\"\"\"\"\" lb = node . parent if not lb : raise exc . UnattachedNode ( \"\" \"\" ) resp , body = self . api . method_delete ( \"\" % ( lb . id , node . id ) ) return resp , body def update_node ( self , node , diff = None ) : \"\"\"\"\"\" lb = node . parent if not lb : raise exc . UnattachedNode ( \"\" \"\" ) if diff is None : diff = node . _diff ( ) req_body = { \"\" : diff } resp , body = self . api . method_put ( \"\" % ( lb . id , node . id ) , body = req_body ) return resp , body def add_virtualip ( self , lb , vip ) : \"\"\"\"\"\" resp , body = self . api . method_post ( \"\" % lb . id , body = vip . to_dict ( ) ) return resp , body def delete_virtualip ( self , loadbalancer , vip ) : \"\"\"\"\"\" lb = vip . parent if not lb : raise exc . UnattachedVirtualIP ( \"\" \"\" ) resp , body = self . api . method_delete ( \"\" % ( lb . id , vip . id ) ) return resp , body def get_access_list ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) return body . get ( \"\" ) def add_access_list ( self , loadbalancer , access_list ) : \"\"\"\"\"\" req_body = { \"\" : access_list } uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_post ( uri , body = req_body ) return body def delete_access_list ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_delete ( uri ) return body def delete_access_list_items ( self , loadbalancer , item_ids ) : \"\"\"\"\"\" if not isinstance ( item_ids , ( list , tuple ) ) : item_ids = [ item_ids ] valid_ids = [ itm [ \"\" ] for itm in self . get_access_list ( loadbalancer ) ] bad_ids = [ str ( itm ) for itm in item_ids if itm not in valid_ids ] if bad_ids : raise exc . AccessListIDNotFound ( \"\" \"\" % \"\" . join ( bad_ids ) ) items = \"\" . join ( [ \"\" % item_id for item_id in item_ids ] ) uri = \"\" % ( utils . get_id ( loadbalancer ) , items ) resp , body = self . api . method_delete ( uri ) return body def get_health_monitor ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) return body . get ( \"\" , { } ) def add_health_monitor ( self , loadbalancer , type , delay = , timeout = , attemptsBeforeDeactivation = , path = \"\" , statusRegex = None , bodyRegex = None , hostHeader = None ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) req_body = { \"\" : { \"\" : type , \"\" : delay , \"\" : timeout , \"\" : attemptsBeforeDeactivation , } } uptype = type . upper ( ) if uptype . startswith ( \"\" ) : lb = self . _get_lb ( loadbalancer ) if uptype != lb . protocol : raise exc . ProtocolMismatch ( \"\" \"\" % ( type , lb . protocol ) ) if not all ( ( path , statusRegex , bodyRegex ) ) : raise exc . MissingHealthMonitorSettings ( \"\" \"\" \"\" ) body_hm = req_body [ \"\" ] body_hm [ \"\" ] = path body_hm [ \"\" ] = statusRegex body_hm [ \"\" ] = bodyRegex if hostHeader : body_hm [ \"\" ] = hostHeader resp , body = self . api . method_put ( uri , body = req_body ) return body def delete_health_monitor ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_delete ( uri ) def get_connection_throttle ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) return body . get ( \"\" , { } ) def add_connection_throttle ( self , loadbalancer , maxConnectionRate = None , maxConnections = None , minConnections = None , rateInterval = None ) : \"\"\"\"\"\" settings = { } if maxConnectionRate : settings [ \"\" ] = maxConnectionRate if maxConnections : settings [ \"\" ] = maxConnections if minConnections : settings [ \"\" ] = minConnections if rateInterval : settings [ \"\" ] = rateInterval req_body = { \"\" : settings } uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_put ( uri , body = req_body ) return body def delete_connection_throttle ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_delete ( uri ) def get_ssl_termination ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) try : resp , body = self . api . method_get ( uri ) except exc . NotFound : return { } return body . get ( \"\" , { } ) def add_ssl_termination ( self , loadbalancer , securePort , privatekey , certificate , intermediateCertificate , enabled = True , secureTrafficOnly = False ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) req_body = { \"\" : { \"\" : certificate , \"\" : enabled , \"\" : secureTrafficOnly , \"\" : privatekey , \"\" : intermediateCertificate , \"\" : securePort , } } resp , body = self . api . method_put ( uri , body = req_body ) return body def update_ssl_termination ( self , loadbalancer , securePort = None , enabled = None , secureTrafficOnly = None ) : \"\"\"\"\"\" ssl_info = self . get_ssl_termination ( loadbalancer ) if not ssl_info : raise exc . NoSSLTerminationConfiguration ( \"\" \"\" \"\" ) if securePort is None : securePort = ssl_info [ \"\" ] if enabled is None : enabled = ssl_info [ \"\" ] if secureTrafficOnly is None : secureTrafficOnly = ssl_info [ \"\" ] uri = \"\" % utils . get_id ( loadbalancer ) req_body = { \"\" : { \"\" : enabled , \"\" : secureTrafficOnly , \"\" : securePort , } } resp , body = self . api . method_put ( uri , body = req_body ) return body def delete_ssl_termination ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_delete ( uri ) def get_metadata ( self , loadbalancer , node = None , raw = False ) : \"\"\"\"\"\" if node : uri = \"\" % ( utils . get_id ( loadbalancer ) , utils . get_id ( node ) ) else : uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) meta = body . get ( \"\" , [ ] ) if raw : return meta ret = dict ( [ ( itm [ \"\" ] , itm [ \"\" ] ) for itm in meta ] ) return ret def set_metadata ( self , loadbalancer , metadata , node = None ) : \"\"\"\"\"\" self . delete_metadata ( loadbalancer , node = node ) metadata_list = [ { \"\" : key , \"\" : val } for key , val in metadata . items ( ) ] if node : uri = \"\" % ( utils . get_id ( loadbalancer ) , utils . get_id ( node ) ) else : uri = \"\" % utils . get_id ( loadbalancer ) req_body = { \"\" : metadata_list } resp , body = self . api . method_post ( uri , body = req_body ) return body def update_metadata ( self , loadbalancer , metadata , node = None ) : \"\"\"\"\"\" md = self . get_metadata ( loadbalancer , raw = True ) id_lookup = dict ( [ ( itm [ \"\" ] , itm [ \"\" ] ) for itm in md ] ) metadata_list = [ ] for key , val in metadata . items ( ) : try : meta_id = id_lookup [ key ] if node : uri = \"\" % ( utils . get_id ( loadbalancer ) , utils . get_id ( node ) , meta_id ) else : uri = \"\" % utils . get_id ( loadbalancer ) req_body = { \"\" : { \"\" : val } } resp , body = self . api . method_put ( uri , body = req_body ) except KeyError : metadata_list . append ( { \"\" : key , \"\" : val } ) if metadata_list : if node : uri = \"\" % ( utils . get_id ( loadbalancer ) , utils . get_id ( node ) ) else : uri = \"\" % utils . get_id ( loadbalancer ) req_body = { \"\" : metadata_list } resp , body = self . api . method_post ( uri , body = req_body ) def delete_metadata ( self , loadbalancer , keys = None , node = None ) : \"\"\"\"\"\" if keys and not isinstance ( keys , ( list , tuple ) ) : keys = [ keys ] md = self . get_metadata ( loadbalancer , node = node , raw = True ) if keys : md = [ dct for dct in md if dct [ \"\" ] in keys ] if not md : return id_list = \"\" . join ( [ \"\" % itm [ \"\" ] for itm in md ] ) if node : uri = \"\" % ( utils . get_id ( loadbalancer ) , utils . get_id ( node ) , id_list ) else : uri = \"\" % ( utils . get_id ( loadbalancer ) , id_list ) resp , body = self . api . method_delete ( uri ) return body def get_error_page ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) return body def set_error_page ( self , loadbalancer , html ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) req_body = { \"\" : { \"\" : html } } resp , body = self . api . method_put ( uri , body = req_body ) return body def clear_error_page ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_delete ( uri ) return body def get_usage ( self , loadbalancer = None , start = None , end = None ) : \"\"\"\"\"\" if start is end is None : period = None else : parts = [ ] startStr = utils . iso_time_string ( start ) if startStr : parts . append ( \"\" % startStr ) endStr = utils . iso_time_string ( end ) if endStr : parts . append ( \"\" % endStr ) period = \"\" . join ( parts ) . strip ( \"\" ) if loadbalancer is None : uri = \"\" else : uri = \"\" % utils . get_id ( loadbalancer ) if period : uri = \"\" % ( uri , period ) resp , body = self . api . method_get ( uri ) return body def get_stats ( self , loadbalancer = None ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) return body def get_session_persistence ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) ret = body [ \"\" ] . get ( \"\" , \"\" ) return ret def set_session_persistence ( self , loadbalancer , val ) : \"\"\"\"\"\" val = val . upper ( ) uri = \"\" % utils . get_id ( loadbalancer ) req_body = { \"\" : { \"\" : val , } } resp , body = self . api . method_put ( uri , body = req_body ) return body def delete_session_persistence ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_delete ( uri ) return body def get_connection_logging ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) ret = body . get ( \"\" , { } ) . get ( \"\" , False ) return ret def set_connection_logging ( self , loadbalancer , val ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) val = str ( val ) . lower ( ) req_body = { \"\" : { \"\" : val , } } resp , body = self . api . method_put ( uri , body = req_body ) return body def get_content_caching ( self , loadbalancer ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) ret = body . get ( \"\" , { } ) . get ( \"\" , False ) return ret def set_content_caching ( self , loadbalancer , val ) : \"\"\"\"\"\" uri = \"\" % utils . get_id ( loadbalancer ) val = str ( val ) . lower ( ) req_body = { \"\" : { \"\" : val , } } resp , body = self . api . method_put ( uri , body = req_body ) return body def _get_lb ( self , lb_or_id ) : \"\"\"\"\"\" if isinstance ( lb_or_id , CloudLoadBalancer ) : ret = lb_or_id else : ret = self . get ( lb_or_id ) return ret class Node ( object ) : \"\"\"\"\"\" def __init__ ( self , address = None , port = None , condition = None , weight = None , status = None , parent = None , type = None , id = None ) : if condition is None : condition = \"\" if not all ( ( address , port ) ) : raise exc . InvalidNodeParameters ( \"\" \"\" ) self . address = address self . port = port self . condition = condition if weight is None : weight = self . weight = weight self . status = status self . parent = parent self . type = type self . id = id self . _original_state = self . to_dict ( ) def __repr__ ( self ) : tmp = \"\" return tmp % ( self . type , self . condition , self . id , self . address , self . port , self . weight ) def __eq__ ( self , other ) : return ( isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ ) ", "answer": "def __ne__ ( self , other ) :"}, {"prompt": " import Gaffer import GafferScene Gaffer . Metadata . registerNode ( GafferScene . Cube , \"\" , \"\"\"\"\"\" , plugs = { \"\" : [ \"\" , ", "answer": "\"\"\"\"\"\" ,"}, {"prompt": " from django . conf . urls . defaults import * from django . conf import settings from django . contrib import admin admin . autodiscover ( ) urlpatterns = patterns ( '' , ( r'' , include ( '' ) ) , ( r'' , include ( admin . site . urls ) ) , ( r'' , include ( '' ) ) , ( r'' , include ( '' ) ) , ) if settings . DEBUG : urlpatterns += patterns ( '' , ( r'' % settings . MEDIA_URL . strip ( '' ) , '' , { '' : settings . MEDIA_ROOT } ) ", "answer": ") "}, {"prompt": " from redwind import db , models s = models . Setting . query . get ( '' ) if not s : ", "answer": "print ( '' )"}, {"prompt": " from builtins import object import logging import subprocess import time from celery import Celery from celery import states as celery_states from airflow . exceptions import AirflowException ", "answer": "from airflow . executors . base_executor import BaseExecutor"}, {"prompt": " \"\"\"\"\"\" from zope . interface import implements from twisted . internet import defer , protocol from twisted . python import reflect from twisted . python . deprecate import deprecated from twisted . python . versions import Version from twisted . words . protocols . jabber import error , jid , xmlstream from twisted . words . protocols . jabber . xmlstream import toResponse from twisted . words . xish import domish , utility from twisted . words . xish . xmlstream import BootstrapMixin from wokkel . iwokkel import IDisco ", "answer": "from wokkel . subprotocols import XMPPHandler"}, {"prompt": " \"\"\"\"\"\" from paver . easy import sh ", "answer": "def scp ( source , dest ) :"}, {"prompt": " \"\"\"\"\"\" __author__ = '' __date__ = '' __version__ = '' __rights__ = '' import sys import pytest def _filter ( fn , iterable ) : pass def _map ( fn , iterable ) : pass def test_filter ( ) : seq = [ , - , , - ] assert ( filter ( lambda x : x > , seq ) == _filter ( lambda x : x > , seq ) ) def test_map ( ) : seq = '' assert ( map ( lambda x : x . upper ( ) , seq ) == _map ( lambda x : x . upper ( ) , seq ) ) ", "answer": "def main ( ) :"}, {"prompt": " from django . shortcuts import render from django . http import HttpResponse from django . core . files . base import ContentFile ", "answer": "from django . core . servers . basehttp import FileWrapper"}, {"prompt": " from traits . api import HasTraits , Str class Person ( HasTraits ) : first_name = Str ( '' , desc = '' , label = '' ) last_name = Str ( '' , desc = '' , ", "answer": "label = '' ) "}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals import sys import requests import requests_oauthlib import logging try : from urllib . parse import urlparse , urlunparse except ImportError : from urlparse import urlparse , urlunparse from trovebox . objects . trovebox_object import TroveboxObject from . errors import TroveboxError , Trovebox404Error , TroveboxDuplicateError from . auth import Auth if sys . version < '' : TEXT_TYPE = unicode else : TEXT_TYPE = str DUPLICATE_RESPONSE = { \"\" : , \"\" : \"\" } class Http ( object ) : \"\"\"\"\"\" _CONFIG_DEFAULTS = { \"\" : None , \"\" : True , } def __init__ ( self , config_file = None , host = None , consumer_key = '' , consumer_secret = '' , token = '' , token_secret = '' , api_version = None ) : self . config = dict ( self . _CONFIG_DEFAULTS ) if api_version is not None : print ( \"\" \"\" ) self . config [ \"\" ] = api_version self . _logger = logging . getLogger ( \"\" ) self . auth = Auth ( config_file , host , consumer_key , consumer_secret , token , token_secret ) self . host = self . auth . host self . last_url = None self . last_params = None self . last_response = None def configure ( self , ** kwds ) : \"\"\"\"\"\" for item in kwds : self . config [ item ] = kwds [ item ] def get ( self , endpoint , process_response = True , ** params ) : \"\"\"\"\"\" params = self . _process_params ( params ) url = self . _construct_url ( endpoint ) if self . auth . consumer_key : auth = requests_oauthlib . OAuth1 ( self . auth . consumer_key , self . auth . consumer_secret , self . auth . token , self . auth . token_secret ) else : auth = None with requests . Session ( ) as session : session . verify = self . config [ \"\" ] response = session . get ( url , params = params , auth = auth ) self . _logger . info ( \"\" ) ", "answer": "self . _logger . info ( \"\" % url )"}, {"prompt": " import unittest import os import sys import json sys . path . append ( os . path . dirname ( os . path . realpath ( __file__ ) . rsplit ( '' , ) [ ] ) ) from app import create_app app = create_app ( '' ) ", "answer": "add_data = \"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" from neutron_lib import exceptions from neutron . _i18n import _ class SriovUnsupportedNetworkType ( exceptions . NeutronException ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals from django . conf import settings from shop . search . indexes import ProductIndex as ProductIndexBase from haystack import indexes if settings . SHOP_TUTORIAL == '' : from myshop . models . simple . smartcard import SmartCard elif settings . SHOP_TUTORIAL == '' : from myshop . models . i18n . smartcard import SmartCard elif settings . SHOP_TUTORIAL == '' : from myshop . models . polymorphic . smartcard import SmartCard from myshop . models . polymorphic . smartphone import SmartPhoneModel class ProductIndex ( ProductIndexBase ) : catalog_media = indexes . CharField ( stored = True , indexed = False , null = True ) ", "answer": "search_media = indexes . CharField ( stored = True , indexed = False , null = True )"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals import re from django . core . validators import EMPTY_VALUES from django . forms import ValidationError from django . forms . fields import CharField , Field , RegexField , Select from django . utils . encoding import force_text from django . utils . translation import ugettext_lazy as _ from . in_states import STATE_CHOICES , STATES_NORMALIZED phone_digits_re = re . compile ( r\"\"\"\"\"\" , re . VERBOSE ) aadhaar_re = re . compile ( r\"\" ) class INZipCodeField ( RegexField ) : \"\"\"\"\"\" default_error_messages = { '' : _ ( '' ) , } def __init__ ( self , max_length = None , min_length = None , * args , ** kwargs ) : super ( INZipCodeField , self ) . __init__ ( r'' , max_length , min_length , * args , ** kwargs ) def clean ( self , value ) : value = super ( INZipCodeField , self ) . clean ( value ) if value in EMPTY_VALUES : return '' value = re . sub ( r'' , r'' , value ) return value class INStateField ( Field ) : \"\"\"\"\"\" default_error_messages = { '' : _ ( '' ) , } def clean ( self , value ) : value = super ( INStateField , self ) . clean ( value ) if value in EMPTY_VALUES : ", "answer": "return ''"}, {"prompt": " import xmlrpclib from django . template . defaultfilters import slugify from cheeserater . packages . models import Package , Topic , Category CHEESESHOP = \"\" def main ( skip_until = None ) : s = xmlrpclib . Server ( CHEESESHOP ) names = sorted ( s . list_packages ( ) , key = lambda s : s . lower ( ) ) ", "answer": "for name in names :"}, {"prompt": " from io import open import os import re import subprocess import sys from setuptools import setup , Command class RunCommand ( Command ) : user_options = [ ] def initialize_options ( self ) : pass def finalize_options ( self ) : pass class PyTest ( RunCommand ) : user_options = [ ( '' , '' , '' ) ] def initialize_options ( self ) : self . match = None def run ( self ) : cli_options = [ '' , self . match ] if self . match else [ ] os . environ [ '' ] = '' . format ( sys . version_info . major , sys . version_info . minor ) errno = subprocess . call ( [ '' ] + cli_options ) raise SystemExit ( errno ) version = '' with open ( '' , '' , encoding = '' ) as f : version = re . search ( r'' , f . read ( ) , re . MULTILINE ) . group ( ) if not version : raise RuntimeError ( '' ) with open ( '' , '' , encoding = '' ) as f : readme = f . read ( ) setup ( name = '' , version = version , description = '' , long_description = readme , author = '' , author_email = '' , ", "answer": "url = '' ,"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Weapon ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " from filesize import size ", "answer": "from filesize import traditional , alternative , verbose , iec , si "}, {"prompt": " \"\"\"\"\"\" from googleads import dfp ACTIVITY_ID = '' def main ( client , activity_id ) : activity_service = client . GetService ( '' , version = '' ) values = [ { '' : '' , '' : { '' : '' , '' : activity_id } } ] query = '' statement = dfp . FilterStatement ( query , values , ) response = activity_service . getActivitiesByStatement ( statement . ToStatement ( ) ) if '' in response : updated_activities = [ ] for activity in response [ '' ] : activity [ '' ] = '' updated_activities . append ( activity ) activities = activity_service . updateActivities ( updated_activities ) ", "answer": "for updated_activity in activities :"}, {"prompt": " import StringIO import sys import time from nose import tools from docker_registry . core import exceptions import docker_registry . testing as testing from docker_registry . testing import mock_boto from . import mock_s3 class StringIOWithError ( StringIO . StringIO ) : '''''' def read ( self , size ) : if self . pos == self . len : raise IOError ( '' ) return StringIO . StringIO . read ( self , size ) class TestDriver ( testing . Driver ) : '''''' def __init__ ( self ) : self . scheme = '' self . path = '' self . config = testing . Config ( { } ) def tearDown ( self ) : self . _storage . _boto_bucket . delete ( ) super ( TestDriver , self ) . tearDown ( ) @ tools . raises ( exceptions . FileNotFoundError ) def test_list_bucket ( self ) : filename1 = self . gen_random_string ( ) filename2 = self . gen_random_string ( ) content = self . gen_random_string ( ) self . _storage . put_content ( filename1 , content ) self . _storage . put_content ( filename2 + '' , content ) assert sorted ( [ filename1 , filename2 ] ) == sorted ( list ( self . _storage . list_directory ( ) ) ) self . _storage . remove ( filename1 ) self . _storage . remove ( filename2 ) s = self . _storage . list_directory ( ) s . next ( ) def test_stream_write ( self ) : self . _storage . buffer_size = * * filename = self . gen_random_string ( ) content = self . gen_random_string ( * * ) io = StringIOWithError ( content ) assert not self . _storage . exists ( filename ) try : self . _storage . stream_write ( filename , io ) except IOError : pass assert self . _storage . exists ( filename ) try : self . _storage . stream_write ( filename , io ) except IOError : pass io . close ( ) self . _storage . remove ( filename ) self . _storage . buffer_size = * * assert not self . _storage . exists ( filename ) def test_init_path ( self ) : root_path = self . _storage . _root_path if root_path . startswith ( '' ) : self . _storage . _root_path = root_path [ : ] assert not self . _storage . _init_path ( ) . startswith ( '' ) self . _storage . _root_path = root_path def test_debug_key ( self ) : filename = self . gen_random_string ( ) content = self . gen_random_string ( ) self . _storage . put_content ( filename , content ) key_path = self . _storage . _init_path ( filename ) key = self . _storage . _boto_bucket . lookup ( key_path ) self . _storage . _debug_key ( key ) saved_stdout = sys . stdout output = StringIO . StringIO ( ) sys . stdout = output dummy = \"\" result = self . _storage . _boto_bucket . connection . make_request ( '' , , v = ) assert output . getvalue ( ) == dummy assert result == '' sys . stdout = saved_stdout def test_get_tags ( self ) : store = self . _storage store . _root_path = '' store . _init_path ( ) assert store . _root_path == '' tag_path = store . tag_path ( '' , '' , '' ) store . put_content ( tag_path , '' ) tags_path = store . tag_path ( '' , '' ) ", "answer": "for fname in store . list_directory ( tags_path ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Tangible ( )"}, {"prompt": " class Song ( object ) : my_public_variable = \"\" __my_private_variable = \"\" _my_protected_variable = \"\" def __init__ ( self , lyrics ) : self . lyrics = lyrics def sing_me_a_song ( self ) : for line in self . lyrics : print line def get_lyrics ( self ) : return self . lyrics def __my_private_method ( self ) : print \"\" happy_bday = Song ( [ \"\" , \"\" , \"\" ] ) bulls_on_parade = Song ( [ \"\" , \"\" ] ) ", "answer": "happy_bday . sing_me_a_song ( )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " \"\"\"\"\"\" import re from django import template from django . template import TemplateSyntaxError , Node , loader , Variable from django . template . defaultfilters import stringfilter from django . utils . html import strip_tags from django . utils . safestring import mark_safe from django . utils . text import smart_split from django . utils . translation import ugettext as _ from planet . models import Author , Feed , Blog , Post from planet . settings import PLANET_CONFIG from tagging . models import Tag , TaggedItem register = template . Library ( ) @ register . inclusion_tag ( '' ) def authors_about ( tag ) : \"\"\"\"\"\" post_ids = TaggedItem . objects . get_by_model ( Post . site_objects , tag ) . values_list ( \"\" , flat = True ) authors = Author . site_objects . filter ( post__in = post_ids ) . distinct ( ) return { \"\" : authors , \"\" : tag } @ register . inclusion_tag ( '' ) def feeds_about ( tag ) : \"\"\"\"\"\" post_ids = TaggedItem . objects . get_by_model ( Post . site_objects , tag ) . values_list ( \"\" , flat = True ) feeds_list = Feed . site_objects . filter ( post__in = post_ids ) . distinct ( ) return { \"\" : feeds_list , \"\" : tag } @ register . inclusion_tag ( \"\" ) def related_tags_for ( tag , count = PLANET_CONFIG [ \"\" ] ) : \"\"\"\"\"\" related_tags = Tag . objects . related_for_model ( [ tag ] , Post , counts = True ) return { \"\" : related_tags [ : count ] } @ register . inclusion_tag ( \"\" ) def post_details ( post , template = \"\" ) : \"\"\"\"\"\" return { \"\" : template , \"\" : post } @ register . inclusion_tag ( \"\" ) def post_full_details ( post ) : \"\"\"\"\"\" return { \"\" : post } @ register . inclusion_tag ( \"\" ) def cloud_for_feed ( feed , min_count = PLANET_CONFIG [ \"\" ] ) : \"\"\"\"\"\" tags_cloud = Tag . objects . cloud_for_model ( Post , filters = { \"\" : feed } , min_count = min_count ) return { \"\" : tags_cloud , \"\" : feed } @ register . inclusion_tag ( \"\" ) def cloud_for_author ( author , min_count = PLANET_CONFIG [ \"\" ] ) : \"\"\"\"\"\" tags_cloud = Tag . objects . cloud_for_model ( Post , filters = { \"\" : author } , min_count = min_count ) ", "answer": "return { \"\" : tags_cloud , \"\" : author }"}, {"prompt": " import json import os import sys import importlib sys . path . append ( os . path . realpath ( '' ) ) ", "answer": "client_module = importlib . import_module ( '' )"}, {"prompt": " import collections import logging import base64 import json import os import six log = logging . getLogger ( __name__ ) class ConsulException ( Exception ) : pass class ACLDisabled ( ConsulException ) : pass class ACLPermissionDenied ( ConsulException ) : pass class NotFound ( ConsulException ) : pass class Timeout ( ConsulException ) : pass class Check ( object ) : \"\"\"\"\"\" @ classmethod def script ( klass , script , interval ) : \"\"\"\"\"\" return { '' : script , '' : interval } @ classmethod def http ( klass , url , interval , timeout = None ) : \"\"\"\"\"\" ret = { '' : url , '' : interval } if timeout : ret [ '' ] = timeout return ret @ classmethod def tcp ( klass , host , port , interval , timeout = None ) : \"\"\"\"\"\" ret = { '' : '' . format ( host = host , port = port ) , '' : interval } if timeout : ret [ '' ] = timeout return ret @ classmethod def ttl ( klass , ttl ) : \"\"\"\"\"\" return { '' : ttl } @ classmethod def docker ( klass , container_id , shell , script , interval ) : \"\"\"\"\"\" ret = { '' : container_id , '' : shell , '' : script , '' : interval } return ret @ classmethod def _compat ( self , script = None , interval = None , ttl = None , http = None , timeout = None ) : if not script and not http and not ttl : return { } log . warn ( '' ) ret = { '' : { } } if script : assert interval and not ( ttl or http ) ret [ '' ] = { '' : script , '' : interval } if ttl : assert not ( interval or script or http ) ret [ '' ] = { '' : ttl } if http : assert interval and not ( script or ttl ) ret [ '' ] = { '' : http , '' : interval } if timeout : assert http ret [ '' ] [ '' ] = timeout return ret Response = collections . namedtuple ( '' , [ '' , '' , '' ] ) def callback ( map = None , is_200 = False , is_json = False , index = False , one = False , allow_404 = True ) : def cb ( response ) : if response . code >= and response . code < : raise ConsulException ( \"\" % ( response . code , response . body ) ) if response . code == : raise ACLPermissionDenied ( response . body ) if response . code == and not allow_404 : raise NotFound ( response . body ) if is_200 : data = response . code == elif is_json : data = json . loads ( response . body ) else : data = response if one : if data == [ ] : data = None if data is not None : data = data [ ] if map : data = map ( data ) if index : return response . headers [ '' ] , data return data return cb class Consul ( object ) : def __init__ ( self , host = '' , port = , token = None , scheme = '' , consistency = '' , dc = None , verify = True ) : \"\"\"\"\"\" if os . getenv ( '' ) : host , port = os . getenv ( '' ) . split ( '' ) use_ssl = os . getenv ( '' ) if use_ssl is not None : scheme = '' if use_ssl == '' else '' if os . getenv ( '' ) is not None : verify = os . getenv ( '' ) == '' self . http = self . connect ( host , port , scheme , verify ) self . token = os . getenv ( '' , token ) self . scheme = scheme self . dc = dc assert consistency in ( '' , '' , '' ) , '' self . consistency = consistency self . event = Consul . Event ( self ) self . kv = Consul . KV ( self ) self . agent = Consul . Agent ( self ) self . catalog = Consul . Catalog ( self ) self . health = Consul . Health ( self ) self . session = Consul . Session ( self ) self . acl = Consul . ACL ( self ) self . status = Consul . Status ( self ) class Event ( object ) : \"\"\"\"\"\" def __init__ ( self , agent ) : self . agent = agent def fire ( self , name , body = \"\" , node = None , service = None , tag = None ) : \"\"\"\"\"\" assert not name . startswith ( '' ) , '' params = { } if node is not None : params [ '' ] = node if service is not None : params [ '' ] = service if tag is not None : params [ '' ] = tag return self . agent . http . put ( callback ( is_json = True ) , '' % name , params = params , data = body ) def list ( self , name = None , index = None , wait = None ) : \"\"\"\"\"\" params = { } if name is not None : params [ '' ] = name if index : params [ '' ] = index if wait : params [ '' ] = wait def callback ( response ) : data = json . loads ( response . body ) for item in data : if item . get ( '' ) is not None : item [ '' ] = base64 . b64decode ( item [ '' ] ) return response . headers [ '' ] , data return self . agent . http . get ( callback , '' , params = params ) class KV ( object ) : \"\"\"\"\"\" def __init__ ( self , agent ) : self . agent = agent def get ( self , key , index = None , recurse = False , wait = None , token = None , consistency = None , keys = False , separator = None , dc = None ) : \"\"\"\"\"\" assert not key . startswith ( '' ) , '' params = { } if index : params [ '' ] = index if wait : params [ '' ] = wait if recurse : params [ '' ] = '' token = token or self . agent . token if token : params [ '' ] = token dc = dc or self . agent . dc if dc : params [ '' ] = dc if keys : params [ '' ] = True if separator : params [ '' ] = separator consistency = consistency or self . agent . consistency if consistency in ( '' , '' ) : params [ consistency ] = '' def callback ( response ) : if response . code == : raise ConsulException ( response . body ) elif response . code == : data = None else : data = json . loads ( response . body ) if not keys : for item in data : if item . get ( '' ) is not None : item [ '' ] = base64 . b64decode ( item [ '' ] ) if not recurse : data = data [ ] return response . headers [ '' ] , data return self . agent . http . get ( callback , '' % key , params = params ) def put ( self , key , value , cas = None , flags = None , acquire = None , release = None , token = None , dc = None ) : \"\"\"\"\"\" assert not key . startswith ( '' ) , '' assert value is None or isinstance ( value , ( six . string_types , six . binary_type ) ) , \"\" params = { } if cas is not None : params [ '' ] = cas if flags is not None : params [ '' ] = flags if acquire : params [ '' ] = acquire if release : params [ '' ] = release token = token or self . agent . token if token : params [ '' ] = token dc = dc or self . agent . dc if dc : params [ '' ] = dc return self . agent . http . put ( callback ( is_json = True ) , '' % key , params = params , data = value ) def delete ( self , key , recurse = None , cas = None , token = None , dc = None ) : \"\"\"\"\"\" assert not key . startswith ( '' ) , '' params = { } if recurse : params [ '' ] = '' if cas is not None : params [ '' ] = cas token = token or self . agent . token if token : params [ '' ] = token dc = dc or self . agent . dc if dc : params [ '' ] = dc def callback ( response ) : if response . code == : raise ACLPermissionDenied ( response . body ) return json . loads ( response . body ) return self . agent . http . delete ( callback , '' % key , params = params ) class Agent ( object ) : \"\"\"\"\"\" def __init__ ( self , agent ) : self . agent = agent self . service = Consul . Agent . Service ( agent ) self . check = Consul . Agent . Check ( agent ) def self ( self ) : \"\"\"\"\"\" return self . agent . http . get ( lambda x : json . loads ( x . body ) , '' ) def services ( self ) : \"\"\"\"\"\" return self . agent . http . get ( lambda x : json . loads ( x . body ) , '' ) def checks ( self ) : \"\"\"\"\"\" return self . agent . http . get ( lambda x : json . loads ( x . body ) , '' ) def members ( self , wan = False ) : \"\"\"\"\"\" params = { } if wan : params [ '' ] = return self . agent . http . get ( lambda x : json . loads ( x . body ) , '' , params = params ) def maintenance ( self , enable , reason = None ) : \"\"\"\"\"\" params = { } params [ '' ] = enable if reason : params [ '' ] = reason return self . agent . http . put ( lambda x : x . code == , '' , params = params ) def join ( self , address , wan = False ) : \"\"\"\"\"\" params = { } if wan : params [ '' ] = return self . agent . http . get ( lambda x : x . code == , '' % address , params = params ) def force_leave ( self , node ) : \"\"\"\"\"\" return self . agent . http . get ( lambda x : x . code == , '' % node ) class Service ( object ) : def __init__ ( self , agent ) : self . agent = agent def register ( self , name , service_id = None , address = None , port = None , tags = None , check = None , token = None , script = None , interval = None , ttl = None , http = None , timeout = None ) : \"\"\"\"\"\" payload = { '' : name } if service_id : payload [ '' ] = service_id if address : payload [ '' ] = address if port : payload [ '' ] = port if tags : payload [ '' ] = tags if check : payload [ '' ] = check else : payload . update ( Check . _compat ( script = script , interval = interval , ttl = ttl , http = http , timeout = timeout ) ) params = { } token = token or self . agent . token if token : params [ '' ] = token return self . agent . http . put ( lambda x : x . code == , '' , params = params , data = json . dumps ( payload ) ) def deregister ( self , service_id ) : \"\"\"\"\"\" return self . agent . http . get ( lambda x : x . code == , '' % service_id ) def maintenance ( self , service_id , enable , reason = None ) : \"\"\"\"\"\" params = { } params [ '' ] = enable if reason : params [ '' ] = reason return self . agent . http . put ( lambda x : x . code == , '' . format ( service_id ) , params = params ) class Check ( object ) : def __init__ ( self , agent ) : self . agent = agent def register ( self , name , check = None , check_id = None , notes = None , service_id = None , token = None , script = None , interval = None , ttl = None , http = None , timeout = None ) : \"\"\"\"\"\" payload = { '' : name } assert check or script or ttl or http , '' if check : payload . update ( check ) else : payload . update ( Check . _compat ( script = script , interval = interval , ttl = ttl , http = http , timeout = timeout ) [ '' ] ) if check_id : payload [ '' ] = check_id if notes : payload [ '' ] = notes if service_id : payload [ '' ] = service_id params = { } token = token or self . agent . token if token : params [ '' ] = token return self . agent . http . put ( lambda x : x . code == , '' , params = params , data = json . dumps ( payload ) ) def deregister ( self , check_id ) : \"\"\"\"\"\" return self . agent . http . get ( lambda x : x . code == , '' % check_id ) def ttl_pass ( self , check_id , notes = None ) : \"\"\"\"\"\" params = { } if notes : params [ '' ] = notes return self . agent . http . get ( lambda x : x . code == , '' % check_id , params = params ) def ttl_fail ( self , check_id , notes = None ) : \"\"\"\"\"\" params = { } if notes : params [ '' ] = notes return self . agent . http . get ( lambda x : x . code == , '' % check_id , params = params ) def ttl_warn ( self , check_id , notes = None ) : \"\"\"\"\"\" params = { } if notes : params [ '' ] = notes return self . agent . http . get ( lambda x : x . code == , '' % check_id , params = params ) class Catalog ( object ) : def __init__ ( self , agent ) : self . agent = agent def register ( self , node , address , service = None , check = None , dc = None ) : \"\"\"\"\"\" data = { '' : node , '' : address } dc = dc or self . agent . dc if dc : data [ '' ] = dc if service : data [ '' ] = service if check : data [ '' ] = check return self . agent . http . put ( callback ( is_200 = True ) , '' , data = json . dumps ( data ) ) def deregister ( self , node , service_id = None , check_id = None , dc = None ) : \"\"\"\"\"\" assert not ( service_id and check_id ) data = { '' : node } dc = dc or self . agent . dc if dc : data [ '' ] = dc if service_id : data [ '' ] = service_id if check_id : data [ '' ] = check_id return self . agent . http . put ( callback ( is_200 = True ) , '' , data = json . dumps ( data ) ) def datacenters ( self ) : \"\"\"\"\"\" return self . agent . http . get ( lambda x : json . loads ( x . body ) , '' ) def nodes ( self , index = None , wait = None , consistency = None , dc = None ) : \"\"\"\"\"\" params = { } dc = dc or self . agent . dc if dc : params [ '' ] = dc if index : params [ '' ] = index if wait : params [ '' ] = wait ", "answer": "consistency = consistency or self . agent . consistency"}, {"prompt": " __copyright__ = '' ", "answer": "version = ( , , )"}, {"prompt": " \"\"\"\"\"\" import sys as _sys __all__ = [ '' , '' , '' ] version = , , pyver = float ( '' % _sys . version_info [ : ] ) try : any except NameError : def any ( iterable ) : for element in iterable : if element : return True return False try : from collections import OrderedDict except ImportError : OrderedDict = None try : basestring except NameError : basestring = str try : unicode except NameError : unicode = str class _RouteClassAttributeToGetattr ( object ) : \"\"\"\"\"\" def __init__ ( self , fget = None ) : self . fget = fget def __get__ ( self , instance , ownerclass = None ) : if instance is None : raise AttributeError ( ) return self . fget ( instance ) def __set__ ( self , instance , value ) : raise AttributeError ( \"\" ) def __delete__ ( self , instance ) : raise AttributeError ( \"\" ) def _is_descriptor ( obj ) : \"\"\"\"\"\" return ( hasattr ( obj , '' ) or hasattr ( obj , '' ) or hasattr ( obj , '' ) ) def _is_dunder ( name ) : \"\"\"\"\"\" return ( name [ : ] == name [ - : ] == '' and name [ : ] != '' and name [ - : - ] != '' and len ( name ) > ) def _is_sunder ( name ) : \"\"\"\"\"\" return ( name [ ] == name [ - ] == '' and name [ : ] != '' and name [ - : - ] != '' and len ( name ) > ) def _make_class_unpicklable ( cls ) : \"\"\"\"\"\" def _break_on_call_reduce ( self , protocol = None ) : raise TypeError ( '' % self ) cls . __reduce_ex__ = _break_on_call_reduce cls . __module__ = '' class _EnumDict ( dict ) : \"\"\"\"\"\" def __init__ ( self ) : super ( _EnumDict , self ) . __init__ ( ) self . _member_names = [ ] def __setitem__ ( self , key , value ) : \"\"\"\"\"\" if pyver >= and key == '' : return if _is_sunder ( key ) : raise ValueError ( '' ) elif _is_dunder ( key ) : pass elif key in self . _member_names : raise TypeError ( '' % key ) elif not _is_descriptor ( value ) : if key in self : raise TypeError ( '' % self [ key ] ) self . _member_names . append ( key ) super ( _EnumDict , self ) . __setitem__ ( key , value ) Enum = None class EnumMeta ( type ) : \"\"\"\"\"\" @ classmethod def __prepare__ ( metacls , cls , bases ) : return _EnumDict ( ) def __new__ ( metacls , cls , bases , classdict ) : if type ( classdict ) is dict : original_dict = classdict classdict = _EnumDict ( ) for k , v in original_dict . items ( ) : classdict [ k ] = v member_type , first_enum = metacls . _get_mixins_ ( bases ) __new__ , save_new , use_args = metacls . _find_new_ ( classdict , member_type , first_enum ) members = dict ( ( k , classdict [ k ] ) for k in classdict . _member_names ) for name in classdict . _member_names : del classdict [ name ] __order__ = classdict . get ( '' ) if __order__ is None : if pyver < : try : __order__ = [ name for ( name , value ) in sorted ( members . items ( ) , key = lambda item : item [ ] ) ] except TypeError : __order__ = [ name for name in sorted ( members . keys ( ) ) ] else : __order__ = classdict . _member_names else : del classdict [ '' ] if pyver < : __order__ = __order__ . replace ( '' , '' ) . split ( ) aliases = [ name for name in members if name not in __order__ ] __order__ += aliases invalid_names = set ( members ) & set ( [ '' ] ) if invalid_names : raise ValueError ( '' % ( '' . join ( invalid_names ) , ) ) enum_class = super ( EnumMeta , metacls ) . __new__ ( metacls , cls , bases , classdict ) enum_class . _member_names_ = [ ] if OrderedDict is not None : enum_class . _member_map_ = OrderedDict ( ) else : enum_class . _member_map_ = { } enum_class . _member_type_ = member_type enum_class . _value2member_map_ = { } if __new__ is None : __new__ = enum_class . __new__ for member_name in __order__ : value = members [ member_name ] if not isinstance ( value , tuple ) : args = ( value , ) else : args = value if member_type is tuple : args = ( args , ) if not use_args or not args : enum_member = __new__ ( enum_class ) if not hasattr ( enum_member , '' ) : enum_member . _value_ = value else : enum_member = __new__ ( enum_class , * args ) if not hasattr ( enum_member , '' ) : enum_member . _value_ = member_type ( * args ) value = enum_member . _value_ enum_member . _name_ = member_name enum_member . __objclass__ = enum_class enum_member . __init__ ( * args ) for name , canonical_member in enum_class . _member_map_ . items ( ) : if canonical_member . value == enum_member . _value_ : enum_member = canonical_member break else : enum_class . _member_names_ . append ( member_name ) enum_class . _member_map_ [ member_name ] = enum_member try : enum_class . _value2member_map_ [ value ] = enum_member except TypeError : pass unpicklable = False if '' not in classdict : if member_type is not object : methods = ( '' , '' , '' , '' ) if not any ( m in member_type . __dict__ for m in methods ) : _make_class_unpicklable ( enum_class ) unpicklable = True for name in ( '' , '' , '' , '' ) : class_method = getattr ( enum_class , name ) obj_method = getattr ( member_type , name , None ) enum_method = getattr ( first_enum , name , None ) if name not in classdict and class_method is not enum_method : if name == '' and unpicklable : continue setattr ( enum_class , name , enum_method ) if pyver < : if issubclass ( enum_class , int ) : setattr ( enum_class , '' , getattr ( int , '' ) ) elif pyver < : if issubclass ( enum_class , int ) : for method in ( '' , '' , '' , '' , '' , '' , '' , ) : setattr ( enum_class , method , getattr ( int , method ) ) if Enum is not None : if save_new : setattr ( enum_class , '' , enum_class . __dict__ [ '' ] ) setattr ( enum_class , '' , Enum . __dict__ [ '' ] ) return enum_class def __call__ ( cls , value , names = None , module = None , type = None ) : \"\"\"\"\"\" if names is None : return cls . __new__ ( cls , value ) return cls . _create_ ( value , names , module = module , type = type ) def __contains__ ( cls , member ) : return isinstance ( member , cls ) and member . name in cls . _member_map_ def __delattr__ ( cls , attr ) : if attr in cls . _member_map_ : raise AttributeError ( \"\" % cls . __name__ ) super ( EnumMeta , cls ) . __delattr__ ( attr ) def __dir__ ( self ) : return ( [ '' , '' , '' , '' ] + self . _member_names_ ) @ property def __members__ ( cls ) : \"\"\"\"\"\" return cls . _member_map_ . copy ( ) def __getattr__ ( cls , name ) : \"\"\"\"\"\" if _is_dunder ( name ) : raise AttributeError ( name ) try : return cls . _member_map_ [ name ] except KeyError : raise AttributeError ( name ) def __getitem__ ( cls , name ) : return cls . _member_map_ [ name ] def __iter__ ( cls ) : return ( cls . _member_map_ [ name ] for name in cls . _member_names_ ) def __reversed__ ( cls ) : return ( cls . _member_map_ [ name ] for name in reversed ( cls . _member_names_ ) ) def __len__ ( cls ) : return len ( cls . _member_names_ ) def __repr__ ( cls ) : return \"\" % cls . __name__ def __setattr__ ( cls , name , value ) : \"\"\"\"\"\" member_map = cls . __dict__ . get ( '' , { } ) if name in member_map : raise AttributeError ( '' ) super ( EnumMeta , cls ) . __setattr__ ( name , value ) def _create_ ( cls , class_name , names = None , module = None , type = None ) : \"\"\"\"\"\" if pyver < : if isinstance ( class_name , unicode ) : try : class_name = class_name . encode ( '' ) except UnicodeEncodeError : raise TypeError ( '' % class_name ) metacls = cls . __class__ if type is None : bases = ( cls , ) else : bases = ( type , cls ) classdict = metacls . __prepare__ ( class_name , bases ) __order__ = [ ] ", "answer": "if isinstance ( names , basestring ) :"}, {"prompt": " '''''' from importlib import import_module def import_optional ( mod_name ) : '''''' try : return import_module ( mod_name ) except ImportError : return None def import_required ( mod_name , error_msg ) : '''''' try : ", "answer": "return import_module ( mod_name )"}, {"prompt": " from __future__ import absolute_import from __future__ import print_function import sys import os sys . path . insert ( , os . path . dirname ( os . path . dirname ( os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) ) ) ) from veriloggen import * def mkLed ( ) : m = Module ( '' ) width = m . Parameter ( '' , ) clk = m . Input ( '' ) rst = m . Input ( '' ) led = m . OutputReg ( '' , width ) count = m . Reg ( '' , ) m . Always ( Posedge ( clk ) ) ( If ( rst ) ( count ( ) ) . Else ( count ( Cond ( count == , , count + ) ) ) ) m . Always ( Posedge ( clk ) ) ( If ( rst ) ( led ( ) ) . Else ( led ( Cond ( count == - , led + , led ) ) ) ) ", "answer": "return m"}, {"prompt": " from collections import defaultdict def queryset_to_dict ( qs , key = '' , singular = True ) : \"\"\"\"\"\" if singular : result = { } for u in qs : result . setdefault ( getattr ( u , key ) , u ) else : result = defaultdict ( list ) for u in qs : result [ getattr ( u , key ) ] . append ( u ) return result def distinct ( l ) : \"\"\"\"\"\" return list ( set ( l ) ) from django . db . models . fields . related import SingleRelatedObjectDescriptor def attach_foreignkey ( objects , field , related = [ ] , database = '' ) : \"\"\"\"\"\" is_foreignkey = isinstance ( field , SingleRelatedObjectDescriptor ) if not is_foreignkey : field = field . field accessor = '' % field . name model = field . rel . to lookup = '' column = field . column key = lookup else : accessor = field . cache_name field = field . related . field model = field . model lookup = field . name column = '' key = field . column values = distinct ( getattr ( o , column ) for o in objects if ( related or getattr ( o , accessor , False ) is False ) ) if not values : return qs = model . objects . filter ( ** { '' % lookup : values } ) . using ( database ) if related : qs = qs . select_related ( * related ) queryset = queryset_to_dict ( qs , key = key ) for o in objects : setattr ( o , accessor , queryset . get ( getattr ( o , column ) ) ) ", "answer": "def attach_foreignkeys ( * object_sets , ** kwargs ) :"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . delete_unique ( '' , [ '' , '' ] ) db . create_unique ( '' , [ '' , '' , '' ] ) def backwards ( self , orm ) : db . delete_unique ( '' , [ '' , '' , '' ] ) db . create_unique ( '' , [ '' , '' ] ) models = { '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { ", "answer": "'' : { '' : \"\" , '' : '' } ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import division \"\"\"\"\"\" \"\"\"\"\"\" DEFAULT_FPS = DEFAULT_VENTRAL_MODE = N_POINTS_NORMALIZED = ", "answer": "\"\"\"\"\"\""}, {"prompt": " import os from setuptools import setup , find_packages def read ( fname ) : return open ( os . path . join ( os . path . dirname ( __file__ ) , fname ) ) . read ( ) setup ( name = \"\" , version = \"\" , author = \"\" , author_email = \"\" , description = \"\" , license = \"\" , keywords = \"\" , url = \"\" , long_description = read ( '' ) , classifiers = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ] , ", "answer": "packages = [ '' ] ,"}, {"prompt": " from __future__ import unicode_literals ", "answer": "from django . db import models , migrations"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " from cloudferry . lib . base . action import action DEFAULT = PATH_ONE = PATH_TWO = class IsOption ( action . Action ) : def __init__ ( self , init , option_name ) : self . option_name = option_name super ( IsOption , self ) . __init__ ( init ) ", "answer": "def run ( self , ** kwargs ) :"}, {"prompt": " import numpy as np from numpy . testing import assert_almost_equal from menpo . math import eigenvalue_decomposition , pca , ipca cov_matrix = np . array ( [ [ , ] , [ , ] ] ) large_samples_data_matrix = np . array ( [ [ , ] , [ , ] , [ , ] , [ , ] , [ , ] , [ , ] , [ , ] , [ , ] , [ , ] , [ , ] ] ) centered_eigenvectors_s = np . array ( [ [ , ] , [ - , ] ] ) non_centered_eigenvectors_s = np . array ( [ [ , ] , [ - , ] ] ) mean_vector_s = np . array ( [ , ] ) eigenvalues_no_centre_s = np . array ( [ , ] ) eigenvalues_centered_s = np . array ( [ , ] ) centered_eigenvectors_f = np . array ( [ [ - , , , , - , , - , , , - ] ] ) non_centered_eigenvectors_f = np . array ( [ [ , , , , , , , , , ] , [ - , , , , - , , - , , , - ] ] ) mean_vector_f = np . array ( [ , , , , , , , , , ] ) eigenvalues_no_centre_f = np . array ( [ , ] ) eigenvalues_centered_f = np . array ( [ ] ) def pcd_samples_nocentre_test ( ) : output = pca ( large_samples_data_matrix , centre = False ) eigenvectors , eigenvalues , mean_vector = output assert_almost_equal ( eigenvalues , eigenvalues_no_centre_s ) assert_almost_equal ( eigenvectors , non_centered_eigenvectors_s ) assert_almost_equal ( mean_vector , [ , ] ) def pcd_samples_yescentre_test ( ) : output = pca ( large_samples_data_matrix , centre = True ) eigenvectors , eigenvalues , mean_vector = output assert_almost_equal ( eigenvalues , eigenvalues_centered_s ) assert_almost_equal ( eigenvectors , centered_eigenvectors_s ) assert_almost_equal ( mean_vector , mean_vector_s ) def pcd_features_nocentre_test ( ) : output = pca ( large_samples_data_matrix . T , centre = False ) eigenvectors , eigenvalues , mean_vector = output assert_almost_equal ( eigenvalues , eigenvalues_no_centre_f ) assert_almost_equal ( eigenvectors , non_centered_eigenvectors_f ) assert_almost_equal ( mean_vector , np . zeros ( ) ) def pcd_features_nocentre_inplace_test ( ) : output = pca ( large_samples_data_matrix . T . copy ( ) , centre = False , inplace = True ) eigenvectors , eigenvalues , mean_vector = output assert_almost_equal ( eigenvalues , eigenvalues_no_centre_f ) assert_almost_equal ( eigenvectors , non_centered_eigenvectors_f ) assert_almost_equal ( mean_vector , np . zeros ( ) ) def pcd_features_yescentre_test ( ) : output = pca ( large_samples_data_matrix . T , centre = True ) eigenvectors , eigenvalues , mean_vector = output assert_almost_equal ( eigenvalues , eigenvalues_centered_f ) assert_almost_equal ( eigenvectors , centered_eigenvectors_f ) assert_almost_equal ( mean_vector , mean_vector_f ) def eigenvalue_decomposition_default_epsilon_test ( ) : pos_eigenvectors , pos_eigenvalues = eigenvalue_decomposition ( cov_matrix ) assert_almost_equal ( pos_eigenvalues , [ , ] ) sqrt_one_over_2 = np . sqrt ( ) / assert_almost_equal ( pos_eigenvectors , [ [ sqrt_one_over_2 , - sqrt_one_over_2 ] , [ sqrt_one_over_2 , sqrt_one_over_2 ] ] ) def eigenvalue_decomposition_large_epsilon_test ( ) : pos_eigenvectors , pos_eigenvalues = eigenvalue_decomposition ( cov_matrix , eps = ) assert_almost_equal ( pos_eigenvalues , [ ] ) sqrt_one_over_2 = np . sqrt ( ) / assert_almost_equal ( pos_eigenvectors , [ [ sqrt_one_over_2 ] , [ sqrt_one_over_2 ] ] ) def ipca_samples_yescentre_test ( ) : ", "answer": "n_a = large_samples_data_matrix . shape [ ] / "}, {"prompt": " import os import pytest from . . utils . indi import PanIndiServer , PanIndiDevice from . . utils . logger import get_logger logger = get_logger ( self ) class TestIndiBasics ( object ) : \"\"\"\"\"\" def test_server_create_and_delete ( self ) : \"\"\"\"\"\" logger . info ( \"\" ) indi_server = PanIndiServer ( ) pid = indi_server . _proc . pid fifo_file = indi_server . _fifo assert pid > , \"\" assert os . getpgid ( pid ) , \"\" assert indi_server . is_connected , \"\" del indi_server assert os . getpgid ( pid ) is not True , \"\" assert os . path . exists ( fifo_file ) is not True , \"\" def test_device_create ( self ) : \"\"\"\"\"\" logger . info ( \"\" ) device = None with pytest . raises ( TypeError ) : device = PanIndiDevice ( ) name = '' driver = '' device = PanIndiDevice ( name , driver ) assert isinstance ( device , PanIndiDevice ) , \"\" assert device . is_loaded is not True , \"\" assert device . is_connected is not True , \"\" def test_basic ( self ) : \"\"\"\"\"\" logger . info ( \"\" ) indi_server = PanIndiServer ( ) assert indi_server . is_connected , \"\" name = '' driver = '' device = PanIndiDevice ( name , driver ) indi_server . load_driver ( name , driver ) assert device . is_loaded , \"\" del indi_server def test_v4l2 ( self ) : \"\"\"\"\"\" logger . info ( \"\" ) indi_server = PanIndiServer ( ) assert indi_server . is_connected , \"\" name = '' ", "answer": "driver = ''"}, {"prompt": " from urllib import urlencode from hilbert . test import ViewTestMixin from mezzanine . core . models import CONTENT_STATUS_PUBLISHED from raspberryio . project . tests . base import ProjectBaseTestCase class SearchViewTestCase ( ViewTestMixin , ProjectBaseTestCase ) : \"\"\"\"\"\" url_name = '' def setUp ( self ) : super ( SearchViewTestCase , self ) . setUp ( ) self . user = self . create_user ( data = { '' : '' } ) self . project = self . create_project ( title = '' , user = self . user , status = CONTENT_STATUS_PUBLISHED ) def get_query_params ( self , query = '' , object_type = None ) : object_type = object_type or { } query_dict = { '' : query , } query_dict . update ( { '' : object_type } ) ", "answer": "return '' + urlencode ( query_dict )"}, {"prompt": " import sys def enabled ( ) : return ( '' in sys . argv and '' in sys . argv ) def register_cli_opts ( ) : from oslo . config import cfg cli_opts = [ cfg . StrOpt ( '' , help = '' '' '' '' '' ) , cfg . IntOpt ( '' , help = '' '' '' '' '' ) ] cfg . CONF . register_cli_opts ( cli_opts , '' ) def init ( ) : from oslo . config import cfg CONF = cfg . CONF if '' not in CONF : return if not ( CONF . remote_debug . host and CONF . remote_debug . port ) : return from rack . openstack . common . gettextutils import _ from rack . openstack . common import log as logging LOG = logging . getLogger ( __name__ ) LOG . debug ( _ ( '' ) , { '' : CONF . remote_debug . host , '' : CONF . remote_debug . port } ) from pydev import pydevd pydevd . settrace ( host = CONF . remote_debug . host , ", "answer": "port = CONF . remote_debug . port ,"}, {"prompt": " import json import sys episode_id = for line in sys . stdin : episode = json . loads ( line ) rewards = [ event [ '' ] for event in episode ] print \"\" . join ( map ( str , [ episode_id , len ( episode ) , sum ( rewards ) ] ) ) ", "answer": "episode_id += "}, {"prompt": " from . log_utils import logger try : from . _ffi_xcursors import ffi except ImportError : import cffi if cffi . __version_info__ [ ] == : from . ffi_build import xcursors_ffi as ffi else : raise ImportError ( \"\" ) class Cursors ( dict ) : def __init__ ( self , conn ) : self . conn = conn cursors = ( ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ( b'' , ) , ", "answer": "( b'' , ) ,"}, {"prompt": " from setuptools import setup ", "answer": "setup ("}, {"prompt": " from st2tests . base import CleanDbTestCase from st2common . models . db . keyvalue import KeyValuePairDB from st2common . persistence . keyvalue import KeyValuePair from st2common . services . keyvalues import KeyValueLookup class TestKeyValueLookup ( CleanDbTestCase ) : def test_non_hierarchical_lookup ( self ) : k1 = KeyValuePair . add_or_update ( KeyValuePairDB ( name = '' , value = '' ) ) k2 = KeyValuePair . add_or_update ( KeyValuePairDB ( name = '' , value = '' ) ) k3 = KeyValuePair . add_or_update ( KeyValuePairDB ( name = '' , value = '' ) ) lookup = KeyValueLookup ( ) self . assertEquals ( str ( lookup . k1 ) , k1 . value ) self . assertEquals ( str ( lookup . k2 ) , k2 . value ) self . assertEquals ( str ( lookup . k3 ) , k3 . value ) def test_hierarchical_lookup_dotted ( self ) : k1 = KeyValuePair . add_or_update ( KeyValuePairDB ( name = '' , value = '' ) ) k2 = KeyValuePair . add_or_update ( KeyValuePairDB ( name = '' , value = '' ) ) k3 = KeyValuePair . add_or_update ( KeyValuePairDB ( name = '' , value = '' ) ) ", "answer": "lookup = KeyValueLookup ( )"}, {"prompt": " from . import string_score import re def filter_commands ( marks , search_string ) : '''''' def sort_marks ( marks , search_string ) : ", "answer": "return sorted ("}, {"prompt": " class RegionInfo ( object ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Static ( ) ", "answer": "result . template = \"\""}, {"prompt": " from oslo_utils import reflection from taskflow . engines . worker_based import types as worker_types from taskflow import test from taskflow . test import mock from taskflow . tests import utils class TestTopicWorker ( test . TestCase ) : def test_topic_worker ( self ) : worker = worker_types . TopicWorker ( \"\" , [ utils . DummyTask ] , identity = \"\" ) self . assertTrue ( worker . performs ( utils . DummyTask ) ) self . assertFalse ( worker . performs ( utils . NastyTask ) ) self . assertEqual ( '' , worker . identity ) self . assertEqual ( '' , worker . topic ) class TestProxyFinder ( test . TestCase ) : @ mock . patch ( \"\" ) def test_expiry ( self , mock_now ) : finder = worker_types . ProxyWorkerFinder ( '' , mock . MagicMock ( ) , [ ] , worker_expiry = ) w , emit = finder . _add ( '' , [ utils . DummyTask ] ) w . last_seen = mock_now . side_effect = [ ] gone = finder . clean ( ) self . assertEqual ( , finder . total_workers ) self . assertEqual ( , gone ) def test_single_topic_worker ( self ) : finder = worker_types . ProxyWorkerFinder ( '' , mock . MagicMock ( ) , [ ] ) w , emit = finder . _add ( '' , [ utils . DummyTask ] ) self . assertIsNotNone ( w ) self . assertTrue ( emit ) ", "answer": "self . assertEqual ( , finder . total_workers )"}, {"prompt": " from __future__ import print_function import os import shutil import time from collections import namedtuple from pkg_resources import safe_name from . common import safe_mkdir from . fetcher import Fetcher from . interpreter import PythonInterpreter from . iterator import Iterator , IteratorInterface from . orderedset import OrderedSet from . package import Package , distribution_compatible from . platforms import Platform from . resolvable import ResolvableRequirement , resolvables_from_iterable from . resolver_options import ResolverOptionsBuilder from . tracer import TRACER from . util import DistributionHelper class Untranslateable ( Exception ) : pass class Unsatisfiable ( Exception ) : pass class StaticIterator ( IteratorInterface ) : \"\"\"\"\"\" def __init__ ( self , packages ) : self . _packages = packages def iter ( self , req ) : for package in self . _packages : if package . satisfies ( req ) : yield package class _ResolvedPackages ( namedtuple ( '' , '' ) ) : @ classmethod def empty ( cls ) : return cls ( None , OrderedSet ( ) , None ) def merge ( self , other ) : if other . resolvable is None : return _ResolvedPackages ( self . resolvable , self . packages , self . parent ) return _ResolvedPackages ( self . resolvable , self . packages & other . packages , self . parent ) class _ResolvableSet ( object ) : @ classmethod def normalize ( cls , name ) : return safe_name ( name ) . lower ( ) def __init__ ( self , tuples = None ) : self . __tuples = tuples or [ ] def _collapse ( self ) : resolvables = { } for resolved_packages in self . __tuples : key = self . normalize ( resolved_packages . resolvable . name ) previous = resolvables . get ( key , _ResolvedPackages . empty ( ) ) if previous . resolvable is None : resolvables [ key ] = resolved_packages else : resolvables [ key ] = previous . merge ( resolved_packages ) return resolvables def _synthesize_parents ( self , name ) : def render_resolvable ( resolved_packages ) : return '' % ( str ( resolved_packages . resolvable ) , '' % resolved_packages . parent if resolved_packages . parent else '' ) return '' . join ( render_resolvable ( resolved_packages ) for resolved_packages in self . __tuples if self . normalize ( resolved_packages . resolvable . name ) == self . normalize ( name ) ) def _check ( self ) : for name , resolved_packages in self . _collapse ( ) . items ( ) : if not resolved_packages . packages : raise Unsatisfiable ( '' % ( resolved_packages . resolvable , self . _synthesize_parents ( name ) ) ) def merge ( self , resolvable , packages , parent = None ) : \"\"\"\"\"\" self . __tuples . append ( _ResolvedPackages ( resolvable , OrderedSet ( packages ) , parent ) ) self . _check ( ) def get ( self , name ) : \"\"\"\"\"\" resolvable , packages , parent = self . _collapse ( ) . get ( self . normalize ( name ) , _ResolvedPackages . empty ( ) ) return packages def packages ( self ) : \"\"\"\"\"\" return list ( self . _collapse ( ) . values ( ) ) def extras ( self , name ) : return set . union ( * [ set ( tup . resolvable . extras ( ) ) for tup in self . __tuples if self . normalize ( tup . resolvable . name ) == self . normalize ( name ) ] ) def replace_built ( self , built_packages ) : \"\"\"\"\"\" def map_packages ( resolved_packages ) : packages = OrderedSet ( built_packages . get ( p , p ) for p in resolved_packages . packages ) return _ResolvedPackages ( resolved_packages . resolvable , packages , resolved_packages . parent ) return _ResolvableSet ( [ map_packages ( rp ) for rp in self . __tuples ] ) class Resolver ( object ) : \"\"\"\"\"\" class Error ( Exception ) : pass @ classmethod def filter_packages_by_interpreter ( cls , packages , interpreter , platform ) : return [ package for package in packages if package . compatible ( interpreter . identity , platform ) ] def __init__ ( self , interpreter = None , platform = None ) : self . _interpreter = interpreter or PythonInterpreter . get ( ) self . _platform = platform or Platform . current ( ) def package_iterator ( self , resolvable , existing = None ) : if existing : existing = resolvable . compatible ( StaticIterator ( existing ) ) else : existing = resolvable . packages ( ) return self . filter_packages_by_interpreter ( existing , self . _interpreter , self . _platform ) def build ( self , package , options ) : context = options . get_context ( ) translator = options . get_translator ( self . _interpreter , self . _platform ) with TRACER . timed ( '' % package . url , V = ) : local_package = Package . from_href ( context . fetch ( package ) ) if local_package is None : raise Untranslateable ( '' % package ) with TRACER . timed ( '' % local_package . local_path , V = ) : dist = translator . translate ( local_package ) if dist is None : raise Untranslateable ( '' % ( package , translator ) ) if not distribution_compatible ( dist , self . _interpreter , self . _platform ) : raise Untranslateable ( '' % ( package , self . _platform ) ) return dist def resolve ( self , resolvables , resolvable_set = None ) : resolvables = [ ( resolvable , None ) for resolvable in resolvables ] resolvable_set = resolvable_set or _ResolvableSet ( ) processed_resolvables = set ( ) processed_packages = { } distributions = { } while resolvables : while resolvables : resolvable , parent = resolvables . pop ( ) if resolvable in processed_resolvables : continue packages = self . package_iterator ( resolvable , existing = resolvable_set . get ( resolvable . name ) ) resolvable_set . merge ( resolvable , packages , parent ) processed_resolvables . add ( resolvable ) built_packages = { } for resolvable , packages , parent in resolvable_set . packages ( ) : assert len ( packages ) > , '' % resolvable package = next ( iter ( packages ) ) if resolvable . name in processed_packages : if package != processed_packages [ resolvable . name ] : raise self . Error ( '' % resolvable ) continue if package not in distributions : dist = self . build ( package , resolvable . options ) built_package = Package . from_href ( dist . location ) built_packages [ package ] = built_package distributions [ built_package ] = dist package = built_package distribution = distributions [ package ] processed_packages [ resolvable . name ] = package new_parent = '' % ( parent , resolvable ) if parent else str ( resolvable ) resolvables . extend ( ( ResolvableRequirement ( req , resolvable . options ) , new_parent ) for req in distribution . requires ( extras = resolvable_set . extras ( resolvable . name ) ) ) resolvable_set = resolvable_set . replace_built ( built_packages ) return list ( distributions . values ( ) ) class CachingResolver ( Resolver ) : \"\"\"\"\"\" @ classmethod def filter_packages_by_ttl ( cls , packages , ttl , now = None ) : now = now if now is not None else time . time ( ) return [ package for package in packages if package . remote or package . local and ( now - os . path . getmtime ( package . local_path ) ) < ttl ] def __init__ ( self , cache , cache_ttl , * args , ** kw ) : self . __cache = cache self . __cache_ttl = cache_ttl safe_mkdir ( self . __cache ) super ( CachingResolver , self ) . __init__ ( * args , ** kw ) def package_iterator ( self , resolvable , existing = None ) : iterator = Iterator ( fetchers = [ Fetcher ( [ self . __cache ] ) ] ) packages = self . filter_packages_by_interpreter ( resolvable . compatible ( iterator ) , self . _interpreter , self . _platform ) if packages : if resolvable . exact : return packages if self . __cache_ttl : packages = self . filter_packages_by_ttl ( packages , self . __cache_ttl ) if packages : return packages return super ( CachingResolver , self ) . package_iterator ( resolvable , existing = existing ) def build ( self , package , options ) : if package . remote : package = Package . from_href ( options . get_context ( ) . fetch ( package , into = self . __cache ) ) os . utime ( package . local_path , None ) dist = super ( CachingResolver , self ) . build ( package , options ) target = os . path . join ( self . __cache , os . path . basename ( dist . location ) ) if not os . path . exists ( target ) : shutil . copyfile ( dist . location , target + '' ) os . rename ( target + '' , target ) os . utime ( target , None ) return DistributionHelper . distribution_from_path ( target ) def resolve ( requirements , fetchers = None , interpreter = None , platform = None , context = None , precedence = None , cache = None , cache_ttl = None ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from bson import DBRef , SON from mongoengine . python_support import txt_type from base import ( BaseDict , BaseList , EmbeddedDocumentList , TopLevelDocumentMetaclass , get_document ) from fields import ( ReferenceField , ListField , DictField , MapField ) from connection import get_db from queryset import QuerySet from document import Document , EmbeddedDocument class DeReference ( object ) : def __call__ ( self , items , max_depth = , instance = None , name = None ) : \"\"\"\"\"\" if items is None or isinstance ( items , basestring ) : return items if isinstance ( items , QuerySet ) : ", "answer": "items = [ i for i in items ]"}, {"prompt": " from __future__ import absolute_import , division , print_function from . constants import MIME_TYPE , PNG_CHUNK_TYPE from . exceptions import InvalidImageStreamError from . helpers import BIG_ENDIAN , StreamReader from . image import BaseImageHeader class Png ( BaseImageHeader ) : \"\"\"\"\"\" @ property def content_type ( self ) : \"\"\"\"\"\" return MIME_TYPE . PNG @ property def default_ext ( self ) : \"\"\"\"\"\" return '' @ classmethod def from_stream ( cls , stream ) : \"\"\"\"\"\" parser = _PngParser . parse ( stream ) px_width = parser . px_width px_height = parser . px_height horz_dpi = parser . horz_dpi vert_dpi = parser . vert_dpi return cls ( px_width , px_height , horz_dpi , vert_dpi ) class _PngParser ( object ) : \"\"\"\"\"\" def __init__ ( self , chunks ) : super ( _PngParser , self ) . __init__ ( ) self . _chunks = chunks @ classmethod def parse ( cls , stream ) : \"\"\"\"\"\" chunks = _Chunks . from_stream ( stream ) return cls ( chunks ) @ property def px_width ( self ) : \"\"\"\"\"\" IHDR = self . _chunks . IHDR return IHDR . px_width @ property def px_height ( self ) : \"\"\"\"\"\" IHDR = self . _chunks . IHDR return IHDR . px_height @ property def horz_dpi ( self ) : \"\"\"\"\"\" pHYs = self . _chunks . pHYs if pHYs is None : return return self . _dpi ( pHYs . units_specifier , pHYs . horz_px_per_unit ) @ property def vert_dpi ( self ) : \"\"\"\"\"\" pHYs = self . _chunks . pHYs if pHYs is None : return return self . _dpi ( pHYs . units_specifier , pHYs . vert_px_per_unit ) @ staticmethod def _dpi ( units_specifier , px_per_unit ) : \"\"\"\"\"\" if units_specifier == and px_per_unit : return int ( round ( px_per_unit * ) ) return class _Chunks ( object ) : \"\"\"\"\"\" def __init__ ( self , chunk_iterable ) : super ( _Chunks , self ) . __init__ ( ) self . _chunks = list ( chunk_iterable ) @ classmethod def from_stream ( cls , stream ) : \"\"\"\"\"\" chunk_parser = _ChunkParser . from_stream ( stream ) chunks = [ chunk for chunk in chunk_parser . iter_chunks ( ) ] return cls ( chunks ) @ property def IHDR ( self ) : \"\"\"\"\"\" match = lambda chunk : chunk . type_name == PNG_CHUNK_TYPE . IHDR IHDR = self . _find_first ( match ) if IHDR is None : raise InvalidImageStreamError ( '' ) return IHDR @ property def pHYs ( self ) : \"\"\"\"\"\" match = lambda chunk : chunk . type_name == PNG_CHUNK_TYPE . pHYs return self . _find_first ( match ) def _find_first ( self , match ) : \"\"\"\"\"\" for chunk in self . _chunks : if match ( chunk ) : return chunk return None class _ChunkParser ( object ) : \"\"\"\"\"\" def __init__ ( self , stream_rdr ) : super ( _ChunkParser , self ) . __init__ ( ) self . _stream_rdr = stream_rdr @ classmethod def from_stream ( cls , stream ) : \"\"\"\"\"\" stream_rdr = StreamReader ( stream , BIG_ENDIAN ) return cls ( stream_rdr ) def iter_chunks ( self ) : \"\"\"\"\"\" for chunk_type , offset in self . _iter_chunk_offsets ( ) : chunk = _ChunkFactory ( chunk_type , self . _stream_rdr , offset ) yield chunk def _iter_chunk_offsets ( self ) : \"\"\"\"\"\" chunk_offset = while True : chunk_data_len = self . _stream_rdr . read_long ( chunk_offset ) chunk_type = self . _stream_rdr . read_str ( , chunk_offset , ) data_offset = chunk_offset + yield chunk_type , data_offset if chunk_type == '' : break chunk_offset += ( + + chunk_data_len + ) def _ChunkFactory ( chunk_type , stream_rdr , offset ) : \"\"\"\"\"\" chunk_cls_map = { PNG_CHUNK_TYPE . IHDR : _IHDRChunk , PNG_CHUNK_TYPE . pHYs : _pHYsChunk , } chunk_cls = chunk_cls_map . get ( chunk_type , _Chunk ) return chunk_cls . from_offset ( chunk_type , stream_rdr , offset ) class _Chunk ( object ) : \"\"\"\"\"\" def __init__ ( self , chunk_type ) : super ( _Chunk , self ) . __init__ ( ) self . _chunk_type = chunk_type @ classmethod def from_offset ( cls , chunk_type , stream_rdr , offset ) : \"\"\"\"\"\" return cls ( chunk_type ) @ property def type_name ( self ) : \"\"\"\"\"\" return self . _chunk_type class _IHDRChunk ( _Chunk ) : \"\"\"\"\"\" def __init__ ( self , chunk_type , px_width , px_height ) : super ( _IHDRChunk , self ) . __init__ ( chunk_type ) self . _px_width = px_width self . _px_height = px_height @ classmethod def from_offset ( cls , chunk_type , stream_rdr , offset ) : \"\"\"\"\"\" px_width = stream_rdr . read_long ( offset ) px_height = stream_rdr . read_long ( offset , ) return cls ( chunk_type , px_width , px_height ) @ property def px_width ( self ) : return self . _px_width @ property def px_height ( self ) : return self . _px_height class _pHYsChunk ( _Chunk ) : \"\"\"\"\"\" def __init__ ( self , chunk_type , horz_px_per_unit , vert_px_per_unit , units_specifier ) : super ( _pHYsChunk , self ) . __init__ ( chunk_type ) self . _horz_px_per_unit = horz_px_per_unit self . _vert_px_per_unit = vert_px_per_unit self . _units_specifier = units_specifier @ classmethod def from_offset ( cls , chunk_type , stream_rdr , offset ) : \"\"\"\"\"\" horz_px_per_unit = stream_rdr . read_long ( offset ) vert_px_per_unit = stream_rdr . read_long ( offset , ) units_specifier = stream_rdr . read_byte ( offset , ) return cls ( ", "answer": "chunk_type , horz_px_per_unit , vert_px_per_unit , units_specifier"}, {"prompt": " DATABASES = { ", "answer": "'' : {"}, {"prompt": " from __future__ import unicode_literals import unittest from irc3 . testing import MagicMock import irc3 class TestProtocol ( unittest . TestCase ) : def callFTU ( self ) : conn = irc3 . IrcConnection ( ) conn . encoding = '' conn . factory = MagicMock ( ) conn . connection_made ( MagicMock ( ) ) return conn def test_buffer ( self ) : conn = self . callFTU ( ) conn . data_received ( b'' ) self . assertEqual ( conn . queue . popleft ( ) , '' ) def test_no_buffer ( self ) : conn = self . callFTU ( ) ", "answer": "conn . data_received ( b'' )"}, {"prompt": " \"\"\"\"\"\" import numpy as np from nitime . lazy import scipy_fftpack as fftpack def wfmorlet_fft ( f0 , sd , sampling_rate , ns = , nt = None ) : \"\"\"\"\"\" if nt == None : st = / ( * np . pi * sd ) ", "answer": "nt = * int ( ns * st * sampling_rate ) + "}, {"prompt": " '''''' def main ( ) : cl1 = [ x * x for x in range ( ) [ : : ] if == x % ] ", "answer": "print '' , cl1"}, {"prompt": " from tests . base import SingleMemberTestCase from tests . util import random_string class TransactionalMultiMapTest ( SingleMemberTestCase ) : def setUp ( self ) : self . multi_map = self . client . get_multi_map ( random_string ( ) ) . blocking ( ) def test_put ( self ) : with self . client . new_transaction ( ) as tx : tx_multi_map = tx . get_multi_map ( self . multi_map . name ) self . assertTrue ( tx_multi_map . put ( \"\" , \"\" ) ) self . assertTrue ( tx_multi_map . put ( \"\" , \"\" ) ) self . assertItemsEqual ( self . multi_map . get ( \"\" ) , [ \"\" , \"\" ] ) def test_put_when_present ( self ) : self . multi_map . put ( \"\" , \"\" ) with self . client . new_transaction ( ) as tx : tx_multi_map = tx . get_multi_map ( self . multi_map . name ) self . assertFalse ( tx_multi_map . put ( \"\" , \"\" ) ) self . assertItemsEqual ( self . multi_map . get ( \"\" ) , [ \"\" ] ) def test_get ( self ) : self . multi_map . put ( \"\" , \"\" ) self . multi_map . put ( \"\" , \"\" ) with self . client . new_transaction ( ) as tx : tx_multi_map = tx . get_multi_map ( self . multi_map . name ) self . assertItemsEqual ( tx_multi_map . get ( \"\" ) , [ \"\" , \"\" ] ) ", "answer": "def test_get_when_missing ( self ) :"}, {"prompt": " from operator import add , mul import os from time import sleep from dask . diagnostics import Profiler , ResourceProfiler , CacheProfiler from dask . threaded import get from dask . utils import ignoring , tmpfile from dask . compatibility import apply import pytest try : import bokeh except : bokeh = None try : import psutil except : psutil = None prof = Profiler ( ) dsk = { '' : , '' : , '' : ( add , '' , '' ) , '' : ( mul , '' , '' ) , '' : ( mul , '' , '' ) } dsk2 = { '' : , '' : , '' : ( lambda a , b : sleep ( ) or ( a + b ) , '' , '' ) } def test_profiler ( ) : with prof : out = get ( dsk , '' ) assert out == prof_data = sorted ( prof . results , key = lambda d : d . key ) keys = [ i . key for i in prof_data ] assert keys == [ '' , '' , '' ] tasks = [ i . task for i in prof_data ] assert tasks == [ ( add , '' , '' ) , ( mul , '' , '' ) , ( mul , '' , '' ) ] prof . clear ( ) assert prof . results == [ ] def test_profiler_works_under_error ( ) : div = lambda x , y : x / y dsk = { '' : ( div , , ) , '' : ( div , '' , ) , '' : ( div , '' , ) } with ignoring ( ZeroDivisionError ) : with prof : out = get ( dsk , '' ) assert all ( len ( v ) == for v in prof . results ) assert len ( prof . results ) == def test_two_gets ( ) : with prof : get ( dsk , '' ) n = len ( prof . results ) dsk2 = { '' : ( add , , ) , '' : ( add , '' , '' ) } with prof : get ( dsk2 , '' ) m = len ( prof . results ) with prof : get ( dsk , '' ) get ( dsk2 , '' ) get ( dsk , '' ) assert len ( prof . results ) == n + m + n @ pytest . mark . skipif ( \"\" ) def test_resource_profiler ( ) : with ResourceProfiler ( dt = ) as rprof : out = get ( dsk2 , '' ) results = rprof . results assert all ( isinstance ( i , tuple ) and len ( i ) == for i in results ) rprof . clear ( ) assert rprof . results == [ ] rprof . close ( ) assert not rprof . _tracker . is_alive ( ) with pytest . raises ( AssertionError ) : with rprof : get ( dsk , '' ) def test_cache_profiler ( ) : with CacheProfiler ( ) as cprof : out = get ( dsk2 , '' ) results = cprof . results assert all ( isinstance ( i , tuple ) and len ( i ) == for i in results ) cprof . clear ( ) assert cprof . results == [ ] tics = [ ] def nbytes ( res ) : tics [ ] += return tics [ ] with CacheProfiler ( nbytes ) as cprof : out = get ( dsk2 , '' ) results = cprof . results assert tics [ - ] == len ( results ) assert tics [ - ] == results [ - ] . metric assert cprof . _metric_name == '' assert CacheProfiler ( metric = nbytes , metric_name = '' ) . _metric_name == '' @ pytest . mark . skipif ( \"\" ) def test_unquote ( ) : from dask . diagnostics . profile_visualize import unquote from dask . delayed import to_task_dasks f = lambda x : to_task_dasks ( x ) [ ] t = { '' : , '' : , '' : } assert unquote ( f ( t ) ) == t t = { '' : [ , , ] , '' : , '' : } assert unquote ( f ( t ) ) == t t = [ , , ] assert unquote ( f ( t ) ) == t @ pytest . mark . skipif ( \"\" ) def test_pprint_task ( ) : from dask . diagnostics . profile_visualize import pprint_task keys = set ( [ '' , '' , '' , '' , '' ] ) assert pprint_task ( ( add , '' , ) , keys ) == '' assert pprint_task ( ( add , ( add , '' , ) ) , keys ) == '' res = '' assert pprint_task ( ( sum , [ , '' , ( add , '' , ) ] ) , keys ) == res assert pprint_task ( ( sum , ( , , , , , , ) ) , keys ) == '' assert len ( pprint_task ( ( sum , list ( keys ) * ) , keys ) ) < assert pprint_task ( ( sum , list ( keys ) * ) , keys ) == '' assert pprint_task ( ( sum , [ , , ( sum , [ '' , ] ) , , ] * ) , keys ) == '' assert pprint_task ( ( sum , [ , , ( sum , [ '' , ( sum , [ , , ] ) ] ) , , ] ) , keys ) == '' def foo ( w , x , y = ( ) , z = ) : return w + x + sum ( y ) + z task = ( apply , foo , ( tuple , [ '' , '' ] ) , ( dict , [ [ '' , [ '' , '' ] ] , [ '' , '' ] ] ) ) assert pprint_task ( task , keys ) == '' task = ( apply , foo , ( tuple , [ '' , '' ] ) , ( dict , [ [ '' , [ '' , ] ] , [ '' , ] ] ) ) assert pprint_task ( task , keys ) == '' @ pytest . mark . skipif ( \"\" ) def test_profiler_plot ( ) : with prof : get ( dsk , '' ) p = prof . visualize ( plot_width = , plot_height = , tools = \"\" , title = \"\" , show = False , save = False ) assert p . plot_width == assert p . plot_height == assert len ( p . tools ) == assert isinstance ( p . tools [ ] , bokeh . models . HoverTool ) ", "answer": "assert p . title == \"\""}, {"prompt": " \"\"\"\"\"\" import re import math try : from _json import encode_basestring_ascii as c_encode_basestring_ascii except ImportError : c_encode_basestring_ascii = None __all__ = [ '' ] ESCAPE = re . compile ( r'' ) ESCAPE_ASCII = re . compile ( r'' ) HAS_UTF8 = re . compile ( r'' ) ESCAPE_DCT = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } for i in range ( ) : ESCAPE_DCT . setdefault ( chr ( i ) , '' . format ( i ) ) FLOAT_REPR = repr def floatstr ( o , allow_nan = True ) : if math . isnan ( o ) : text = '' elif math . isinf ( o ) : if math . copysign ( , o ) == : text = '' else : text = '' else : return FLOAT_REPR ( o ) if not allow_nan : msg = \"\" + repr ( o ) raise ValueError ( msg ) return text def encode_basestring ( s ) : \"\"\"\"\"\" def replace ( match ) : return ESCAPE_DCT [ match . group ( ) ] return '' + ESCAPE . sub ( replace , s ) + '' def py_encode_basestring_ascii ( s ) : if isinstance ( s , str ) and HAS_UTF8 . search ( s ) is not None : s = s . decode ( '' ) def replace ( match ) : s = match . group ( ) try : return ESCAPE_DCT [ s ] except KeyError : n = ord ( s ) if n < : return '' . format ( n ) else : n -= s1 = | ( ( n >> ) & ) s2 = | ( n & ) return '' . format ( s1 , s2 ) return '' + str ( ESCAPE_ASCII . sub ( replace , s ) ) + '' if c_encode_basestring_ascii is not None : encode_basestring_ascii = c_encode_basestring_ascii else : encode_basestring_ascii = py_encode_basestring_ascii class JSONEncoder ( object ) : \"\"\"\"\"\" __all__ = [ '' , '' , '' , '' ] item_separator = '' key_separator = '' def __init__ ( self , skipkeys = False , ensure_ascii = True , check_circular = True , allow_nan = True , sort_keys = False , indent = None , separators = None , encoding = '' , default = None ) : \"\"\"\"\"\" self . skipkeys = skipkeys self . ensure_ascii = ensure_ascii self . check_circular = check_circular self . allow_nan = allow_nan self . sort_keys = sort_keys self . indent = indent self . current_indent_level = if separators is not None : self . item_separator , self . key_separator = separators if default is not None : self . default = default self . encoding = encoding def _newline_indent ( self ) : return '' + ( '' * ( self . indent * self . current_indent_level ) ) def _iterencode_list ( self , lst , markers = None ) : if not lst : yield '' return if markers is not None : markerid = id ( lst ) if markerid in markers : raise ValueError ( \"\" ) markers [ markerid ] = lst yield '' if self . indent is not None : self . current_indent_level += newline_indent = self . _newline_indent ( ) separator = self . item_separator + newline_indent yield newline_indent else : newline_indent = None separator = self . item_separator first = True for value in lst : if first : first = False else : yield separator for chunk in self . _iterencode ( value , markers ) : yield chunk if newline_indent is not None : self . current_indent_level -= ", "answer": "yield self . _newline_indent ( )"}, {"prompt": " \"\"\"\"\"\" from . array_source import ArraySource from . builtin_image import BuiltinImage from . builtin_surface import BuiltinSurface from . chaco_reader import ChacoReader from . image_reader import ImageReader from . parametric_surface import ParametricSurface from . plot3d_reader import PLOT3DReader from . point_load import PointLoad ", "answer": "from . poly_data_reader import PolyDataReader"}, {"prompt": " \"\"\"\"\"\" import os import sys __version__ = '' __build__ = \"\" class MethodNotFound ( Exception ) : def __init__ ( self , name ) : Exception . __init__ ( self , \"\" % name ) class PortNotFound ( Exception ) : def __init__ ( self , name ) : Exception . __init__ ( self , \"\" % name ) class ServiceNotFound ( Exception ) : def __init__ ( self , name ) : Exception . __init__ ( self , \"\" % name ) class TypeNotFound ( Exception ) : def __init__ ( self , name ) : Exception . __init__ ( self , \"\" % tostr ( name ) ) class BuildError ( Exception ) : msg = \"\"\"\"\"\" def __init__ ( self , name , exception ) : Exception . __init__ ( self , BuildError . msg % ( name , exception ) ) class SoapHeadersNotPermitted ( Exception ) : msg = \"\"\"\"\"\" def __init__ ( self , name ) : Exception . __init__ ( self , self . msg % name ) class WebFault ( Exception ) : def __init__ ( self , fault , document ) : if hasattr ( fault , '' ) : Exception . __init__ ( self , \"\" % fault . faultstring ) self . fault = fault self . document = document class Repr : def __init__ ( self , x ) : self . x = x def __str__ ( self ) : return repr ( self . x ) def tostr ( object , encoding = None ) : \"\"\"\"\"\" if isinstance ( object , basestring ) : if encoding is None : return object else : return object . encode ( encoding ) if isinstance ( object , tuple ) : s = [ '' ] for item in object : if isinstance ( item , basestring ) : s . append ( item ) else : s . append ( tostr ( item ) ) s . append ( '' ) s . append ( '' ) return '' . join ( s ) if isinstance ( object , list ) : s = [ '' ] for item in object : if isinstance ( item , basestring ) : s . append ( item ) else : s . append ( tostr ( item ) ) s . append ( '' ) s . append ( '' ) return '' . join ( s ) if isinstance ( object , dict ) : s = [ '' ] for item in object . items ( ) : if isinstance ( item [ ] , basestring ) : s . append ( item [ ] ) else : s . append ( tostr ( item [ ] ) ) s . append ( '' ) if isinstance ( item [ ] , basestring ) : s . append ( item [ ] ) else : s . append ( tostr ( item [ ] ) ) s . append ( '' ) s . append ( '' ) return '' . join ( s ) try : return unicode ( object ) except : return str ( object ) class null : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from numba import cuda from numba . cuda . cudadrv . driver import driver from numba import numpy_support as nps import math def transpose ( a , b = None ) : \"\"\"\"\"\" if not b : cols , rows = a . shape strides = a . dtype . itemsize * cols , a . dtype . itemsize b = cuda . cudadrv . devicearray . DeviceNDArray ( ( rows , cols ) , strides , dtype = a . dtype ) dt = nps . from_dtype ( a . dtype ) tpb = driver . get_device ( ) . MAX_THREADS_PER_BLOCK tile_width = int ( math . pow ( , math . log ( tpb , ) / ) ) tile_height = int ( tpb / tile_width ) tile_shape = ( tile_height , tile_width + ) @ cuda . jit def kernel ( input , output ) : tile = cuda . shared . array ( shape = tile_shape , dtype = dt ) tx = cuda . threadIdx . x ty = cuda . threadIdx . y bx = cuda . blockIdx . x * cuda . blockDim . x by = cuda . blockIdx . y * cuda . blockDim . y x = by + tx y = bx + ty if by + ty < input . shape [ ] and bx + tx < input . shape [ ] : ", "answer": "tile [ ty , tx ] = input [ by + ty , bx + tx ]"}, {"prompt": " \"\"\"\"\"\" NUM_THREADS = FILES_PER_THREAD = import tempfile from test . test_support import start_threads , run_unittest , import_module ", "answer": "threading = import_module ( '' )"}, {"prompt": " import itertools from . . import names from . . builder import build_fn from . . ndtypes import Int64 , repeat_tuple , NoneType , ScalarT , TupleT , ArrayT from . . syntax import ( ParFor , IndexReduce , IndexScan , Index , Map , OuterMap , Var , Const , Expr ) from . . syntax . helpers import get_types , none , zero_i64 from . . syntax . adverb_helpers import max_rank_arg , max_rank from transform import Transform class IndexifyAdverbs ( Transform ) : \"\"\"\"\"\" def fresh_input_name ( self , expr ) : if expr is Var : return names . refresh ( expr . name ) else : return names . fresh ( \"\" ) def fresh_fn_name ( self , prefix , fn ) : return names . fresh ( prefix + names . original ( self . get_fn ( fn ) . name ) ) def fresh_index_names ( self , n ) : name_supply = itertools . cycle ( [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] ) return [ names . fresh ( name_supply . next ( ) ) for _ in xrange ( n ) ] _indexed_fn_cache = { } def indexify_fn ( self , fn , axis , array_args , cartesian_product = False , output = None , index_offsets = None ) : \"\"\"\"\"\" array_args = tuple ( array_args ) array_arg_types = tuple ( get_types ( array_args ) ) closure_args = self . closure_elts ( fn ) closure_arg_types = tuple ( get_types ( closure_args ) ) n_closure_args = len ( closure_args ) fn = self . get_fn ( fn ) axes = self . normalize_axes ( array_args , axis ) key = ( fn . cache_key , axes , closure_arg_types , array_arg_types , output is None , cartesian_product , index_offsets , ) def mk_closure ( ) : new_fn = self . _indexed_fn_cache [ key ] if output is None : return self . closure ( new_fn , closure_args + array_args ) else : return self . closure ( new_fn , ( output , ) + closure_args + array_args ) if key in self . _indexed_fn_cache : result = mk_closure ( ) return result if cartesian_product : n_indices = for axis , arg_t in zip ( axes , array_arg_types ) : if axis is None : n_indices += self . rank ( arg_t ) elif isinstance ( arg_t , ArrayT ) : n_indices += else : if any ( axis is None for axis in axes ) : assert all ( axis is None for axis in axes ) , \"\" % axes n_indices = max_rank ( array_arg_types ) else : assert all ( isinstance ( axis , ( int , long ) ) for axis in axes ) , \"\" % axes n_indices = index_input_types = ( Int64 , ) * n_indices if output is None : inner_input_types = closure_arg_types + array_arg_types + index_input_types new_return_type = fn . return_type else : inner_input_types = ( output . type , ) + closure_arg_types + array_arg_types + index_input_types new_return_type = NoneType input_names = [ ] if output is not None : if output is Var : local_output_name = names . refresh ( output . name ) else : local_output_name = names . fresh ( \"\" ) input_names . append ( local_output_name ) for old_input_name in fn . arg_names : input_names . append ( names . refresh ( old_input_name ) ) input_names . extend ( self . fresh_index_names ( n_indices ) ) new_fn_name = self . fresh_fn_name ( \"\" , fn ) new_fn , builder , input_vars = build_fn ( inner_input_types , new_return_type , name = new_fn_name , input_names = input_names ) index_input_vars = input_vars [ - n_indices : ] if output is None : output_var = None closure_arg_vars = input_vars [ : n_closure_args ] array_arg_vars = input_vars [ n_closure_args : - n_indices ] else : output_var = input_vars [ ] closure_arg_vars = input_vars [ : n_closure_args + ] array_arg_vars = input_vars [ n_closure_args + : - n_indices ] slice_values = self . get_slices ( builder , array_arg_vars , axes , index_input_vars , cartesian_product , index_offsets ) elt_result = builder . call ( fn , tuple ( closure_arg_vars ) + tuple ( slice_values ) ) if output is None : builder . return_ ( elt_result ) else : if len ( index_input_vars ) > : builder . setidx ( output_var , builder . tuple ( index_input_vars ) , elt_result ) else : builder . setidx ( output_var , index_input_vars [ ] , elt_result ) builder . return_ ( none ) new_fn . created_by = self . fn . created_by new_fn . transform_history = self . fn . transform_history self . _indexed_fn_cache [ key ] = new_fn return mk_closure ( ) def get_slices ( self , builder , array_arg_vars , axes , index_input_vars , cartesian_product = False , index_offsets = None ) : slice_values = [ ] axes = self . normalize_axes ( array_arg_vars , axes ) if cartesian_product : idx_counter = for i , curr_array in enumerate ( array_arg_vars ) : axis = axes [ i ] rank = curr_array . type . rank if rank <= and axis is None : axis = if axis is None : start = idx_counter stop = idx_counter + rank curr_indices = index_input_vars [ start : stop ] idx_counter = stop curr_slice = builder . index ( curr_array , curr_indices ) elif rank > axis : idx = index_input_vars [ idx_counter ] idx_counter += curr_slice = builder . slice_along_axis ( curr_array , axis , idx ) else : curr_slice = curr_array slice_values . append ( curr_slice ) else : for i , curr_array in enumerate ( array_arg_vars ) : axis = axes [ i ] rank = curr_array . type . rank if rank <= and axis is None : axis = if axis is None : assert len ( index_input_vars ) <= rank , \"\" % ( curr_array , curr_array . type ) curr_indices = index_input_vars [ - rank : ] curr_slice = builder . index ( curr_array , curr_indices ) elif rank > axis : curr_idx = index_input_vars [ ] if index_offsets is not None : assert len ( index_offsets ) > i curr_offset = index_offsets [ i ] if not isinstance ( curr_offset , Expr ) : curr_offset = builder . int ( curr_offset ) curr_idx = builder . add ( curr_idx , curr_offset ) curr_slice = builder . slice_along_axis ( curr_array , axis , curr_idx ) else : curr_slice = curr_array slice_values . append ( curr_slice ) return slice_values def create_map_output_array ( self , fn , array_args , axes , cartesian_product = False , name = \"\" ) : \"\"\"\"\"\" assert self . is_fn ( fn ) , \"\" % ( fn , ) assert isinstance ( array_args , ( list , tuple ) ) , \"\" % ( array_args , ) axes = self . normalize_axes ( array_args , axes ) n_indices = for arg , axis in zip ( array_args , axes ) : r = self . rank ( arg ) if r == : continue if axis is None : if cartesian_product : n_indices += self . rank ( arg ) else : n_indices = max ( n_indices , self . rank ( arg ) ) elif r <= axis : continue else : if cartesian_product : n_indices += else : n_indices = max ( n_indices , ) inner_args = self . get_slices ( builder = self , array_arg_vars = array_args , axes = axes , index_input_vars = [ zero_i64 ] * ( n_indices ) , cartesian_product = cartesian_product ) if cartesian_product : extra_dims = [ ] for array , axis in zip ( array_args , axes ) : rank = self . rank ( array ) if axis is None : dim = elif rank > axis : dim = self . shape ( array , axis ) else : dim = extra_dims . append ( dim ) outer_shape_tuple = self . tuple ( extra_dims ) else : outer_shape_tuple = self . iter_bounds ( array_args , axes ) if isinstance ( outer_shape_tuple . type , ScalarT ) : outer_shape_tuple = self . tuple ( [ outer_shape_tuple ] ) return self . create_output_array ( fn , inner_args , outer_shape_tuple , name ) def insert_parfor ( self , index_fn , bounds , n_read_only , n_write_only = ) : read_only = ( [ False ] * n_write_only ) + ( [ True ] * n_read_only ) write_only = ( [ True ] * n_write_only ) + ( [ False ] * n_read_only ) stmt = ParFor ( index_fn , bounds , read_only = read_only , write_only = write_only ) self . blocks += stmt def transform_Map ( self , expr , output = None ) : args = self . transform_expr_list ( expr . args ) axes = self . normalize_axes ( args , expr . axis ) old_fn = expr . fn if output is None : output = self . create_map_output_array ( old_fn , args , axes ) bounds = self . iter_bounds ( args , axes ) index_fn = self . indexify_fn ( expr . fn , axes , args , cartesian_product = False , output = output ) self . insert_parfor ( index_fn , bounds , n_read_only = len ( args ) , n_write_only = ) return output def transform_OuterMap ( self , expr ) : args = self . transform_expr_list ( expr . args ) axes = self . normalize_axes ( args , expr . axis ) fn = expr . fn outer_shape = self . iter_bounds ( args , axes , cartesian_product = True ) zero = self . int ( ) first_values = [ self . slice_along_axis ( arg , axis , zero ) for ( arg , axis ) in zip ( args , axes ) ] output = self . create_output_array ( fn , first_values , outer_shape ) loop_body = self . indexify_fn ( fn , axes , args , cartesian_product = True , output = output ) self . insert_parfor ( loop_body , outer_shape , len ( args ) ) return output def transform_IndexMap ( self , expr , output = None ) : shape = expr . shape fn = expr . fn dims = self . tuple_elts ( shape ) n_dims = len ( dims ) if n_dims == : shape = dims [ ] if output is None : output = self . create_output_array ( fn , [ shape ] , shape ) old_closure_args = self . closure_elts ( fn ) old_closure_arg_types = get_types ( old_closure_args ) fn = self . get_fn ( fn ) closure_arg_names = [ self . fresh_input_name ( clos_arg ) for clos_arg in old_closure_args ] new_closure_vars = [ Var ( name , type = t ) for name , t in zip ( closure_arg_names , old_closure_arg_types ) ] old_input_types = fn . input_types last_input_type = old_input_types [ - ] index_is_tuple = isinstance ( last_input_type , TupleT ) if index_is_tuple : index_types = last_input_type . elt_types else : index_types = old_input_types [ - n_dims : ] idx_names = self . fresh_index_names ( n_dims ) assert len ( index_types ) == n_dims , \"\" % ( dims , len ( index_types ) ) output_name = names . refresh ( \"\" ) new_input_names = [ output_name ] + closure_arg_names + idx_names new_input_types = [ output . type ] + old_closure_arg_types + list ( index_types ) new_fn_name = names . fresh ( \"\" + names . original ( fn . name ) ) new_fn , builder , input_vars = build_fn ( new_input_types , NoneType , name = new_fn_name , input_names = new_input_names ) ", "answer": "new_fn . created_by = self . fn . created_by"}, {"prompt": " import pdb import os , sys import itertools from cPickle import * from collections import defaultdict , namedtuple from pbtools . pbtranscript . Utils import check_ids_unique import pbtools . pbtranscript . tofu_wrap as tofu_wrap import pbtools . pbtranscript . BioReaders as BioReaders import pbtools . pbtranscript . branch . branch_simple2 as branch_simple2 import pbtools . pbtranscript . counting . compare_junctions as compare_junctions from pbtools . pbtranscript . io . SeqReaders import LazyFastaReader , LazyFastqReader from pbcore . io . FastaIO import FastaWriter from pbcore . io . FastqIO import FastqWriter from bx . intervals . cluster import ClusterTree def pick_rep ( fa_fq_filename , sam_filename , gff_filename , group_filename , output_filename , is_fq = False , pick_least_err_instead = False ) : \"\"\"\"\"\" if is_fq : fd = LazyFastqReader ( fa_fq_filename ) fout = FastqWriter ( output_filename ) else : fd = LazyFastaReader ( fa_fq_filename ) fout = FastaWriter ( output_filename ) rep_info = { } id_to_rep = { } for line in open ( group_filename ) : pb_id , members = line . strip ( ) . split ( '' ) print >> sys . stderr , \"\" , pb_id best_id = None best_seq = None best_qual = None best_err = err = max_len = for x in members . split ( '' ) : if is_fq and pick_least_err_instead : err = sum ( i ** - ( i / ) for i in fd [ x ] . quality ) if ( is_fq and pick_least_err_instead and err < best_err ) or ( ( not is_fq or not pick_least_err_instead ) and len ( fd [ x ] . sequence ) >= max_len ) : best_id = x best_seq = fd [ x ] . sequence if is_fq : best_qual = fd [ x ] . quality best_err = err max_len = len ( fd [ x ] . sequence ) rep_info [ pb_id ] = ( best_id , best_seq , best_qual ) id_to_rep [ best_id ] = pb_id f_gff = open ( gff_filename , '' ) coords = { } record_storage = { } for r in BioReaders . GMAPSAMReader ( sam_filename , True ) : if r . qID in id_to_rep : pb_id = id_to_rep [ r . qID ] best_id , best_seq , best_qual = rep_info [ pb_id ] if r . qID not in coords : coords [ r . qID ] = \"\" . format ( r . sID , r . sStart , r . sEnd , r . flag . strand ) isoform_index = record_storage [ pb_id ] = r else : coords [ r . qID ] += \"\" . format ( r . sID , r . sStart , r . sEnd , r . flag . strand ) isoform_index = old_r = record_storage [ pb_id ] f_gff . write ( \"\" . format ( chr = old_r . sID , s = old_r . segments [ ] . start + , e = old_r . segments [ - ] . end , pi = pb_id , j = isoform_index , strand = old_r . flag . strand ) ) for s in old_r . segments : f_gff . write ( \"\" . format ( chr = old_r . sID , s = s . start + , e = s . end , pi = pb_id , j = isoform_index , strand = old_r . flag . strand ) ) isoform_index = f_gff . write ( \"\" . format ( chr = r . sID , s = r . segments [ ] . start + , e = r . segments [ - ] . end , pi = pb_id , j = isoform_index , strand = r . flag . strand ) ) for s in r . segments : f_gff . write ( \"\" . format ( chr = r . sID , s = s . start + , e = s . end , pi = pb_id , j = isoform_index , strand = r . flag . strand ) ) f_gff . close ( ) for pb_id in rep_info : best_id , best_seq , best_qual = rep_info [ pb_id ] _id_ = \"\" . format ( pb_id , coords [ best_id ] , best_id ) _seq_ = best_seq if is_fq : fout . writeRecord ( _id_ , _seq_ , best_qual ) else : fout . writeRecord ( _id_ , _seq_ ) def sep_by_strand ( records ) : output = { '' : [ ] , '' : [ ] } for r in records : output [ r . flag . strand ] . append ( r ) return output def is_fusion_compatible ( r1 , r2 , max_fusion_point_dist , max_exon_end_dist , allow_extra_5_exons ) : \"\"\"\"\"\" assert r1 . flag . strand == r2 . flag . strand if r1 . qStart <= * r1 . qLen : if r2 . qStart > * r2 . qLen : return False in_5_portion = True else : if r2 . qStart <= * r2 . qLen : return False in_5_portion = False plus_is_5end = ( r1 . flag . strand == '' ) type = compare_junctions . compare_junctions ( r1 , r2 ) if type == '' : if len ( r1 . segments ) == : if len ( r2 . segments ) == : if in_5_portion and plus_is_5end : dist = abs ( r1 . sStart - r2 . sStart ) else : dist = abs ( r1 . sEnd - r2 . sEnd ) return dist <= max_fusion_point_dist else : raise Exception , \"\" + \"\" else : return True elif type == '' or type == '' : if allow_extra_5_exons : if in_5_portion and plus_is_5end : if abs ( r1 . segments [ - ] . start - r2 . segments [ - ] . start ) > max_exon_end_dist : return False if abs ( r1 . segments [ - ] . end - r2 . segments [ - ] . end ) > max_fusion_point_dist : return False return True ", "answer": "elif in_5_portion and ( not plus_is_5end ) :"}, {"prompt": " \"\"\"\"\"\" from django . conf import settings from django . core import signals from django . core . cache . backends . base import ( InvalidCacheBackendError , CacheKeyWarning , BaseCache ) from django . core . exceptions import ImproperlyConfigured from django . utils import importlib from django . utils . module_loading import import_by_path from django . utils . six . moves . urllib . parse import parse_qsl __all__ = [ '' , '' , '' ] BACKENDS = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } DEFAULT_CACHE_ALIAS = '' def parse_backend_uri ( backend_uri ) : \"\"\"\"\"\" if backend_uri . find ( '' ) == - : ", "answer": "raise InvalidCacheBackendError ( \"\" )"}, {"prompt": " import unittest import string import sys import os import tempfile import zipfile import shutil import copy from pynhost import ruleparser from pynhost import matching class TestRuleMatching ( unittest . TestCase ) : @ classmethod def setUpClass ( cls ) : pass def test_overflow1 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . remaining_words ) , [ '' ] ) def test_overflow2 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' , '' ] ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . remaining_words ) , [ '' , '' , '' ] ) def test_basic1 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_basic2 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_basic3 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) def test_basic4 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_basic5 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' , '' ] ) def test_basic6 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertIsNone ( matching . get_rule_match ( rule , words ) ) def test_basic7 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_basic8 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' , '' ] ) def test_basic9 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_list1 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) def test_list2 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) def test_list3 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . remaining_words ) , [ '' ] ) def test_list4 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_list5 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_list6 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' , '' ] ) def test_list7 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . remaining_words ) , [ '' , '' ] ) def test_list8 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_num0 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) def test_num1 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) def test_num2 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) def test_num3 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertIsNone ( matching . get_rule_match ( rule , words ) ) def test_num4 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_num5 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_num6 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . remaining_words ) , [ '' ] ) def test_num10 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . remaining_words ) , [ '' ] ) def test_num7 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' , '' , '' ] ) def test_num8 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' , '' , '' , '' , '' ] ) def test_num9 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) def test_any1 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) def test_any2 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' ] ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . remaining_words ) , [ '' ] ) def test_any3 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertTrue ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' ] ) def test_any4 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertEqual ( list ( matching . get_rule_match ( rule , words ) . matched_words ) , [ '' , '' , '' , '' ] ) def test_any5 ( self ) : rule = ruleparser . Rule ( '' ) words = '' . split ( ) self . assertIsNone ( matching . get_rule_match ( rule , words ) ) def test_any6 ( self ) : rule = ruleparser . Rule ( '' ) ", "answer": "words = '' . split ( )"}, {"prompt": " import atexit import imp import os import sys import traceback import eventlet from eventlet import event , greenio , greenthread , patcher , timeout from eventlet . support import six __all__ = [ '' , '' , '' , '' ] EXC_CLASSES = ( Exception , timeout . Timeout ) SYS_EXCS = ( GeneratorExit , KeyboardInterrupt , SystemExit ) QUIET = True socket = patcher . original ( '' ) threading = patcher . original ( '' ) if six . PY2 : Queue_module = patcher . original ( '' ) if six . PY3 : Queue_module = patcher . original ( '' ) Empty = Queue_module . Empty Queue = Queue_module . Queue _bytetosend = b'' _coro = None _nthreads = int ( os . environ . get ( '' , ) ) _reqq = _rspq = None _rsock = _wsock = None _setup_already = False _threads = [ ] def tpool_trampoline ( ) : global _rspq while True : try : _c = _rsock . recv ( ) assert _c except ValueError : break while not _rspq . empty ( ) : try : ( e , rv ) = _rspq . get ( block = False ) e . send ( rv ) e = rv = None except Empty : pass def tworker ( ) : global _rspq while True : try : msg = _reqq . get ( ) except AttributeError : return if msg is None : return ( e , meth , args , kwargs ) = msg rv = None try : rv = meth ( * args , ** kwargs ) except SYS_EXCS : raise except EXC_CLASSES : rv = sys . exc_info ( ) _rspq . put ( ( e , rv ) ) msg = meth = args = kwargs = e = rv = None _wsock . sendall ( _bytetosend ) def execute ( meth , * args , ** kwargs ) : \"\"\"\"\"\" setup ( ) my_thread = threading . currentThread ( ) if my_thread in _threads or imp . lock_held ( ) or _nthreads == : return meth ( * args , ** kwargs ) e = event . Event ( ) _reqq . put ( ( e , meth , args , kwargs ) ) rv = e . wait ( ) if isinstance ( rv , tuple ) and len ( rv ) == and isinstance ( rv [ ] , EXC_CLASSES ) : ( c , e , tb ) = rv if not QUIET : traceback . print_exception ( c , e , tb ) traceback . print_stack ( ) six . reraise ( c , e , tb ) return rv def proxy_call ( autowrap , f , * args , ** kwargs ) : \"\"\"\"\"\" if kwargs . pop ( '' , False ) : rv = f ( * args , ** kwargs ) else : rv = execute ( f , * args , ** kwargs ) if isinstance ( rv , autowrap ) : return Proxy ( rv , autowrap ) else : return rv class Proxy ( object ) : \"\"\"\"\"\" def __init__ ( self , obj , autowrap = ( ) , autowrap_names = ( ) ) : self . _obj = obj self . _autowrap = autowrap self . _autowrap_names = autowrap_names def __getattr__ ( self , attr_name ) : f = getattr ( self . _obj , attr_name ) if not hasattr ( f , '' ) : if isinstance ( f , self . _autowrap ) or attr_name in self . _autowrap_names : return Proxy ( f , self . _autowrap ) return f def doit ( * args , ** kwargs ) : result = proxy_call ( self . _autowrap , f , * args , ** kwargs ) if attr_name in self . _autowrap_names and not isinstance ( result , Proxy ) : return Proxy ( result ) return result return doit def __getitem__ ( self , key ) : return proxy_call ( self . _autowrap , self . _obj . __getitem__ , key ) def __setitem__ ( self , key , value ) : return proxy_call ( self . _autowrap , self . _obj . __setitem__ , key , value ) def __deepcopy__ ( self , memo = None ) : return proxy_call ( self . _autowrap , self . _obj . __deepcopy__ , memo ) def __copy__ ( self , memo = None ) : return proxy_call ( self . _autowrap , self . _obj . __copy__ , memo ) def __call__ ( self , * a , ** kw ) : if '' in self . _autowrap_names : return Proxy ( proxy_call ( self . _autowrap , self . _obj , * a , ** kw ) ) else : return proxy_call ( self . _autowrap , self . _obj , * a , ** kw ) def __enter__ ( self ) : return proxy_call ( self . _autowrap , self . _obj . __enter__ ) def __exit__ ( self , * exc ) : return proxy_call ( self . _autowrap , self . _obj . __exit__ , * exc ) def __eq__ ( self , rhs ) : return self . _obj == rhs def __hash__ ( self ) : return self . _obj . __hash__ ( ) def __repr__ ( self ) : return self . _obj . __repr__ ( ) def __str__ ( self ) : return self . _obj . __str__ ( ) def __len__ ( self ) : return len ( self . _obj ) def __nonzero__ ( self ) : return bool ( self . _obj ) __bool__ = __nonzero__ def __iter__ ( self ) : it = iter ( self . _obj ) if it == self . _obj : return self else : return Proxy ( it ) def next ( self ) : return proxy_call ( self . _autowrap , next , self . _obj ) __next__ = next def setup ( ) : global _rsock , _wsock , _coro , _setup_already , _rspq , _reqq if _setup_already : return else : _setup_already = True assert _nthreads >= , \"\" if _nthreads == : import warnings warnings . warn ( \"\" , RuntimeWarning ) _reqq = Queue ( maxsize = - ) _rspq = Queue ( maxsize = - ) sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sock . bind ( ( '' , ) ) sock . listen ( ) csock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) csock . connect ( sock . getsockname ( ) ) csock . setsockopt ( socket . IPPROTO_TCP , socket . TCP_NODELAY , True ) _wsock , _addr = sock . accept ( ) _wsock . setsockopt ( socket . IPPROTO_TCP , socket . TCP_NODELAY , True ) sock . close ( ) _rsock = greenio . GreenSocket ( csock ) for i in six . moves . range ( _nthreads ) : t = threading . Thread ( target = tworker , name = \"\" % i ) t . setDaemon ( True ) t . start ( ) _threads . append ( t ) _coro = greenthread . spawn_n ( tpool_trampoline ) eventlet . sleep ( ) @ atexit . register def killall ( ) : global _setup_already , _rspq , _rsock , _wsock ", "answer": "if not _setup_already :"}, {"prompt": " import sys import os from tempfile import mkdtemp , mkstemp from rdflib import RDF , RDFS , URIRef , BNode , Variable , plugin from rdflib . graph import QuotedGraph , ConjunctiveGraph implies = URIRef ( \"\" ) testN3 = \"\"\"\"\"\" from nose . tools import nottest from nose . exc import SkipTest @ nottest def testFormulaStore ( store = \"\" , configString = None ) : try : g = ConjunctiveGraph ( store = store ) except ImportError : raise SkipTest ( \"\" % store ) if configString : g . destroy ( configString ) g . open ( configString ) else : if store == '' : _ , path = mkstemp ( prefix = '' , dir = '' , suffix = '' ) g . open ( path , create = True ) else : g . open ( mkdtemp ( ) , create = True ) g . parse ( data = testN3 , format = \"\" ) try : for s , p , o in g . triples ( ( None , implies , None ) ) : formulaA = s formulaB = o assert type ( formulaA ) == QuotedGraph and type ( formulaB ) == QuotedGraph b = URIRef ( '' ) c = URIRef ( '' ) d = URIRef ( '' ) v = Variable ( '' ) universe = ConjunctiveGraph ( g . store ) assert len ( list ( universe . triples ( ( formulaA , implies , formulaB ) ) ) ) == assert len ( list ( formulaB . triples ( ( None , None , v ) ) ) ) == for s , p , o in formulaB . triples ( ( None , d , None ) ) : if o != c : assert isinstance ( o , Variable ) assert o == v s = list ( universe . subjects ( RDF . type , RDFS . Class ) ) [ ] assert isinstance ( s , BNode ) assert len ( list ( universe . triples ( ( None , implies , None ) ) ) ) == assert len ( list ( universe . triples ( ( None , RDF . type , None ) ) ) ) == assert len ( list ( formulaA . triples ( ( None , RDF . type , None ) ) ) ) == assert len ( list ( formulaA . triples ( ( None , None , None ) ) ) ) == assert len ( list ( formulaB . triples ( ( None , None , None ) ) ) ) == assert len ( list ( universe . triples ( ( None , None , None ) ) ) ) == assert len ( list ( formulaB . triples ( ( None , URIRef ( '' ) , None ) ) ) ) == assert len ( list ( universe . triples ( ( None , URIRef ( '' ) , None ) ) ) ) == universe . remove ( ( None , implies , None ) ) assert len ( list ( universe . triples ( ( None , implies , None ) ) ) ) == assert len ( list ( formulaA . triples ( ( None , None , None ) ) ) ) == assert len ( list ( formulaB . triples ( ( None , None , None ) ) ) ) == formulaA . remove ( ( None , b , None ) ) assert len ( list ( formulaA . triples ( ( None , None , None ) ) ) ) == formulaA . remove ( ( None , RDF . type , None ) ) assert len ( list ( formulaA . triples ( ( None , None , None ) ) ) ) == universe . remove ( ( None , RDF . type , RDFS . Class ) ) universe . remove_context ( formulaB ) assert len ( list ( universe . triples ( ( None , RDF . type , None ) ) ) ) == assert len ( universe ) == assert len ( formulaB ) == universe . remove ( ( None , None , None ) ) assert len ( universe ) == g . close ( ) if store == '' : os . unlink ( path ) else : g . store . destroy ( configString ) except : g . close ( ) if store == '' : os . unlink ( path ) else : g . store . destroy ( configString ) raise def testFormulaStores ( ) : pluginname = None if __name__ == '' : if len ( sys . argv ) > : pluginname = sys . argv [ ] for s in plugin . plugins ( pluginname , plugin . Store ) : ", "answer": "if s . name in ("}, {"prompt": " \"\"\"\"\"\" from . commands import * from . numerics import * ", "answer": "from . protocol import IRC"}, {"prompt": " import os import time from setuptools import setup , find_packages , findall def read ( fname ) : return open ( os . path . join ( os . path . dirname ( __file__ ) , fname ) ) . read ( ) PISTON_VERSION = os . environ . get ( '' , time . strftime ( '' , time . localtime ( ) ) ) setup ( name = \"\" , ", "answer": "version = PISTON_VERSION ,"}, {"prompt": " from comet . handler . relay import * ", "answer": "from comet . handler . spawn import * "}, {"prompt": " from __future__ import absolute_import , unicode_literals import os import json from . util import u , slugify import codecs def get_tags_count ( journal ) : \"\"\"\"\"\" tags = [ tag for entry in journal . entries for tag in set ( entry . tags ) ] tag_counts = set ( [ ( tags . count ( tag ) , tag ) for tag in tags ] ) return tag_counts def to_tag_list ( journal ) : \"\"\"\"\"\" tag_counts = get_tags_count ( journal ) result = \"\" if not tag_counts : return '' elif min ( tag_counts ) [ ] == : tag_counts = filter ( lambda x : x [ ] > , tag_counts ) result += '' result += \"\" . join ( \"\" . format ( tag , n ) for n , tag in sorted ( tag_counts , reverse = True ) ) return result def to_json ( journal ) : \"\"\"\"\"\" tags = get_tags_count ( journal ) result = { \"\" : dict ( ( tag , count ) for count , tag in tags ) , \"\" : [ e . to_dict ( ) for e in journal . entries ] } return json . dumps ( result , indent = ) def to_md ( journal ) : \"\"\"\"\"\" out = [ ] year , month = - , - for e in journal . entries : if not e . date . year == year : year = e . date . year out . append ( str ( year ) ) out . append ( \"\" * len ( str ( year ) ) + \"\" ) if not e . date . month == month : month = e . date . month out . append ( e . date . strftime ( \"\" ) ) out . append ( '' * len ( e . date . strftime ( \"\" ) ) + \"\" ) out . append ( e . to_md ( ) ) result = \"\" . join ( out ) return result def to_txt ( journal ) : \"\"\"\"\"\" return journal . pprint ( ) def export ( journal , format , output = None ) : \"\"\"\"\"\" maps = { \"\" : to_json , \"\" : to_txt , \"\" : to_txt , \"\" : to_md , \"\" : to_md } if format not in maps : return \"\" . format ( format ) if output and os . path . isdir ( output ) : return write_files ( journal , output , format ) else : content = maps [ format ] ( journal ) if output : try : with codecs . open ( output , \"\" , \"\" ) as f : f . write ( content ) return \"\" . format ( output ) except IOError as e : ", "answer": "return \"\" . format ( e . filename , e . strerror )"}, {"prompt": " import re import textwrap class Summary ( object ) : def __init__ ( self , df ) : self . _df = df def budget ( self , type = \"\" , size = ) : summary = [ ] if size == \"\" : summary = self . _df [ \"\" ] . tolist ( ) elif type == \"\" : remaining = size for idx , sent in self . _df . iterrows ( ) : num_words = min ( len ( sent [ \"\" ] ) , remaining ) summary . append ( u\"\" . join ( sent [ \"\" ] [ : num_words ] ) ) remaining -= num_words if remaining < : break elif type == \"\" : remaining = size ", "answer": "for idx , sent in self . _df . iterrows ( ) :"}, {"prompt": " from django import http from django . conf import settings from django . contrib import messages from django . contrib . auth import login as auth_login from django . contrib . auth import logout as auth_logout from django . contrib . auth import update_session_auth_hash from django . contrib . sites . shortcuts import get_current_site from django . core . exceptions import ObjectDoesNotExist from django . core . urlresolvers import reverse , reverse_lazy from django . shortcuts import get_object_or_404 , redirect from django . utils . translation import ugettext_lazy as _ from django . views import generic from oscar . apps . customer . utils import get_password_reset_url from oscar . core . compat import get_user_model from oscar . core . loading import ( get_class , get_classes , get_model , get_profile_class ) from oscar . core . utils import safe_referrer from oscar . views . generic import PostActionMixin from . import signals PageTitleMixin , RegisterUserMixin = get_classes ( '' , [ '' , '' ] ) Dispatcher = get_class ( '' , '' ) EmailAuthenticationForm , EmailUserCreationForm , OrderSearchForm = get_classes ( '' , [ '' , '' , '' ] ) PasswordChangeForm = get_class ( '' , '' ) ProfileForm , ConfirmPasswordForm = get_classes ( '' , [ '' , '' ] ) UserAddressForm = get_class ( '' , '' ) Order = get_model ( '' , '' ) Line = get_model ( '' , '' ) Basket = get_model ( '' , '' ) UserAddress = get_model ( '' , '' ) Email = get_model ( '' , '' ) ProductAlert = get_model ( '' , '' ) CommunicationEventType = get_model ( '' , '' ) User = get_user_model ( ) class AccountSummaryView ( generic . RedirectView ) : \"\"\"\"\"\" pattern_name = settings . OSCAR_ACCOUNTS_REDIRECT_URL class AccountRegistrationView ( RegisterUserMixin , generic . FormView ) : form_class = EmailUserCreationForm template_name = '' redirect_field_name = '' def get ( self , request , * args , ** kwargs ) : if request . user . is_authenticated ( ) : return redirect ( settings . LOGIN_REDIRECT_URL ) return super ( AccountRegistrationView , self ) . get ( request , * args , ** kwargs ) def get_logged_in_redirect ( self ) : return reverse ( '' ) def get_form_kwargs ( self ) : kwargs = super ( AccountRegistrationView , self ) . get_form_kwargs ( ) kwargs [ '' ] = { '' : self . request . GET . get ( '' , '' ) , '' : self . request . GET . get ( self . redirect_field_name , '' ) } kwargs [ '' ] = self . request . get_host ( ) return kwargs def get_context_data ( self , * args , ** kwargs ) : ctx = super ( AccountRegistrationView , self ) . get_context_data ( * args , ** kwargs ) ctx [ '' ] = safe_referrer ( self . request , '' ) return ctx def form_valid ( self , form ) : self . register_user ( form ) return redirect ( form . cleaned_data [ '' ] ) class AccountAuthView ( RegisterUserMixin , generic . TemplateView ) : \"\"\"\"\"\" template_name = '' login_prefix , registration_prefix = '' , '' login_form_class = EmailAuthenticationForm registration_form_class = EmailUserCreationForm redirect_field_name = '' def get ( self , request , * args , ** kwargs ) : if request . user . is_authenticated ( ) : return redirect ( settings . LOGIN_REDIRECT_URL ) return super ( AccountAuthView , self ) . get ( request , * args , ** kwargs ) def get_context_data ( self , * args , ** kwargs ) : ctx = super ( AccountAuthView , self ) . get_context_data ( * args , ** kwargs ) if '' not in kwargs : ctx [ '' ] = self . get_login_form ( ) if '' not in kwargs : ctx [ '' ] = self . get_registration_form ( ) return ctx def post ( self , request , * args , ** kwargs ) : if u'' in request . POST : return self . validate_login_form ( ) elif u'' in request . POST : return self . validate_registration_form ( ) return http . HttpResponseBadRequest ( ) def get_login_form ( self , bind_data = False ) : return self . login_form_class ( ** self . get_login_form_kwargs ( bind_data ) ) def get_login_form_kwargs ( self , bind_data = False ) : kwargs = { } kwargs [ '' ] = self . request . get_host ( ) kwargs [ '' ] = self . login_prefix kwargs [ '' ] = { '' : self . request . GET . get ( self . redirect_field_name , '' ) , } if bind_data and self . request . method in ( '' , '' ) : kwargs . update ( { '' : self . request . POST , '' : self . request . FILES , } ) return kwargs def validate_login_form ( self ) : form = self . get_login_form ( bind_data = True ) if form . is_valid ( ) : user = form . get_user ( ) old_session_key = self . request . session . session_key auth_login ( self . request , form . get_user ( ) ) signals . user_logged_in . send_robust ( sender = self , request = self . request , user = user , old_session_key = old_session_key ) msg = self . get_login_success_message ( form ) if msg : messages . success ( self . request , msg ) return redirect ( self . get_login_success_url ( form ) ) ctx = self . get_context_data ( login_form = form ) return self . render_to_response ( ctx ) def get_login_success_message ( self , form ) : return _ ( \"\" ) def get_login_success_url ( self , form ) : redirect_url = form . cleaned_data [ '' ] if redirect_url : return redirect_url if self . request . user . is_staff : return reverse ( '' ) return settings . LOGIN_REDIRECT_URL def get_registration_form ( self , bind_data = False ) : return self . registration_form_class ( ** self . get_registration_form_kwargs ( bind_data ) ) def get_registration_form_kwargs ( self , bind_data = False ) : kwargs = { } kwargs [ '' ] = self . request . get_host ( ) kwargs [ '' ] = self . registration_prefix kwargs [ '' ] = { '' : self . request . GET . get ( self . redirect_field_name , '' ) , } if bind_data and self . request . method in ( '' , '' ) : kwargs . update ( { '' : self . request . POST , '' : self . request . FILES , } ) return kwargs def validate_registration_form ( self ) : form = self . get_registration_form ( bind_data = True ) if form . is_valid ( ) : self . register_user ( form ) msg = self . get_registration_success_message ( form ) messages . success ( self . request , msg ) return redirect ( self . get_registration_success_url ( form ) ) ctx = self . get_context_data ( registration_form = form ) return self . render_to_response ( ctx ) def get_registration_success_message ( self , form ) : return _ ( \"\" ) def get_registration_success_url ( self , form ) : redirect_url = form . cleaned_data [ '' ] if redirect_url : return redirect_url return settings . LOGIN_REDIRECT_URL class LogoutView ( generic . RedirectView ) : url = settings . OSCAR_HOMEPAGE permanent = False def get ( self , request , * args , ** kwargs ) : auth_logout ( request ) response = super ( LogoutView , self ) . get ( request , * args , ** kwargs ) for cookie in settings . OSCAR_COOKIES_DELETE_ON_LOGOUT : response . delete_cookie ( cookie ) return response class ProfileView ( PageTitleMixin , generic . TemplateView ) : template_name = '' page_title = _ ( '' ) active_tab = '' def get_context_data ( self , ** kwargs ) : ctx = super ( ProfileView , self ) . get_context_data ( ** kwargs ) ctx [ '' ] = self . get_profile_fields ( self . request . user ) return ctx def get_profile_fields ( self , user ) : field_data = [ ] for field_name in User . _meta . additional_fields : field_data . append ( self . get_model_field_data ( user , field_name ) ) profile_class = get_profile_class ( ) if profile_class : try : profile = profile_class . objects . get ( user = user ) except ObjectDoesNotExist : profile = profile_class ( user = user ) field_names = [ f . name for f in profile . _meta . local_fields ] for field_name in field_names : if field_name in ( '' , '' ) : continue field_data . append ( self . get_model_field_data ( profile , field_name ) ) return field_data def get_model_field_data ( self , model_class , field_name ) : \"\"\"\"\"\" field = model_class . _meta . get_field ( field_name ) if field . choices : value = getattr ( model_class , '' % field_name ) ( ) else : value = getattr ( model_class , field_name ) return { '' : getattr ( field , '' ) , '' : value , } class ProfileUpdateView ( PageTitleMixin , generic . FormView ) : form_class = ProfileForm template_name = '' communication_type_code = '' page_title = _ ( '' ) active_tab = '' success_url = reverse_lazy ( '' ) def get_form_kwargs ( self ) : kwargs = super ( ProfileUpdateView , self ) . get_form_kwargs ( ) kwargs [ '' ] = self . request . user return kwargs def form_valid ( self , form ) : try : old_user = User . objects . get ( id = self . request . user . id ) except User . DoesNotExist : old_user = None form . save ( ) new_email = form . cleaned_data . get ( '' ) if new_email and old_user and new_email != old_user . email : ctx = { '' : self . request . user , '' : get_current_site ( self . request ) , '' : get_password_reset_url ( old_user ) , '' : new_email , } msgs = CommunicationEventType . objects . get_and_render ( code = self . communication_type_code , context = ctx ) Dispatcher ( ) . dispatch_user_messages ( old_user , msgs ) messages . success ( self . request , _ ( \"\" ) ) return redirect ( self . get_success_url ( ) ) class ProfileDeleteView ( PageTitleMixin , generic . FormView ) : form_class = ConfirmPasswordForm template_name = '' page_title = _ ( '' ) active_tab = '' success_url = settings . OSCAR_HOMEPAGE def get_form_kwargs ( self ) : kwargs = super ( ProfileDeleteView , self ) . get_form_kwargs ( ) kwargs [ '' ] = self . request . user return kwargs def form_valid ( self , form ) : self . request . user . delete ( ) messages . success ( self . request , _ ( \"\" ) ) return redirect ( self . get_success_url ( ) ) class ChangePasswordView ( PageTitleMixin , generic . FormView ) : form_class = PasswordChangeForm template_name = '' communication_type_code = '' page_title = _ ( '' ) active_tab = '' success_url = reverse_lazy ( '' ) def get_form_kwargs ( self ) : kwargs = super ( ChangePasswordView , self ) . get_form_kwargs ( ) kwargs [ '' ] = self . request . user return kwargs def form_valid ( self , form ) : form . save ( ) update_session_auth_hash ( self . request , self . request . user ) messages . success ( self . request , _ ( \"\" ) ) ctx = { '' : self . request . user , '' : get_current_site ( self . request ) , '' : get_password_reset_url ( self . request . user ) , } msgs = CommunicationEventType . objects . get_and_render ( code = self . communication_type_code , context = ctx ) Dispatcher ( ) . dispatch_user_messages ( self . request . user , msgs ) return redirect ( self . get_success_url ( ) ) class EmailHistoryView ( PageTitleMixin , generic . ListView ) : context_object_name = \"\" template_name = '' paginate_by = settings . OSCAR_EMAILS_PER_PAGE page_title = _ ( '' ) active_tab = '' def get_queryset ( self ) : return Email . _default_manager . filter ( user = self . request . user ) class EmailDetailView ( PageTitleMixin , generic . DetailView ) : \"\"\"\"\"\" template_name = \"\" context_object_name = '' active_tab = '' def get_object ( self , queryset = None ) : return get_object_or_404 ( Email , user = self . request . user , id = self . kwargs [ '' ] ) def get_page_title ( self ) : \"\"\"\"\"\" return u'' % ( _ ( '' ) , self . object . subject ) class OrderHistoryView ( PageTitleMixin , generic . ListView ) : \"\"\"\"\"\" context_object_name = \"\" template_name = '' paginate_by = settings . OSCAR_ORDERS_PER_PAGE model = Order form_class = OrderSearchForm page_title = _ ( '' ) active_tab = '' def get ( self , request , * args , ** kwargs ) : if '' in request . GET : self . form = self . form_class ( self . request . GET ) if not self . form . is_valid ( ) : self . object_list = self . get_queryset ( ) ctx = self . get_context_data ( object_list = self . object_list ) return self . render_to_response ( ctx ) data = self . form . cleaned_data if data [ '' ] and not ( data [ '' ] or data [ '' ] ) : try : order = Order . objects . get ( number = data [ '' ] , user = self . request . user ) except Order . DoesNotExist : pass else : return redirect ( '' , order_number = order . number ) else : self . form = self . form_class ( ) return super ( OrderHistoryView , self ) . get ( request , * args , ** kwargs ) def get_queryset ( self ) : qs = self . model . _default_manager . filter ( user = self . request . user ) if self . form . is_bound and self . form . is_valid ( ) : qs = qs . filter ( ** self . form . get_filters ( ) ) return qs def get_context_data ( self , * args , ** kwargs ) : ctx = super ( OrderHistoryView , self ) . get_context_data ( * args , ** kwargs ) ctx [ '' ] = self . form return ctx class OrderDetailView ( PageTitleMixin , PostActionMixin , generic . DetailView ) : model = Order active_tab = '' def get_template_names ( self ) : return [ \"\" ] def get_page_title ( self ) : \"\"\"\"\"\" return u'' % ( _ ( '' ) , self . object . number ) def get_object ( self , queryset = None ) : return get_object_or_404 ( self . model , user = self . request . user , number = self . kwargs [ '' ] ) def do_reorder ( self , order ) : \"\"\"\"\"\" basket = self . request . basket lines_to_add = [ ] warnings = [ ] for line in order . lines . all ( ) : is_available , reason = line . is_available_to_reorder ( basket , self . request . strategy ) if is_available : lines_to_add . append ( line ) else : warnings . append ( reason ) total_quantity = sum ( [ line . quantity for line in lines_to_add ] ) is_quantity_allowed , reason = basket . is_quantity_allowed ( total_quantity ) if not is_quantity_allowed : messages . warning ( self . request , reason ) self . response = redirect ( '' ) return for warning in warnings : messages . warning ( self . request , warning ) for line in lines_to_add : options = [ ] for attribute in line . attributes . all ( ) : if attribute . option : options . append ( { '' : attribute . option , '' : attribute . value } ) basket . add_product ( line . product , line . quantity , options ) if len ( lines_to_add ) > : self . response = redirect ( '' ) messages . info ( self . request , _ ( \"\" \"\" ) % { '' : order . number } ) else : self . response = redirect ( '' ) messages . warning ( self . request , _ ( \"\" \"\" ) % { '' : order . number } ) class OrderLineView ( PostActionMixin , generic . DetailView ) : \"\"\"\"\"\" def get_object ( self , queryset = None ) : order = get_object_or_404 ( Order , user = self . request . user , number = self . kwargs [ '' ] ) return order . lines . get ( id = self . kwargs [ '' ] ) def do_reorder ( self , line ) : self . response = redirect ( '' , self . kwargs [ '' ] ) basket = self . request . basket line_available_to_reorder , reason = line . is_available_to_reorder ( basket , self . request . strategy ) if not line_available_to_reorder : messages . warning ( self . request , reason ) return self . response = redirect ( '' ) options = [ ] for attribute in line . attributes . all ( ) : if attribute . option : options . append ( { '' : attribute . option , '' : attribute . value } ) basket . add_product ( line . product , line . quantity , options ) if line . quantity > : msg = _ ( \"\" \"\" ) % { '' : line . quantity , '' : line . product } else : msg = _ ( \"\" ) % line . product messages . info ( self . request , msg ) class AnonymousOrderDetailView ( generic . DetailView ) : ", "answer": "model = Order"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Intangible ( )"}, {"prompt": " import os import sys import shutil from optparse import make_option from django . conf import settings from django . core . files . storage import get_storage_class from django . core . management . base import CommandError , NoArgsCommand from django . utils . encoding import smart_str from django . contrib . staticfiles import finders class Command ( NoArgsCommand ) : \"\"\"\"\"\" option_list = NoArgsCommand . option_list + ( make_option ( '' , action = '' , dest = '' , default = True , help = \"\" ) , make_option ( '' , '' , action = '' , default = [ ] , dest = '' , metavar = '' , help = \"\" \"\" ) , make_option ( '' , '' , action = '' , dest = '' , default = False , help = \"\" ) , make_option ( '' , '' , action = '' , dest = '' , default = False , help = \"\" ) , make_option ( '' , action = '' , dest = '' , default = True , help = \"\" \"\" ) , ) help = \"\" def __init__ ( self , * args , ** kwargs ) : super ( NoArgsCommand , self ) . __init__ ( * args , ** kwargs ) self . copied_files = [ ] self . symlinked_files = [ ] self . unmodified_files = [ ] self . storage = get_storage_class ( settings . STATICFILES_STORAGE ) ( ) try : self . storage . path ( '' ) except NotImplementedError : self . local = False else : self . local = True os . stat_float_times ( False ) def handle_noargs ( self , ** options ) : symlink = options [ '' ] ignore_patterns = options [ '' ] if options [ '' ] : ignore_patterns += [ '' , '' , '' ] ignore_patterns = list ( set ( ignore_patterns ) ) self . verbosity = int ( options . get ( '' , ) ) if symlink : if sys . platform == '' : raise CommandError ( \"\" \"\" % sys . platform ) if not self . local : raise CommandError ( \"\" ) if options . get ( '' ) : confirm = raw_input ( u\"\"\"\"\"\" ) if confirm != '' : raise CommandError ( \"\" ) processed_files = [ ] for finder in finders . get_finders ( ) : for path , storage in finder . list ( ignore_patterns ) : if getattr ( storage , '' , None ) : prefixed_path = os . path . join ( storage . prefix , path ) else : prefixed_path = path if prefixed_path in processed_files : continue if symlink : self . link_file ( path , prefixed_path , storage , ** options ) else : self . copy_file ( path , prefixed_path , storage , ** options ) processed_files . append ( prefixed_path ) actual_count = len ( self . copied_files ) + len ( self . symlinked_files ) unmodified_count = len ( self . unmodified_files ) if self . verbosity >= : self . stdout . write ( smart_str ( u\"\" % ( actual_count , actual_count != and '' or '' , symlink and '' or '' , settings . STATIC_ROOT , unmodified_count and '' % unmodified_count or '' ) ) ) def log ( self , msg , level = ) : \"\"\"\"\"\" msg = smart_str ( msg ) if not msg . endswith ( \"\" ) : msg += \"\" if self . verbosity >= level : self . stdout . write ( msg ) def delete_file ( self , path , prefixed_path , source_storage , ** options ) : symlink = options [ '' ] if self . storage . exists ( prefixed_path ) : try : target_last_modified = self . storage . modified_time ( prefixed_path ) except ( OSError , NotImplementedError ) : ", "answer": "pass"}, {"prompt": " import sys from datetime import datetime from django . conf import settings from django . db import models from django . db . models . signals import post_save from django . utils . translation import get_language_from_request , ugettext_lazy as _ from django . contrib . auth . models import User , AnonymousUser from emailconfirmation . models import EmailAddress , EmailConfirmation from emailconfirmation . signals import email_confirmed from timezones . fields import TimeZoneField class Account ( models . Model ) : user = models . ForeignKey ( User , unique = True , verbose_name = _ ( \"\" ) ) timezone = TimeZoneField ( _ ( \"\" ) ) language = models . CharField ( _ ( \"\" ) , max_length = , choices = settings . LANGUAGES , default = settings . LANGUAGE_CODE ) def __unicode__ ( self ) : return self . user . username class OtherServiceInfo ( models . Model ) : ", "answer": "user = models . ForeignKey ( User , verbose_name = _ ( \"\" ) )"}, {"prompt": " import os import select import socket import thread import Queue import threading ", "answer": "import __builtin__"}, {"prompt": " contacts = { } contacts = { '' : '' , '' : '' , '' : '' } contacts [ '' ] ", "answer": "contacts [ '' ] = ''"}, {"prompt": " \"\"\"\"\"\" import pytest import os from util_functions import run_ofSM @ pytest . mark . usefixtures ( '' ) ", "answer": "class TestArchive :"}, {"prompt": " from django . core . management . base import NoArgsCommand from django . conf import settings from openflow . optin_manager . xmlrpc_server . models import FVServerProxy from openflow . optin_manager . flowspace . helper import * from openflow . optin_manager . opts . models import * from openflow . optin_manager . users . models import Priority from django . contrib . auth . models import User from openflow . optin_manager . opts . helper import opt_fs_into_exp try : import cpickle as pickle except : import pickle import os import time path = \"\" FLOWVISOR_SLEEP_TIME = class Command ( NoArgsCommand ) : help = \"\" def handle_noargs ( self , ** options ) : \"\"\"\"\"\" try : f = open ( \"\" % path , \"\" ) ids = pickle . load ( f ) f . close ( ) ", "answer": "os . remove ( \"\" % path )"}, {"prompt": " class HTTPError ( Exception ) : \"\" pass class SSLError ( Exception ) : \"\" pass class MaxRetryError ( HTTPError ) : \"\" ", "answer": "pass"}, {"prompt": " import gc import StringIO , sys , types from twisted . trial import unittest , runner from twisted . scripts import trial from twisted . python import util from twisted . python . compat import set from twisted . python . filepath import FilePath from twisted . trial . test . test_loader import testNames pyunit = __import__ ( '' ) def sibpath ( filename ) : \"\"\"\"\"\" return util . sibpath ( __file__ , filename ) class ForceGarbageCollection ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . config = trial . Options ( ) self . log = [ ] self . patch ( gc , '' , self . collect ) test = pyunit . FunctionTestCase ( self . simpleTest ) self . test = runner . TestSuite ( [ test , test ] ) def simpleTest ( self ) : \"\"\"\"\"\" self . log . append ( '' ) def collect ( self ) : \"\"\"\"\"\" self . log . append ( '' ) def makeRunner ( self ) : \"\"\"\"\"\" runner = trial . _makeRunner ( self . config ) runner . stream = StringIO . StringIO ( ) return runner def test_forceGc ( self ) : \"\"\"\"\"\" self . config [ '' ] = True self . config . postOptions ( ) runner = self . makeRunner ( ) runner . run ( self . test ) self . assertEqual ( self . log , [ '' , '' , '' , '' , '' , '' ] ) def test_unforceGc ( self ) : \"\"\"\"\"\" self . config . postOptions ( ) runner = self . makeRunner ( ) runner . run ( self . test ) self . assertEqual ( self . log , [ '' , '' ] ) class TestSuiteUsed ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" self . config = trial . Options ( ) def test_defaultSuite ( self ) : \"\"\"\"\"\" loader = trial . _getLoader ( self . config ) self . assertEquals ( loader . suiteFactory , runner . DestructiveTestSuite ) def test_untilFailureSuite ( self ) : \"\"\"\"\"\" self . config [ '' ] = True loader = trial . _getLoader ( self . config ) self . assertEquals ( loader . suiteFactory , runner . TestSuite ) class TestModuleTest ( unittest . TestCase ) : def setUp ( self ) : self . config = trial . Options ( ) def tearDown ( self ) : self . config = None def test_testNames ( self ) : \"\"\"\"\"\" self . assertEqual ( testNames ( self ) , [ self . id ( ) ] ) def assertSuitesEqual ( self , test1 , names ) : loader = runner . TestLoader ( ) names1 = testNames ( test1 ) names2 = testNames ( runner . TestSuite ( map ( loader . loadByName , names ) ) ) names1 . sort ( ) names2 . sort ( ) self . assertEqual ( names1 , names2 ) def test_baseState ( self ) : self . failUnlessEqual ( , len ( self . config [ '' ] ) ) def test_testmoduleOnModule ( self ) : \"\"\"\"\"\" self . config . opt_testmodule ( sibpath ( '' ) ) self . assertSuitesEqual ( trial . _getSuite ( self . config ) , [ '' ] ) def test_testmoduleTwice ( self ) : \"\"\"\"\"\" self . config . opt_testmodule ( sibpath ( '' ) ) self . config . opt_testmodule ( sibpath ( '' ) ) self . assertSuitesEqual ( trial . _getSuite ( self . config ) , [ '' ] ) def test_testmoduleOnSourceAndTarget ( self ) : \"\"\"\"\"\" self . config . opt_testmodule ( sibpath ( '' ) ) self . config . opt_testmodule ( sibpath ( '' ) ) self . assertSuitesEqual ( trial . _getSuite ( self . config ) , [ '' ] ) def test_testmoduleOnSelfModule ( self ) : \"\"\"\"\"\" self . config . opt_testmodule ( sibpath ( '' ) ) self . assertSuitesEqual ( trial . _getSuite ( self . config ) , [ '' ] ) def test_testmoduleOnScript ( self ) : \"\"\"\"\"\" self . config . opt_testmodule ( sibpath ( '' ) ) self . assertSuitesEqual ( trial . _getSuite ( self . config ) , [ '' , '' ] ) def test_testmoduleOnNonexistentFile ( self ) : \"\"\"\"\"\" buffy = StringIO . StringIO ( ) stderr , sys . stderr = sys . stderr , buffy filename = '' try : self . config . opt_testmodule ( filename ) self . failUnlessEqual ( , len ( self . config [ '' ] ) ) self . failUnlessEqual ( \"\" % ( filename , ) , buffy . getvalue ( ) ) finally : sys . stderr = stderr def test_testmoduleOnEmptyVars ( self ) : \"\"\"\"\"\" self . config . opt_testmodule ( sibpath ( '' ) ) self . failUnlessEqual ( , len ( self . config [ '' ] ) ) def test_testmoduleOnModuleName ( self ) : \"\"\"\"\"\" buffy = StringIO . StringIO ( ) stderr , sys . stderr = sys . stderr , buffy moduleName = '' try : self . config . opt_testmodule ( moduleName ) self . failUnlessEqual ( , len ( self . config [ '' ] ) ) self . failUnlessEqual ( \"\" % ( moduleName , ) , buffy . getvalue ( ) ) finally : sys . stderr = stderr def test_parseLocalVariable ( self ) : declaration = '' localVars = trial . _parseLocalVariables ( declaration ) ", "answer": "self . failUnlessEqual ( { '' :"}, {"prompt": " import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import testing from chainer . testing import attr class TestDropout ( unittest . TestCase ) : def setUp ( self ) : self . x = numpy . random . uniform ( - , , ( , ) ) . astype ( numpy . float32 ) self . gy = numpy . random . uniform ( - , , ( , ) ) . astype ( numpy . float32 ) def check_type_forward ( self , x_data ) : x = chainer . Variable ( x_data ) functions . dropout ( x ) def test_type_forward_cpu ( self ) : self . check_type_forward ( self . x ) @ attr . gpu def test_type_forward_gpu ( self ) : self . check_type_forward ( cuda . to_gpu ( self . x ) ) ", "answer": "testing . run_module ( __name__ , __file__ ) "}, {"prompt": " from __future__ import unicode_literals ", "answer": "from django . db import models , migrations"}, {"prompt": " import json import mock from awscli . testutils import unittest , FileCreator from awscli . topictags import TopicTagDB class TestTopicTagDB ( unittest . TestCase ) : def setUp ( self ) : self . topic_tag_db = TopicTagDB ( ) self . file_creator = FileCreator ( ) def tearDown ( self ) : self . file_creator . remove_all ( ) class TestTopicTagDBGeneral ( TestTopicTagDB ) : def test_valid_tags ( self ) : self . assertCountEqual ( self . topic_tag_db . valid_tags , [ '' , '' , '' , '' , '' ] ) def test_topic_dir ( self ) : self . topic_tag_db = TopicTagDB ( topic_dir = '' ) self . assertEqual ( self . topic_tag_db . topic_dir , '' ) self . topic_tag_db . topic_dir = '' self . assertEqual ( self . topic_tag_db . topic_dir , '' ) def test_index_file ( self ) : self . topic_tag_db = TopicTagDB ( index_file = '' ) self . assertEqual ( self . topic_tag_db . index_file , '' ) self . topic_tag_db . index_file = '' self . assertEqual ( self . topic_tag_db . index_file , '' ) def test_get_all_topic_names ( self ) : tag_dict = { '' : { '' : [ '' ] , } , '' : { '' : [ '' ] , } } reference_topic_list = [ '' , '' ] self . topic_tag_db = TopicTagDB ( tag_dict ) self . assertCountEqual ( self . topic_tag_db . get_all_topic_names ( ) , reference_topic_list ) def test_get_all_topic_source_files ( self ) : source_files = [ ] topic_dir = self . file_creator . rootdir self . topic_tag_db = TopicTagDB ( topic_dir = topic_dir ) for i in range ( ) : topic_name = '' + str ( i ) source_files . append ( self . file_creator . create_file ( topic_name , '' ) ) self . assertCountEqual ( self . topic_tag_db . get_all_topic_src_files ( ) , source_files ) def test_get_all_topic_source_files_ignore_index ( self ) : topic_filename = '' index_filename = '' source_files = [ ] source_files . append ( self . file_creator . create_file ( topic_filename , '' ) ) index_file = self . file_creator . create_file ( index_filename , '' ) topic_dir = self . file_creator . rootdir self . topic_tag_db = TopicTagDB ( index_file = index_file , topic_dir = topic_dir ) self . assertCountEqual ( self . topic_tag_db . get_all_topic_src_files ( ) , source_files ) def test_get_all_topic_source_files_ignore_hidden ( self ) : topic_filename = '' hidden_filename = '' + topic_filename source_files = [ ] source_files . append ( self . file_creator . create_file ( topic_filename , '' ) ) self . file_creator . create_file ( hidden_filename , '' ) topic_dir = self . file_creator . rootdir self . topic_tag_db = TopicTagDB ( topic_dir = topic_dir ) self . assertCountEqual ( self . topic_tag_db . get_all_topic_src_files ( ) , source_files ) def test_get_tag_value_all_tags ( self ) : topic_name = '' tag_dict = { topic_name : { '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) value = self . topic_tag_db . get_tag_value ( topic_name , '' ) self . assertEqual ( value , [ '' ] ) value = self . topic_tag_db . get_tag_value ( topic_name , '' ) self . assertEqual ( value , [ '' ] ) value = self . topic_tag_db . get_tag_value ( topic_name , '' ) self . assertEqual ( value , [ '' ] ) value = self . topic_tag_db . get_tag_value ( topic_name , '' ) self . assertEqual ( value , [ '' ] ) value = self . topic_tag_db . get_tag_value ( topic_name , '' ) self . assertEqual ( value , [ '' ] ) def test_get_tag_multi_value ( self ) : topic_name = '' tag_dict = { topic_name : { '' : [ '' , '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) value = self . topic_tag_db . get_tag_value ( topic_name , '' ) self . assertEqual ( value , [ '' , '' ] ) def test_get_tag_topic_no_exists ( self ) : topic_name = '' tag_dict = { topic_name : { '' : [ '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) value = self . topic_tag_db . get_tag_value ( '' , '' ) self . assertEqual ( value , None ) def test_get_tag_no_exist_tag ( self ) : topic_name = '' tag_dict = { topic_name : { '' : [ '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) value = self . topic_tag_db . get_tag_value ( topic_name , '' ) self . assertEqual ( value , None ) def test_get_tag_no_exist_use_default ( self ) : topic_name = '' tag_dict = { topic_name : { '' : [ '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) value = self . topic_tag_db . get_tag_value ( '' , '' , [ ] ) self . assertEqual ( value , [ ] ) def test_get_tag_single_value ( self ) : topic_name = '' tag_dict = { topic_name : { '' : [ '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) value = self . topic_tag_db . get_tag_single_value ( '' , '' ) self . assertEqual ( value , '' ) def test_get_tag_single_value_exception ( self ) : topic_name = '' tag_dict = { topic_name : { '' : [ '' , '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) with self . assertRaises ( ValueError ) : self . topic_tag_db . get_tag_single_value ( '' , '' ) def test_get_tag_single_value_no_exists ( self ) : topic_name = '' tag_dict = { topic_name : { '' : [ '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) value = self . topic_tag_db . get_tag_single_value ( '' , '' ) self . assertEqual ( value , None ) def test_load_and_save_json_index ( self ) : tag_dict = { '' : { '' : [ '' ] , '' : [ '' ] , '' : [ '' , '' ] , '' : [ '' ] , '' : [ '' ] } , '' : { '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] } } json_index = self . file_creator . create_file ( '' , '' ) tag_json = json . dumps ( tag_dict , indent = , sort_keys = True ) with open ( json_index , '' ) as f : f . write ( tag_json ) self . topic_tag_db = TopicTagDB ( index_file = json_index ) self . topic_tag_db . load_json_index ( ) saved_json_index = self . file_creator . create_file ( '' , '' ) self . topic_tag_db . index_file = saved_json_index self . topic_tag_db . save_to_json_index ( ) with open ( saved_json_index , '' ) as f : self . assertEqual ( f . read ( ) , tag_json ) class TestTopicTagDBQuery ( TestTopicTagDB ) : def test_query_all_tags_single_topic ( self ) : tag_dict = { '' : { '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) query_dict = self . topic_tag_db . query ( '' ) self . assertEqual ( query_dict , { '' : [ '' ] } ) query_dict = self . topic_tag_db . query ( '' ) self . assertEqual ( query_dict , { '' : [ '' ] } ) query_dict = self . topic_tag_db . query ( '' ) self . assertEqual ( query_dict , { '' : [ '' ] } ) query_dict = self . topic_tag_db . query ( '' ) self . assertEqual ( query_dict , { '' : [ '' ] } ) query_dict = self . topic_tag_db . query ( '' ) self . assertEqual ( query_dict , { '' : [ '' ] } ) def test_query_tag_multi_values ( self ) : tag_dict = { '' : { '' : [ '' , '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) query_dict = self . topic_tag_db . query ( '' ) self . assertEqual ( query_dict , { '' : [ '' ] , '' : [ '' ] } ) def test_query_tag_multi_values ( self ) : tag_dict = { '' : { '' : [ '' , '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) query_dict = self . topic_tag_db . query ( '' ) self . assertEqual ( query_dict , { '' : [ '' ] , '' : [ '' ] } ) def test_query_multiple_topics ( self ) : tag_dict = { '' : { '' : [ '' ] } , '' : { '' : [ '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) query_dict = self . topic_tag_db . query ( '' ) self . assertEqual ( query_dict , { '' : [ '' ] , '' : [ '' ] } ) def test_query_multiple_topics_with_multi_values ( self ) : tag_dict = { '' : { '' : [ '' , '' ] } , '' : { '' : [ '' , '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) query_dict = self . topic_tag_db . query ( '' ) self . assertEqual ( query_dict , { '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] } ) def test_query_multiple_topics_with_overlap_values ( self ) : tag_dict = { '' : { '' : [ '' , '' ] } , '' : { '' : [ '' , '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) query_dict = self . topic_tag_db . query ( '' ) self . assertCountEqual ( query_dict , { '' : [ '' ] , '' : [ '' ] , '' : [ '' , '' ] } ) def test_query_with_limit_single_value ( self ) : tag_dict = { '' : { '' : [ '' , '' ] } , '' : { '' : [ '' , '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) query_dict = self . topic_tag_db . query ( '' , [ '' ] ) self . assertCountEqual ( query_dict , { '' : [ '' , '' ] } ) def test_query_with_limit_multi_value ( self ) : tag_dict = { '' : { '' : [ '' , '' ] } , '' : { '' : [ '' , '' ] } } self . topic_tag_db = TopicTagDB ( tag_dict ) query_dict = self . topic_tag_db . query ( '' , [ '' , '' ] ) ", "answer": "self . assertCountEqual ( query_dict ,"}, {"prompt": " from __future__ import division import numpy as np from collections import defaultdict import json import itertools from sklearn import cluster , preprocessing , manifold from datetime import datetime import sys class KeplerMapper ( object ) : def __init__ ( self , verbose = ) : self . verbose = verbose self . chunk_dist = [ ] self . overlap_dist = [ ] self . d = [ ] self . nr_cubes = self . overlap_perc = self . clusterer = False def fit_transform ( self , X , projection = \"\" , scaler = preprocessing . MinMaxScaler ( ) ) : self . scaler = scaler self . projection = str ( projection ) if str ( type ( projection ) ) [ : ] == \"\" : reducer = projection if self . verbose > : try : projection . set_params ( ** { \"\" : self . verbose } ) except : pass print ( \"\" % str ( projection ) ) X = reducer . fit_transform ( X ) if isinstance ( projection , str ) : if self . verbose > : print ( \"\" % ( projection ) ) if projection == \"\" : X = np . sum ( X , axis = ) . reshape ( ( X . shape [ ] , ) ) if projection == \"\" : X = np . mean ( X , axis = ) . reshape ( ( X . shape [ ] , ) ) if projection == \"\" : X = np . median ( X , axis = ) . reshape ( ( X . shape [ ] , ) ) if projection == \"\" : X = np . max ( X , axis = ) . reshape ( ( X . shape [ ] , ) ) if projection == \"\" : X = np . min ( X , axis = ) . reshape ( ( X . shape [ ] , ) ) if projection == \"\" : X = np . std ( X , axis = ) . reshape ( ( X . shape [ ] , ) ) if projection == \"\" : X_mean = np . mean ( X , axis = ) X = np . sum ( np . sqrt ( ( X - X_mean ) ** ) , axis = ) . reshape ( ( X . shape [ ] , ) ) if isinstance ( projection , list ) : if self . verbose > : print ( \"\" % ( str ( projection ) ) ) X = X [ : , np . array ( projection ) ] if scaler is not None : if self . verbose > : print ( \"\" % str ( scaler ) ) X = scaler . fit_transform ( X ) return X def map ( self , projected_X , inverse_X = None , clusterer = cluster . DBSCAN ( eps = , min_samples = ) , nr_cubes = , overlap_perc = ) : start = datetime . now ( ) def cube_coordinates_all ( nr_cubes , nr_dimensions ) : l = [ ] for x in range ( nr_cubes ) : l += [ x ] * nr_dimensions return [ np . array ( list ( f ) ) for f in sorted ( set ( itertools . permutations ( l , nr_dimensions ) ) ) ] nodes = defaultdict ( list ) links = defaultdict ( list ) complex = { } self . nr_cubes = nr_cubes self . clusterer = clusterer self . overlap_perc = overlap_perc if self . verbose > : print ( \"\" % ( str ( projected_X . shape ) ) ) if inverse_X is None : inverse_X = projected_X self . chunk_dist = ( np . max ( projected_X , axis = ) - np . min ( projected_X , axis = ) ) / nr_cubes self . overlap_dist = self . overlap_perc * self . chunk_dist self . d = np . min ( projected_X , axis = ) di = np . array ( [ x for x in range ( projected_X . shape [ ] ) ] ) ids = np . array ( [ x for x in range ( projected_X . shape [ ] ) ] ) projected_X = np . c_ [ ids , projected_X ] inverse_X = np . c_ [ ids , inverse_X ] if self . verbose > : total_cubes = len ( cube_coordinates_all ( nr_cubes , projected_X . shape [ ] ) ) print ( \"\" % total_cubes ) for i , coor in enumerate ( cube_coordinates_all ( nr_cubes , di . shape [ ] ) ) : hypercube = projected_X [ np . invert ( np . any ( ( projected_X [ : , di + ] >= self . d [ di ] + ( coor * self . chunk_dist [ di ] ) ) & ( projected_X [ : , di + ] < self . d [ di ] + ( coor * self . chunk_dist [ di ] ) + self . chunk_dist [ di ] + self . overlap_dist [ di ] ) == False , axis = ) ) ] if self . verbose > : print ( \"\" % ( hypercube . shape [ ] , i , total_cubes , self . d [ di ] + ( coor * self . chunk_dist [ di ] ) ) ) if hypercube . shape [ ] > : inverse_x = inverse_X [ [ int ( nn ) for nn in hypercube [ : , ] ] ] clusterer . fit ( inverse_x [ : , : ] ) if self . verbose > : print ( \"\" % ( np . unique ( clusterer . labels_ [ clusterer . labels_ > - ] ) . shape [ ] , i ) ) for a in np . c_ [ hypercube [ : , ] , clusterer . labels_ ] : if a [ ] != - : cluster_id = str ( coor [ ] ) + \"\" + str ( i ) + \"\" + str ( a [ ] ) + \"\" + str ( coor ) + \"\" + str ( self . d [ di ] + ( coor * self . chunk_dist [ di ] ) ) nodes [ cluster_id ] . append ( int ( a [ ] ) ) else : if self . verbose > : print ( \"\" % ( i ) ) candidates = itertools . combinations ( nodes . keys ( ) , ) for candidate in candidates : if len ( nodes [ candidate [ ] ] + nodes [ candidate [ ] ] ) != len ( set ( nodes [ candidate [ ] ] + nodes [ candidate [ ] ] ) ) : links [ candidate [ ] ] . append ( candidate [ ] ) if self . verbose > : nr_links = for k in links : nr_links += len ( links [ k ] ) print ( \"\" % ( nr_links , len ( nodes ) , str ( datetime . now ( ) - start ) ) ) complex [ \"\" ] = nodes complex [ \"\" ] = links complex [ \"\" ] = self . projection ", "answer": "return complex"}, {"prompt": " from nose . tools import * from nose import SkipTest import networkx from nose . plugins . attrib import attr from networkx import edge_current_flow_betweenness_centrality as edge_current_flow from networkx import edge_current_flow_betweenness_centrality_subset as edge_current_flow_subset class TestFlowBetweennessCentrality ( object ) : numpy = @ classmethod def setupClass ( cls ) : ", "answer": "global np"}, {"prompt": " __all__ = [ '' ] import bson from st2common . triggers import register_internal_trigger_types from st2common . rbac . types import PermissionType from st2common . rbac . types import ResourceType from st2common . persistence . auth import User from st2common . persistence . rbac import Role from st2common . persistence . rbac import UserRoleAssignment from st2common . persistence . rbac import PermissionGrant from st2common . persistence . rule import Rule from st2common . persistence . rule_enforcement import RuleEnforcement from st2common . models . db . auth import UserDB from st2common . models . db . rbac import RoleDB from st2common . models . db . rbac import UserRoleAssignmentDB from st2common . models . db . rbac import PermissionGrantDB from st2common . models . db . rule import RuleDB from st2common . models . db . rule_enforcement import RuleEnforcementDB from st2common . rbac . resolvers import RuleEnforcementPermissionsResolver from tests . unit . test_rbac_resolvers import BasePermissionsResolverTestCase class RuleEnforcementPermissionsResolverTestCase ( BasePermissionsResolverTestCase ) : def setUp ( self ) : super ( RuleEnforcementPermissionsResolverTestCase , self ) . setUp ( ) register_internal_trigger_types ( ) user_1_db = UserDB ( name = '' ) user_1_db = User . add_or_update ( user_1_db ) self . users [ '' ] = user_1_db user_2_db = UserDB ( name = '' ) user_2_db = User . add_or_update ( user_2_db ) self . users [ '' ] = user_2_db user_3_db = UserDB ( name = '' ) user_3_db = User . add_or_update ( user_3_db ) self . users [ '' ] = user_3_db user_4_db = UserDB ( name = '' ) user_4_db = User . add_or_update ( user_4_db ) self . users [ '' ] = user_4_db user_5_db = UserDB ( name = '' ) user_5_db = User . add_or_update ( user_5_db ) self . users [ '' ] = user_5_db user_6_db = UserDB ( name = '' ) user_6_db = User . add_or_update ( user_6_db ) self . users [ '' ] = user_6_db user_7_db = UserDB ( name = '' ) user_7_db = User . add_or_update ( user_7_db ) self . users [ '' ] = user_7_db user_8_db = UserDB ( name = '' ) user_8_db = User . add_or_update ( user_8_db ) self . users [ '' ] = user_8_db user_9_db = UserDB ( name = '' ) user_9_db = User . add_or_update ( user_9_db ) self . users [ '' ] = user_9_db user_10_db = UserDB ( name = '' ) user_10_db = User . add_or_update ( user_10_db ) self . users [ '' ] = user_10_db rule_1_db = RuleDB ( pack = '' , name = '' , action = { '' : '' } , trigger = '' ) rule_1_db = Rule . add_or_update ( rule_1_db ) self . resources [ '' ] = rule_1_db rule_enforcement_1_db = RuleEnforcementDB ( trigger_instance_id = str ( bson . ObjectId ( ) ) , execution_id = str ( bson . ObjectId ( ) ) , rule = { '' : rule_1_db . ref , '' : rule_1_db . uid , '' : str ( rule_1_db . id ) } ) rule_enforcement_1_db = RuleEnforcement . add_or_update ( rule_enforcement_1_db ) self . resources [ '' ] = rule_enforcement_1_db rule_2_db = RuleDB ( pack = '' , name = '' ) rule_2_db = Rule . add_or_update ( rule_2_db ) self . resources [ '' ] = rule_2_db rule_enforcement_2_db = RuleEnforcementDB ( trigger_instance_id = str ( bson . ObjectId ( ) ) , execution_id = str ( bson . ObjectId ( ) ) , rule = { '' : rule_2_db . ref , '' : rule_2_db . uid , '' : str ( rule_2_db . id ) } ) rule_enforcement_2_db = RuleEnforcement . add_or_update ( rule_enforcement_2_db ) self . resources [ '' ] = rule_enforcement_2_db rule_3_db = RuleDB ( pack = '' , name = '' ) rule_3_db = Rule . add_or_update ( rule_3_db ) self . resources [ '' ] = rule_3_db rule_enforcement_3_db = RuleEnforcementDB ( trigger_instance_id = str ( bson . ObjectId ( ) ) , execution_id = str ( bson . ObjectId ( ) ) , rule = { '' : rule_3_db . ref , '' : rule_3_db . uid , '' : str ( rule_3_db . id ) } ) rule_enforcement_3_db = RuleEnforcement . add_or_update ( rule_enforcement_3_db ) self . resources [ '' ] = rule_enforcement_3_db grant_db = PermissionGrantDB ( resource_uid = self . resources [ '' ] . get_uid ( ) , resource_type = ResourceType . PACK , permission_types = [ PermissionType . RULE_VIEW ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) permission_grants = [ str ( grant_db . id ) ] role_3_db = RoleDB ( name = '' , permission_grants = permission_grants ) role_3_db = Role . add_or_update ( role_3_db ) self . roles [ '' ] = role_3_db grant_db = PermissionGrantDB ( resource_uid = self . resources [ '' ] . get_uid ( ) , resource_type = ResourceType . RULE , permission_types = [ PermissionType . RULE_VIEW ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) permission_grants = [ str ( grant_db . id ) ] role_4_db = RoleDB ( name = '' , permission_grants = permission_grants ) role_4_db = Role . add_or_update ( role_4_db ) self . roles [ '' ] = role_4_db grant_db = PermissionGrantDB ( resource_uid = self . resources [ '' ] . get_uid ( ) , resource_type = ResourceType . PACK , permission_types = [ PermissionType . RULE_ALL ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) permission_grants = [ str ( grant_db . id ) ] role_4_db = RoleDB ( name = '' , permission_grants = permission_grants ) role_4_db = Role . add_or_update ( role_4_db ) self . roles [ '' ] = role_4_db grant_db = PermissionGrantDB ( resource_uid = self . resources [ '' ] . get_uid ( ) , resource_type = ResourceType . RULE , permission_types = [ PermissionType . RULE_ALL ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) permission_grants = [ str ( grant_db . id ) ] role_4_db = RoleDB ( name = '' , permission_grants = permission_grants ) role_4_db = Role . add_or_update ( role_4_db ) self . roles [ '' ] = role_4_db grant_db = PermissionGrantDB ( resource_uid = self . resources [ '' ] . get_uid ( ) , resource_type = ResourceType . RULE , permission_types = [ PermissionType . RULE_MODIFY ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) permission_grants = [ str ( grant_db . id ) ] role_5_db = RoleDB ( name = '' , permission_grants = permission_grants ) role_5_db = Role . add_or_update ( role_5_db ) self . roles [ '' ] = role_5_db grant_db = PermissionGrantDB ( resource_uid = self . resources [ '' ] . get_uid ( ) , resource_type = ResourceType . PACK , permission_types = [ PermissionType . RULE_CREATE ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) permission_grants = [ str ( grant_db . id ) ] role_6_db = RoleDB ( name = '' , permission_grants = permission_grants ) role_6_db = Role . add_or_update ( role_6_db ) self . roles [ '' ] = role_6_db grant_db = PermissionGrantDB ( resource_uid = self . resources [ '' ] . get_uid ( ) , resource_type = ResourceType . PACK , permission_types = [ PermissionType . RULE_ALL ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) permission_grants = [ str ( grant_db . id ) ] role_7_db = RoleDB ( name = '' , permission_grants = permission_grants ) role_7_db = Role . add_or_update ( role_7_db ) self . roles [ '' ] = role_7_db grant_db = PermissionGrantDB ( resource_uid = self . resources [ '' ] . get_uid ( ) , resource_type = ResourceType . RULE , permission_types = [ PermissionType . RULE_CREATE ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) permission_grants = [ str ( grant_db . id ) ] role_8_db = RoleDB ( name = '' , permission_grants = permission_grants ) role_8_db = Role . add_or_update ( role_8_db ) self . roles [ '' ] = role_8_db grant_db = PermissionGrantDB ( resource_uid = self . resources [ '' ] . get_uid ( ) , resource_type = ResourceType . RULE , permission_types = [ PermissionType . RULE_ALL ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) permission_grants = [ str ( grant_db . id ) ] role_9_db = RoleDB ( name = '' , permission_grants = permission_grants ) role_9_db = Role . add_or_update ( role_9_db ) self . roles [ '' ] = role_9_db grant_db = PermissionGrantDB ( resource_uid = None , resource_type = None , permission_types = [ PermissionType . RULE_LIST ] ) grant_db = PermissionGrant . add_or_update ( grant_db ) ", "answer": "permission_grants = [ str ( grant_db . id ) ]"}, {"prompt": " from __future__ import absolute_import , unicode_literals from . mongorest_error import * from . unauthorized_error import * from . pymongo_error import * ", "answer": "from . document_error import *"}, {"prompt": " from sellmo . core . apps import SellmoAppConfig ", "answer": "class DefaultConfig ( SellmoAppConfig ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Creature ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " import time start_time = time . time ( ) import numpy as np from sklearn . metrics import classification_report from sklearn . metrics import precision_recall_curve , roc_curve , auc from sklearn . cross_validation import KFold from sklearn import neighbors from data import chosen , chosen_meta from utils import plot_pr from utils import plot_feat_importance from utils import load_meta from utils import fetch_posts from utils import plot_feat_hist from utils import plot_bias_variance from utils import plot_k_complexity meta , id_to_idx , idx_to_id = load_meta ( chosen_meta ) import nltk all_questions = sorted ( [ q for q , v in meta . items ( ) if v [ '' ] == - ] ) all_answers = sorted ( [ q for q , v in meta . items ( ) if v [ '' ] != - ] ) feature_names = np . array ( ( '' , '' , '' , '' , '' , '' , '' , '' ) ) def prepare_sent_features ( ) : for pid , text in fetch_posts ( chosen , with_index = True ) : if not text : meta [ pid ] [ '' ] = meta [ pid ] [ '' ] = else : from platform import python_version if python_version ( ) . startswith ( '' ) : text = text . decode ( '' ) sent_lens = [ len ( nltk . word_tokenize ( sent ) ) for sent in nltk . sent_tokenize ( text ) ] meta [ pid ] [ '' ] = np . mean ( sent_lens ) meta [ pid ] [ '' ] = np . mean ( [ len ( w ) for w in nltk . word_tokenize ( text ) ] ) meta [ pid ] [ '' ] = np . sum ( [ word . isupper ( ) for word in nltk . word_tokenize ( text ) ] ) meta [ pid ] [ '' ] = text . count ( '' ) prepare_sent_features ( ) def get_features ( aid ) : return tuple ( meta [ aid ] [ fn ] for fn in feature_names ) qa_X = np . asarray ( [ get_features ( aid ) for aid in all_answers ] ) classifying_answer = \"\" if classifying_answer == \"\" : qa_Y = np . asarray ( [ meta [ aid ] [ '' ] > for aid in all_answers ] ) elif classifying_answer == \"\" : qa_Y = np . asarray ( [ meta [ aid ] [ '' ] <= for aid in all_answers ] ) else : raise Exception ( \"\" % classifying_answer ) for idx , feat in enumerate ( feature_names ) : plot_feat_hist ( [ ( qa_X [ : , idx ] , feat ) ] ) avg_scores_summary = [ ] def measure ( clf_class , parameters , name , data_size = None , plot = False ) : start_time_clf = time . time ( ) if data_size is None : X = qa_X Y = qa_Y else : X = qa_X [ : data_size ] Y = qa_Y [ : data_size ] cv = KFold ( n = len ( X ) , n_folds = , indices = True ) train_errors = [ ] test_errors = [ ] scores = [ ] roc_scores = [ ] fprs , tprs = [ ] , [ ] pr_scores = [ ] precisions , recalls , thresholds = [ ] , [ ] , [ ] for fold_idx , ( train , test ) in enumerate ( cv ) : X_train , y_train = X [ train ] , Y [ train ] X_test , y_test = X [ test ] , Y [ test ] only_one_class_in_train = len ( set ( y_train ) ) == only_one_class_in_test = len ( set ( y_test ) ) == if only_one_class_in_train or only_one_class_in_test : continue clf = clf_class ( ** parameters ) clf . fit ( X_train , y_train ) train_score = clf . score ( X_train , y_train ) test_score = clf . score ( X_test , y_test ) train_errors . append ( - train_score ) test_errors . append ( - test_score ) scores . append ( test_score ) proba = clf . predict_proba ( X_test ) label_idx = fpr , tpr , roc_thresholds = roc_curve ( y_test , proba [ : , label_idx ] ) precision , recall , pr_thresholds = precision_recall_curve ( y_test , proba [ : , label_idx ] ) roc_scores . append ( auc ( fpr , tpr ) ) fprs . append ( fpr ) tprs . append ( tpr ) pr_scores . append ( auc ( recall , precision ) ) precisions . append ( precision ) recalls . append ( recall ) thresholds . append ( pr_thresholds ) threshold_for_detecting_good_answers = print ( \"\" % fold_idx ) print ( classification_report ( y_test , proba [ : , label_idx ] > threshold_for_detecting_good_answers , target_names = [ '' , '' ] ) ) scores_to_sort = pr_scores medium = np . argsort ( scores_to_sort ) [ len ( scores_to_sort ) / ] print ( \"\" % medium ) if plot : plot_pr ( pr_scores [ medium ] , name , precisions [ medium ] , recalls [ medium ] , classifying_answer + \"\" ) if hasattr ( clf , '' ) : plot_feat_importance ( feature_names , clf , name ) summary = ( name , np . mean ( scores ) , np . std ( scores ) , np . mean ( roc_scores ) , np . std ( roc_scores ) , np . mean ( pr_scores ) , np . std ( pr_scores ) , time . time ( ) - start_time_clf ) print ( summary ) avg_scores_summary . append ( summary ) precisions = precisions [ medium ] recalls = recalls [ medium ] thresholds = np . hstack ( ( [ ] , thresholds [ medium ] ) ) idx80 = precisions >= print ( \"\" % ( precisions [ idx80 ] [ ] , recalls [ idx80 ] [ ] , thresholds [ idx80 ] [ ] ) ) return np . mean ( train_errors ) , np . mean ( test_errors ) def bias_variance_analysis ( clf_class , parameters , name ) : data_sizes = np . arange ( , , ) train_errors = [ ] test_errors = [ ] for data_size in data_sizes : train_error , test_error = measure ( clf_class , parameters , name , data_size = data_size ) train_errors . append ( train_error ) test_errors . append ( test_error ) plot_bias_variance ( data_sizes , train_errors , test_errors , name , \"\" % name ) def k_complexity_analysis ( clf_class , parameters ) : ks = np . hstack ( ( np . arange ( , ) , np . arange ( , , ) ) ) train_errors = [ ] test_errors = [ ] for k in ks : ", "answer": "parameters [ '' ] = k"}, {"prompt": " from collections import defaultdict import numpy as np from pgmpy . base import UndirectedGraph from pgmpy . factors import factor_product from pgmpy . extern . six . moves import filter , range , zip class ClusterGraph ( UndirectedGraph ) : r\"\"\"\"\"\" def __init__ ( self , ebunch = None ) : super ( ClusterGraph , self ) . __init__ ( ) if ebunch : self . add_edges_from ( ebunch ) self . factors = [ ] def add_node ( self , node , ** kwargs ) : \"\"\"\"\"\" if not isinstance ( node , ( list , set , tuple ) ) : raise TypeError ( '' ) node = tuple ( node ) super ( ClusterGraph , self ) . add_node ( node , ** kwargs ) def add_nodes_from ( self , nodes , ** kwargs ) : \"\"\"\"\"\" for node in nodes : self . add_node ( node , ** kwargs ) def add_edge ( self , u , v , ** kwargs ) : \"\"\"\"\"\" set_u = set ( u ) set_v = set ( v ) if set_u . isdisjoint ( set_v ) : raise ValueError ( '' ) super ( ClusterGraph , self ) . add_edge ( u , v ) def add_factors ( self , * factors ) : \"\"\"\"\"\" for factor in factors : factor_scope = set ( factor . scope ( ) ) nodes = [ set ( node ) for node in self . nodes ( ) ] if factor_scope not in nodes : raise ValueError ( '' '' ) self . factors . append ( factor ) def get_factors ( self , node = None ) : \"\"\"\"\"\" if node is None : return self . factors else : nodes = [ set ( n ) for n in self . nodes ( ) ] if set ( node ) not in nodes : ", "answer": "raise ValueError ( '' )"}, {"prompt": " import os import unittest import IECore import Gaffer import GafferImage import GafferImageTest class ObjectToImageTest ( GafferImageTest . ImageTestCase ) : fileName = os . path . expandvars ( \"\" ) negFileName = os . path . expandvars ( \"\" ) def test ( self ) : i = IECore . Reader . create ( self . fileName ) . read ( ) n = GafferImage . ObjectToImage ( ) n [ \"\" ] . setValue ( i ) self . assertEqual ( n [ \"\" ] . image ( ) , i ) def testImageWithANegativeDataWindow ( self ) : i = IECore . Reader . create ( self . negFileName ) . read ( ) n = GafferImage . ObjectToImage ( ) n [ \"\" ] . setValue ( i ) self . assertEqual ( n [ \"\" ] . image ( ) , i ) def testHashVariesPerTileAndChannel ( self ) : n = GafferImage . ObjectToImage ( ) n [ \"\" ] . setValue ( IECore . Reader . create ( self . fileName ) . read ( ) ) self . assertNotEqual ( n [ \"\" ] . channelDataHash ( \"\" , IECore . V2i ( ) ) , n [ \"\" ] . channelDataHash ( \"\" , IECore . V2i ( ) ) ) self . assertNotEqual ( n [ \"\" ] . channelDataHash ( \"\" , IECore . V2i ( ) ) , n [ \"\" ] . channelDataHash ( \"\" , IECore . V2i ( GafferImage . ImagePlug . tileSize ( ) ) ) ", "answer": ")"}, {"prompt": " \"\"\"\"\"\" import os import sys import unittest if not hasattr ( unittest . defaultTestLoader , '' ) : try : import unittest2 as unittest except ImportError : raise ImportError ( '' ) def additional_tests ( ) : setup_file = sys . modules [ '' ] . __file__ setup_dir = os . path . abspath ( os . path . dirname ( setup_file ) ) test_dir = os . path . join ( setup_dir , '' ) test_suite = unittest . defaultTestLoader . discover ( test_dir ) blacklist = [ ] if '' in __file__ : ", "answer": "blacklist . append ( '' )"}, {"prompt": " import logging import os import sys from sparts . vservice import VService class AtcdVService ( VService ) : def initLogging ( self ) : super ( AtcdVService , self ) . initLogging ( ) sh = logging . handlers . SysLogHandler ( address = self . _syslog_address ( ) ) sh . setLevel ( logging . DEBUG ) self . logger . addHandler ( sh ) sparts_tasks_logger = logging . getLogger ( '' ) sparts_tasks_logger . addHandler ( sh ) def _syslog_address ( self ) : address = None if sys . platform == '' : address = '' elif sys . platform == '' : address = '' ", "answer": "if address is None or not os . path . exists ( address ) :"}, {"prompt": " \"\"\"\"\"\" \"\"\"\"\"\" import pulp dealers = [ \"\" , \"\" , \"\" ] variable_costs = { \"\" : , \"\" : , \"\" : } fixed_costs = { \"\" : , \"\" : , \"\" : } quantities = pulp . LpVariable . dicts ( \"\" , dealers , lowBound = , cat = pulp . LpInteger ) is_orders = pulp . LpVariable . dicts ( \"\" , dealers , cat = pulp . LpBinary ) \"\"\"\"\"\" model = pulp . LpProblem ( \"\" , pulp . LpMinimize ) model += sum ( [ ( variable_costs [ i ] * quantities [ i ] + fixed_costs [ i ] ) * is_orders [ i ] for i in dealers ] ) , \"\" model += sum ( [ quantities [ i ] for i in dealers ] ) == , \"\" ", "answer": "model += <= quantities [ \"\" ] <= , \"\""}, {"prompt": " \"\"\"\"\"\" import sys from unittest import TestLoader , TextTestRunner sys . path . insert ( , u'' ) if __name__ == '' : test_suite = TestLoader ( ) . discover ( '' , pattern = '' ) ", "answer": "test_results = TextTestRunner ( verbosity = ) . run ( test_suite )"}, {"prompt": " from totalimpact . providers import provider from totalimpact . providers . provider import Provider , ProviderContentMalformedError import simplejson , os , re , urllib import logging logger = logging . getLogger ( '' ) class Plosalm ( Provider ) : example_id = ( \"\" , \"\" ) ", "answer": "url = \"\""}, {"prompt": " x = if x : y = print \"\" elif x : y = print \"\" elif x : ", "answer": "y = "}, {"prompt": " import os import sys from setuptools import setup , find_packages assert sys . version_info >= ( , ) , '' def read ( fname ) : return open ( os . path . join ( os . path . dirname ( __file__ ) , fname ) ) . read ( ) ", "answer": "setup ("}, {"prompt": " \"\"\"\"\"\" __author__ = '' __version__ = '' import sys import os import signal import struct import cStringIO as StringIO import select import socket import errno import traceback try : import thread import threading thread_available = True except ImportError : import dummy_thread as thread import dummy_threading as threading thread_available = False if not hasattr ( socket , '' ) : socket . SHUT_WR = __all__ = [ '' ] FCGI_LISTENSOCK_FILENO = FCGI_HEADER_LEN = FCGI_VERSION_1 = FCGI_BEGIN_REQUEST = FCGI_ABORT_REQUEST = FCGI_END_REQUEST = FCGI_PARAMS = FCGI_STDIN = FCGI_STDOUT = FCGI_STDERR = FCGI_DATA = FCGI_GET_VALUES = FCGI_GET_VALUES_RESULT = FCGI_UNKNOWN_TYPE = FCGI_MAXTYPE = FCGI_UNKNOWN_TYPE FCGI_NULL_REQUEST_ID = FCGI_KEEP_CONN = FCGI_RESPONDER = FCGI_AUTHORIZER = FCGI_FILTER = FCGI_REQUEST_COMPLETE = FCGI_CANT_MPX_CONN = FCGI_OVERLOADED = FCGI_UNKNOWN_ROLE = FCGI_MAX_CONNS = '' FCGI_MAX_REQS = '' FCGI_MPXS_CONNS = '' FCGI_Header = '' FCGI_BeginRequestBody = '' FCGI_EndRequestBody = '' FCGI_UnknownTypeBody = '' FCGI_EndRequestBody_LEN = struct . calcsize ( FCGI_EndRequestBody ) FCGI_UnknownTypeBody_LEN = struct . calcsize ( FCGI_UnknownTypeBody ) if __debug__ : import time DEBUG = DEBUGLOG = '' def _debug ( level , msg ) : if DEBUG < level : return try : f = open ( DEBUGLOG , '' ) f . write ( '' % ( time . ctime ( ) [ : - ] , msg ) ) f . close ( ) except : pass class InputStream ( object ) : \"\"\"\"\"\" def __init__ ( self , conn ) : self . _conn = conn self . _shrinkThreshold = conn . server . inputStreamShrinkThreshold self . _buf = '' self . _bufList = [ ] self . _pos = self . _avail = self . _eof = False def _shrinkBuffer ( self ) : \"\"\"\"\"\" if self . _pos >= self . _shrinkThreshold : self . _buf = self . _buf [ self . _pos : ] self . _avail -= self . _pos self . _pos = assert self . _avail >= def _waitForData ( self ) : \"\"\"\"\"\" self . _conn . process_input ( ) def read ( self , n = - ) : if self . _pos == self . _avail and self . _eof : return '' while True : if n < or ( self . _avail - self . _pos ) < n : if self . _eof : newPos = self . _avail break else : self . _waitForData ( ) continue else : newPos = self . _pos + n break if self . _bufList : self . _buf += '' . join ( self . _bufList ) self . _bufList = [ ] r = self . _buf [ self . _pos : newPos ] self . _pos = newPos self . _shrinkBuffer ( ) return r def readline ( self , length = None ) : if self . _pos == self . _avail and self . _eof : return '' while True : if self . _bufList : self . _buf += '' . join ( self . _bufList ) self . _bufList = [ ] i = self . _buf . find ( '' , self . _pos ) if i < : if self . _eof : newPos = self . _avail break else : self . _waitForData ( ) continue else : newPos = i + break if length is not None : if self . _pos + length < newPos : newPos = self . _pos + length r = self . _buf [ self . _pos : newPos ] self . _pos = newPos self . _shrinkBuffer ( ) return r def readlines ( self , sizehint = ) : total = lines = [ ] line = self . readline ( ) while line : lines . append ( line ) total += len ( line ) if < sizehint <= total : break line = self . readline ( ) return lines def __iter__ ( self ) : return self def next ( self ) : r = self . readline ( ) if not r : raise StopIteration return r def add_data ( self , data ) : if not data : self . _eof = True else : self . _bufList . append ( data ) self . _avail += len ( data ) class MultiplexedInputStream ( InputStream ) : \"\"\"\"\"\" def __init__ ( self , conn ) : super ( MultiplexedInputStream , self ) . __init__ ( conn ) lock = threading . RLock ( ) self . _lock = threading . Condition ( lock ) def _waitForData ( self ) : self . _lock . wait ( ) def read ( self , n = - ) : self . _lock . acquire ( ) try : return super ( MultiplexedInputStream , self ) . read ( n ) finally : self . _lock . release ( ) def readline ( self , length = None ) : self . _lock . acquire ( ) try : return super ( MultiplexedInputStream , self ) . readline ( length ) finally : self . _lock . release ( ) def add_data ( self , data ) : self . _lock . acquire ( ) try : super ( MultiplexedInputStream , self ) . add_data ( data ) self . _lock . notify ( ) finally : self . _lock . release ( ) class OutputStream ( object ) : \"\"\"\"\"\" def __init__ ( self , conn , req , type , buffered = False ) : self . _conn = conn self . _req = req self . _type = type self . _buffered = buffered self . _bufList = [ ] self . dataWritten = False self . closed = False def _write ( self , data ) : length = len ( data ) while length : toWrite = min ( length , self . _req . server . maxwrite - FCGI_HEADER_LEN ) rec = Record ( self . _type , self . _req . requestId ) rec . contentLength = toWrite rec . contentData = data [ : toWrite ] self . _conn . writeRecord ( rec ) data = data [ toWrite : ] length -= toWrite def write ( self , data ) : assert not self . closed if not data : return self . dataWritten = True if self . _buffered : self . _bufList . append ( data ) else : self . _write ( data ) def writelines ( self , lines ) : assert not self . closed for line in lines : self . write ( line ) def flush ( self ) : if self . _buffered : data = '' . join ( self . _bufList ) self . _bufList = [ ] self . _write ( data ) def close ( self ) : \"\"\"\"\"\" if not self . closed and self . dataWritten : self . flush ( ) rec = Record ( self . _type , self . _req . requestId ) self . _conn . writeRecord ( rec ) self . closed = True class TeeOutputStream ( object ) : \"\"\"\"\"\" def __init__ ( self , streamList ) : self . _streamList = streamList def write ( self , data ) : for f in self . _streamList : f . write ( data ) def writelines ( self , lines ) : for line in lines : self . write ( line ) def flush ( self ) : for f in self . _streamList : f . flush ( ) class StdoutWrapper ( object ) : \"\"\"\"\"\" def __init__ ( self , stdout ) : self . _file = stdout self . dataWritten = False def write ( self , data ) : if data : self . dataWritten = True self . _file . write ( data ) def writelines ( self , lines ) : for line in lines : self . write ( line ) def __getattr__ ( self , name ) : return getattr ( self . _file , name ) def decode_pair ( s , pos = ) : \"\"\"\"\"\" nameLength = ord ( s [ pos ] ) if nameLength & : nameLength = struct . unpack ( '' , s [ pos : pos + ] ) [ ] & pos += else : pos += valueLength = ord ( s [ pos ] ) if valueLength & : valueLength = struct . unpack ( '' , s [ pos : pos + ] ) [ ] & pos += else : pos += name = s [ pos : pos + nameLength ] pos += nameLength value = s [ pos : pos + valueLength ] pos += valueLength return ( pos , ( name , value ) ) def encode_pair ( name , value ) : \"\"\"\"\"\" nameLength = len ( name ) if nameLength < : s = chr ( nameLength ) else : s = struct . pack ( '' , nameLength | L ) valueLength = len ( value ) if valueLength < : s += chr ( valueLength ) else : s += struct . pack ( '' , valueLength | L ) return s + name + value class Record ( object ) : \"\"\"\"\"\" def __init__ ( self , type = FCGI_UNKNOWN_TYPE , requestId = FCGI_NULL_REQUEST_ID ) : self . version = FCGI_VERSION_1 self . type = type self . requestId = requestId self . contentLength = self . paddingLength = self . contentData = '' @ staticmethod def _recvall ( sock , length ) : \"\"\"\"\"\" dataList = [ ] recvLen = while length : try : data = sock . recv ( length ) except socket . error as e : if e [ ] == errno . EAGAIN : select . select ( [ sock ] , [ ] , [ ] ) continue else : raise if not data : break dataList . append ( data ) dataLen = len ( data ) recvLen += dataLen length -= dataLen return '' . join ( dataList ) , recvLen def read ( self , sock ) : \"\"\"\"\"\" try : header , length = self . _recvall ( sock , FCGI_HEADER_LEN ) except : raise EOFError if length < FCGI_HEADER_LEN : raise EOFError self . version , self . type , self . requestId , self . contentLength , self . paddingLength = struct . unpack ( FCGI_Header , header ) if __debug__ : _debug ( , '' '' % ( sock . fileno ( ) , self . type , self . requestId , self . contentLength ) ) if self . contentLength : try : self . contentData , length = self . _recvall ( sock , self . contentLength ) except : raise EOFError if length < self . contentLength : raise EOFError ", "answer": "if self . paddingLength :"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import re import gflags as flags from googleapis . codegen import api from googleapis . codegen import api_library_generator from googleapis . codegen import cpp_import_manager from googleapis . codegen import data_types from googleapis . codegen import language_model from googleapis . codegen import utilities from googleapis . codegen . import_definition import ImportDefinition FLAGS = flags . FLAGS flags . DEFINE_boolean ( '' , True , '' ) DT_DD_PATTERN_RE = re . compile ( r\"\"\"\"\"\" , re . VERBOSE ) MAX_DD_LEN = _DL_PATTERN = r\"\"\"\"\"\" % MAX_DD_LEN DL_PATTERN_RE = re . compile ( _DL_PATTERN , re . VERBOSE ) class CppGenerator ( api_library_generator . ApiLibraryGenerator ) : \"\"\"\"\"\" def __init__ ( self , discovery , language = '' , language_model = None , options = None ) : if not language_model : language_model = CppLanguageModel ( options ) super ( CppGenerator , self ) . __init__ ( CppApi , discovery , language , language_model , options = options ) def _InnerModelClassesSupported ( self ) : \"\"\"\"\"\" return True def _HeaderFileName ( self , path , filename ) : if not path : return '' % filename return '' % ( path , filename ) def _DLifyDescription ( self , text ) : \"\"\"\"\"\" sentinel = '' dl_partitions = DL_PATTERN_RE . split ( sentinel + text ) dl_partitions [ ] = dl_partitions [ ] [ len ( sentinel ) : ] if len ( dl_partitions ) == : return text result = [ ] for partition in dl_partitions : dl = DT_DD_PATTERN_RE . split ( partition ) if len ( dl ) == : if dl [ ] : result . append ( dl [ ] ) continue else : if result : result . append ( '' ) num_triples = len ( dl ) / if num_triples == : result . append ( partition ) continue runoff = '' result . append ( '' ) for i in range ( num_triples ) : dt_value = dl [ * i + ] . strip ( ) dd_value = dl [ * i + ] . strip ( ) result . append ( '' % dt_value ) if i < ( num_triples - ) or len ( dd_value ) < MAX_DD_LEN : if not dd_value . endswith ( '' ) : dd_value += '' result . append ( '' % dd_value ) else : period = dd_value . find ( '' ) if period < : period = len ( dd_value ) - result . append ( '' % dd_value [ : period + ] ) runoff = dd_value [ period + : ] result . append ( '' ) result . append ( runoff ) return '' . join ( result ) def AnnotateDocumentation ( self , code_obj ) : \"\"\"\"\"\" description = code_obj . values . get ( '' ) if not description : return if description . endswith ( '' ) : description = description [ : len ( description ) - ] if not description . endswith ( '' ) : description += '' if re . match ( r'' , description , re . IGNORECASE ) : code_obj . SetTemplateValue ( '' , True ) description = self . _DLifyDescription ( description ) code_obj . SetTemplateValue ( '' , description ) def AnnotateApiForLanguage ( self , the_api ) : super ( CppGenerator , self ) . AnnotateApiForLanguage ( the_api ) unsorted_list = the_api . TopLevelModelClasses ( ) have = set ( ) sorted_list = [ ] for m in unsorted_list : self . _AddDependencies ( the_api , m , have , sorted_list ) the_api . SetTemplateValue ( '' , sorted_list ) def AnnotateApi ( self , the_api ) : \"\"\"\"\"\" super ( CppGenerator , self ) . AnnotateApi ( the_api ) for schema in the_api . TopLevelModelClasses ( ) : filename = utilities . UnCamelCase ( schema . class_name ) schema . SetTemplateValue ( '' , filename ) schema . SetTemplateValue ( '' , self . _HeaderFileName ( schema . module . path , schema . values [ '' ] ) ) include_guard = '' % ( the_api . module . name . upper ( ) , filename . upper ( ) ) schema . SetTemplateValue ( '' , include_guard ) the_api . SetTemplateValue ( '' , utilities . UnCamelCase ( the_api . class_name ) ) the_api . SetTemplateValue ( '' , self . _HeaderFileName ( the_api . module . path , the_api . values [ '' ] ) ) monolithic_source_name = the_api . GetTemplateValue ( '' ) if monolithic_source_name : the_api . SetTemplateValue ( '' , monolithic_source_name ) else : plain_api_filename = utilities . UnCamelCase ( the_api . values [ '' ] ) the_api . SetTemplateValue ( '' , '' % plain_api_filename ) authscopes = the_api . values . get ( '' ) if authscopes : for scope in authscopes : self . AnnotateDocumentation ( scope ) self . AnnotateDocumentation ( the_api ) def _AddDependencies ( self , the_api , model , have , dep_list ) : if model not in have : have . add ( model ) import_manager = cpp_import_manager . CppImportManager . ForElement ( model ) for dependent in import_manager . type_dependencies : schema = the_api . SchemaByName ( dependent . values [ '' ] ) self . _AddDependencies ( the_api , schema , have , dep_list ) dep_list . append ( model ) def AnnotateMethod ( self , the_api , method , unused_rsrc ) : \"\"\"\"\"\" super ( CppGenerator , self ) . AnnotateMethod ( the_api , method , unused_rsrc ) import_manager = cpp_import_manager . CppImportManager . ForElement ( the_api ) request_type = method . values . get ( '' ) response_type = method . values . get ( '' ) if request_type : self . _HandleImports ( request_type , import_manager ) if method . values . get ( '' ) : media_upload_h = '' import_manager . AddImport ( media_upload_h ) if response_type != the_api . void_type : request_pager_h = '' self . _HandleImports ( method . values [ '' ] , import_manager ) if method . values . get ( '' ) : import_manager . AddImport ( request_pager_h ) method . SetTemplateValue ( '' , '' % utilities . CamelCase ( method . values [ '' ] ) ) self . AnnotateDocumentation ( method ) def AnnotateParameter ( self , unused_method , parameter ) : \"\"\"\"\"\" super ( CppGenerator , self ) . AnnotateParameter ( unused_method , parameter ) parameter . SetTemplateValue ( '' , self . _IsPrimitiveType ( parameter . data_type ) ) if parameter . data_type . code_type == '' : parameter . SetTemplateValue ( '' , '' ) else : parameter . SetTemplateValue ( '' , parameter . data_type . code_type ) self . _HandleImports ( parameter ) self . AnnotateDocumentation ( parameter ) def AnnotateProperty ( self , unused_api , prop , unused_schema ) : \"\"\"\"\"\" super ( CppGenerator , self ) . AnnotateProperty ( unused_api , prop , unused_schema ) prop . SetTemplateValue ( '' , self . _IsPrimitiveType ( prop . data_type ) ) base_type = prop . data_type if base_type . GetTemplateValue ( '' ) : base_type = base_type . GetTemplateValue ( '' ) try : has_parent = base_type . parent except AttributeError : has_parent = False if not base_type . GetTemplateValue ( '' ) and not has_parent : prop . SetTemplateValue ( '' , True ) self . _HandleImports ( prop ) self . AnnotateDocumentation ( prop ) def AnnotateSchema ( self , the_api , schema ) : \"\"\"\"\"\" super ( CppGenerator , self ) . AnnotateSchema ( the_api , schema ) self . AnnotateDocumentation ( schema ) def _IsPrimitiveType ( self , data_type ) : \"\"\"\"\"\" return ( data_type . json_type == '' or data_type . json_type == '' or data_type . json_type == '' or ( hasattr ( data_type , '' ) and ( data_type . json_format == '' or data_type . json_format == '' or data_type . json_format == '' or data_type . json_format == '' ) ) ) def _HandleImports ( self , element , import_manager = None ) : \"\"\"\"\"\" element = getattr ( element , '' , element ) if isinstance ( element , data_types . ComplexDataType ) : parent = element data_type = element else : parent = element . schema data_type = element . data_type data_type = getattr ( data_type , '' , data_type ) if not import_manager : if self . _InnerModelClassesSupported ( ) : while parent . parent : parent = parent . parent import_manager = cpp_import_manager . CppImportManager . ForElement ( parent ) while isinstance ( data_type , ( data_types . ArrayDataType , data_types . MapDataType ) ) : data_type = data_type . _base_type data_type = getattr ( data_type , '' , data_type ) if not data_type : return json_type = data_type . json_type json_format = data_type . values . get ( '' ) if json_type == '' : if not data_type . parent : import_manager . AddDataType ( data_type ) return datatype_and_imports = ( self . language_model . type_map . get ( ( json_type , json_format ) ) ) if datatype_and_imports : import_definition = datatype_and_imports [ ] for required_import in import_definition . imports : if required_import : import_manager . AddImport ( required_import ) for template_value in import_definition . template_values : element . SetTemplateValue ( template_value , True ) elif data_type : if not data_type . parent : import_manager . AddDataType ( data_type ) return class CppLanguageModel ( language_model . LanguageModel ) : \"\"\"\"\"\" language = '' member_policy = language_model . NamingPolicy ( language_model . LOWER_UNCAMEL_CASE , '' , '' ) getter_policy = language_model . NamingPolicy ( language_model . LOWER_UNCAMEL_CASE , '' , '' ) setter_policy = language_model . NamingPolicy ( language_model . LOWER_UNCAMEL_CASE , '' , '' ) has_policy = language_model . NamingPolicy ( language_model . LOWER_UNCAMEL_CASE , '' , '' ) unset_policy = language_model . NamingPolicy ( language_model . LOWER_UNCAMEL_CASE , '' , '' ) parameter_name_policy = language_model . NamingPolicy ( language_model . LOWER_UNCAMEL_CASE , '' , '' , conflict_policy = language_model . NamingPolicy ( language_model . LOWER_UNCAMEL_CASE , '' , '' ) ) _CPP_KEYWORDS = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] _SPECIAL_CLASS_NAMES = [ '' , '' ] RESERVED_CLASS_NAMES = _SPECIAL_CLASS_NAMES reserved_words = RESERVED_CLASS_NAMES + _CPP_KEYWORDS def __init__ ( self , options = None ) : super ( CppLanguageModel , self ) . __init__ ( class_name_delimiter = '' , module_name_delimiter = '' ) self . type_map = self . _BuildTypeMap ( options ) self . _SUPPORTED_TYPES [ '' ] = self . _Boolean self . _SUPPORTED_TYPES [ '' ] = self . _Int def _BuildTypeMap ( self , options = None ) : \"\"\"\"\"\" self . global_namespace_ = '' self . client_namespace_ = '' builtin_type_h = None integral_type_h = '' json_type_h = '' date_time_h = '' date_h = date_time_h self . date_namespace_ = self . client_namespace_ return { ( '' , None ) : ( '' , ImportDefinition ( [ builtin_type_h ] ) ) , ( '' , None ) : ( self . client_namespace_ + '' , ImportDefinition ( [ json_type_h ] ) ) , ( '' , None ) : ( '' , ImportDefinition ( [ integral_type_h ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ integral_type_h ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ integral_type_h ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ integral_type_h ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ integral_type_h ] ) ) , ( '' , None ) : ( '' , ImportDefinition ( [ builtin_type_h ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ builtin_type_h ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ builtin_type_h ] ) ) , ( '' , None ) : ( self . client_namespace_ + '' , ImportDefinition ( [ json_type_h ] ) ) , ( '' , None ) : ( '' , ImportDefinition ( [ '' ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ '' ] ) ) , ( '' , '' ) : ( self . date_namespace_ + '' , ImportDefinition ( [ date_h ] ) ) , ( '' , '' ) : ( self . client_namespace_ + '' , ImportDefinition ( [ date_time_h ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ '' ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ '' ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ integral_type_h ] ) ) , ( '' , '' ) : ( '' , ImportDefinition ( [ integral_type_h ] ) ) , } def _Boolean ( self , data_value ) : \"\"\"\"\"\" ", "answer": "return unicode ( bool ( data_value . value ) ) . lower ( )"}, {"prompt": " import unittest from pledger . parser import Parser class AccountTest ( unittest . TestCase ) : def setUp ( self ) : self . parser = Parser ( ) self . account = self . parser . parse_account ( \"\" ) def testAccountAdd ( self ) : amount = self . parser . parse_value ( \"\" ) entry = self . account + amount self . assertEqual ( self . account , entry . account ) self . assertEqual ( amount , entry . amount ) def testAccountSub ( self ) : amount = self . parser . parse_value ( \"\" ) entry = self . account - amount self . assertEqual ( self . account , entry . account ) self . assertEqual ( - amount , entry . amount ) def testRoot ( self ) : self . assertEqual ( self . parser . accounts [ \"\" ] , self . account . root ( ) ) def testShortenedName ( self ) : account = self . account [ \"\" ] size = name = account . shortened_name ( size ) self . assertLessEqual ( len ( name ) , size ) self . assertEqual ( , len ( filter ( lambda x : x == '' , name ) ) ) def testSubName ( self ) : account = self . account [ \"\" ] ", "answer": "self . assertEqual ( u'' , self . account . parent . sub_name ( account ) )"}, {"prompt": " \"\"\"\"\"\" from itertools import islice import networkx as nx from ... utils import BinaryHeap from ... utils import not_implemented_for from ... utils import arbitrary_element __author__ = '' __all__ = [ '' ] @ not_implemented_for ( '' ) @ not_implemented_for ( '' ) def stoer_wagner ( G , weight = '' , heap = BinaryHeap ) : \"\"\"\"\"\" n = len ( G ) if n < : raise nx . NetworkXError ( '' ) if not nx . is_connected ( G ) : raise nx . NetworkXError ( '' ) G = nx . Graph ( ( u , v , { '' : e . get ( weight , ) } ) for u , v , e in G . edges ( data = True ) if u != v ) for u , v , e , in G . edges ( data = True ) : if e [ '' ] < : raise nx . NetworkXError ( '' ) cut_value = float ( '' ) nodes = set ( G ) contractions = [ ] for i in range ( n - ) : u = arbitrary_element ( G ) A = set ( [ u ] ) h = heap ( ) for v , e in G [ u ] . items ( ) : h . insert ( v , - e [ '' ] ) for j in range ( n - i - ) : u = h . pop ( ) [ ] A . add ( u ) for v , e , in G [ u ] . items ( ) : if v not in A : h . insert ( v , h . get ( v , ) - e [ '' ] ) v , w = h . min ( ) w = - w if w < cut_value : cut_value = w best_phase = i contractions . append ( ( u , v ) ) for w , e in G [ v ] . items ( ) : if w != u : if w not in G [ u ] : G . add_edge ( u , w , weight = e [ '' ] ) else : G [ u ] [ w ] [ '' ] += e [ '' ] ", "answer": "G . remove_node ( v )"}, {"prompt": " from django . http import Http404 from django . test import TestCase from source . code . models import Code from source . tags . models import TechnologyTag , ConceptTag from source . tags . utils import ( get_validated_tag_list , get_tag_filtered_queryset , filter_queryset_by_tags ) class BaseTestCase ( TestCase ) : def assertQuerysetEqual ( self , qs1 , qs2 ) : pk = lambda o : o . pk return self . assertEqual ( list ( sorted ( qs1 , key = pk ) ) , list ( sorted ( qs2 , key = pk ) ) ) class TestCodeTagAdd ( BaseTestCase ) : code_model = Code tech_tag_model = TechnologyTag concept_tag_model = ConceptTag def setUp ( self ) : self . tech_tag = self . tech_tag_model . objects . create ( name = \"\" , slug = \"\" ) self . concept_tag = self . concept_tag_model . objects . create ( name = \"\" , slug = \"\" ) self . code_one = self . code_model . objects . create ( name = \"\" , slug = \"\" ) self . code_two = self . code_model . objects . create ( name = \"\" , slug = \"\" ) self . code_three = self . code_model . objects . create ( name = \"\" , slug = \"\" ) def test_code_entries ( self ) : ", "answer": "self . assertEqual ( self . code_one . title , \"\" )"}, {"prompt": " from kombu import Connection from tapiriik . settings import RABBITMQ_BROKER_URL mq = Connection ( RABBITMQ_BROKER_URL , transport_options = { '' : True } ) ", "answer": "mq . connect ( ) "}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function , unicode_literals import os import json import time from datetime import datetime , timedelta from copy import deepcopy from flexmock import flexmock from osbs . api import OSBS import osbs . conf from atomic_reactor . inner import DockerBuildWorkflow from atomic_reactor . plugin import ExitPluginsRunner from atomic_reactor . plugins . post_rpmqa import PostBuildRPMqaPlugin from atomic_reactor . plugins . exit_store_metadata_in_osv3 import StoreMetadataInOSv3Plugin from atomic_reactor . plugins . exit_koji_promote import KojiPromotePlugin from atomic_reactor . plugins . pre_cp_dockerfile import CpDockerfilePlugin from atomic_reactor . plugins . pre_pyrpkg_fetch_artefacts import DistgitFetchArtefactsPlugin from atomic_reactor . util import ImageName , LazyGit import pytest from tests . constants import LOCALHOST_REGISTRY , DOCKER0_REGISTRY , TEST_IMAGE , INPUT_IMAGE from tests . util import is_string_type DIGEST1 = \"\" DIGEST2 = \"\" class Y ( object ) : pass class X ( object ) : image_id = INPUT_IMAGE source = Y ( ) source . dockerfile_path = None source . path = None base_image = ImageName ( repo = \"\" , tag = \"\" ) def prepare ( ) : def set_annotations_on_build ( build_id , labels ) : pass def update_labels_on_build ( build_id , labels ) : pass new_environ = deepcopy ( os . environ ) new_environ [ \"\" ] = '''''' flexmock ( OSBS , set_annotations_on_build = set_annotations_on_build ) flexmock ( OSBS , update_labels_on_build = update_labels_on_build ) ( flexmock ( osbs . conf ) . should_call ( \"\" ) . with_args ( namespace = \"\" , conf_file = None , verify_ssl = True , openshift_url = \"\" , openshift_uri = \"\" , use_auth = True ) ) flexmock ( os ) os . should_receive ( \"\" ) . and_return ( new_environ ) workflow = DockerBuildWorkflow ( { \"\" : \"\" , \"\" : \"\" } , \"\" ) workflow . push_conf . add_pulp_registry ( \"\" , LOCALHOST_REGISTRY ) workflow . tag_conf . add_primary_image ( TEST_IMAGE ) workflow . tag_conf . add_unique_image ( \"\" ) r = workflow . push_conf . add_docker_registry ( DOCKER0_REGISTRY ) r . digests [ TEST_IMAGE ] = DIGEST1 r . digests [ \"\" ] = DIGEST2 setattr ( workflow , '' , X ) setattr ( workflow , '' , { '' : '' } ) workflow . build_logs = [ \"\" , \"\" , ] workflow . source . lg = LazyGit ( None , commit = \"\" ) ", "answer": "flexmock ( workflow . source . lg )"}, {"prompt": " import sublime , sublime_plugin import re , time from collections import namedtuple BracketPosition = namedtuple ( \"\" , \"\" ) BracketResult = namedtuple ( \"\" , \"\" ) bracketGuardRegions = \"\" class EventListener ( sublime_plugin . EventListener ) : def __init__ ( self ) : self . latest_keypresses = { } def on_modified ( self , view ) : if view . settings ( ) . get ( \"\" , False ) : self . highlightBracketError ( view ) def on_modified_async ( self , view ) : self . clearRegions ( view ) if self . doAutoCheck ( view ) : self . debounce ( view , \"\" , self . highlightBracketError ) def on_post_save_async ( self , view ) : if self . checkOnSave ( ) and not self . doAutoCheck ( view ) : self . highlightBracketError ( view ) def clearRegions ( self , view ) : view . erase_regions ( bracketGuardRegions ) def settings ( self ) : return sublime . load_settings ( \"\" ) def checkOnSave ( self ) : return self . settings ( ) . get ( \"\" ) def doAutoCheck ( self , view ) : threshold = self . settings ( ) . get ( \"\" ) return threshold == - or threshold >= view . size ( ) def highlightBracketError ( self , view ) : bracketResult = self . getFirstBracketError ( view ) if not bracketResult . success : openerRegion = sublime . Region ( bracketResult . start , bracketResult . start + ) closerRegion = sublime . Region ( bracketResult . end , bracketResult . end + ) view . add_regions ( bracketGuardRegions , [ openerRegion , closerRegion ] , \"\" ) def debounce ( self , view , event_type , func ) : key = ( event_type , view . file_name ( ) ) this_keypress = time . time ( ) self . latest_keypresses [ key ] = this_keypress debounceTime = self . settings ( ) . get ( \"\" , ) def callback ( ) : latest_keypress = self . latest_keypresses . get ( key , None ) if this_keypress == latest_keypress : func ( view ) sublime . set_timeout_async ( callback , debounceTime ) def getFirstBracketError ( self , view ) : opener = list ( \"\" ) closer = list ( \"\" ) matchingStack = [ ] successResult = BracketResult ( True , - , - ) codeStr = view . substr ( sublime . Region ( , view . size ( ) ) ) for index , char in enumerate ( codeStr ) : if char not in opener and not char in closer : continue scopeName = view . scope_name ( index ) hasScope = lambda s : s in scopeName markdownBracketScopeBegin = \"\" markdownBracketScopeEnd = \"\" isMarkdownStringBeginOrEnd = lambda s : hasScope ( markdownBracketScopeBegin ) or hasScope ( markdownBracketScopeEnd ) if hasScope ( \"\" ) and not hasScope ( \"\" ) and not isMarkdownStringBeginOrEnd ( markdownBracketScopeBegin ) or hasScope ( \"\" ) : continue if char in opener : matchingStack . append ( BracketPosition ( index , char ) ) elif char in closer : matchingOpener = opener [ closer . index ( char ) ] if len ( matchingStack ) == : return BracketResult ( False , - , index ) poppedOpener = matchingStack . pop ( ) if matchingOpener != poppedOpener . opener : return BracketResult ( False , poppedOpener . position , index ) ", "answer": "if len ( matchingStack ) == :"}, {"prompt": " import distutils . command . bdist_wininst as orig ", "answer": "class bdist_wininst ( orig . bdist_wininst ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import json , os dir = os . path . abspath ( os . path . dirname ( __file__ ) ) def populate_cogatlas ( apps , schema_editor ) : CognitiveAtlasTask = apps . get_model ( \"\" , \"\" ) CognitiveAtlasContrast = apps . get_model ( \"\" , \"\" ) json_content = open ( os . path . join ( dir , \"\" ) ) . read ( ) json_content = json_content . decode ( \"\" ) . replace ( '' , '' ) ", "answer": "data = json . loads ( json_content )"}, {"prompt": " \"\"\"\"\"\" __metaclass__ = type from zope . interface import implements from twisted . python import log from twisted . python . reflect import fullyQualifiedName from twisted . python . failure import Failure from twisted . python . compat import set from twisted . internet . interfaces import IConsumer , IPushProducer from twisted . internet . error import ConnectionDone from twisted . internet . defer import Deferred , succeed , fail , maybeDeferred from twisted . internet . protocol import Protocol from twisted . protocols . basic import LineReceiver from twisted . web . iweb import UNKNOWN_LENGTH , IResponse from twisted . web . http_headers import Headers from twisted . web . http import NO_CONTENT , NOT_MODIFIED from twisted . web . http import _DataLoss , PotentialDataLoss from twisted . web . http import _IdentityTransferDecoder , _ChunkedTransferDecoder STATUS = '' HEADER = '' BODY = '' DONE = '' class BadHeaders ( Exception ) : \"\"\"\"\"\" class ExcessWrite ( Exception ) : \"\"\"\"\"\" class ParseError ( Exception ) : \"\"\"\"\"\" def __init__ ( self , reason , data ) : Exception . __init__ ( self , reason , data ) self . data = data class BadResponseVersion ( ParseError ) : \"\"\"\"\"\" class _WrapperException ( Exception ) : \"\"\"\"\"\" def __init__ ( self , reasons ) : Exception . __init__ ( self , reasons ) self . reasons = reasons class RequestGenerationFailed ( _WrapperException ) : \"\"\"\"\"\" class RequestTransmissionFailed ( _WrapperException ) : \"\"\"\"\"\" class ConnectionAborted ( Exception ) : \"\"\"\"\"\" class WrongBodyLength ( Exception ) : \"\"\"\"\"\" class ResponseDone ( Exception ) : \"\"\"\"\"\" class ResponseFailed ( _WrapperException ) : \"\"\"\"\"\" def __init__ ( self , reasons , response = None ) : ", "answer": "_WrapperException . __init__ ( self , reasons )"}, {"prompt": " \"\"\"\"\"\" import uuid from googleads import dfp HIERARCHY_LEVEL_ONE_KEY_ID = '' HIERARCHY_LEVEL_TWO_KEY_ID = '' def main ( client , hierarchy_level_one_key_id , hierarchy_level_two_key_id ) : content_metadata_key_hierarchy_service = client . GetService ( '' , version = '' ) hierarchy_level_1 = { '' : hierarchy_level_one_key_id , ", "answer": "'' : ''"}, {"prompt": " import errno import os import re import subprocess import sys def get_keywords ( ) : git_refnames = \"\" git_full = \"\" keywords = { \"\" : git_refnames , \"\" : git_full } return keywords class VersioneerConfig : pass def get_config ( ) : cfg = VersioneerConfig ( ) cfg . VCS = \"\" cfg . style = \"\" cfg . tag_prefix = \"\" cfg . parentdir_prefix = \"\" cfg . versionfile_source = \"\" cfg . verbose = False return cfg class NotThisMethod ( Exception ) : pass LONG_VERSION_PY = { } HANDLERS = { } def register_vcs_handler ( vcs , method ) : def decorate ( f ) : if vcs not in HANDLERS : HANDLERS [ vcs ] = { } HANDLERS [ vcs ] [ method ] = f return f return decorate def run_command ( commands , args , cwd = None , verbose = False , hide_stderr = False ) : assert isinstance ( commands , list ) p = None for c in commands : try : dispcmd = str ( [ c ] + args ) p = subprocess . Popen ( [ c ] + args , cwd = cwd , stdout = subprocess . PIPE , stderr = ( subprocess . PIPE if hide_stderr else None ) ) break except EnvironmentError : e = sys . exc_info ( ) [ ] if e . errno == errno . ENOENT : continue if verbose : print ( \"\" % dispcmd ) print ( e ) return None else : if verbose : print ( \"\" % ( commands , ) ) return None stdout = p . communicate ( ) [ ] . strip ( ) if sys . version_info [ ] >= : stdout = stdout . decode ( ) if p . returncode != : if verbose : print ( \"\" % dispcmd ) return None return stdout def versions_from_parentdir ( parentdir_prefix , root , verbose ) : dirname = os . path . basename ( root ) if not dirname . startswith ( parentdir_prefix ) : if verbose : print ( \"\" \"\" % ( root , dirname , parentdir_prefix ) ) raise NotThisMethod ( \"\" ) return { \"\" : dirname [ len ( parentdir_prefix ) : ] , \"\" : None , \"\" : False , \"\" : None } @ register_vcs_handler ( \"\" , \"\" ) def git_get_keywords ( versionfile_abs ) : keywords = { } try : f = open ( versionfile_abs , \"\" ) for line in f . readlines ( ) : if line . strip ( ) . startswith ( \"\" ) : mo = re . search ( r'' , line ) if mo : keywords [ \"\" ] = mo . group ( ) if line . strip ( ) . startswith ( \"\" ) : mo = re . search ( r'' , line ) if mo : keywords [ \"\" ] = mo . group ( ) f . close ( ) except EnvironmentError : pass return keywords @ register_vcs_handler ( \"\" , \"\" ) def git_versions_from_keywords ( keywords , tag_prefix , verbose ) : if not keywords : raise NotThisMethod ( \"\" ) refnames = keywords [ \"\" ] . strip ( ) if refnames . startswith ( \"\" ) : if verbose : print ( \"\" ) raise NotThisMethod ( \"\" ) refs = set ( [ r . strip ( ) for r in refnames . strip ( \"\" ) . split ( \"\" ) ] ) TAG = \"\" tags = set ( [ r [ len ( TAG ) : ] for r in refs if r . startswith ( TAG ) ] ) if not tags : tags = set ( [ r for r in refs if re . search ( r'' , r ) ] ) if verbose : print ( \"\" % \"\" . join ( refs - tags ) ) if verbose : print ( \"\" % \"\" . join ( sorted ( tags ) ) ) for ref in sorted ( tags ) : if ref . startswith ( tag_prefix ) : r = ref [ len ( tag_prefix ) : ] if verbose : print ( \"\" % r ) return { \"\" : r , \"\" : keywords [ \"\" ] . strip ( ) , \"\" : False , \"\" : None } if verbose : print ( \"\" ) return { \"\" : \"\" , \"\" : keywords [ \"\" ] . strip ( ) , \"\" : False , \"\" : \"\" } @ register_vcs_handler ( \"\" , \"\" ) def git_pieces_from_vcs ( tag_prefix , root , verbose , run_command = run_command ) : if not os . path . exists ( os . path . join ( root , \"\" ) ) : if verbose : print ( \"\" % root ) raise NotThisMethod ( \"\" ) GITS = [ \"\" ] if sys . platform == \"\" : GITS = [ \"\" , \"\" ] describe_out = run_command ( GITS , [ \"\" , \"\" , \"\" , \"\" , \"\" ] , cwd = root ) if describe_out is None : raise NotThisMethod ( \"\" ) describe_out = describe_out . strip ( ) full_out = run_command ( GITS , [ \"\" , \"\" ] , cwd = root ) if full_out is None : raise NotThisMethod ( \"\" ) full_out = full_out . strip ( ) pieces = { } pieces [ \"\" ] = full_out pieces [ \"\" ] = full_out [ : ] pieces [ \"\" ] = None git_describe = describe_out dirty = git_describe . endswith ( \"\" ) pieces [ \"\" ] = dirty if dirty : git_describe = git_describe [ : git_describe . rindex ( \"\" ) ] if \"\" in git_describe : mo = re . search ( r'' , git_describe ) if not mo : pieces [ \"\" ] = ( \"\" % describe_out ) return pieces full_tag = mo . group ( ) if not full_tag . startswith ( tag_prefix ) : if verbose : fmt = \"\" print ( fmt % ( full_tag , tag_prefix ) ) pieces [ \"\" ] = ( \"\" % ( full_tag , tag_prefix ) ) return pieces pieces [ \"\" ] = full_tag [ len ( tag_prefix ) : ] pieces [ \"\" ] = int ( mo . group ( ) ) pieces [ \"\" ] = mo . group ( ) else : pieces [ \"\" ] = None count_out = run_command ( GITS , [ \"\" , \"\" , \"\" ] , cwd = root ) pieces [ \"\" ] = int ( count_out ) return pieces def plus_or_dot ( pieces ) : if \"\" in pieces . get ( \"\" , \"\" ) : ", "answer": "return \"\""}, {"prompt": " from django_roa . remoteauth . models import User from django . contrib . auth . backends import ModelBackend class RemoteUserModelBackend ( ModelBackend ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from aristotle_mdr . apps import AristotleExtensionBaseConfig class DownloadTestMDRConfig ( AristotleExtensionBaseConfig ) : ", "answer": "name = ''"}, {"prompt": " import time from collections import deque from weakref import WeakValueDictionary from redis import ConnectionPool from redis . client import StrictRedis from lampost . context . resource import m_requires from lampost . datastore . classes import get_dbo_class , get_mixed_type from lampost . datastore . exceptions import ObjectExistsError , NonUniqueError m_requires ( __name__ , '' , '' , '' ) class RedisStore ( ) : def __init__ ( self , db_host , db_port , db_num , db_pw ) : self . pool = ConnectionPool ( max_connections = , db = db_num , host = db_host , port = db_port , password = db_pw , decode_responses = True ) self . redis = StrictRedis ( connection_pool = self . pool ) self . redis . ping ( ) self . _object_map = WeakValueDictionary ( ) def create_object ( self , dbo_class , dbo_dict , update_timestamp = True ) : dbo_class = get_dbo_class ( getattr ( dbo_class , '' , dbo_class ) ) if not dbo_class : return try : dbo_id = dbo_dict [ '' ] except KeyError : dbo_id , dbo_dict = dbo_dict , { } if dbo_id is None or dbo_id == '' : warn ( \"\" ) return dbo_id = str ( dbo_id ) . lower ( ) if self . object_exists ( dbo_class . dbo_key_type , dbo_id ) : raise ObjectExistsError ( dbo_id ) dbo = dbo_class ( ) dbo . dbo_id = dbo_id dbo . hydrate ( dbo_dict ) dbo . db_created ( ) if dbo . dbo_set_key : self . redis . sadd ( dbo . dbo_set_key , dbo . dbo_id ) self . save_object ( dbo , update_timestamp ) return dbo def save_object ( self , dbo , update_timestamp = False , autosave = False ) : if update_timestamp : dbo . dbo_ts = int ( time . time ( ) ) if dbo . dbo_indexes : self . _update_indexes ( dbo ) self . _clear_old_refs ( dbo ) save_root , new_refs = dbo . to_db_value ( ) self . redis . set ( dbo . dbo_key , json_encode ( save_root ) ) if new_refs : self . _set_new_refs ( dbo , new_refs ) debug ( \"\" , dbo . dbo_key , \"\" if autosave else \"\" ) self . _object_map [ dbo . dbo_key ] = dbo return dbo def save_raw ( self , key , raw ) : self . redis . set ( key , json_encode ( raw ) ) def load_raw ( self , key , default = None ) : json = self . redis . get ( key ) if json : return json_decode ( json ) return default def load_cached ( self , dbo_key ) : return self . _object_map . get ( dbo_key ) def load_object ( self , dbo_key , key_type = None , silent = False ) : if key_type : try : key_type = key_type . dbo_key_type except AttributeError : pass try : dbo_key , dbo_id = '' . join ( [ key_type , dbo_key ] ) , dbo_key except TypeError : if not silent : exception ( \"\" , stack_info = True ) return else : key_type , _ , dbo_id = dbo_key . partition ( '' ) cached_dbo = self . _object_map . get ( dbo_key ) if cached_dbo : return cached_dbo json_str = self . redis . get ( dbo_key ) if not json_str : if not silent : warn ( \"\" , dbo_key ) return return self . load_from_json ( json_str , key_type , dbo_id ) def load_from_json ( self , json_str , key_type , dbo_id ) : dbo_dict = json_decode ( json_str ) dbo = get_mixed_type ( key_type , dbo_dict . get ( '' ) ) ( ) dbo . dbo_id = dbo_id self . _object_map [ dbo . dbo_key ] = dbo dbo . hydrate ( dbo_dict ) return dbo def object_exists ( self , obj_type , obj_id ) : return self . redis . exists ( '' . format ( obj_type , obj_id ) ) def load_object_set ( self , dbo_class , set_key = None ) : key_type = dbo_class . dbo_key_type if not set_key : set_key = dbo_class . dbo_set_key results = set ( ) keys = deque ( ) pipeline = self . redis . pipeline ( ) for key in self . fetch_set_keys ( set_key ) : dbo_key = '' . join ( [ key_type , key ] ) try : results . add ( self . _object_map [ dbo_key ] ) except KeyError : keys . append ( key ) pipeline . get ( dbo_key ) for dbo_id , json_str in zip ( keys , pipeline . execute ( ) ) : if json_str : obj = self . load_from_json ( json_str , key_type , dbo_id ) if obj : results . add ( obj ) continue warn ( \"\" , set_key ) self . delete_set_key ( set_key , dbo_id ) return results def delete_object_set ( self , dbo_class , set_key = None ) : if not set_key : set_key = dbo_class . dbo_set_key for dbo in self . load_object_set ( dbo_class , set_key ) : self . delete_object ( dbo ) self . delete_key ( set_key ) def update_object ( self , dbo , dbo_dict ) : dbo . hydrate ( dbo_dict ) return self . save_object ( dbo , True ) def delete_object ( self , dbo ) : key = dbo . dbo_key dbo . db_deleted ( ) self . delete_key ( key ) self . _clear_old_refs ( dbo ) if dbo . dbo_set_key : self . redis . srem ( dbo . dbo_set_key , dbo . dbo_id ) for children_type in dbo . dbo_children_types : self . delete_object_set ( get_dbo_class ( children_type ) , \"\" . format ( dbo . dbo_key_type , children_type , dbo . dbo_id ) ) for ix_name in dbo . dbo_indexes : ix_value = getattr ( dbo , ix_name , None ) if ix_value is not None and ix_value != '' : self . delete_index ( '' . format ( dbo . dbo_key_type , ix_name ) , ix_value ) debug ( \"\" , key ) self . evict_object ( dbo ) def reload_object ( self , dbo_key ) : dbo = self . _object_map . get ( dbo_key ) if dbo : json_str = self . redis . get ( dbo_key ) if not json_str : warn ( \"\" , dbo_key ) return None return self . update_object ( dbo , json_decode ( json_str ) ) return self . load_object ( dbo_key ) def evict_object ( self , dbo ) : self . _object_map . pop ( dbo . dbo_key , None ) def fetch_set_keys ( self , set_key ) : return self . redis . smembers ( set_key ) def add_set_key ( self , set_key , * values ) : self . redis . sadd ( set_key , * values ) def delete_set_key ( self , set_key , value ) : self . redis . srem ( set_key , value ) def set_key_exists ( self , set_key , value ) : return self . redis . sismember ( set_key , value ) def db_counter ( self , counter_id , inc = ) : return self . redis . incr ( \"\" . format ( counter_id ) , inc ) def delete_key ( self , key ) : self . redis . delete ( key ) def set_index ( self , index_name , key , value ) : return self . redis . hset ( index_name , key , value ) def get_index ( self , index_name , key ) : return self . redis . hget ( index_name , key ) def get_full_index ( self , index_name ) : ", "answer": "return self . redis . hgetall ( index_name )"}, {"prompt": " from biicode . server . conf import BII_MONGO_URI , BII_MAX_MONGO_POOL_SIZE from biicode . common . migrations . migration_manager import MigrationManager from biicode . server . store . migration_store import MigrationStore from biicode . server . store . mongo_server_store import MongoServerStore import time from pymongo . mongo_client import MongoClient from biicode . server . migrations . migrations import SERVER_MIGRATIONS from biicode . common . output_stream import OutputStream def launch ( ) : mongo_connection = MongoClient ( BII_MONGO_URI , max_pool_size = BII_MAX_MONGO_POOL_SIZE ) migration_store = MigrationStore ( mongo_connection ) server_store = MongoServerStore ( mongo_connection ) biiout = OutputStream ( ) manager = MigrationManager ( migration_store , SERVER_MIGRATIONS , biiout ) ", "answer": "n1 = time . time ( )"}, {"prompt": " \"\"\"\"\"\" from scapy . packet import * from scapy . fields import * from scapy . layers . inet import TCP skinny_messages = { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , ", "answer": " : \"\" ,"}, {"prompt": " from __future__ import unicode_literals from datetime import datetime from functools import reduce import operator from django . core . exceptions import ImproperlyConfigured from django . db import models from django . utils import six from django . utils . encoding import python_2_unicode_compatible , force_text ", "answer": "from django . utils . translation import ugettext_lazy as _"}, {"prompt": " import random from flask import Blueprint , Response , render_template from . _common import GITHUB_SLUG , get_tid , samples blueprint = Blueprint ( '' , __name__ , url_prefix = \"\" ) @ blueprint . route ( \"\" ) def get_index ( ) : template_images = list ( samples ( blank = True ) ) sample_images = list ( samples ( ) ) return Response ( render_template ( \"\" , template_images = template_images , default_template = random . choice ( template_images ) [ '' ] , sample_images = sample_images , github_slug = GITHUB_SLUG , ga_tid = get_tid ( ) , ) ) @ blueprint . route ( \"\" ) def get_javascript ( ) : return Response ( render_template ( \"\" , ", "answer": "ga_tid = get_tid ( ) ,"}, {"prompt": " from framework . dependency_management . dependency_resolver import ServiceLocator \"\"\"\"\"\" ", "answer": "DESCRIPTION = \"\""}, {"prompt": " RECORD_TYPES = [ '' , '' , '' , '' , '' , '' , '' , '' ] from boto . resultset import ResultSet class ResourceRecordSets ( ResultSet ) : ChangeResourceRecordSetsBody = \"\"\"\"\"\" ChangeXML = \"\"\"\"\"\" def __init__ ( self , connection = None , hosted_zone_id = None , comment = None ) : self . connection = connection self . hosted_zone_id = hosted_zone_id self . comment = comment self . changes = [ ] self . next_record_name = None self . next_record_type = None ResultSet . __init__ ( self , [ ( '' , Record ) ] ) def __repr__ ( self ) : return '' % self . hosted_zone_id def add_change ( self , action , name , type , ttl = , alias_hosted_zone_id = None , alias_dns_name = None ) : \"\"\"\"\"\" change = Record ( name , type , ttl , alias_hosted_zone_id = alias_hosted_zone_id , alias_dns_name = alias_dns_name ) self . changes . append ( [ action , change ] ) return change def to_xml ( self ) : \"\"\"\"\"\" changesXML = \"\" for change in self . changes : changeParams = { \"\" : change [ ] , \"\" : change [ ] . to_xml ( ) } changesXML += self . ChangeXML % changeParams params = { \"\" : self . comment , \"\" : changesXML } return self . ChangeResourceRecordSetsBody % params def commit ( self ) : \"\"\"\"\"\" if not self . connection : import boto self . connection = boto . connect_route53 ( ) return self . connection . change_rrsets ( self . hosted_zone_id , self . to_xml ( ) ) def endElement ( self , name , value , connection ) : \"\"\"\"\"\" if name == '' : self . next_record_name = value elif name == '' : self . next_record_type = value ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import re import urllib import urlparse try : from xml . etree import cElementTree as ElementTree except ImportError : try : import cElementTree as ElementTree except ImportError : try : from xml . etree import ElementTree except ImportError : from elementtree import ElementTree import atom . service import gdata import atom import atom . http_interface import atom . token_store import gdata . auth AUTH_SERVER_HOST = '' SCOPE_URL_PARAM_NAME = '' CLIENT_LOGIN_SCOPES = { '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' , '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' , '' ] , '' : [ '' ] , '' : [ '' , '' , '' , '' ] , '' : [ '' , '' ] , '' : [ '' ] , '' : [ '' , '' , '' ] } def lookup_scopes ( service_name ) : \"\"\"\"\"\" if service_name in CLIENT_LOGIN_SCOPES : return CLIENT_LOGIN_SCOPES [ service_name ] return None http_request_handler = atom . service class Error ( Exception ) : pass class CaptchaRequired ( Error ) : pass class BadAuthentication ( Error ) : pass class NotAuthenticated ( Error ) : pass class NonAuthSubToken ( Error ) : pass class RequestError ( Error ) : pass class UnexpectedReturnType ( Error ) : pass class BadAuthenticationServiceURL ( Error ) : pass class TokenUpgradeFailed ( Error ) : pass class AuthorizationRequired ( Error ) : pass class TokenHadNoScope ( Error ) : pass class GDataService ( atom . service . AtomService ) : \"\"\"\"\"\" handler = None auth_token = None tokens = None def __init__ ( self , email = None , password = None , account_type = '' , service = None , auth_service_url = None , source = None , server = None , additional_headers = None , handler = None , tokens = None , http_client = None , token_store = None ) : \"\"\"\"\"\" atom . service . AtomService . __init__ ( self , http_client = http_client , token_store = token_store ) self . email = email self . password = password self . account_type = account_type self . service = service self . auth_service_url = auth_service_url self . server = server self . additional_headers = additional_headers or { } self . __SetSource ( source ) self . __captcha_token = None self . __captcha_url = None self . __gsessionid = None if http_request_handler . __name__ == '' : import gdata . alt . appengine self . http_client = gdata . alt . appengine . AppEngineHttpClient ( ) def _SetAuthSubToken ( self , auth_token , scopes = None ) : \"\"\"\"\"\" self . SetAuthSubToken ( auth_token , scopes = scopes ) def __SetAuthSubToken ( self , auth_token , scopes = None ) : \"\"\"\"\"\" self . _SetAuthSubToken ( auth_token , scopes = scopes ) def _GetAuthToken ( self ) : \"\"\"\"\"\" current_scopes = lookup_scopes ( self . service ) if current_scopes : token = self . token_store . find_token ( current_scopes [ ] ) if hasattr ( token , '' ) : return token . auth_header return None def _GetCaptchaToken ( self ) : \"\"\"\"\"\" return self . __captcha_token def __GetCaptchaToken ( self ) : return self . _GetCaptchaToken ( ) captcha_token = property ( __GetCaptchaToken , doc = \"\"\"\"\"\" ) def _GetCaptchaURL ( self ) : \"\"\"\"\"\" return self . __captcha_url def __GetCaptchaURL ( self ) : return self . _GetCaptchaURL ( ) captcha_url = property ( __GetCaptchaURL , doc = \"\"\"\"\"\" ) def GetAuthSubToken ( self ) : \"\"\"\"\"\" if isinstance ( self . current_token , gdata . auth . AuthSubToken ) : return self . current_token . get_token_string ( ) current_scopes = lookup_scopes ( self . service ) if current_scopes : token = self . token_store . find_token ( current_scopes [ ] ) if isinstance ( token , gdata . auth . AuthSubToken ) : return token . get_token_string ( ) else : token = self . token_store . find_token ( atom . token_store . SCOPE_ALL ) if isinstance ( token , gdata . auth . ClientLoginToken ) : return token . get_token_string ( ) return None def SetAuthSubToken ( self , token , scopes = None ) : \"\"\"\"\"\" if not isinstance ( token , gdata . auth . AuthSubToken ) : token_string = token token = gdata . auth . AuthSubToken ( ) token . set_token_string ( token_string ) if not token . scopes : if scopes is None : scopes = lookup_scopes ( self . service ) if scopes is None : scopes = [ atom . token_store . SCOPE_ALL ] token . scopes = scopes if self . auto_set_current_token : self . current_token = token if self . auto_store_tokens : self . token_store . add_token ( token ) def GetClientLoginToken ( self ) : \"\"\"\"\"\" if isinstance ( self . current_token , gdata . auth . ClientLoginToken ) : return self . current_token . get_token_string ( ) current_scopes = lookup_scopes ( self . service ) if current_scopes : token = self . token_store . find_token ( current_scopes [ ] ) if isinstance ( token , gdata . auth . ClientLoginToken ) : return token . get_token_string ( ) else : token = self . token_store . find_token ( atom . token_store . SCOPE_ALL ) if isinstance ( token , gdata . auth . ClientLoginToken ) : return token . get_token_string ( ) return None def SetClientLoginToken ( self , token , scopes = None ) : \"\"\"\"\"\" if not isinstance ( token , gdata . auth . ClientLoginToken ) : token_string = token token = gdata . auth . ClientLoginToken ( ) token . set_token_string ( token_string ) if not token . scopes : if scopes is None : scopes = lookup_scopes ( self . service ) if scopes is None : scopes = [ atom . token_store . SCOPE_ALL ] token . scopes = scopes if self . auto_set_current_token : self . current_token = token if self . auto_store_tokens : self . token_store . add_token ( token ) def __GetSource ( self ) : return self . __source def __SetSource ( self , new_source ) : self . __source = new_source self . additional_headers [ '' ] = atom . http_interface . USER_AGENT % ( self . __source , ) source = property ( __GetSource , __SetSource , doc = \"\"\"\"\"\" ) def ProgrammaticLogin ( self , captcha_token = None , captcha_response = None ) : \"\"\"\"\"\" request_body = gdata . auth . generate_client_login_request_body ( self . email , self . password , self . service , self . source , self . account_type , captcha_token , captcha_response ) if not self . auth_service_url : auth_request_url = AUTH_SERVER_HOST + '' else : auth_request_url = self . auth_service_url auth_response = self . http_client . request ( '' , auth_request_url , data = request_body , headers = { '' : '' } ) response_body = auth_response . read ( ) if auth_response . status == : self . SetClientLoginToken ( gdata . auth . get_client_login_token ( response_body ) ) self . __captcha_token = None self . __captcha_url = None elif auth_response . status == : captcha_parameters = gdata . auth . get_captcha_challenge ( response_body , captcha_base_url = '' % AUTH_SERVER_HOST ) if captcha_parameters : self . __captcha_token = captcha_parameters [ '' ] self . __captcha_url = captcha_parameters [ '' ] raise CaptchaRequired , '' elif response_body . splitlines ( ) [ ] == '' : self . __captcha_token = None self . __captcha_url = None raise BadAuthentication , '' else : self . __captcha_token = None self . __captcha_url = None raise Error , '' elif auth_response . status == : self . __captcha_token = None self . __captcha_url = None raise BadAuthenticationServiceURL , '' def ClientLogin ( self , username , password , account_type = None , service = None , auth_service_url = None , source = None , captcha_token = None , captcha_response = None ) : \"\"\"\"\"\" self . email = username self . password = password if account_type : self . account_type = account_type if service : self . service = service if source : self . source = source if auth_service_url : self . auth_service_url = auth_service_url self . ProgrammaticLogin ( captcha_token , captcha_response ) def GenerateAuthSubURL ( self , next , scope , secure = False , session = True , domain = '' ) : \"\"\"\"\"\" if not isinstance ( scope , ( list , tuple ) ) : scope = ( scope , ) return gdata . auth . generate_auth_sub_url ( next , scope , secure = secure , session = session , request_url = '' % AUTH_SERVER_HOST , domain = domain ) def UpgradeToSessionToken ( self , token = None ) : \"\"\"\"\"\" if token is None : scopes = lookup_scopes ( self . service ) if scopes : token = self . token_store . find_token ( scopes [ ] ) else : token = self . token_store . find_token ( atom . token_store . SCOPE_ALL ) if not isinstance ( token , gdata . auth . AuthSubToken ) : raise NonAuthSubToken self . SetAuthSubToken ( self . upgrade_to_session_token ( token ) ) def upgrade_to_session_token ( self , token ) : \"\"\"\"\"\" response = token . perform_request ( self . http_client , '' , AUTH_SERVER_HOST + '' , headers = { '' : '' } ) response_body = response . read ( ) if response . status == : token . set_token_string ( gdata . auth . token_from_http_body ( response_body ) ) return token else : raise TokenUpgradeFailed ( { '' : response . status , '' : '' , '' : response_body } ) def RevokeAuthSubToken ( self ) : \"\"\"\"\"\" scopes = lookup_scopes ( self . service ) token = self . token_store . find_token ( scopes ) if not isinstance ( token , gdata . auth . AuthSubToken ) : raise NonAuthSubToken response = token . perform_request ( self . http_client , '' , AUTH_SERVER_HOST + '' , headers = { '' : '' } ) if response . status == : self . token_store . remove_token ( token ) def Get ( self , uri , extra_headers = None , redirects_remaining = , encoding = '' , converter = None ) : \"\"\"\"\"\" if extra_headers is None : extra_headers = { } if self . __gsessionid is not None : if uri . find ( '' ) < : if uri . find ( '' ) > - : uri += '' % ( self . __gsessionid , ) else : uri += '' % ( self . __gsessionid , ) server_response = self . request ( '' , uri , headers = extra_headers ) result_body = server_response . read ( ) if server_response . status == : if converter : return converter ( result_body ) feed = gdata . GDataFeedFromString ( result_body ) if not feed : entry = gdata . GDataEntryFromString ( result_body ) if not entry : return result_body return entry return feed elif server_response . status == : if redirects_remaining > : location = server_response . getheader ( '' ) if location is not None : m = re . compile ( '' ) . search ( location ) if m is not None : self . __gsessionid = m . group ( ) return GDataService . Get ( self , location , extra_headers , redirects_remaining - , encoding = encoding , converter = converter ) else : raise RequestError , { '' : server_response . status , '' : '' , '' : result_body } else : raise RequestError , { '' : server_response . status , '' : '' , '' : result_body } else : raise RequestError , { '' : server_response . status , '' : server_response . reason , '' : result_body } def GetMedia ( self , uri , extra_headers = None ) : \"\"\"\"\"\" response_handle = self . request ( '' , uri , headers = extra_headers ) return gdata . MediaSource ( response_handle , response_handle . getheader ( '' ) , response_handle . getheader ( '' ) ) def GetEntry ( self , uri , extra_headers = None ) : \"\"\"\"\"\" result = GDataService . Get ( self , uri , extra_headers , converter = atom . EntryFromString ) if isinstance ( result , atom . Entry ) : return result else : raise UnexpectedReturnType , '' def GetFeed ( self , uri , extra_headers = None , converter = gdata . GDataFeedFromString ) : \"\"\"\"\"\" result = GDataService . Get ( self , uri , extra_headers , converter = converter ) if isinstance ( result , atom . Feed ) : return result else : raise UnexpectedReturnType , '' def GetNext ( self , feed ) : \"\"\"\"\"\" next_link = feed . GetNextLink ( ) def ConvertToFeedClass ( xml_string ) : return atom . CreateClassFromXMLString ( feed . __class__ , xml_string ) if next_link and next_link . href : return GDataService . Get ( self , next_link . href , converter = ConvertToFeedClass ) else : return None def Post ( self , data , uri , extra_headers = None , url_params = None , escape_params = True , redirects_remaining = , media_source = None , converter = None ) : \"\"\"\"\"\" return GDataService . PostOrPut ( self , '' , data , uri , extra_headers = extra_headers , url_params = url_params , escape_params = escape_params , redirects_remaining = redirects_remaining , media_source = media_source , converter = converter ) def PostOrPut ( self , verb , data , uri , extra_headers = None , url_params = None , escape_params = True , redirects_remaining = , media_source = None , converter = None ) : \"\"\"\"\"\" if extra_headers is None : extra_headers = { } if self . __gsessionid is not None : if uri . find ( '' ) < : if uri . find ( '' ) > - : uri += '' % ( self . __gsessionid , ) else : uri += '' % ( self . __gsessionid , ) if data and media_source : if ElementTree . iselement ( data ) : data_str = ElementTree . tostring ( data ) else : data_str = str ( data ) multipart = [ ] multipart . append ( '' + '' ) multipart . append ( '' + media_source . content_type + '' ) multipart . append ( '' ) extra_headers [ '' ] = '' extra_headers [ '' ] = str ( len ( multipart [ ] ) + len ( multipart [ ] ) + len ( multipart [ ] ) + len ( data_str ) + media_source . content_length ) extra_headers [ '' ] = '' server_response = self . request ( verb , uri , data = [ multipart [ ] , data_str , multipart [ ] , media_source . file_handle , multipart [ ] ] , headers = extra_headers ) result_body = server_response . read ( ) elif media_source or isinstance ( data , gdata . MediaSource ) : if isinstance ( data , gdata . MediaSource ) : media_source = data extra_headers [ '' ] = str ( media_source . content_length ) extra_headers [ '' ] = media_source . content_type server_response = self . request ( verb , uri , data = media_source . file_handle , headers = extra_headers ) result_body = server_response . read ( ) else : http_data = data content_type = '' extra_headers [ '' ] = content_type server_response = self . request ( verb , uri , data = http_data , headers = extra_headers ) result_body = server_response . read ( ) if server_response . status == or server_response . status == : if converter : return converter ( result_body ) feed = gdata . GDataFeedFromString ( result_body ) if not feed : entry = gdata . GDataEntryFromString ( result_body ) if not entry : return result_body return entry return feed elif server_response . status == : if redirects_remaining > : location = server_response . getheader ( '' ) if location is not None : m = re . compile ( '' ) . search ( location ) if m is not None : self . __gsessionid = m . group ( ) return GDataService . PostOrPut ( self , verb , data , location , extra_headers , url_params , escape_params , redirects_remaining - , media_source , converter = converter ) else : raise RequestError , { '' : server_response . status , '' : '' , '' : result_body } else : raise RequestError , { '' : server_response . status , '' : '' , '' : result_body } else : raise RequestError , { '' : server_response . status , '' : server_response . reason , '' : result_body } def Put ( self , data , uri , extra_headers = None , url_params = None , escape_params = True , redirects_remaining = , media_source = None , converter = None ) : \"\"\"\"\"\" return GDataService . PostOrPut ( self , '' , data , uri , extra_headers = extra_headers , url_params = url_params , escape_params = escape_params , redirects_remaining = redirects_remaining , media_source = media_source , converter = converter ) def Delete ( self , uri , extra_headers = None , url_params = None , escape_params = True , redirects_remaining = ) : \"\"\"\"\"\" if extra_headers is None : extra_headers = { } if self . __gsessionid is not None : if uri . find ( '' ) < : if uri . find ( '' ) > - : uri += '' % ( self . __gsessionid , ) else : uri += '' % ( self . __gsessionid , ) server_response = self . request ( '' , uri , headers = extra_headers ) result_body = server_response . read ( ) if server_response . status == : return True elif server_response . status == : if redirects_remaining > : location = server_response . getheader ( '' ) if location is not None : m = re . compile ( '' ) . search ( location ) if m is not None : self . __gsessionid = m . group ( ) return GDataService . Delete ( self , location , extra_headers , url_params , escape_params , redirects_remaining - ) else : raise RequestError , { '' : server_response . status , '' : '' , '' : result_body } else : raise RequestError , { '' : server_response . status , '' : '' , '' : result_body } else : raise RequestError , { '' : server_response . status , '' : server_response . reason , '' : result_body } def ExtractToken ( url , scopes_included_in_next = True ) : \"\"\"\"\"\" parsed = urlparse . urlparse ( url ) token = gdata . auth . AuthSubTokenFromUrl ( parsed [ ] ) scopes = '' ", "answer": "if scopes_included_in_next :"}, {"prompt": " \"\"\"\"\"\" from . library import * from . array import * ", "answer": "from . features import *"}, {"prompt": " import logging import pymysql import sqlparse from . packages import connection , special _logger = logging . getLogger ( __name__ ) class SQLExecute ( object ) : databases_query = '''''' tables_query = '''''' version_query = '''''' version_comment_query = '''''' show_candidates_query = '''''' users_query = '''''' functions_query = '''''' table_columns_query = '''''' ", "answer": "def __init__ ( self , database , user , password , host , port , socket , charset ,"}, {"prompt": " import collections import hashlib import hmac import logging from flask import abort , request class Webhook ( object ) : \"\"\"\"\"\" def __init__ ( self , app , endpoint = '' , secret = None ) : app . add_url_rule ( endpoint , view_func = self . _postreceive , methods = [ '' ] ) self . _hooks = collections . defaultdict ( list ) self . _logger = logging . getLogger ( '' ) self . _secret = secret def hook ( self , event_type = '' ) : \"\"\"\"\"\" def decorator ( func ) : self . _hooks [ event_type ] . append ( func ) return func return decorator def _get_digest ( self ) : \"\"\"\"\"\" return hmac . new ( self . _secret , request . data , hashlib . sha1 ) . hexdigest ( ) if self . _secret else None def _postreceive ( self ) : \"\"\"\"\"\" digest = self . _get_digest ( ) if digest is not None : sig_parts = _get_header ( '' ) . split ( '' , ) if ( len ( sig_parts ) < or sig_parts [ ] != '' or not hmac . compare_digest ( sig_parts [ ] , unicode ( digest ) ) ) : abort ( , '' ) event_type = _get_header ( '' ) data = request . get_json ( ) if data is None : abort ( , '' ) self . _logger . info ( '' , _format_event ( event_type , data ) , _get_header ( '' ) ) for hook in self . _hooks . get ( event_type , [ ] ) : hook ( data ) return '' , def _get_header ( key ) : \"\"\"\"\"\" try : return request . headers [ key ] ", "answer": "except KeyError :"}, {"prompt": " from django . contrib . auth . models import Group from django . db import models from djangotoolbox . fields import ListField from django . contrib . auth import get_user_model User = get_user_model ( ) class UserPermissionList ( models . Model ) : user = models . ForeignKey ( User ) permission_list = ListField ( models . CharField ( max_length = ) ) ", "answer": "permission_fk_list = ListField ( models . CharField ( max_length = ) )"}, {"prompt": " import logging import json from dateutil . parser import parse as dateutil_parse from uuid import uuid4 from nucleus import create_session , notification_signals , PersonaNotFoundError , UnauthorizedError , VesicleStateError , CHANGE_TYPES from nucleus . models import Persona , Star , Planet , Starmap , Group , Oneup from nucleus . vesicle import Vesicle from synapse . electrical import ElectricalSynapse from web_ui import app ALLOWED_MESSAGE_TYPES = [ \"\" , \"\" , ] OBJECT_TYPES = ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) class Synapse ( ) : \"\"\"\"\"\" _instance = None def __new__ ( cls , * args , ** kwargs ) : \"\"\"\"\"\" if not cls . _instance : cls . _instance = super ( ElectricalSynapse , cls ) . __new__ ( cls , * args , ** kwargs ) return cls . _instance def __init__ ( self ) : self . logger = logging . getLogger ( '' ) self . logger . setLevel ( app . config [ '' ] ) self . starmap = Starmap . query . get ( app . config [ '' ] ) self . electrical = ElectricalSynapse ( parent = self ) self . _connect_signals ( ) def _connect_signals ( self ) : \"\"\"\"\"\" signal = notification_signals . signal signal ( '' ) . connect ( self . on_local_model_change ) signal ( '' ) . connect ( self . on_new_contact ) signal ( '' ) . connect ( self . on_request_objects ) def _distribute_vesicle ( self , vesicle , recipients = None ) : \"\"\"\"\"\" self . logger . debug ( \"\" . format ( vesicle , len ( recipients ) if recipients is not None else \"\" , \"\" if app . config [ \"\" ] else \"\" ) ) if not hasattr ( vesicle , \"\" ) : raise ValueError ( \"\" ) if vesicle . encrypted ( ) : keycrypt = json . loads ( vesicle . keycrypt ) keycrypt = json . loads ( vesicle . keycrypt ) remove_recipients = set ( keycrypt . keys ( ) ) - set ( [ r . id for r in recipients ] ) for recipient_id in remove_recipients : if recipient_id != vesicle . author_id : del keycrypt [ recipient_id ] vesicle . keycrypt = json . dumps ( keycrypt ) vesicle . add_recipients ( recipients ) self . logger . debug ( \"\" . format ( vesicle ) ) else : vesicle . encrypt ( recipients = recipients ) try : vesicle . sign ( ) except VesicleStateError : self . logger . info ( \"\" . format ( vesicle ) ) if app . config [ \"\" ] : self . electrical . myelin_store ( vesicle ) return vesicle def _find_source ( self , obj ) : \"\"\"\"\"\" connected_to = lambda p : len ( p . contacts . filter ( Persona . crypt_private != \"\" ) ) > sources = list ( ) if isinstance ( obj , Star ) : if connected_to ( obj . author ) : sources . append ( obj . author ) for starmap in obj . starmaps : if connected_to ( starmap . author ) : sources . append ( starmap . author ) elif isinstance ( obj , Planet ) : for star in obj . stars : if connected_to ( star . author ) : sources . append ( star . author ) for starmap in star . starmaps : if connected_to ( starmap . author ) : sources . append ( starmap . author ) elif isinstance ( obj , Starmap ) : if connected_to ( obj . author ) : sources . append ( obj . author ) return sources def _log_errors ( self , msg , errors , level = \"\" ) : \"\"\"\"\"\" if level not in [ \"\" , \"\" , \"\" , \"\" ] : raise ValueError ( \"\" . format ( level ) ) call = getattr ( self . logger , level ) call ( \"\" . format ( msg = msg , list = \"\" . join ( str ( e ) for e in errors ) ) ) def handle_object ( self , vesicle , reader_persona , session ) : \"\"\"\"\"\" errors = list ( ) try : action = vesicle . data [ \"\" ] object_type = vesicle . data [ \"\" ] obj = vesicle . data [ \"\" ] author = vesicle . author except KeyError , e : errors . append ( \"\" . format ( e ) ) if object_type not in OBJECT_TYPES : errors . append ( \"\" . format ( object_type ) ) if action not in CHANGE_TYPES : errors . append ( \"\" . format ( action ) ) if errors : self . logger . error ( \"\" . format ( \"\" . join ( errors ) ) ) else : handler = getattr ( self , \"\" . format ( action ) ) new_obj = handler ( author , reader_persona , object_type , obj , session ) if new_obj is not None : vesicle . handled = True new_obj . vesicles . append ( vesicle ) session . add ( new_obj ) session . add ( vesicle ) session . commit ( ) def handle_object_request ( self , vesicle , reader_persona , session ) : \"\"\"\"\"\" errors = [ ] object_id = None object_type = None try : object_id = vesicle . data [ \"\" ] object_type = vesicle . data [ \"\" ] recipient = vesicle . author except KeyError , e : errors . append ( \"\" . format ( vesicle , e ) ) if object_type not in OBJECT_TYPES : errors . append ( \"\" . format ( object_type ) ) if errors : self . _log_errors ( \"\" , errors ) else : obj_class = globals ( ) [ object_type ] obj = obj_class . query . get ( object_id ) if obj is None : self . logger . error ( \"\" . format ( type = object_type , id = object_id [ : ] ) ) elif hasattr ( obj , \"\" ) and recipient not in obj . author . contacts : self . logger . info ( \"\" . format ( obj , recipient ) ) elif isinstance ( obj , Persona ) and recipient not in obj . contacts : self . logger . info ( \"\" . format ( obj , recipient ) ) else : for v in obj . vesicles : self . _distribute_vesicle ( v , recipients = [ recipient , ] ) self . logger . info ( \"\" . format ( obj , len ( obj . vesicles ) , recipient ) ) vesicle . handled = True session . add ( vesicle ) session . commit ( ) def handle_vesicle ( self , data ) : \"\"\"\"\"\" try : vesicle = Vesicle . read ( data ) except PersonaNotFoundError , e : self . logger . info ( \"\" ) resp , errors = self . electrical . persona_info ( e [ ] ) if errors : self . logger . warning ( \"\" . format ( \"\" . join ( errors ) ) ) return else : vesicle = Vesicle . read ( data ) if vesicle is None : self . logger . error ( \"\" ) else : old_vesicle = Vesicle . query . get ( vesicle . id ) if old_vesicle is not None : vesicle = old_vesicle session = create_session ( ) import keyczar if not vesicle . decrypted ( ) : try : reader_persona = vesicle . decrypt ( ) except UnauthorizedError : self . logger . info ( \"\" . format ( vesicle ) ) except keyczar . errors . InvalidSignatureError : self . logger . warning ( \"\" . format ( vesicle , vesicle . id , vesicle . _get_hashcode ( ) ) ) return vesicle if old_vesicle is None : session . add ( vesicle ) session . commit ( ) if not vesicle . decrypted ( ) : self . logger . debug ( \"\" . format ( vesicle ) ) else : self . logger . info ( \"\" . format ( vesicle , json . dumps ( vesicle . data , indent = ) ) ) try : if vesicle is not None and not vesicle . handled and vesicle . message_type in ALLOWED_MESSAGE_TYPES : handler = getattr ( self , \"\" . format ( vesicle . message_type ) ) try : handler ( vesicle , reader_persona , session ) except UnauthorizedError , e : self . logger . error ( \"\" . format ( vesicle , e ) ) except : session . rollback ( ) raise finally : session . flush ( ) return vesicle def object_insert ( self , author , recipient , object_type , obj , session ) : obj_class = globals ( ) [ object_type ] missing_keys = obj_class . validate_changeset ( obj ) if len ( missing_keys ) > : raise KeyError ( \"\" . format ( \"\" . join ( missing_keys ) , obj_class . __name__ ) ) if hasattr ( obj , \"\" ) and author . id != obj [ \"\" ] : raise UnauthorizedError ( \"\" . format ( author , obj [ \"\" ] [ : ] ) ) o = obj_class . query . get ( obj [ \"\" ] ) if o is None or ( hasattr ( o , \"\" ) and o . get_state ( ) == - ) or ( isinstance ( o , Persona ) and o . _stub is True ) : o = obj_class . create_from_changeset ( obj , stub = o , update_sender = author , update_recipient = recipient ) session . add ( o ) if isinstance ( o , Persona ) : o . stub = False else : o . set_state ( ) self . logger . info ( \"\" . format ( o ) ) return o def object_update ( self , author , recipient , object_type , obj , session ) : obj_class = globals ( ) [ object_type ] missing_keys = obj_class . validate_changeset ( obj , update = True ) if len ( missing_keys ) > : raise KeyError ( \"\" . format ( obj_class . __name__ ) ) obj_modified = dateutil_parse ( obj [ \"\" ] ) o = obj_class . query . get ( obj [ \"\" ] ) if o is None : self . logger . warning ( \"\" . format ( object_type , obj [ \"\" ] [ : ] ) ) o = obj_class ( id = obj [ \"\" ] ) o . set_state ( - ) session . add ( o ) self . request_object ( object_type = object_type , object_id = obj [ \"\" ] , author = recipient , recipient = author , session = session ) else : if o . authorize ( \"\" , author . id ) : if o . modified <= obj_modified or ( hasattr ( o , \"\" ) and o . _stub is True ) : o . update_from_changeset ( obj , update_sender = author , update_recipient = recipient ) if isinstance ( o , Persona ) : o . stub = False session . add ( o ) self . logger . info ( \"\" . format ( o ) ) else : self . logger . info ( \"\" . format ( obj ) ) else : self . logger . warning ( \"\" . format ( author , o ) ) return o def object_delete ( self , author , recipient , object_type , obj , session ) : obj_class = globals ( ) [ object_type ] for k in [ \"\" , \"\" ] : if k not in obj . keys ( ) : raise KeyError ( \"\" . format ( k , obj_class . __name__ ) ) o = obj_class . query . get ( obj [ \"\" ] ) if o is None : self . logger . info ( \"\" . format ( object_type , obj [ \"\" ] ) ) else : if o . authorize ( \"\" , author . id ) : if hasattr ( o , \"\" ) : o . set_state ( - ) o . text = None session . add ( o ) self . logger . info ( \"\" . format ( o ) ) else : name = str ( o ) session . delete ( o ) o = None self . logger . info ( \"\" . format ( name ) ) else : ", "answer": "self . logger . warning ( \"\" )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Intangible ( )"}, {"prompt": " '''''' import functools import itertools from . compat import contextlib , mock from . stubs import VCRHTTPConnection , VCRHTTPSConnection from six . moves import http_client as httplib _HTTPConnection = httplib . HTTPConnection _HTTPSConnection = httplib . HTTPSConnection try : import requests . packages . urllib3 . connectionpool as cpool except ImportError : pass else : _VerifiedHTTPSConnection = cpool . VerifiedHTTPSConnection _cpoolHTTPConnection = cpool . HTTPConnection _cpoolHTTPSConnection = cpool . HTTPSConnection try : import urllib3 except ImportError : pass else : _VerifiedHTTPSConnection = urllib3 . connectionpool . VerifiedHTTPSConnection try : import httplib2 except ImportError : pass else : _HTTPConnectionWithTimeout = httplib2 . HTTPConnectionWithTimeout _HTTPSConnectionWithTimeout = httplib2 . HTTPSConnectionWithTimeout _SCHEME_TO_CONNECTION = httplib2 . SCHEME_TO_CONNECTION try : import boto . https_connection except ImportError : pass else : _CertValidatingHTTPSConnection = boto . https_connection . CertValidatingHTTPSConnection try : import tornado . simple_httpclient except ImportError : pass else : _SimpleAsyncHTTPClient_fetch_impl = tornado . simple_httpclient . SimpleAsyncHTTPClient . fetch_impl try : import tornado . curl_httpclient except ImportError : ", "answer": "pass"}, {"prompt": " \"\"\"\"\"\" from cafe . drivers . unittest . decorators import tags from cloudcafe . blockstorage . volumes_api . v1 . models import statuses from cloudcafe . common . tools . datagen import rand_name from cloudcafe . compute . common . exceptions import ItemNotFound from cloudroast . compute . fixtures import ServerFromVolumeV1Fixture from cloudroast . compute . instance_actions . api . test_delete_server import DeleteServersTest class AutoDeleteVolumeServersTest ( object ) : @ tags ( type = '' , net = '' ) def test_volume_deleted_after_server_deletion_by_default ( self ) : \"\"\"\"\"\" with self . assertRaises ( ItemNotFound ) : self . blockstorage_behavior . client . delete_volume ( self . volume . id_ ) class PersistentDeleteVolumeServersTest ( object ) : @ tags ( type = '' , net = '' ) def test_volume_not_deleted_after_server_deletion ( self ) : \"\"\"\"\"\" self . blockstorage_behavior . wait_for_volume_status ( self . volume . id_ , statuses . Volume . AVAILABLE , self . volume_delete_timeout ) server_response = self . server_behaviors . create_active_server ( block_device_mapping = self . block_data , flavor_ref = self . flavors_config . primary_flavor , name = rand_name ( \"\" ) ) server_sec = server_response . entity self . servers_client . delete_server ( server_sec . id ) self . server_behaviors . wait_for_server_to_be_deleted ( server_sec . id ) result = self . blockstorage_behavior . client . delete_volume ( self . volume . id_ ) self . assertTrue ( result ) class ServerFromVolumeV1AutoDeleteServerTests ( ServerFromVolumeV1Fixture , DeleteServersTest , AutoDeleteVolumeServersTest ) : @ classmethod def setUpClass ( cls ) : \"\"\"\"\"\" super ( ServerFromVolumeV1AutoDeleteServerTests , cls ) . setUpClass ( ) cls . create_server ( ) cls . resp = cls . servers_client . delete_server ( cls . server . id ) cls . server_behaviors . wait_for_server_to_be_deleted ( cls . server . id ) class ServerFromVolumeV1PersistentDeleteServerTests ( ServerFromVolumeV1Fixture , PersistentDeleteVolumeServersTest ) : @ classmethod ", "answer": "def setUpClass ( cls ) :"}, {"prompt": " \"\"\"\"\"\" import time , re from cookielib import ( _warn_unhandled_exception , FileCookieJar , LoadError , Cookie , MISSING_FILENAME_TEXT , join_header_words , split_header_words , iso2time , time2isoz ) def lwp_cookie_str ( cookie ) : \"\"\"\"\"\" h = [ ( cookie . name , cookie . value ) , ( \"\" , cookie . path ) , ( \"\" , cookie . domain ) ] if cookie . port is not None : h . append ( ( \"\" , cookie . port ) ) if cookie . path_specified : h . append ( ( \"\" , None ) ) if cookie . port_specified : h . append ( ( \"\" , None ) ) if cookie . domain_initial_dot : h . append ( ( \"\" , None ) ) if cookie . secure : h . append ( ( \"\" , None ) ) if cookie . expires : h . append ( ( \"\" , time2isoz ( float ( cookie . expires ) ) ) ) if cookie . discard : h . append ( ( \"\" , None ) ) if cookie . comment : h . append ( ( \"\" , cookie . comment ) ) if cookie . comment_url : h . append ( ( \"\" , cookie . comment_url ) ) keys = cookie . _rest . keys ( ) keys . sort ( ) for k in keys : h . append ( ( k , str ( cookie . _rest [ k ] ) ) ) h . append ( ( \"\" , str ( cookie . version ) ) ) return join_header_words ( [ h ] ) class LWPCookieJar ( FileCookieJar ) : \"\"\"\"\"\" def as_lwp_str ( self , ignore_discard = True , ignore_expires = True ) : \"\"\"\"\"\" now = time . time ( ) r = [ ] for cookie in self : if not ignore_discard and cookie . discard : continue if not ignore_expires and cookie . is_expired ( now ) : continue r . append ( \"\" % lwp_cookie_str ( cookie ) ) return \"\" . join ( r + [ \"\" ] ) def save ( self , filename = None , ignore_discard = False , ignore_expires = False ) : if filename is None : if self . filename is not None : filename = self . filename else : raise ValueError ( MISSING_FILENAME_TEXT ) f = open ( filename , \"\" ) try : f . write ( \"\" ) f . write ( self . as_lwp_str ( ignore_discard , ignore_expires ) ) finally : f . close ( ) def _really_load ( self , f , filename , ignore_discard , ignore_expires ) : magic = f . readline ( ) if not re . search ( self . magic_re , magic ) : msg = ( \"\" \"\" % filename ) raise LoadError ( msg ) now = time . time ( ) header = \"\" boolean_attrs = ( \"\" , \"\" , \"\" , \"\" , \"\" ) value_attrs = ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) try : while : line = f . readline ( ) if line == \"\" : break if not line . startswith ( header ) : continue line = line [ len ( header ) : ] . strip ( ) for data in split_header_words ( [ line ] ) : name , value = data [ ] standard = { } rest = { } for k in boolean_attrs : standard [ k ] = False for k , v in data [ : ] : if k is not None : lc = k . lower ( ) else : lc = None if ( lc in value_attrs ) or ( lc in boolean_attrs ) : k = lc if k in boolean_attrs : if v is None : v = True standard [ k ] = v elif k in value_attrs : standard [ k ] = v else : rest [ k ] = v h = standard . get expires = h ( \"\" ) discard = h ( \"\" ) if expires is not None : expires = iso2time ( expires ) if expires is None : discard = True domain = h ( \"\" ) domain_specified = domain . startswith ( \"\" ) c = Cookie ( h ( \"\" ) , name , value , h ( \"\" ) , h ( \"\" ) , domain , domain_specified , h ( \"\" ) , h ( \"\" ) , h ( \"\" ) , h ( \"\" ) , expires , discard , h ( \"\" ) , h ( \"\" ) , rest ) if not ignore_discard and c . discard : continue if not ignore_expires and c . is_expired ( now ) : continue self . set_cookie ( c ) except IOError : raise ", "answer": "except Exception :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations def create_ocr_setting_for_existing_document_types ( apps , schema_editor ) : DocumentType = apps . get_model ( '' , '' ) DocumentTypeSettings = apps . get_model ( '' , '' ) for document_type in DocumentType . objects . all ( ) : try : DocumentTypeSettings . objects . create ( document_type = document_type ) except DocumentTypeSettings . DoesNotExists : pass class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ( '' , '' ) , ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . BooleanField ( default = True , verbose_name = '' '' ) ) , ( ", "answer": "'' , models . OneToOneField ("}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = - "}, {"prompt": " \"\"\"\"\"\" import re from os import path from json import dumps as dict_to_str , loads as str_to_dict from cafe . engine . models . base import AutoMarshallingModel class Secret ( AutoMarshallingModel ) : def __init__ ( self , name = None , expiration = None , algorithm = None , bit_length = None , mode = None , payload_content_type = None , payload = None , content_types = None , payload_content_encoding = None ) : super ( Secret , self ) . __init__ ( ) self . name = name self . payload_content_type = payload_content_type self . expiration = expiration self . algorithm = algorithm self . bit_length = bit_length self . mode = mode self . payload = payload self . content_types = content_types self . payload_content_encoding = payload_content_encoding def _obj_to_json ( self ) : return dict_to_str ( self . _obj_to_dict ( ) ) def _obj_to_dict ( self ) : \"\"\"\"\"\" converted = { } if self . name is not None : converted [ '' ] = self . name if self . payload_content_type is not None : converted [ '' ] = self . payload_content_type if self . expiration is not None : converted [ '' ] = self . expiration if self . algorithm is not None : converted [ '' ] = self . algorithm if self . bit_length is not None : converted [ '' ] = self . bit_length if self . mode is not None : converted [ '' ] = self . mode if self . payload is not None : converted [ '' ] = self . payload if self . content_types is not None : converted [ '' ] = self . content_types if self . payload_content_encoding is not None : converted [ '' ] = self . payload_content_encoding return converted @ classmethod def _json_to_obj ( cls , serialized_str ) : json_dict = str_to_dict ( serialized_str ) return cls . _dict_to_obj ( json_dict ) @ classmethod def _dict_to_obj ( cls , json_dict ) : \"\"\"\"\"\" return Secret ( ** json_dict ) class SecretMetadata ( Secret ) : def __init__ ( self , name , expiration , algorithm , bit_length , mode , payload_content_type = None , payload = None , status = None , updated = None , created = None , secret_ref = None , content_types = None , content_encodings = None ) : super ( SecretMetadata , self ) . __init__ ( name , expiration , algorithm , bit_length , mode , payload_content_type , payload , content_types , content_encodings ) self . status = status self . updated = updated ", "answer": "self . created = created"}, {"prompt": " class blank ( object ) : def __init__ ( self ) : object . __init__ ( self ) deployment_settings = blank ( ) deployment_settings . web2py = blank ( ) deployment_settings . web2py . port = deployment_settings . database = blank ( ) deployment_settings . database . db_type = \"\" deployment_settings . database . host = \"\" deployment_settings . database . port = None deployment_settings . database . database = \"\" ", "answer": "deployment_settings . database . username = \"\""}, {"prompt": " \"\"\"\"\"\" import subprocess import socket import os from optparse import OptionParser def run_command ( command , fail = True ) : \"\"\"\"\"\" rcode = subprocess . call ( command . split ( '' ) ) if rcode != and fail : raise Exception ( '' . format ( command , rcode ) ) parser = OptionParser ( description = '' ) parser . add_option ( '' , '' , dest = '' , help = \"\" ) parser . add_option ( '' , '' , dest = '' , help = \"\" ) ( options , args ) = parser . parse_args ( ) def disks_are_member_of_raid ( disks ) : disk_in_raid = False if os . path . exists ( '' ) : output = subprocess . check_output ( [ '' , '' ] ) for line in str ( output ) . splitlines ( ) : if '' in line : for disk in disks : disk_in_raid = disk in line if disk_in_raid : break if disk_in_raid : break return disk_in_raid if not options . additional_hostnames : hostname = socket . gethostname ( ) disks = options . disks . split ( '' ) ceph_disks = '' for disk in disks : ceph_disks += '' . format ( hostname , disk ) single_node = True ; else : single_node = False ; hostname = socket . gethostname ( ) disks = options . disks . split ( '' ) ceph_disks = '' for disk in disks : ceph_disks += '' . format ( hostname , disk ) hosts = options . additional_hostnames . split ( '' ) for host in hosts : hostname = hostname + '' + host for disk in disks : ceph_disks += '' . format ( host , disk ) if disks and disks_are_member_of_raid ( disks ) : raise RuntimeError ( \"\" . format ( disks ) ) if os . path . exists ( '' ) : raise RuntimeError ( '' ) ceph_disks = ceph_disks [ : ] os . chdir ( '' ) run_command ( '' ) run_command ( '' ) run_command ( '' . format ( hostname ) ) run_command ( '' . format ( hostname ) ) run_command ( '' . format ( hostname ) ) run_command ( '' . format ( socket . gethostname ( ) ) , fail = False ) run_command ( '' . format ( socket . gethostname ( ) ) , fail = False ) from time import sleep sleep ( ) run_command ( '' . format ( socket . gethostname ( ) ) ) ceph_disks = ceph_disks . split ( '' ) for disk in ceph_disks : run_command ( '' . format ( disk ) ) run_command ( '' . format ( disk ) ) run_command ( '' . format ( hostname ) ) run_command ( '' ) run_command ( '' ) if not options . additional_hostnames : if len ( disks ) > : run_command ( '' ) run_command ( '' ) fh = open ( '' , '' ) fc = fh . readlines ( ) fh . close ( ) nfc = list ( ) for line in fc : if line . find ( '' ) > - : nfc . append ( line . replace ( '' , '' ) ) else : nfc . append ( line ) fh = open ( '' , '' ) fh . write ( '' . join ( nfc ) ) fh . close ( ) run_command ( '' ) run_command ( '' ) run_command ( '' ) fh = open ( '' , '' ) fh . write ( '' . format ( socket . gethostname ( ) ) ) fh . close ( ) run_command ( '' ) run_command ( '' ) ", "answer": "run_command ( '' )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " \"\"\"\"\"\" from docopt import docopt from functools import partial import os import re import shutil import sys from sphinx import quickstart RE_COMMAND_NAME = re . compile ( r'' ) RE_RST_STATEMENT = re . compile ( r'' ) RE_HTML_THEME = re . compile ( r\"\" ) RE_PROJECT_NAME = re . compile ( r'' , re . I ) SETUP_TEMPLATE = u\"\"\"\"\"\" SETUP_CFG_TEMPLATE = \"\"\"\"\"\" BSD_LICENSE_HEADER = \"\"\"\"\"\" NAMESPACE_INIT = \"\" DOC_CMDLINE = \"\"\"\"\"\" DOC_PYTHON_REFERENCE = \"\"\"\"\"\" CMDREGEN_RULE = u\"\"\"\"\"\" def die ( msg , * args , ** kwargs ) : output = msg . format ( * args , ** kwargs ) if isinstance ( output , unicode ) : output = output . encode ( '' ) sys . stderr . write ( output ) sys . stderr . write ( '' ) sys . exit ( ) try : ask = raw_input except : ask = input def write_init ( config , output_path , namespace_package = False ) : with open ( output_path , '' ) as init_file : init_file . write ( BSD_LICENSE_HEADER ) if namespace_package : init_file . write ( NAMESPACE_INIT ) init_file . write ( '' ) def write_setup ( config , output_path ) : values = { '' : str ( config [ '' ] ) } for key , value in config . items ( ) : if key != '' and isinstance ( value , unicode ) : value = value . encode ( '' ) elif key == '' and isinstance ( value , str ) : value = value . decode ( '' ) values [ key ] = value values [ '' + key ] = '' if not value else '' with open ( output_path , '' ) as setup_file : setup_file . write ( SETUP_TEMPLATE . format ( ** values ) . encode ( '' ) ) def write_setup_cfg ( config , output_path ) : with open ( output_path , '' ) as setup_file : setup_file . write ( SETUP_CFG_TEMPLATE ) def write_empty ( config , output_path ) : with open ( output_path , '' ) : pass def write_cmdline ( config , output_path ) : with open ( output_path , '' ) as cmdline_file : name = str ( config [ '' ] ) . capitalize ( ) ", "answer": "match = RE_PROJECT_NAME . match ( config [ '' ] )"}, {"prompt": " import argparse import sys \"\"\"\"\"\" class MyArgumentParser ( argparse . ArgumentParser ) : def _print_message ( self , message , fd = None ) : if message : fd = sys . stdout ", "answer": "fd . write ( message ) "}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import unittest import phlgit_checkout import phlgit_commit import phlgit_fetch import phlgit_merge import phlgit_push import phlgit_rebase import phlgit_revparse import phlgitu_fixture import phlgitx_refcache import abdt_branch import abdt_classicnaming import abdt_differresultcache import abdt_git import abdt_naming import abdt_rbranchnaming class Test ( unittest . TestCase ) : def __init__ ( self , data ) : super ( Test , self ) . __init__ ( data ) self . repos = None self . repo_central = None self . repo_dev = None self . repo_arcyd = None def setUp ( self ) : self . repos = phlgitu_fixture . CentralisedWithTwoWorkers ( ) self . repo_central = self . repos . central_repo self . repo_dev = self . repos . w0 . repo sys_repo = self . repos . w1 . repo refcache_repo = phlgitx_refcache . Repo ( sys_repo ) differ_cache = abdt_differresultcache . Cache ( refcache_repo ) self . repo_arcyd = abdt_git . Repo ( refcache_repo , differ_cache , '' , '' ) def tearDown ( self ) : self . repos . close ( ) def test_A_Breathing ( self ) : remote = \"\" expected_branches = [ '' , '' , '' , ] for branch in expected_branches : phlgit_push . push_asymmetrical ( self . repo_dev , '' , branch , remote ) self . repo_arcyd ( \"\" ) branches = abdt_git . get_managed_branches ( self . repo_arcyd , \"\" , abdt_rbranchnaming . Naming ( ) ) actual_branches = [ b . review_branch_name ( ) for b in branches ] self . assertSetEqual ( set ( expected_branches ) , set ( actual_branches ) ) for b in branches : self . repo_arcyd . archive_to_abandoned ( b . review_branch_hash ( ) , b . review_branch_name ( ) , '' ) self . repo_arcyd . archive_to_landed ( b . review_branch_hash ( ) , b . review_branch_name ( ) , '' , '' , '' ) def _get_updated_branch ( self , branch_name ) : phlgit_fetch . all_prune ( self . repo_arcyd ) branch_list = abdt_git . get_managed_branches ( self . repo_arcyd , \"\" , abdt_classicnaming . Naming ( ) ) self . assertEqual ( len ( branch_list ) , ) branch = branch_list [ ] self . assertEqual ( branch . review_branch_name ( ) , branch_name ) return branch def test_B_RawDiffNewCommits ( self ) : base , branch_name , branch = self . _setup_for_tracked_branch ( ) self . assertIs ( branch . has_new_commits ( ) , False ) phlgit_checkout . branch ( self . repo_dev , branch_name ) filename = '' self . _create_new_file ( self . repo_dev , filename ) self . repo_dev ( '' , filename ) phlgit_commit . index ( self . repo_dev , message = filename ) phlgit_push . branch ( self . repo_dev , branch_name ) branch = self . _get_updated_branch ( branch_name ) self . assertIs ( branch . has_new_commits ( ) , True ) branch . describe_new_commits ( ) self . assertIn ( filename , branch . make_raw_diff ( ) . diff ) branch . mark_ok_in_review ( ) self . assertIs ( branch . has_new_commits ( ) , False ) branch . describe_new_commits ( ) self . assertIn ( filename , branch . make_raw_diff ( ) . diff ) self . assertIn ( filename , branch . make_message_digest ( ) ) self . assertEqual ( branch . get_commit_message_from_tip ( ) . strip ( ) , filename ) self . assertTrue ( len ( branch . get_any_author_emails ( ) ) > ) self . assertTrue ( len ( branch . get_author_names_emails ( ) ) > ) phlgit_checkout . branch ( self . repo_dev , '' ) filename = '' self . _create_new_file ( self . repo_dev , filename ) self . repo_dev ( '' , filename ) phlgit_commit . index ( self . repo_dev , message = filename ) phlgit_push . branch ( self . repo_dev , '' ) branch = self . _get_updated_branch ( branch_name ) self . assertIs ( branch . has_new_commits ( ) , False ) phlgit_checkout . branch ( self . repo_dev , branch_name ) phlgit_merge . no_ff ( self . repo_dev , '' ) phlgit_push . branch ( self . repo_dev , branch_name ) self . assertIs ( branch . has_new_commits ( ) , False ) branch = self . _get_updated_branch ( branch_name ) self . assertNotIn ( filename , branch . make_raw_diff ( ) . diff ) branch . mark_ok_in_review ( ) self . assertIs ( branch . has_new_commits ( ) , False ) phlgit_checkout . branch ( self . repo_dev , branch_name ) phlgit_rebase . onto_upstream ( self . repo_dev , '' ) phlgit_push . force_branch ( self . repo_dev , branch_name ) self . assertIs ( branch . has_new_commits ( ) , False ) branch = self . _get_updated_branch ( branch_name ) self . assertIs ( branch . has_new_commits ( ) , True ) branch . describe_new_commits ( ) branch . mark_ok_in_review ( ) self . assertIs ( branch . has_new_commits ( ) , False ) def _setup_for_tracked_branch ( self ) : base , branch_name , branch = self . _setup_for_untracked_branch ( ) branch . mark_ok_new_review ( ) return base , branch_name , branch def _setup_for_untracked_branch ( self , repo_name = '' , branch_url = None ) : base = abdt_naming . EXAMPLE_REVIEW_BRANCH_BASE naming = abdt_classicnaming . Naming ( ) branch_name = abdt_classicnaming . EXAMPLE_REVIEW_BRANCH_NAME self . repo_dev ( '' , '' , branch_name ) phlgit_push . push ( self . repo_dev , branch_name , '' ) ", "answer": "self . repo_arcyd ( '' , '' )"}, {"prompt": " import theano from theano . compile . mode import Mode , AddFeatureOptimizer from theano . gof . toolbox import NoOutputFromInplace import theano . tensor as T def test_no_output_from_implace ( ) : x = T . matrix ( ) y = T . matrix ( ) a = T . dot ( x , y ) b = T . tanh ( a ) fct_no_opt = theano . function ( [ x , y ] , b , mode = \"\" ) op = fct_no_opt . maker . fgraph . outputs [ ] . owner . op assert ( hasattr ( op , '' ) and in op . destroy_map ) ", "answer": "opt = AddFeatureOptimizer ( NoOutputFromInplace ( ) )"}, {"prompt": " \"\"\"\"\"\" from . . import util from . . orm import attributes , interfaces HYBRID_METHOD = util . symbol ( '' ) \"\"\"\"\"\" HYBRID_PROPERTY = util . symbol ( '' ) \"\"\"\"\"\" class hybrid_method ( interfaces . _InspectionAttr ) : \"\"\"\"\"\" is_attribute = True extension_type = HYBRID_METHOD def __init__ ( self , func , expr = None ) : \"\"\"\"\"\" self . func = func self . expr = expr or func def __get__ ( self , instance , owner ) : if instance is None : return self . expr . __get__ ( owner , owner . __class__ ) else : return self . func . __get__ ( instance , owner ) def expression ( self , expr ) : \"\"\"\"\"\" self . expr = expr return self class hybrid_property ( interfaces . _InspectionAttr ) : \"\"\"\"\"\" is_attribute = True extension_type = HYBRID_PROPERTY def __init__ ( self , fget , fset = None , fdel = None , expr = None ) : \"\"\"\"\"\" self . fget = fget self . fset = fset self . fdel = fdel self . expr = expr or fget util . update_wrapper ( self , fget ) ", "answer": "def __get__ ( self , instance , owner ) :"}, {"prompt": " \"\"\"\"\"\" import urllib from docutils import nodes , utils def make_trac_link ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : env = inliner . document . settings . env trac_url = env . config . traclinks_base_url ref = trac_url + '' + urllib . quote ( text , safe = '' ) node = nodes . reference ( rawtext , utils . unescape ( text ) , refuri = ref , ", "answer": "** options )"}, {"prompt": " from test import CollectorTestCase from test import get_collector_config from test import unittest from drbd import DRBDCollector class TestDRBDCollector ( CollectorTestCase ) : def setUp ( self ) : config = get_collector_config ( '' , { } ) self . collector = DRBDCollector ( config , None ) def test_import ( self ) : ", "answer": "self . assertTrue ( DRBDCollector )"}, {"prompt": " from flask import Flask , url_for from . view_classes import BasicView , IndexView , RouteBaseView , VarBaseView from nose . tools import * app = Flask ( \"\" ) BasicView . register ( app ) IndexView . register ( app ) RouteBaseView . register ( app ) VarBaseView . register ( app ) client = app . test_client ( ) def test_index_url ( ) : with app . test_request_context ( ) : url = url_for ( \"\" ) eq_ ( \"\" , url ) def test_basic_index_url ( ) : with app . test_request_context ( ) : url = url_for ( \"\" ) eq_ ( \"\" , url ) def test_custom_endpoint_url ( ) : ", "answer": "with app . test_request_context ( ) :"}, {"prompt": " import hashlib from amonone . web . apps . core . basemodel import BaseModel class UserModel ( BaseModel ) : def __init__ ( self ) : super ( UserModel , self ) . __init__ ( ) self . collection = self . mongo . get_collection ( '' ) def create_user ( self , userdata ) : userdata [ '' ] = hashlib . sha1 ( userdata [ '' ] ) . hexdigest ( ) self . collection . save ( userdata ) def check_user ( self , userdata ) : userdata [ '' ] = hashlib . sha1 ( userdata [ '' ] ) . hexdigest ( ) result = self . collection . find_one ( { \"\" : userdata [ '' ] , \"\" : userdata [ '' ] } ) return result if result else { } def count_users ( self ) : return self . collection . count ( ) def username_exists ( self , username ) : result = self . collection . find ( { \"\" : username } ) . count ( ) return result def get_all ( self ) : return self . collection . find ( ) def get ( self , id ) : try : object_id = self . mongo . get_object_id ( id ) except : object_id = False if object_id : return self . collection . find_one ( object_id ) def update ( self , data , id ) : id = self . mongo . get_object_id ( id ) servers = data . get ( '' , None ) if servers is not None : self . collection . update ( { \"\" : id } , { \"\" : { \"\" : data [ '' ] } } ) password = data . get ( '' , None ) if password is not None : data [ '' ] = hashlib . sha1 ( data [ '' ] ) . hexdigest ( ) self . collection . update ( { \"\" : id } , { \"\" : { \"\" : data [ '' ] } } ) def delete ( self , id ) : try : object_id = self . mongo . get_object_id ( id ) except : ", "answer": "object_id = False"}, {"prompt": " \"\"\"\"\"\" import threading import keyring from oauth2client . client import Credentials from oauth2client . client import Storage as BaseStorage __author__ = '' class Storage ( BaseStorage ) : \"\"\"\"\"\" def __init__ ( self , service_name , user_name ) : \"\"\"\"\"\" super ( Storage , self ) . __init__ ( lock = threading . Lock ( ) ) self . _service_name = service_name self . _user_name = user_name def locked_get ( self ) : \"\"\"\"\"\" credentials = None content = keyring . get_password ( self . _service_name , self . _user_name ) if content is not None : try : credentials = Credentials . new_from_json ( content ) credentials . set_store ( self ) except ValueError : ", "answer": "pass"}, {"prompt": " import sys import re import urllib2 import traceback import threading import time ", "answer": "requests = '' ; urls_accessible_http = [ ]"}, {"prompt": " from swgpy . object import * ", "answer": "def create ( kernel ) :"}, {"prompt": " import os . path from django . conf import settings from django . test import TransactionTestCase from panda import solr from panda . exceptions import DataUploadNotDeletable ", "answer": "from panda . models import Dataset , DataUpload"}, {"prompt": " from appkit . api . v0_2_4 . app import * import os import unittest class AppKitUnitTest ( unittest . TestCase ) : def setUp ( self ) : app = App ( __file__ ) @ app . route ( '' ) def index ( ) : return '''''' @ app . route ( '' ) def hi ( ) : return '' @ app . route ( '' ) def sum ( arg1 , arg2 ) : return int ( arg1 ) + int ( arg2 ) self . app = app def test_init_gtk ( self ) : try : Gtk . init ( '' ) except : ", "answer": "raise Exception ( '' )"}, {"prompt": " from sys import version_info identity = lambda arg : arg def _apply ( f , args = None , kwargs = None ) : return f ( * ( args or [ ] ) , ** ( kwargs or { } ) ) apply = apply if version_info [ ] == else _apply def call ( f , * args , ** kwargs ) : return f ( * args , ** kwargs ) def flip ( f ) : \"\"\"\"\"\" flipper = getattr ( f , \"\" , None ) if flipper is not None : return flipper ", "answer": "def _flipper ( a , b ) :"}, {"prompt": " \"\"\"\"\"\" import os from pyexcel_io import get_data , save_data , RWManager from pyexcel_io . utils import AVAILABLE_READERS , AVAILABLE_WRITERS from . . constants import DEFAULT_SHEET_NAME from . import params from . base import FileSource , one_sheet_tuple class IOSource ( FileSource ) : \"\"\"\"\"\" @ classmethod def can_i_handle ( cls , action , file_type ) : if action == params . READ_ACTION : status = file_type in RWManager . reader_factories or file_type in AVAILABLE_READERS elif action == params . WRITE_ACTION : status = file_type in RWManager . writer_factories or file_type in AVAILABLE_WRITERS else : status = False return status class SheetSource ( IOSource ) : \"\"\"\"\"\" fields = [ params . FILE_NAME ] targets = ( params . SHEET , ) actions = ( params . READ_ACTION , params . WRITE_ACTION ) def __init__ ( self , file_name = None , ** keywords ) : self . file_name = file_name self . keywords = keywords def get_data ( self ) : \"\"\"\"\"\" ", "answer": "sheets = get_data ( self . file_name , ** self . keywords )"}, {"prompt": " from django . db import models ", "answer": "class CorsModel ( models . Model ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " import logging from botocore import xform_name from . params import create_request_parameters from . response import RawHandler , ResourceHandler from . model import Action from boto3 . docs . docstring import ActionDocstring from boto3 . utils import inject_attribute logger = logging . getLogger ( __name__ ) class ServiceAction ( object ) : \"\"\"\"\"\" def __init__ ( self , action_model , factory = None , service_context = None ) : self . _action_model = action_model resource_response_model = action_model . resource if resource_response_model : self . _response_handler = ResourceHandler ( search_path = resource_response_model . path , factory = factory , resource_model = resource_response_model , service_context = service_context , operation_name = action_model . request . operation ) else : self . _response_handler = RawHandler ( action_model . path ) def __call__ ( self , parent , * args , ** kwargs ) : \"\"\"\"\"\" operation_name = xform_name ( self . _action_model . request . operation ) params = create_request_parameters ( parent , self . _action_model . request ) params . update ( kwargs ) logger . info ( '' , parent . meta . service_name , operation_name , params ) response = getattr ( parent . meta . client , operation_name ) ( ** params ) logger . debug ( '' , response ) return self . _response_handler ( parent , params , response ) class BatchAction ( ServiceAction ) : \"\"\"\"\"\" def __call__ ( self , parent , * args , ** kwargs ) : \"\"\"\"\"\" service_name = None client = None responses = [ ] operation_name = xform_name ( self . _action_model . request . operation ) for page in parent . pages ( ) : params = { } for index , resource in enumerate ( page ) : if service_name is None : service_name = resource . meta . service_name if client is None : client = resource . meta . client create_request_parameters ( resource , self . _action_model . request , params = params , index = index ) if not params : break params . update ( kwargs ) logger . info ( '' , service_name , operation_name , params ) response = getattr ( client , operation_name ) ( ** params ) logger . debug ( '' , response ) responses . append ( self . _response_handler ( parent , params , response ) ) return responses class WaiterAction ( object ) : \"\"\"\"\"\" def __init__ ( self , waiter_model , waiter_resource_name ) : self . _waiter_model = waiter_model self . _waiter_resource_name = waiter_resource_name def __call__ ( self , parent , * args , ** kwargs ) : \"\"\"\"\"\" client_waiter_name = xform_name ( self . _waiter_model . waiter_name ) params = create_request_parameters ( parent , self . _waiter_model ) params . update ( kwargs ) logger . info ( '' , parent . meta . service_name , self . _waiter_resource_name , params ) client = parent . meta . client waiter = client . get_waiter ( client_waiter_name ) response = waiter . wait ( ** params ) logger . debug ( '' , response ) class CustomModeledAction ( object ) : \"\"\"\"\"\" def __init__ ( self , action_name , action_model , function , event_emitter ) : \"\"\"\"\"\" self . name = action_name self . model = action_model self . function = function self . emitter = event_emitter def inject ( self , class_attributes , service_context , event_name , ** kwargs ) : resource_name = event_name . rsplit ( \"\" ) [ - ] action = Action ( self . name , self . model , { } ) self . function . __name__ = self . name self . function . __doc__ = ActionDocstring ( resource_name = resource_name , event_emitter = self . emitter , action_model = action , service_model = service_context . service_model , include_signature = False ) ", "answer": "inject_attribute ( class_attributes , self . name , self . function ) "}, {"prompt": " \"\"\"\"\"\" from flask import url_for class PluginMount ( type ) : def __init__ ( cls , name , bases , attrs ) : if not hasattr ( cls , '' ) : cls . plugins = { } else : cls . slug = getattr ( cls , '' , None ) or cls . title . replace ( '' , '' ) . lower ( ) cls . plugins [ cls . slug ] = cls class GroupActionProvider : __metaclass__ = PluginMount new_window = False @ classmethod def get_url ( cls , group_id ) : return url_for ( '' , group_id = group_id , slug = cls . slug ) def __init__ ( self , group_id ) : self . url = self . __class__ . get_url ( group_id ) def __call__ ( self , request , group ) : self . selected = request . path == self . url if not self . selected : return return self . view ( request , group ) def view ( self ) : \"\"\"\"\"\" def tags ( self , request , tag_list , group ) : \"\"\"\"\"\" return tag_list def actions ( self , request , action_list , group ) : \"\"\"\"\"\" return action_list ", "answer": "def panels ( self , request , panel_list , group ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division __all__ = [ \"\" ] import math def max_tile_size ( tile_count , rect_size ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from swgpy . object import * def create ( kernel ) : ", "answer": "result = Weapon ( )"}, {"prompt": " class ListNode : def __init__ ( self , x ) : self . val = x self . next = None def __repr__ ( self ) : ", "answer": "if self :"}, {"prompt": " from wtforms import TextField , TextAreaField , SelectField , BooleanField from wtforms . validators import DataRequired from flask . ext . babel import lazy_gettext as _ from . _base import BaseForm from . . models import Node class NodeForm ( BaseForm ) : title = TextField ( _ ( '' ) , validators = [ DataRequired ( ) ] , description = _ ( '' ) ) urlname = TextField ( _ ( '' ) , validators = [ DataRequired ( ) ] , description = _ ( '' ) ) description = TextAreaField ( _ ( '' ) ) role = SelectField ( _ ( '' ) , description = _ ( '' ) , choices = [ ( '' , _ ( '' ) ) , ( '' , _ ( '' ) ) , ( '' , _ ( '' ) ) ] , default = '' , ) on_home = BooleanField ( _ ( '' ) , default = True ) ", "answer": "def validate_urlname ( self , field ) :"}, {"prompt": " from datetime import datetime from uuid import UUID from changes . api . serializer import serialize from changes . models . log import LogSource , LogChunk def test_simple ( ) : logchunk = LogChunk ( id = UUID ( hex = '' ) , source_id = UUID ( hex = '' ) , ", "answer": "source = LogSource ( id = UUID ( hex = '' ) ) ,"}, {"prompt": " CSP_REPORT_ONLY = False ", "answer": "DATABASES = {"}, {"prompt": " from copy import deepcopy from datetime import datetime as dt import os . path as op import numpy as np from scipy import linalg from . pick import channel_type from . constants import FIFF from . open import fiff_open from . tree import dir_tree_find from . tag import read_tag , find_tag from . proj import _read_proj , _write_proj , _uniquify_projs , _normalize_proj from . ctf_comp import read_ctf_comp , write_ctf_comp from . write import ( start_file , end_file , start_block , end_block , write_string , write_dig_point , write_float , write_int , write_coord_trans , write_ch_info , write_name_list , write_julian , write_float_matrix ) from . proc_history import _read_proc_history , _write_proc_history from . . utils import logger , verbose , warn from . . fixes import Counter from . . import __version__ from . . externals . six import b , BytesIO , string_types , text_type _kind_dict = dict ( eeg = ( FIFF . FIFFV_EEG_CH , FIFF . FIFFV_COIL_EEG , FIFF . FIFF_UNIT_V ) , mag = ( FIFF . FIFFV_MEG_CH , FIFF . FIFFV_COIL_VV_MAG_T3 , FIFF . FIFF_UNIT_T ) , grad = ( FIFF . FIFFV_MEG_CH , FIFF . FIFFV_COIL_VV_PLANAR_T1 , FIFF . FIFF_UNIT_T_M ) , ref_meg = ( FIFF . FIFFV_REF_MEG_CH , FIFF . FIFFV_COIL_VV_MAG_T3 , FIFF . FIFF_UNIT_T ) , misc = ( FIFF . FIFFV_MISC_CH , FIFF . FIFFV_COIL_NONE , FIFF . FIFF_UNIT_NONE ) , stim = ( FIFF . FIFFV_STIM_CH , FIFF . FIFFV_COIL_NONE , FIFF . FIFF_UNIT_V ) , eog = ( FIFF . FIFFV_EOG_CH , FIFF . FIFFV_COIL_NONE , FIFF . FIFF_UNIT_V ) , ecg = ( FIFF . FIFFV_ECG_CH , FIFF . FIFFV_COIL_NONE , FIFF . FIFF_UNIT_V ) , seeg = ( FIFF . FIFFV_SEEG_CH , FIFF . FIFFV_COIL_EEG , FIFF . FIFF_UNIT_V ) , bio = ( FIFF . FIFFV_BIO_CH , FIFF . FIFFV_COIL_NONE , FIFF . FIFF_UNIT_V ) , ecog = ( FIFF . FIFFV_ECOG_CH , FIFF . FIFFV_COIL_EEG , FIFF . FIFF_UNIT_V ) , ) def _summarize_str ( st ) : \"\"\"\"\"\" return st [ : ] [ : : - ] . split ( '' , ) [ - ] [ : : - ] + '' class Info ( dict ) : \"\"\"\"\"\" def copy ( self ) : \"\"\"\"\"\" return Info ( deepcopy ( self ) ) def normalize_proj ( self ) : \"\"\"\"\"\" _normalize_proj ( self ) def __repr__ ( self ) : \"\"\"\"\"\" strs = [ '' ] non_empty = for k , v in self . items ( ) : if k in [ '' , '' ] : entr = ( '' . join ( b for ii , b in enumerate ( v ) if ii < ) if v else '' ) if len ( entr ) >= : entr = _summarize_str ( entr ) elif k == '' and v : path , fname = op . split ( v ) entr = path [ : ] + '' + fname elif k == '' and v : entr = '' . join ( p [ '' ] + '' % { : '' , : '' } [ p [ '' ] ] for p in v ) if len ( entr ) >= : entr = _summarize_str ( entr ) elif k == '' and np . iterable ( v ) : entr = dt . fromtimestamp ( v [ ] ) . strftime ( '' ) else : this_len = ( len ( v ) if hasattr ( v , '' ) else ( '' % v if v is not None else None ) ) entr = ( ( '' % this_len ) if isinstance ( this_len , int ) else ( '' % this_len if this_len else '' ) ) if entr : non_empty += entr = '' + entr if k == '' : ch_types = [ channel_type ( self , idx ) for idx in range ( len ( v ) ) ] ch_counts = Counter ( ch_types ) entr += \"\" % '' . join ( \"\" % ( ch_type . upper ( ) , count ) for ch_type , count in ch_counts . items ( ) ) strs . append ( '' % ( k , str ( type ( v ) ) [ : - ] , entr ) ) if k in [ '' , '' , '' ] : strs [ - ] += '' strs_non_empty = sorted ( s for s in strs if '' in s ) strs_empty = sorted ( s for s in strs if '' not in s ) st = '' . join ( strs_non_empty + strs_empty ) st += '' st %= non_empty return st def _anonymize ( self ) : if self . get ( '' ) is not None : del self [ '' ] self [ '' ] = [ , ] for key_1 in ( '' , '' ) : for key_2 in ( '' , '' , '' ) : self [ key_1 ] [ key_2 ] = def _check_consistency ( self ) : \"\"\"\"\"\" missing = [ bad for bad in self [ '' ] if bad not in self [ '' ] ] if len ( missing ) > : raise RuntimeError ( '' % ( missing , ) ) chs = [ ch [ '' ] for ch in self [ '' ] ] if len ( self [ '' ] ) != len ( chs ) or any ( ch_1 != ch_2 for ch_1 , ch_2 in zip ( self [ '' ] , chs ) ) or self [ '' ] != len ( chs ) : raise RuntimeError ( '' '' ) for key in ( '' , '' , '' ) : if self . get ( key ) is not None : self [ key ] = float ( self [ key ] ) unique_ids = np . unique ( self [ '' ] , return_index = True ) [ ] if len ( unique_ids ) != self [ '' ] : dups = set ( self [ '' ] [ x ] for x in np . setdiff1d ( range ( self [ '' ] ) , unique_ids ) ) raise RuntimeError ( '' '' % dups ) def _update_redundant ( self ) : \"\"\"\"\"\" self [ '' ] = [ ch [ '' ] for ch in self [ '' ] ] self [ '' ] = len ( self [ '' ] ) def read_fiducials ( fname ) : \"\"\"\"\"\" fid , tree , _ = fiff_open ( fname ) with fid : isotrak = dir_tree_find ( tree , FIFF . FIFFB_ISOTRAK ) isotrak = isotrak [ ] ", "answer": "pts = [ ]"}, {"prompt": " \"\"\"\"\"\" import numpy as np try : from sklearn import cluster , datasets from sklearn . preprocessing import StandardScaler except ImportError : raise ImportError ( '' ) from bokeh . plotting import Figure , show , output_file , vplot , hplot N = PLOT_SIZE = np . random . seed ( ) noisy_circles = datasets . make_circles ( n_samples = N , factor = , noise = ) noisy_moons = datasets . make_moons ( n_samples = N , noise = ) centers = [ ( - , ) , ( , ) , ( - , - ) , ( , - ) ] blobs1 = datasets . make_blobs ( centers = centers , n_samples = N , cluster_std = , random_state = ) blobs2 = datasets . make_blobs ( centers = centers , n_samples = N , cluster_std = , random_state = ) colors = np . array ( [ x for x in ( '' , '' , '' , '' , '' , '' ) ] ) colors = np . hstack ( [ colors ] * ) dbscan = cluster . DBSCAN ( eps = ) birch = cluster . Birch ( n_clusters = ) means = cluster . MiniBatchKMeans ( n_clusters = ) spectral = cluster . SpectralClustering ( n_clusters = , eigen_solver = '' , affinity = \"\" ) affinity = cluster . AffinityPropagation ( damping = , preference = - ) algorithm = dbscan plots = [ ] ", "answer": "for dataset in ( noisy_circles , noisy_moons , blobs1 , blobs2 ) :"}, {"prompt": " from abc import abstractmethod from neupy . core . base import BaseSkeleton from neupy . core . config import ConfigurableABC __all__ = ( '' , ) class BaseEnsemble ( BaseSkeleton , ConfigurableABC ) : \"\"\"\"\"\" def __init__ ( self , networks ) : ", "answer": "self . networks = networks"}, {"prompt": " \"\"\"\"\"\" import logging from envisage . api import ( bind_extension_point , ExtensionPoint , Plugin , ServiceOffer ) from traits . api import Instance , List IPYTHON_KERNEL_PROTOCOL = '' IPYTHON_NAMESPACE = '' logger = logging . getLogger ( __name__ ) class IPythonKernelPlugin ( Plugin ) : \"\"\"\"\"\" SERVICE_OFFERS = '' id = '' name = '' def stop ( self ) : logger . info ( '' ) self . kernel . shutdown ( ) kernel_namespace = ExtensionPoint ( List , id = IPYTHON_NAMESPACE , desc = \"\"\"\"\"\" ) kernel = Instance ( IPYTHON_KERNEL_PROTOCOL ) service_offers = List ( contributes_to = SERVICE_OFFERS ) def _service_offers_default ( self ) : ipython_kernel_service_offer = ServiceOffer ( protocol = IPYTHON_KERNEL_PROTOCOL , factory = self . _create_kernel , ) return [ ipython_kernel_service_offer ] def _create_kernel ( self ) : return self . kernel def _kernel_default ( self ) : from . internal_ipkernel import InternalIPKernel kernel = InternalIPKernel ( ) bind_extension_point ( kernel , '' , IPYTHON_NAMESPACE , self . application ) ", "answer": "return kernel "}, {"prompt": " \"\"\"\"\"\" import collections import os from datetime import datetime import re import sys try : import StringIO as io except ImportError : import io import logging try : from urllib . request import URLopener except ImportError : from urllib import URLopener from . resource_container import ResourceContainer from . sitemap import Sitemap class ListBase ( ResourceContainer ) : \"\"\"\"\"\" def __init__ ( self , resources = None , count = None , md = None , ln = None , uri = None , capability_name = '' ) : super ( ListBase , self ) . __init__ ( resources = resources , md = md , ln = ln , uri = uri , capability_name = capability_name ) self . count = count self . sitemapindex = False self . pretty_xml = False self . logger = logging . getLogger ( '' ) self . bytes_read = self . parsed_index = None def __iter__ ( self ) : \"\"\"\"\"\" return ( iter ( self . resources ) ) def __len__ ( self ) : \"\"\"\"\"\" if ( self . count is not None ) : return ( self . count ) return ( len ( self . resources ) ) def read ( self , uri = None ) : \"\"\"\"\"\" self . parse ( uri = uri ) def parse ( self , uri = None , fh = None , str_data = None , ** kwargs ) : \"\"\"\"\"\" if ( uri is not None ) : try : fh = URLopener ( ) . open ( uri ) except IOError as e : raise Exception ( \"\" % ( uri , str ( e ) ) ) ", "answer": "elif ( str_data is not None ) :"}, {"prompt": " \"\"\"\"\"\" import TestGyp import sys if sys . platform == '' : test = TestGyp . TestGyp ( formats = [ '' , '' ] ) CHDIR = '' test . run_gyp ( '' , chdir = CHDIR ) test . build ( '' , test . ALL , chdir = CHDIR ) def CheckForSectionString ( binary , search_for , should_exist ) : output = test . run_dumpbin ( '' , binary ) if should_exist and search_for not in output : print '' % ( search_for , binary ) test . fail_test ( ) elif not should_exist and search_for in output : print '' % ( search_for , binary ) test . fail_test ( ) def Object ( proj , obj ) : sep = '' if test . format == '' else '' ", "answer": "return '' % ( proj , sep , obj )"}, {"prompt": " import IECore class parameterChangedCallback ( IECore . Parameterised ) : def __init__ ( self ) : ", "answer": "IECore . Parameterised . __init__ ( self , \"\" )"}, {"prompt": " import abc import os import uuid import xml . dom . minidom as xml from oslo_config import cfg import six from sahara import conductor as c from sahara import context from sahara . service . edp import base_engine from sahara . service . edp . binary_retrievers import dispatch from sahara . service . edp import hdfs_helper as h from sahara . service . edp import job_utils from sahara . service . edp . oozie import oozie as o from sahara . service . edp . oozie . workflow_creator import workflow_factory from sahara . service . validations . edp import job_execution as j from sahara . utils import edp from sahara . utils import remote from sahara . utils import xmlutils as x CONF = cfg . CONF conductor = c . API @ six . add_metaclass ( abc . ABCMeta ) class OozieJobEngine ( base_engine . JobEngine ) : def __init__ ( self , cluster ) : self . cluster = cluster self . plugin = job_utils . get_plugin ( self . cluster ) def _get_client ( self ) : return o . OozieClient ( self . get_oozie_server_uri ( self . cluster ) , self . get_oozie_server ( self . cluster ) ) def _get_oozie_job_params ( self , hdfs_user , path_to_workflow , oozie_params , use_hbase_lib , scheduled_params = None , job_dir = None , job_execution_type = None ) : oozie_libpath_key = \"\" oozie_libpath = \"\" rm_path = self . get_resource_manager_uri ( self . cluster ) nn_path = self . get_name_node_uri ( self . cluster ) hbase_common_lib_path = \"\" % ( nn_path , h . HBASE_COMMON_LIB_PATH ) if use_hbase_lib : if oozie_libpath_key in oozie_params : oozie_libpath = \"\" % ( oozie_params . get ( oozie_libpath_key , \"\" ) , hbase_common_lib_path ) else : oozie_libpath = hbase_common_lib_path if job_execution_type == \"\" : app_path = \"\" job_parameters = { \"\" : scheduled_params . get ( '' ) , \"\" : scheduled_params . get ( '' ) , \"\" : scheduled_params . get ( '' ) , \"\" : \"\" % ( nn_path , job_dir ) , app_path : \"\" % ( nn_path , job_dir ) } else : app_path = \"\" job_parameters = { app_path : \"\" % ( nn_path , path_to_workflow ) } job_parameters [ \"\" ] = nn_path job_parameters [ \"\" ] = hdfs_user job_parameters [ \"\" ] = rm_path job_parameters [ oozie_libpath_key ] = oozie_libpath job_parameters [ \"\" ] = \"\" if app_path in oozie_params : del oozie_params [ app_path ] if oozie_libpath_key in oozie_params : del oozie_params [ oozie_libpath_key ] job_parameters . update ( oozie_params ) return job_parameters def _upload_workflow_file ( self , where , job_dir , wf_xml , hdfs_user ) : with remote . get_remote ( where ) as r : h . put_file_to_hdfs ( r , wf_xml , \"\" , job_dir , hdfs_user ) return \"\" % job_dir def _upload_coordinator_file ( self , where , job_dir , wf_xml , hdfs_user ) : with remote . get_remote ( where ) as r : h . put_file_to_hdfs ( r , wf_xml , \"\" , job_dir , hdfs_user ) ", "answer": "return \"\" % job_dir"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Intangible ( ) result . template = \"\" result . attribute_template_id = - ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " import sys , os ", "answer": "docs_dir = os . path . dirname ( __file__ )"}, {"prompt": " from __future__ import print_function import argparse import distutils . spawn import getpass import logging import os import sys from . server import env logger = logging . getLogger ( __name__ ) DESCRIPTION = \"\"\"\"\"\" def run_gunicorn ( ) : \"\"\"\"\"\" parser = argparse . ArgumentParser ( description = DESCRIPTION , formatter_class = argparse . RawTextHelpFormatter ) parser . parse_args ( ) gunicorn_path = distutils . spawn . find_executable ( '' ) if not gunicorn_path : print ( '' , file = sys . stderr ) sys . exit ( ) address = '' % ( env . source ( '' ) , env . source ( '' ) ) args = [ gunicorn_path , '' , '' , env . source ( '' ) , '' , env . source ( '' ) , '' , '' , '' , '' , '' , env . source ( '' ) , ", "answer": "'' , env . source ( '' ) ,"}, {"prompt": " import unittest from stix . test import EntityTestCase , assert_warnings from stix . test import data_marking_test from stix . test . common import related_test , identity_test , kill_chains_test from stix . core import STIXPackage import stix . ttp as ttp from stix . ttp import ( resource , infrastructure , exploit_targets , malware_instance , exploit , attack_pattern , behavior ) class ExploitTargetsTests ( EntityTestCase , unittest . TestCase ) : klass = exploit_targets . ExploitTargets _full_dict = { '' : '' , '' : [ related_test . RelatedExploitTargetTests . _full_dict ] } class PersonasTests ( EntityTestCase , unittest . TestCase ) : klass = resource . Personas _full_dict = [ identity_test . IdentityTests . _full_dict ] class InfrastructureTests ( EntityTestCase , unittest . TestCase ) : klass = infrastructure . Infrastructure _full_dict = { '' : '' , '' : '' , '' : '' , '' : [ '' , '' ] , '' : { '' : , '' : , '' : , '' : [ { '' : \"\" } ] } } class ResourcesTests ( EntityTestCase , unittest . TestCase ) : klass = ttp . Resource _full_dict = { '' : PersonasTests . _full_dict , '' : [ { '' : \"\" } ] , '' : InfrastructureTests . _full_dict } class MalwareInstanceTests ( EntityTestCase , unittest . TestCase ) : klass = malware_instance . MalwareInstance _full_dict = _full_dict = { '' : '' , '' : '' , '' : '' , '' : '' , '' : [ '' , '' ] } class MalwareInstancesTests ( EntityTestCase , unittest . TestCase ) : klass = behavior . MalwareInstances _full_dict = [ MalwareInstanceTests . _full_dict ] class ExploitTests ( EntityTestCase , unittest . TestCase ) : klass = exploit . Exploit ", "answer": "_full_dict = {"}, {"prompt": " for i in xrange ( ) : ", "answer": "print - i"}, {"prompt": " import contextlib import json import shutil import socket import tarfile import tempfile import threading import pytest import six from six . moves import BaseHTTPServer from six . moves import socketserver import docker from . . import helpers BUSYBOX = helpers . BUSYBOX class ListImagesTest ( helpers . BaseTestCase ) : def test_images ( self ) : res1 = self . client . images ( all = True ) self . assertIn ( '' , res1 [ ] ) res10 = res1 [ ] self . assertIn ( '' , res10 ) self . assertIn ( '' , res10 ) distinct = [ ] for img in res1 : if img [ '' ] not in distinct : distinct . append ( img [ '' ] ) self . assertEqual ( len ( distinct ) , self . client . info ( ) [ '' ] ) def test_images_quiet ( self ) : res1 = self . client . images ( quiet = True ) self . assertEqual ( type ( res1 [ ] ) , six . text_type ) class PullImageTest ( helpers . BaseTestCase ) : def test_pull ( self ) : try : self . client . remove_image ( '' ) except docker . errors . APIError : pass res = self . client . pull ( '' ) self . tmp_imgs . append ( '' ) self . assertEqual ( type ( res ) , six . text_type ) self . assertGreaterEqual ( len ( self . client . images ( '' ) ) , ) img_info = self . client . inspect_image ( '' ) self . assertIn ( '' , img_info ) def test_pull_streaming ( self ) : try : self . client . remove_image ( '' ) except docker . errors . APIError : pass stream = self . client . pull ( '' , stream = True ) self . tmp_imgs . append ( '' ) for chunk in stream : if six . PY3 : chunk = chunk . decode ( '' ) json . loads ( chunk ) self . assertGreaterEqual ( len ( self . client . images ( '' ) ) , ) img_info = self . client . inspect_image ( '' ) self . assertIn ( '' , img_info ) class CommitTest ( helpers . BaseTestCase ) : def test_commit ( self ) : container = self . client . create_container ( BUSYBOX , [ '' , '' ] ) id = container [ '' ] self . client . start ( id ) self . tmp_containers . append ( id ) res = self . client . commit ( id ) self . assertIn ( '' , res ) img_id = res [ '' ] self . tmp_imgs . append ( img_id ) img = self . client . inspect_image ( img_id ) self . assertIn ( '' , img ) self . assertTrue ( img [ '' ] . startswith ( id ) ) self . assertIn ( '' , img ) self . assertIn ( '' , img [ '' ] ) self . assertEqual ( BUSYBOX , img [ '' ] [ '' ] ) busybox_id = self . client . inspect_image ( BUSYBOX ) [ '' ] self . assertIn ( '' , img ) self . assertEqual ( img [ '' ] , busybox_id ) def test_commit_with_changes ( self ) : cid = self . client . create_container ( BUSYBOX , [ '' , '' ] ) self . tmp_containers . append ( cid ) self . client . start ( cid ) img_id = self . client . commit ( cid , changes = [ '' , '' ] ) self . tmp_imgs . append ( img_id ) img = self . client . inspect_image ( img_id ) assert '' in img assert img [ '' ] . startswith ( cid [ '' ] ) assert '' in img [ '' ] [ '' ] assert img [ '' ] [ '' ] == [ '' ] class RemoveImageTest ( helpers . BaseTestCase ) : def test_remove ( self ) : container = self . client . create_container ( BUSYBOX , [ '' , '' ] ) ", "answer": "id = container [ '' ]"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " __copyright__ = \"\" import os import glob import subprocess import platform import wx from Cura . util import profile from Cura . util . resources import getPathForImage try : from opencv import cv from opencv import highgui except : cv = None try : import vidcap as win32vidcap except : win32vidcap = None def hasWebcamSupport ( ) : if cv is None and win32vidcap is None : return False if not os . path . exists ( getFFMPEGpath ( ) ) : return False return True def getFFMPEGpath ( ) : if platform . system ( ) == \"\" : return os . path . normpath ( os . path . join ( os . path . split ( __file__ ) [ ] , \"\" ) ) elif os . path . exists ( '' ) : return '' return os . path . normpath ( os . path . join ( os . path . split ( __file__ ) [ ] , \"\" ) ) class webcam ( object ) : def __init__ ( self ) : self . _cam = None self . _cameraList = None self . _activeId = - self . _overlayImage = wx . Bitmap ( getPathForImage ( '' ) ) self . _overlayUltimaker = wx . Bitmap ( getPathForImage ( '' ) ) self . _doTimelapse = False self . _bitmap = None cameraList = [ ] tryNext = True self . _camId = while tryNext : tryNext = False self . _openCam ( ) if self . _cam is not None : cameraList . append ( self . _cam . getdisplayname ( ) ) tryNext = True del self . _cam self . _cam = None self . _camId += self . _camId = self . _activeId = - self . _cameraList = cameraList def hasCamera ( self ) : return len ( self . _cameraList ) > def listCameras ( self ) : return self . _cameraList def setActiveCamera ( self , cameraIdx ) : self . _camId = cameraIdx def _openCam ( self ) : if self . _cameraList is not None and self . _camId >= len ( self . _cameraList ) : return False if self . _cam is not None : if self . _activeId != self . _camId : del self . _cam self . _cam = None else : return True self . _activeId = self . _camId if cv is not None : self . _cam = highgui . cvCreateCameraCapture ( self . _camId ) elif win32vidcap is not None : try : self . _cam = win32vidcap . new_Dev ( self . _camId , False ) except : pass return self . _cam is not None def propertyPages ( self ) : if cv is not None : return [ ] elif win32vidcap is not None : return [ '' , '' ] def openPropertyPage ( self , pageType = ) : if not self . _openCam ( ) : return if cv is not None : pass elif win32vidcap is not None : if pageType == : self . _cam . displaycapturefilterproperties ( ) else : del self . _cam self . _cam = None tmp = win32vidcap . new_Dev ( , False ) tmp . displaycapturepinproperties ( ) self . _cam = tmp def takeNewImage ( self , withOverlay = True ) : if not self . _openCam ( ) : return if cv is not None : frame = cv . QueryFrame ( self . _cam ) cv . CvtColor ( frame , frame , cv . CV_BGR2RGB ) bitmap = wx . BitmapFromBuffer ( frame . width , frame . height , frame . imageData ) elif win32vidcap is not None : buffer , width , height = self . _cam . getbuffer ( ) try : wxImage = wx . EmptyImage ( width , height ) wxImage . SetData ( buffer [ : : - ] ) wxImage = wxImage . Mirror ( ) if self . _bitmap is not None : del self . _bitmap bitmap = wxImage . ConvertToBitmap ( ) del wxImage del buffer except : ", "answer": "pass"}, {"prompt": " import numpy as np from sklearn . cross_validation import KFold from sklearn . linear_model import LinearRegression , ElasticNet , Lasso , Ridge , ElasticNetCV from sklearn . metrics import mean_squared_error , r2_score from time import time from sklearn . feature_extraction . text import TfidfVectorizer from sklearn . feature_selection import SelectPercentile , f_classif , chi2 from sklearn . feature_selection import SelectKBest , f_regression import pickle from sklearn import preprocessing from sklearn import cross_validation import matplotlib . pyplot as plt from itertools import cycle def plot ( nFeatures , data ) : colors = cycle ( '' ) algorithm = sorted ( data ) fig = plt . figure ( ) ax = fig . add_subplot ( ) for j , c in zip ( algorithm , colors ) : ax . plot ( nFeatures , data [ j ] , label = j , color = c ) ax . scatter ( nFeatures , data [ j ] , color = c ) plt . xlabel ( \"\" ) plt . ylabel ( \"\" ) plt . title ( \"\" ) box = ax . get_position ( ) ", "answer": "ax . set_position ( [ box . x0 , box . y0 + box . height * ,"}, {"prompt": " \"\"\"\"\"\" import subprocess import shlex ", "answer": "import time"}, {"prompt": " from __future__ import absolute_import , division , with_statement from fabric . contrib . console import confirm from fabric . utils import abort , warn ", "answer": "from fabric . utils import fastprint as put_fast"}, {"prompt": " from datetime import datetime import random import string from django . test import TestCase from casexml . apps . case . tests . util import delete_all_xforms from casexml . apps . stock . utils import get_current_ledger_transactions , get_current_ledger_state from corehq . apps . commtrack . models import SQLProduct from casexml . apps . stock . const import REPORT_TYPE_BALANCE from casexml . apps . stock . models import StockReport , StockTransaction from corehq . apps . commtrack . processing import StockProcessingResult from corehq . apps . domain . shortcuts import create_domain from corehq . form_processor . interfaces . processor import FormProcessorInterface from corehq . form_processor . parsers . ledgers . helpers import StockReportHelper , StockTransactionHelper from couchforms . models import XFormInstance DOMAIN_MAX_LENGTH = class StockReportDomainTest ( TestCase ) : def _get_name_for_domain ( self ) : ", "answer": "return '' . join ("}, {"prompt": " '''''' __author__ = \"\" __email__ = \"\" __version__ = \"\" [ : - ] import time import sys import traceback import os import types __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' ] __all__ . extend ( [ '' , '' , '' ] ) if sys . version_info [ : ] < ( , ) : False , True = , def isinstance ( obj , clsinfo ) : import __builtin__ if type ( clsinfo ) in ( tuple , list ) : for cls in clsinfo : if cls is type : cls = types . ClassType if __builtin__ . isinstance ( obj , cls ) : return return else : return __builtin__ . isinstance ( obj , clsinfo ) __metaclass__ = type def _strclass ( cls ) : return \"\" % ( cls . __module__ , cls . __name__ ) __unittest = class TestResult : \"\"\"\"\"\" def __init__ ( self ) : self . failures = [ ] self . errors = [ ] self . testsRun = self . shouldStop = def startTest ( self , test ) : \"\" self . testsRun = self . testsRun + def stopTest ( self , test ) : \"\" pass def addError ( self , test , err ) : \"\"\"\"\"\" self . errors . append ( ( test , self . _exc_info_to_string ( err , test ) ) ) def addFailure ( self , test , err ) : \"\"\"\"\"\" self . failures . append ( ( test , self . _exc_info_to_string ( err , test ) ) ) def addSuccess ( self , test ) : \"\" pass def wasSuccessful ( self ) : \"\" return len ( self . failures ) == len ( self . errors ) == def stop ( self ) : \"\" self . shouldStop = True def _exc_info_to_string ( self , err , test ) : \"\"\"\"\"\" exctype , value , tb = err while tb and self . _is_relevant_tb_level ( tb ) : tb = tb . tb_next if exctype is test . failureException : length = self . _count_relevant_tb_levels ( tb ) return '' . join ( traceback . format_exception ( exctype , value , tb , length ) ) return '' . join ( traceback . format_exception ( exctype , value , tb ) ) def _is_relevant_tb_level ( self , tb ) : return tb . tb_frame . f_globals . has_key ( '' ) def _count_relevant_tb_levels ( self , tb ) : length = while tb and not self . _is_relevant_tb_level ( tb ) : length += ", "answer": "tb = tb . tb_next"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " from ajenti . api import * from ajenti . plugins import * ", "answer": "info = PluginInfo ("}, {"prompt": " \"\"\"\"\"\" import socket , struct from scapy . config import conf from scapy . packet import * from scapy . fields import * from scapy . supersocket import SuperSocket from scapy . data import MTU class HCI_Hdr ( Packet ) : name = \"\" fields_desc = [ ByteEnumField ( \"\" , , { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" } ) , ] def mysummary ( self ) : return self . sprintf ( \"\" ) class HCI_ACL_Hdr ( Packet ) : name = \"\" fields_desc = [ ByteField ( \"\" , ) , ByteField ( \"\" , ) , LEShortField ( \"\" , None ) , ] def post_build ( self , p , pay ) : p += pay if self . len is None : l = len ( p ) - p = p [ : ] + bytes ( [ ( l & ) , ( ( l >> ) & ) ] ) + p [ : ] return p class L2CAP_Hdr ( Packet ) : name = \"\" fields_desc = [ LEShortField ( \"\" , None ) , LEShortEnumField ( \"\" , , { : \"\" } ) , ] def post_build ( self , p , pay ) : p += pay if self . len is None : l = len ( p ) - p = p [ : ] + bytes ( [ ( l & ) , ( ( l >> ) & ) ] ) + p [ : ] return p class L2CAP_CmdHdr ( Packet ) : name = \"\" fields_desc = [ ByteEnumField ( \"\" , , { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" } ) , ByteField ( \"\" , ) , LEShortField ( \"\" , None ) ] def post_build ( self , p , pay ) : p += pay if self . len is None : l = len ( p ) - p = p [ : ] + bytes ( [ ( l & ) , ( ( l >> ) & ) ] ) + p [ : ] return p def answers ( self , other ) : if other . id == self . id : if self . code == : return if other . code in [ , , , , ] and self . code == other . code + : if other . code == : return return self . payload . answers ( other . payload ) return class L2CAP_ConnReq ( Packet ) : name = \"\" fields_desc = [ LEShortEnumField ( \"\" , , { : \"\" , : \"\" , : \"\" } ) , LEShortField ( \"\" , ) , ] class L2CAP_ConnResp ( Packet ) : name = \"\" fields_desc = [ LEShortField ( \"\" , ) , LEShortField ( \"\" , ) , LEShortEnumField ( \"\" , , [ \"\" , \"\" , \"\" ] ) , LEShortEnumField ( \"\" , , [ \"\" , \"\" , \"\" , \"\" , \"\" ] ) , ] def answers ( self , other ) : return self . scid == other . scid class L2CAP_CmdRej ( Packet ) : name = \"\" fields_desc = [ LEShortField ( \"\" , ) , ] class L2CAP_ConfReq ( Packet ) : name = \"\" fields_desc = [ LEShortField ( \"\" , ) , LEShortField ( \"\" , ) , ] class L2CAP_ConfResp ( Packet ) : name = \"\" fields_desc = [ LEShortField ( \"\" , ) , LEShortField ( \"\" , ) , LEShortEnumField ( \"\" , , [ \"\" , \"\" , \"\" , \"\" ] ) , ] def answers ( self , other ) : return self . scid == other . scid class L2CAP_DisconnReq ( Packet ) : name = \"\" fields_desc = [ LEShortField ( \"\" , ) , LEShortField ( \"\" , ) , ] class L2CAP_DisconnResp ( Packet ) : name = \"\" fields_desc = [ LEShortField ( \"\" , ) , LEShortField ( \"\" , ) , ] def answers ( self , other ) : return self . scid == other . scid class L2CAP_InfoReq ( Packet ) : name = \"\" fields_desc = [ LEShortEnumField ( \"\" , , { : \"\" , : \"\" } ) , StrField ( \"\" , \"\" ) ] class L2CAP_InfoResp ( Packet ) : name = \"\" fields_desc = [ LEShortField ( \"\" , ) , LEShortEnumField ( \"\" , , [ \"\" , \"\" ] ) , StrField ( \"\" , \"\" ) , ] def answers ( self , other ) : return self . type == other . type bind_layers ( HCI_Hdr , HCI_ACL_Hdr , type = ) bind_layers ( HCI_Hdr , conf . raw_layer , ) bind_layers ( HCI_ACL_Hdr , L2CAP_Hdr , ) bind_layers ( L2CAP_Hdr , L2CAP_CmdHdr , cid = ) ", "answer": "bind_layers ( L2CAP_CmdHdr , L2CAP_CmdRej , code = )"}, {"prompt": " import pytest from io import BytesIO from thefuck . rules . git_checkout import match , get_branches , get_new_command from tests . utils import Command @ pytest . fixture def did_not_match ( target , did_you_forget = False ) : error = ( \"\" \"\" . format ( target ) ) if did_you_forget : error = ( \"\" . format ( error ) ) return error @ pytest . fixture def git_branch ( mocker , branches ) : mock = mocker . patch ( '' ) mock . return_value . stdout = BytesIO ( branches ) return mock @ pytest . mark . parametrize ( '' , [ Command ( script = '' , stderr = did_not_match ( '' ) ) , Command ( script = '' , stderr = did_not_match ( '' ) ) ] ) def test_match ( command ) : assert match ( command ) @ pytest . mark . parametrize ( '' , [ Command ( script = '' , stderr = did_not_match ( '' , True ) ) , Command ( script = '' , stderr = ( '' ) ) , Command ( script = '' , stderr = ( '' ) ) ] ) def test_not_match ( command ) : assert not match ( command ) @ pytest . mark . parametrize ( '' , [ ( b'' , [ ] ) , ( b'' , [ '' ] ) , ( b'' , [ '' ] ) , ( b'' , [ '' ] ) , ( b'' , [ '' , '' ] ) , ( b'' , [ '' , '' , '' ] ) ] ) def test_get_branches ( branches , branch_list , git_branch ) : ", "answer": "git_branch ( branches )"}, {"prompt": " class GCConnectionStatus : GCConnectionStatus_HAVE_SESSION = GCConnectionStatus_GC_GOING_DOWN = GCConnectionStatus_NO_SESSION = GCConnectionStatus_NO_SESSION_IN_LOGON_QUEUE = GCConnectionStatus_NO_STEAM = class EGCSystemMsg : k_EGCMsgInvalid = k_EGCMsgMulti = k_EGCMsgGenericReply = k_EGCMsgSystemBase = k_EGCMsgAchievementAwarded = k_EGCMsgConCommand = k_EGCMsgStartPlaying = k_EGCMsgStopPlaying = k_EGCMsgStartGameserver = k_EGCMsgStopGameserver = k_EGCMsgWGRequest = k_EGCMsgWGResponse = k_EGCMsgGetUserGameStatsSchema = k_EGCMsgGetUserGameStatsSchemaResponse = k_EGCMsgGetUserStatsDEPRECATED = k_EGCMsgGetUserStatsResponse = k_EGCMsgAppInfoUpdated = k_EGCMsgValidateSession = k_EGCMsgValidateSessionResponse = k_EGCMsgLookupAccountFromInput = k_EGCMsgSendHTTPRequest = k_EGCMsgSendHTTPRequestResponse = k_EGCMsgPreTestSetup = k_EGCMsgRecordSupportAction = k_EGCMsgGetAccountDetails_DEPRECATED = k_EGCMsgReceiveInterAppMessage = k_EGCMsgFindAccounts = k_EGCMsgPostAlert = k_EGCMsgGetLicenses = k_EGCMsgGetUserStats = k_EGCMsgGetCommands = k_EGCMsgGetCommandsResponse = k_EGCMsgAddFreeLicense = k_EGCMsgAddFreeLicenseResponse = k_EGCMsgGetIPLocation = k_EGCMsgGetIPLocationResponse = k_EGCMsgSystemStatsSchema = k_EGCMsgGetSystemStats = k_EGCMsgGetSystemStatsResponse = k_EGCMsgSendEmail = k_EGCMsgSendEmailResponse = k_EGCMsgGetEmailTemplate = k_EGCMsgGetEmailTemplateResponse = k_EGCMsgGrantGuestPass = k_EGCMsgGrantGuestPassResponse = k_EGCMsgGetAccountDetails = k_EGCMsgGetAccountDetailsResponse = k_EGCMsgGetPersonaNames = k_EGCMsgGetPersonaNamesResponse = k_EGCMsgMultiplexMsg = k_EGCMsgWebAPIRegisterInterfaces = k_EGCMsgWebAPIJobRequest = k_EGCMsgWebAPIJobRequestHttpResponse = k_EGCMsgWebAPIJobRequestForwardResponse = k_EGCMsgMemCachedGet = k_EGCMsgMemCachedGetResponse = k_EGCMsgMemCachedSet = k_EGCMsgMemCachedDelete = k_EGCMsgMemCachedStats = k_EGCMsgMemCachedStatsResponse = k_EGCMsgMasterSetDirectory = k_EGCMsgMasterSetDirectoryResponse = k_EGCMsgMasterSetWebAPIRouting = k_EGCMsgMasterSetWebAPIRoutingResponse = k_EGCMsgMasterSetClientMsgRouting = k_EGCMsgMasterSetClientMsgRoutingResponse = k_EGCMsgSetOptions = k_EGCMsgSetOptionsResponse = k_EGCMsgSystemBase2 = k_EGCMsgGetPurchaseTrustStatus = k_EGCMsgGetPurchaseTrustStatusResponse = k_EGCMsgUpdateSession = k_EGCMsgGCAccountVacStatusChange = k_EGCMsgCheckFriendship = k_EGCMsgCheckFriendshipResponse = class ESOMsg : k_ESOMsg_Create = k_ESOMsg_Update = k_ESOMsg_Destroy = k_ESOMsg_CacheSubscribed = k_ESOMsg_CacheUnsubscribed = k_ESOMsg_UpdateMultiple = k_ESOMsg_CacheSubscriptionCheck = k_ESOMsg_CacheSubscriptionRefresh = class EGCBaseClientMsg : k_EMsgGCClientWelcome = k_EMsgGCServerWelcome = k_EMsgGCClientHello = ", "answer": "k_EMsgGCServerHello = "}, {"prompt": " import unittest from zen import * import random import time import gc import sys use_networkx = False try : import networkx use_networkx = True except : pass def timer ( fxn , args ) : gc . disable ( ) t1 = time . time ( ) R = fxn ( * args ) t2 = time . time ( ) gc . enable ( ) return R , ( t2 - t1 ) class TestEigenvectorCentrality ( unittest . TestCase ) : pass class TestBetweennessCentrality ( unittest . TestCase ) : def test_random_dir_weights ( self ) : if not use_networkx : sys . stderr . write ( '' ) return Gnx = networkx . DiGraph ( ) G = DiGraph ( ) nodes = range ( ) random . shuffle ( nodes ) while len ( nodes ) > : n1 = nodes . pop ( ) n2 = nodes . pop ( ) w = random . randint ( , ) eidx = G . add_edge ( n1 , n2 ) G . set_weight_ ( eidx , w ) Gnx . add_edge ( n1 , n2 , weight = w ) nodes = range ( ) random . shuffle ( nodes ) while len ( nodes ) > : n1 = nodes . pop ( ) n2 = nodes . pop ( ) if not G . has_edge ( n1 , n2 ) : w = random . randint ( , ) eidx = G . add_edge ( n1 , n2 ) G . set_weight_ ( eidx , w ) Gnx . add_edge ( n1 , n2 , weight = w ) R = betweenness_centrality_ ( G , True , True ) Rnx = networkx . betweenness_centrality ( Gnx , normalized = True , weight = '' ) for n in G . nodes_iter ( ) : self . assertAlmostEqual ( Rnx [ n ] , R [ G . node_idx ( n ) ] ) def test_random_dir_noweights ( self ) : if not use_networkx : sys . stderr . write ( '' ) return Gnx = networkx . DiGraph ( ) G = DiGraph ( ) nodes = range ( ) random . shuffle ( nodes ) while len ( nodes ) > : n1 = nodes . pop ( ) n2 = nodes . pop ( ) w = random . randint ( , ) eidx = G . add_edge ( n1 , n2 ) G . set_weight_ ( eidx , w ) Gnx . add_edge ( n1 , n2 , weight = w ) nodes = range ( ) random . shuffle ( nodes ) while len ( nodes ) > : n1 = nodes . pop ( ) n2 = nodes . pop ( ) if not G . has_edge ( n1 , n2 ) : w = random . randint ( , ) eidx = G . add_edge ( n1 , n2 ) G . set_weight_ ( eidx , w ) Gnx . add_edge ( n1 , n2 , weight = w ) R = betweenness_centrality_ ( G , True , False ) Rnx = networkx . betweenness_centrality ( Gnx , normalized = True , weight = None ) for n in G . nodes_iter ( ) : self . assertAlmostEqual ( Rnx [ n ] , R [ G . node_idx ( n ) ] ) def test_random_udir_weights ( self ) : if not use_networkx : sys . stderr . write ( '' ) return Gnx = networkx . Graph ( ) G = Graph ( ) ", "answer": "nodes = range ( )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import heapq from ipyparallel . error import RemoteError def mergesort ( list_of_lists , key = None ) : \"\"\"\"\"\" heap = [ ] for i , itr in enumerate ( iter ( pl ) for pl in list_of_lists ) : try : item = next ( itr ) if key : toadd = ( key ( item ) , i , item , itr ) else : toadd = ( item , i , itr ) heap . append ( toadd ) except StopIteration : pass heapq . heapify ( heap ) if key : ", "answer": "while heap :"}, {"prompt": " \"\"\"\"\"\" from traits . api import Interface , List from . action_set import ActionSet class IActionManagerBuilder ( Interface ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" import new import os ", "answer": "import sys"}, {"prompt": " import os from . list_databases_command import ListDatabasesCommand from . run_file_command import RunFileCommand from . ml_lint_command import mlLintCommand from . mark_logic_auto_complete import MarkLogicAutoComplete from . open_help_command import OpenHelpCommand from . open_help_search_command import OpenHelpSearchCommand from . ml_set_content_database_command import mlSetContentDatabaseCommand from . ml_set_modules_database_command import mlSetModulesDatabaseCommand from . ml_toggle_lint_command import mlToggleLintCommand from . ml_open_options_command import mlOpenOptionsCommand from . ml_event_listeners import mlEventListeners __all__ = [ '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" import unittest from ganeti import constants from ganeti . cmdlib import instance_storage from ganeti import errors from ganeti import objects from ganeti import opcodes import testutils import mock import time from testsupport import CmdlibTestCase class TestCheckNodesFreeDiskOnVG ( unittest . TestCase ) : def setUp ( self ) : self . node_uuid = \"\" self . node_uuids = [ self . node_uuid ] self . node_info = mock . Mock ( ) self . es = True self . ndparams = { constants . ND_EXCLUSIVE_STORAGE : self . es } mock_rpc = mock . Mock ( ) mock_rpc . call_node_info = mock . Mock ( ) mock_cfg = mock . Mock ( ) mock_cfg . GetNodeInfo = mock . Mock ( return_value = self . node_info ) mock_cfg . GetNdParams = mock . Mock ( return_value = self . ndparams ) self . hvname = \"\" self . hvparams = mock . Mock ( ) self . clusterinfo = mock . Mock ( ) self . clusterinfo . hvparams = { self . hvname : self . hvparams } mock_cfg . GetHypervisorType = mock . Mock ( return_value = self . hvname ) mock_cfg . GetClusterInfo = mock . Mock ( return_value = self . clusterinfo ) self . lu = mock . Mock ( ) self . lu . rpc = mock_rpc self . lu . cfg = mock_cfg self . vg = \"\" self . node_name = \"\" self . space_info = [ { \"\" : constants . ST_LVM_VG , \"\" : self . vg , \"\" : , \"\" : } ] def testPerformNodeInfoCall ( self ) : expected_hv_arg = [ ( self . hvname , self . hvparams ) ] expected_storage_arg = { self . node_uuid : [ ( constants . ST_LVM_VG , self . vg , [ self . es ] ) , ( constants . ST_LVM_PV , self . vg , [ self . es ] ) ] } instance_storage . _PerformNodeInfoCall ( self . lu , self . node_uuids , self . vg ) self . lu . rpc . call_node_info . assert_called_with ( self . node_uuids , expected_storage_arg , expected_hv_arg ) def testCheckVgCapacityForNode ( self ) : requested = node_info = ( None , self . space_info , None ) instance_storage . _CheckVgCapacityForNode ( self . node_name , node_info , self . vg , requested ) def testCheckVgCapacityForNodeNotEnough ( self ) : requested = node_info = ( None , self . space_info , None ) self . assertRaises ( errors . OpPrereqError , instance_storage . _CheckVgCapacityForNode , self . node_name , node_info , self . vg , requested ) def testCheckVgCapacityForNodeNoStorageData ( self ) : node_info = ( None , [ ] , None ) self . assertRaises ( errors . OpPrereqError , instance_storage . _CheckVgCapacityForNode , self . node_name , node_info , self . vg , NotImplemented ) def testCheckVgCapacityForNodeBogusSize ( self ) : broken_space_info = [ { \"\" : constants . ST_LVM_VG , \"\" : self . vg , \"\" : \"\" , \"\" : \"\" } ] node_info = ( None , broken_space_info , None ) self . assertRaises ( errors . OpPrereqError , instance_storage . _CheckVgCapacityForNode , self . node_name , node_info , self . vg , NotImplemented ) class TestCheckComputeDisksInfo ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from pysb import * ", "answer": "Model ( ) "}, {"prompt": " import logging from xml . dom import minidom , Node from xml . parsers . expat import ExpatError , ErrorString class GoodReadsParser ( object ) : def parse_result ( self , url_handler ) : try : goodreads_dom = minidom . parse ( url_handler ) return goodreads_dom except ExpatError , e : logging . error ( \"\" % ( ErrorString ( e . code ) , e . lineno , e . offset ) ) return None def get_text ( self , element ) : value = \"\" for text in element . childNodes : try : value += text . data except AttributeError : logging . error ( \"\" + text . toxml ( ) ) raise if value : return value . strip ( ) else : return None def parse_books ( self , url_handler ) : goodreads_dom = self . parse_result ( url_handler ) books = [ ] for book_element in goodreads_dom . getElementsByTagName ( \"\" ) : ", "answer": "book = self . handle_book ( book_element )"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( u'' , '' , self . gf ( '' ) ( default = , related_name = u'' , on_delete = models . PROTECT , to = orm [ '' ] ) , keep_default = False ) db . execute ( \"\" ) def backwards ( self , orm ) : db . delete_column ( u'' , '' ) models = { u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' } ) } , u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , ", "answer": "u'' : ( '' , [ ] , { '' : '' } ) ,"}, {"prompt": " \"\"\"\"\"\" from xml . etree import ElementTree import subprocess import os import glob import re import time import libvirt from ovs . extensions . generic . sshclient import SSHClient from ovs . extensions . generic . system import System from ovs . log . logHandler import LogHandler logger = LogHandler . get ( '' , name = '' ) ROOT_PATH = '' RUN_PATH = '' def _recurse ( treeitem ) : result = { } for key , item in treeitem . items ( ) : result [ key ] = item for child in treeitem . getchildren ( ) : result [ child . tag ] = _recurse ( child ) for key , item in child . items ( ) : result [ child . tag ] [ key ] = item result [ child . tag ] [ '' ] = child . text return result def authenticated ( function ) : \"\"\"\"\"\" def new_function ( self , * args , ** kwargs ) : self . __doc__ = function . __doc__ try : if self . _conn is None : self . _connect ( ) return function ( self , * args , ** kwargs ) finally : try : self . _disconnect ( ) except : pass return new_function class Sdk ( object ) : \"\"\"\"\"\" def __init__ ( self , host = '' , login = '' ) : logger . debug ( '' ) self . states = { libvirt . VIR_DOMAIN_NOSTATE : '' , libvirt . VIR_DOMAIN_RUNNING : '' , libvirt . VIR_DOMAIN_BLOCKED : '' , libvirt . VIR_DOMAIN_PAUSED : '' , libvirt . VIR_DOMAIN_SHUTDOWN : '' , libvirt . VIR_DOMAIN_SHUTOFF : '' , libvirt . VIR_DOMAIN_CRASHED : '' } self . libvirt = libvirt self . host = host self . login = login self . _conn = None self . ssh_client = SSHClient ( self . host , username = '' ) logger . debug ( '' ) def _connect ( self , attempt = ) : if self . _conn : self . _disconnect ( ) logger . debug ( '' , self . host , self . login , os . getgid ( ) , os . getuid ( ) ) try : if self . host . lower ( ) in [ '' , '' ] : self . host = '' self . _conn = self . libvirt . open ( '' ) else : self . _conn = self . libvirt . open ( '' . format ( self . login , self . host ) ) except self . libvirt . libvirtError as le : logger . error ( '' , str ( le ) , le . get_error_code ( ) ) if attempt < : time . sleep ( ) self . _connect ( attempt + ) else : raise return True def _disconnect ( self ) : logger . debug ( '' ) if self . _conn : try : self . _conn . close ( ) except self . libvirt . libvirtError as le : logger . error ( '' , str ( le ) , le . get_error_code ( ) ) self . _conn = None return True @ authenticated def test_connection ( self ) : \"\"\"\"\"\" _ = self return True @ staticmethod def _get_disks ( vm_object ) : tree = ElementTree . fromstring ( vm_object . XMLDesc ( ) ) return [ _recurse ( item ) for item in tree . findall ( '' ) ] @ staticmethod def _get_nics ( vm_object ) : tree = ElementTree . fromstring ( vm_object . XMLDesc ( ) ) return [ _recurse ( item ) for item in tree . findall ( '' ) ] @ staticmethod def _get_nova_name ( vm_object ) : tree = ElementTree . fromstring ( vm_object . XMLDesc ( ) ) metadata = tree . findall ( '' ) [ ] nova_instance_namespace_tag = metadata . getchildren ( ) [ ] . tag nova_instance_namespace = nova_instance_namespace_tag [ nova_instance_namespace_tag . find ( '' ) + : nova_instance_namespace_tag . find ( '' ) ] instance = metadata . findall ( '' % nova_instance_namespace ) [ ] name = instance . findall ( '' % nova_instance_namespace ) [ ] return name . text @ staticmethod def _get_ram ( vm_object ) : \"\"\"\"\"\" tree = ElementTree . fromstring ( vm_object . XMLDesc ( ) ) mem = tree . findall ( '' ) [ ] unit = mem . items ( ) [ ] [ ] value = mem . text if unit == '' : return int ( value ) elif unit == '' : return int ( value ) / elif unit == '' : return int ( value ) * @ staticmethod def _get_disk_size ( filename ) : cmd = [ '' , '' , filename ] try : out = subprocess . check_output ( '' . join ( cmd ) , stderr = subprocess . STDOUT , shell = True ) except subprocess . CalledProcessError as cpe : return cpe . output . strip ( ) out = out . split ( '' ) for line in out : if line . startswith ( '' ) : size = line . split ( '' ) [ ] . split ( '' ) [ ] return size return def _get_vm_pid ( self , vm_object ) : \"\"\"\"\"\" if self . get_power_state ( vm_object . name ( ) ) == '' : pid_path = '' . format ( RUN_PATH , vm_object . name ( ) ) try : with open ( pid_path , '' ) as pid_file : pid = pid_file . read ( ) return int ( pid ) except IOError : return '' return '' @ authenticated def make_agnostic_config ( self , vm_object ) : \"\"\"\"\"\" storage_ip = '' regex = '' config = { '' : [ ] } mountpoints = [ ] order = for disk in Sdk . _get_disks ( vm_object ) : if disk [ '' ] == '' : continue if '' in disk [ '' ] : backingfilename = disk [ '' ] [ '' ] elif '' in disk [ '' ] : backingfilename = disk [ '' ] [ '' ] else : continue match = re . search ( regex , backingfilename ) if match is None : continue mountpoint = '' . format ( match . group ( ) ) filename = backingfilename . replace ( mountpoint , '' ) . strip ( '' ) diskname = filename . split ( '' ) [ - ] . split ( '' ) [ ] config [ '' ] . append ( { '' : filename , '' : filename , '' : mountpoint , '' : diskname , '' : order } ) order += mountpoints . append ( mountpoint ) if self . ssh_client is None : self . ssh_client = SSHClient ( self . host , username = '' ) vm_filename = self . ssh_client . run ( \"\" . format ( vm_object . UUIDString ( ) , ROOT_PATH ) ) vm_filename = vm_filename . strip ( ) . split ( '' ) [ - ] vm_location = System . get_my_machine_id ( self . ssh_client ) vm_datastore = None possible_datastores = self . ssh_client . run ( \"\" . format ( vm_filename ) ) . split ( '' ) for datastore in possible_datastores : if '' . format ( vm_location , vm_filename ) in datastore . strip ( ) : for mountpoint in mountpoints : if mountpoint in datastore . strip ( ) : vm_datastore = mountpoint try : config [ '' ] = self . _get_nova_name ( vm_object ) except Exception as ex : logger . debug ( '' . format ( ex ) ) config [ '' ] = vm_object . name ( ) config [ '' ] = str ( vm_object . UUIDString ( ) ) config [ '' ] = { '' : '' . format ( vm_location , vm_filename ) , '' : vm_datastore } config [ '' ] = dict ( ( mountpoint , '' . format ( storage_ip , mountpoint ) ) for mountpoint in mountpoints ) return config @ authenticated def get_power_state ( self , vmid ) : \"\"\"\"\"\" vm = self . get_vm_object ( vmid ) state = vm . info ( ) [ ] return self . states . get ( state , '' ) @ authenticated def get_vm_object ( self , vmid ) : \"\"\"\"\"\" func = '' try : import uuid uuid . UUID ( vmid ) except ValueError : func = '' try : return getattr ( self . _conn , func ) ( vmid ) except self . libvirt . libvirtError as le : logger . error ( str ( le ) ) try : self . _connect ( ) return getattr ( self . _conn , func ) ( vmid ) except self . libvirt . libvirtError as le : logger . error ( str ( le ) ) raise RuntimeError ( '' . format ( vmid ) ) def get_vm_object_by_filename ( self , filename ) : \"\"\"\"\"\" vmid = filename . split ( '' ) [ - ] . replace ( '' , '' ) return self . get_vm_object ( vmid ) @ authenticated def get_vms ( self ) : \"\"\"\"\"\" return self . _conn . listAllDomains ( ) def shutdown ( self , vmid ) : \"\"\"\"\"\" vm_object = self . get_vm_object ( vmid ) vm_object . shutdown ( ) return self . get_power_state ( vmid ) @ authenticated def delete_vm ( self , vmid , devicename , disks_info ) : \"\"\"\"\"\" if self . ssh_client is None : self . ssh_client = SSHClient ( self . host , username = '' ) vm_object = None try : vm_object = self . get_vm_object ( vmid ) except Exception as ex : logger . error ( '' . format ( ex ) ) found_files = self . find_devicename ( devicename ) if found_files is not None : for found_file in found_files : self . ssh_client . file_delete ( found_file ) logger . info ( '' . format ( found_file ) ) if vm_object : found_file = '' for disk in self . _get_disks ( vm_object ) : if disk [ '' ] == '' : continue if '' in disk [ '' ] : found_file = disk [ '' ] [ '' ] elif '' in disk [ '' ] : found_file = disk [ '' ] [ '' ] if found_file and os . path . exists ( found_file ) and os . path . isfile ( found_file ) : self . ssh_client . file_delete ( found_file ) logger . info ( '' . format ( found_file ) ) vm_object . undefine ( ) elif disks_info : for path , devicename in disks_info : found_file = '' . format ( path , devicename ) if os . path . exists ( found_file ) and os . path . isfile ( found_file ) : self . ssh_client . file_delete ( found_file ) logger . info ( '' . format ( found_file ) ) return True def power_on ( self , vmid ) : \"\"\"\"\"\" vm_object = self . get_vm_object ( vmid ) vm_object . create ( ) return self . get_power_state ( vmid ) def find_devicename ( self , devicename ) : \"\"\"\"\"\" _ = self file_matcher = '' . format ( devicename ) matches = [ ] for found_file in glob . glob ( file_matcher ) : if os . path . exists ( found_file ) and os . path . isfile ( found_file ) : matches . append ( found_file ) return matches if matches else None def is_datastore_available ( self , mountpoint ) : \"\"\"\"\"\" if self . ssh_client is None : self . ssh_client = SSHClient ( self . host , username = '' ) return self . ssh_client . run ( \"\" . format ( mountpoint ) ) == '' @ authenticated def clone_vm ( self , vmid , name , disks , mountpoint ) : \"\"\"\"\"\" source_vm = self . get_vm_object ( vmid ) return self . create_vm_from_template ( name , source_vm , disks , mountpoint ) def create_volume ( self , location , size ) : \"\"\"\"\"\" if self . ssh_client . file_exists ( location ) : raise RuntimeError ( '' % location ) command = '' . format ( size , location ) output = self . ssh_client . run ( command ) if not self . ssh_client . file_exists ( location ) : raise RuntimeError ( '' % ( location , output ) ) logger . info ( '' . format ( command , output ) ) def delete_volume ( self , location ) : \"\"\"\"\"\" if not self . ssh_client . file_exists ( location ) : logger . error ( '' % location ) return command = '' . format ( location ) output = self . ssh_client . run ( command ) logger . info ( '' . format ( command , output ) ) if self . ssh_client . file_exists ( location ) : raise RuntimeError ( '' % ( location , output ) ) def extend_volume ( self , location , size ) : \"\"\"\"\"\" if not self . ssh_client . file_exists ( location ) : ", "answer": "raise RuntimeError ( '' % location )"}, {"prompt": " from __future__ import unicode_literals , absolute_import from py4j . java_gateway import JavaGateway , GatewayParameters from py4j . tests . java_gateway_test import ( start_example_app_process ) ", "answer": "from contextlib import contextmanager"}, {"prompt": " from aliyunsdkcore . request import RpcRequest class DescribeImageSharePermissionRequest ( RpcRequest ) : def __init__ ( self ) : RpcRequest . __init__ ( self , '' , '' , '' ) def get_OwnerId ( self ) : return self . get_query_params ( ) . get ( '' ) def set_OwnerId ( self , OwnerId ) : self . add_query_param ( '' , OwnerId ) def get_ResourceOwnerAccount ( self ) : return self . get_query_params ( ) . get ( '' ) def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : self . add_query_param ( '' , ResourceOwnerAccount ) def get_ResourceOwnerId ( self ) : return self . get_query_params ( ) . get ( '' ) def set_ResourceOwnerId ( self , ResourceOwnerId ) : self . add_query_param ( '' , ResourceOwnerId ) def get_ImageId ( self ) : return self . get_query_params ( ) . get ( '' ) def set_ImageId ( self , ImageId ) : self . add_query_param ( '' , ImageId ) def get_PageNumber ( self ) : return self . get_query_params ( ) . get ( '' ) def set_PageNumber ( self , PageNumber ) : self . add_query_param ( '' , PageNumber ) def get_PageSize ( self ) : return self . get_query_params ( ) . get ( '' ) def set_PageSize ( self , PageSize ) : self . add_query_param ( '' , PageSize ) ", "answer": "def get_OwnerAccount ( self ) :"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) from unittest import expectedFailure from pants . core_tasks . list_goals import ListGoals from pants . goal . goal import Goal from pants_test . tasks . task_test_base import ConsoleTaskTestBase class ListGoalsTest ( ConsoleTaskTestBase ) : _INSTALLED_HEADER = '' _UNDOCUMENTED_HEADER = '' _LIST_GOALS_NAME = '' _LIST_GOALS_DESC = '' _LLAMA_NAME = '' _LLAMA_DESC = '' _ALPACA_NAME = '' @ classmethod def task_type ( cls ) : return ListGoals def test_list_goals ( self ) : Goal . clear ( ) self . assert_console_output ( self . _INSTALLED_HEADER ) Goal . register ( self . _LIST_GOALS_NAME , self . _LIST_GOALS_DESC ) self . assert_console_output ( self . _INSTALLED_HEADER , ", "answer": "'' . format ( self . _LIST_GOALS_NAME , self . _LIST_GOALS_DESC ) ,"}, {"prompt": " from unittest import TestCase from multimodal . lib . utils import random_split , leave_one_out class TestRandomSplit ( TestCase ) : n = ratio = def test_returns_train_test ( self ) : self . assertTrue ( all ( [ len ( x ) == for x in random_split ( self . n , self . ratio ) ] ) ) def test_returns_10_sets ( self ) : self . assertEqual ( , len ( [ x for x in random_split ( self . n , ) ] ) ) def test_returns_9_sets ( self ) : self . assertEqual ( , len ( [ x for x in random_split ( self . n , ) ] ) ) def test_are_disjoint ( self ) : self . assertTrue ( all ( [ set ( test ) . isdisjoint ( set ( train ) ) for train , test in random_split ( self . n , self . ratio ) ] ) ) def test_have_all_same_size ( self ) : sizes = [ ( len ( train ) , len ( test ) ) for train , test in random_split ( self . n , self . ratio ) ] self . assertEqual ( len ( set ( sizes ) ) , ) class TestRandomSplit2 ( TestRandomSplit ) : n = class TestLeaveOneOut ( TestCase ) : n = def test_returns_train_test ( self ) : self . assertTrue ( all ( [ len ( x ) == for x in leave_one_out ( self . n ) ] ) ) def test_returns_37_sets ( self ) : self . assertEqual ( , len ( [ x for x in leave_one_out ( self . n ) ] ) ) def test_are_disjoint ( self ) : self . assertTrue ( all ( [ set ( test ) . isdisjoint ( set ( train ) ) for train , test in leave_one_out ( self . n ) ] ) ) def test_have_all_same_size ( self ) : ", "answer": "sizes = [ ( len ( train ) , len ( test ) )"}, {"prompt": " \"\"\"\"\"\" __author__ = \"\" __email__ = \"\" __version__ = \"\" ", "answer": "__url__ = \"\""}, {"prompt": " \"\"\"\"\"\" from django . conf import settings from django . core . urlresolvers import reverse from django_openstack import models from django_openstack . nova . tests . base import BaseViewTests class CredentialViewTests ( BaseViewTests ) : def test_download_expired_credentials ( self ) : auth_token = '' self . mox . StubOutWithMock ( models . CredentialsAuthorization , '' ) models . CredentialsAuthorization . get_by_token ( auth_token ) . AndReturn ( None ) self . mox . ReplayAll ( ) res = self . client . get ( reverse ( '' , args = [ auth_token ] ) ) self . assertTemplateUsed ( res , '' ) self . mox . VerifyAll ( ) def test_download_good_credentials ( self ) : auth_token = '' creds = models . CredentialsAuthorization ( ) creds . username = '' creds . project = '' creds . auth_token = auth_token self . mox . StubOutWithMock ( models . CredentialsAuthorization , '' ) self . mox . StubOutWithMock ( creds , '' ) ", "answer": "models . CredentialsAuthorization . get_by_token ( auth_token ) . AndReturn ( creds )"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = ", "answer": "result . stfName ( \"\" , \"\" )"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . rename_column ( '' , '' , '' ) def backwards ( self , orm ) : db . rename_column ( '' , '' , '' ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' } ) ,"}, {"prompt": " from __future__ import print_function import dxpy import sys import magic import subprocess import argparse parser = argparse . ArgumentParser ( description = '' ) parser . add_argument ( '' , help = '' ) parser . add_argument ( '' , help = '' ) parser . add_argument ( '' , dest = '' , default = '' , help = '' ) parser . add_argument ( '' , default = None , help = '' ) parser . add_argument ( '' , default = [ ] , action = '' , help = '' ) parser . add_argument ( '' , default = [ ] , action = '' , help = '' ) parser . add_argument ( '' , default = [ ] , action = '' , help = '' ) parser . add_argument ( '' , default = [ ] , action = '' , help = '' ) @ dxpy . entry_point ( '' ) def importGTF ( ** args ) : if len ( args ) == : command_line_args = parser . parse_args ( sys . argv [ : ] ) fileName = command_line_args . fileName reference = command_line_args . reference outputName = command_line_args . outputName tag = command_line_args . tag property_key = command_line_args . property_key property_value = command_line_args . property_value additional_type = command_line_args . additional_type file_id = command_line_args . file_id else : fileName = args [ '' ] reference = args [ '' ] outputName = '' if args . get ( '' ) != None : outputName = args [ '' ] tag = [ ] if args . get ( '' ) : tag = args [ '' ] if args . get ( '' ) != None : property_key = args [ '' ] if args . get ( '' ) != None : property_value = args [ '' ] if args . get ( '' ) != None : additional_type = args [ '' ] if args . get ( '' ) != None : file_id = args [ '' ] inputFileName = unpack ( fileName ) capturedTypes = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } spansTable , additionalColumns = constructTable ( inputFileName ) spansTable . add_tags ( tag ) types = [ \"\" , \"\" ] for x in additional_type : types . append ( x ) spansTable . add_types ( types ) details = { '' : dxpy . dxlink ( reference ) } if len ( property_key ) != len ( property_value ) : raise dxpy . AppError ( \"\" ) for i in range ( len ( property_key ) ) : details [ property_key [ i ] ] = property_value [ i ] for x in additional_type : types . append ( x ) if file_id != None : details [ '' ] = dxpy . dxlink ( file_id ) spansTable . set_details ( details ) if outputName == '' : spansTable . rename ( fileName ) else : spansTable . rename ( outputName ) genes = { } transcripts = { } spanId = frames = { } stopCodons = { } inputFile = open ( inputFileName , '' ) for line in inputFile : if line [ ] != \"\" : values = parseLine ( line , capturedTypes ) if values [ \"\" ] == \"\" : if frames . get ( values [ \"\" ] ) == None : frames [ values [ \"\" ] ] = { } frames [ values [ \"\" ] ] [ values [ \"\" ] ] = values [ \"\" ] for [ element , hashId , elementType ] in [ [ genes , values [ \"\" ] , \"\" ] , [ transcripts , values [ \"\" ] , \"\" ] ] : if element . get ( hashId ) == None : element [ hashId ] = { values [ \"\" ] : { \"\" : values [ \"\" ] , \"\" : values [ \"\" ] , \"\" : - , \"\" : - , \"\" : values [ \"\" ] , \"\" : values [ \"\" ] , \"\" : values [ \"\" ] , \"\" : False , \"\" : spanId , \"\" : values [ elementType ] , \"\" : values [ \"\" ] [ \"\" ] , \"\" : values [ \"\" ] [ \"\" ] } } spanId += elif element [ hashId ] . get ( values [ \"\" ] ) == None : element [ hashId ] [ values [ \"\" ] ] = { \"\" : values [ \"\" ] , \"\" : values [ \"\" ] , \"\" : - , \"\" : - , \"\" : values [ \"\" ] , \"\" : values [ \"\" ] , \"\" : values [ \"\" ] , \"\" : False , \"\" : spanId , \"\" : values [ elementType ] , \"\" : values [ \"\" ] [ \"\" ] , \"\" : values [ \"\" ] [ \"\" ] } spanId += else : if values [ \"\" ] < element [ hashId ] [ values [ \"\" ] ] [ \"\" ] : element [ hashId ] [ values [ \"\" ] ] [ \"\" ] = values [ \"\" ] if values [ \"\" ] > element [ hashId ] [ values [ \"\" ] ] [ \"\" ] : element [ hashId ] [ values [ \"\" ] ] [ \"\" ] = values [ \"\" ] if values [ \"\" ] == \"\" : if stopCodons . get ( values [ \"\" ] ) == None : stopCodons [ values [ \"\" ] ] = [ [ values [ \"\" ] , values [ \"\" ] ] ] else : stopCodons [ values [ \"\" ] ] . append ( [ values [ \"\" ] , values [ \"\" ] ] ) if values [ \"\" ] == \"\" or values [ \"\" ] == \"\" or values [ \"\" ] == \"\" : if values [ \"\" ] > transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] : transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] = values [ \"\" ] if values [ \"\" ] < transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] or transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] == - : transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] = values [ \"\" ] genes [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] = True transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] = True for gId , chrList in genes . iteritems ( ) : for k , v in chrList . iteritems ( ) : entry = [ k , v [ \"\" ] , v [ \"\" ] , v [ \"\" ] , v [ \"\" ] , \"\" , v [ \"\" ] , v [ \"\" ] , v [ \"\" ] , - , - , '' , '' , v [ \"\" ] , '' ] for x in additionalColumns : if x != \"\" and x != \"\" : entry . append ( '' ) spansTable . add_rows ( [ entry ] ) for gId , chrList in transcripts . iteritems ( ) : for k , v in chrList . iteritems ( ) : entry = [ k , v [ \"\" ] , v [ \"\" ] , v [ \"\" ] , v [ \"\" ] , \"\" , v [ \"\" ] , v [ \"\" ] , genes [ v [ \"\" ] ] [ k ] [ \"\" ] , genes [ v [ \"\" ] ] [ k ] [ \"\" ] , - , '' , '' , v [ \"\" ] , v [ \"\" ] ] for x in additionalColumns : if x != \"\" and x != \"\" : entry . append ( '' ) spansTable . add_rows ( [ entry ] ) exons = { } inputFile = open ( inputFileName , '' ) for line in inputFile : if line [ ] != \"\" : values = parseLine ( line , capturedTypes ) if exons . get ( values [ \"\" ] ) != None : if exons [ values [ \"\" ] ] . get ( values [ \"\" ] ) == None : exons [ values [ \"\" ] ] [ values [ \"\" ] ] = [ ] else : exons [ values [ \"\" ] ] = { values [ \"\" ] : [ ] } if capturedTypes . get ( values [ \"\" ] ) != None : if values [ \"\" ] == \"\" or values [ \"\" ] == \"\" or values [ \"\" ] == \"\" or values [ \"\" ] == \"\" or values [ \"\" ] == \"\" : writeEntry ( spansTable , spanId , exons [ values [ \"\" ] ] , additionalColumns , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , [ values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , spanId , capturedTypes [ values [ \"\" ] ] , values [ \"\" ] , values [ \"\" ] , False , transcripts [ values [ \"\" ] ] [ \"\" ] , values [ \"\" ] , '' , values [ \"\" ] ] ) if \"\" in values [ \"\" ] : values [ \"\" ] += \"\" + values [ \"\" ] [ \"\" ] if values [ \"\" ] == \"\" : if stopCodons . get ( values [ \"\" ] ) != None : for x in stopCodons [ values [ \"\" ] ] : if values [ \"\" ] == x [ ] : values [ \"\" ] = x [ ] break if [ values [ \"\" ] , values [ \"\" ] ] not in exons [ values [ \"\" ] ] [ values [ \"\" ] ] : spanId = writeEntry ( spansTable , spanId , exons [ values [ \"\" ] ] , additionalColumns , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , [ values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , spanId , capturedTypes [ values [ \"\" ] ] , values [ \"\" ] , values [ \"\" ] , True , transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] , values [ \"\" ] , '' , values [ \"\" ] ] ) if values [ \"\" ] == \"\" : values [ \"\" ] = \"\" values [ \"\" ] = - ( values [ \"\" ] - values [ \"\" ] ) if values [ \"\" ] == \"\" : if ( transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] != - and transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] != - ) : if frames . get ( values [ \"\" ] ) != None : if frames [ values [ \"\" ] ] . get ( values [ \"\" ] ) != None : values [ \"\" ] = frames [ values [ \"\" ] ] [ values [ \"\" ] ] for x in splitExons ( transcripts [ values [ \"\" ] ] , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] ) : spanId = writeEntry ( spansTable , spanId , exons [ values [ \"\" ] ] , additionalColumns , values [ \"\" ] , x [ ] , x [ ] , values [ \"\" ] , [ values [ \"\" ] , x [ ] , x [ ] , values [ \"\" ] , spanId , x [ ] , values [ \"\" ] , values [ \"\" ] , x [ ] , transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] , values [ \"\" ] , '' , values [ \"\" ] ] ) else : spanId = writeEntry ( spansTable , spanId , exons [ values [ \"\" ] ] , additionalColumns , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , [ values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , values [ \"\" ] , spanId , capturedTypes [ values [ \"\" ] ] , values [ \"\" ] , values [ \"\" ] , False , transcripts [ values [ \"\" ] ] [ values [ \"\" ] ] [ \"\" ] , values [ \"\" ] , '' , values [ \"\" ] ] ) spansTable . flush ( ) spansTable . close ( ) outputFile = open ( \"\" , '' ) outputFile . write ( spansTable . get_id ( ) ) outputFile . close ( ) print ( spansTable . get_id ( ) ) return spansTable . get_id ( ) def writeEntry ( spansTable , spanId , exonInfo , additionalColumns , chromosome , lo , hi , attributes , entry ) : if [ lo , hi ] not in exonInfo [ chromosome ] and [ lo , hi - ] not in exonInfo [ chromosome ] : checkOverlap = trimOverlap ( exonInfo [ chromosome ] , lo , hi ) if checkOverlap [ \"\" ] - checkOverlap [ \"\" ] > : entry [ ] = checkOverlap [ \"\" ] entry [ ] = checkOverlap [ \"\" ] if entry [ ] == \"\" : entry [ ] = int ( entry [ ] ) + checkOverlap [ \"\" ] % else : entry [ ] = int ( entry [ ] ) + checkOverlap [ \"\" ] % exonInfo [ chromosome ] . append ( [ lo , hi ] ) spanId += for x in additionalColumns : if attributes . get ( x ) != None : entry . append ( attributes [ x ] ) else : entry . append ( '' ) spansTable . add_rows ( [ entry ] ) return spanId def trimOverlap ( exons , lo , hi ) : loChange = hiChange = for x in exons : if lo >= x [ ] and lo <= x [ ] : loChange = x [ ] - lo lo = x [ ] if hi >= x [ ] and hi <= x [ ] : hiChange = hi - x [ ] hi = x [ ] return { \"\" : lo , \"\" : hi , \"\" : loChange , \"\" : hiChange } def splitExons ( transcriptInfo , chromosome , lo , hi , strand ) : upstream = \"\" downstream = \"\" if strand == \"\" : upstream = \"\" downstream = \"\" result = [ [ \"\" , lo , hi , True ] ] if hi < transcriptInfo [ chromosome ] [ \"\" ] : result [ ] [ ] = upstream elif lo > transcriptInfo [ chromosome ] [ \"\" ] : result [ ] [ ] = downstream if lo < transcriptInfo [ chromosome ] [ \"\" ] : result [ ] [ ] = transcriptInfo [ chromosome ] [ \"\" ] result . append ( [ upstream , lo , transcriptInfo [ chromosome ] [ \"\" ] , False ] ) if hi > transcriptInfo [ chromosome ] [ \"\" ] : result [ ] [ ] = transcriptInfo [ chromosome ] [ \"\" ] result . append ( [ downstream , transcriptInfo [ chromosome ] [ \"\" ] , hi , False ] ) return result def parseLine ( line , capturedTypes ) : tabSplit = line . split ( \"\" ) if len ( tabSplit ) == : tabSplit = line . split ( \"\" ) if len ( tabSplit ) < : raise dxpy . AppError ( \"\" + line ) tabSplit [ ] = \"\" . join ( tabSplit [ : ] ) tabSplit = tabSplit [ : ] chromosome = tabSplit [ ] source = tabSplit [ ] typ = tabSplit [ ] if capturedTypes . get ( typ ) == None : message = '' + \"\" . join ( capturedTypes . keys ( ) ) raise dxpy . AppError ( \"\" + message + \"\" + line + \"\" + typ ) try : score = float ( tabSplit [ ] ) except ValueError : if tabSplit [ ] == \"\" or tabSplit [ ] == '' : score = dxpy . NULL else : raise dxpy . AppError ( \"\" + \"\" + line + \"\" + tabSplit [ ] ) if tabSplit [ ] != \"\" and tabSplit [ ] != \"\" and tabSplit [ ] != \"\" : raise dxpy . AppError ( \"\" + \"\" + line + \"\" + tabSplit [ ] ) else : strand = tabSplit [ ] try : lo = int ( tabSplit [ ] ) - except ValueError : raise dxpy . AppError ( \"\" + \"\" + line + \"\" + tabSplit [ ] ) try : hi = int ( tabSplit [ ] ) except ValueError : raise dxpy . AppError ( \"\" + \"\" + line + \"\" + tabSplit [ ] ) try : frame = int ( tabSplit [ ] ) if frame > or frame < : raise dxpy . AppError ( \"\" + \"\" + line + \"\" + tabSplit [ ] ) except ValueError : if tabSplit [ ] == \"\" : frame = - else : raise dxpy . AppError ( \"\" + \"\" + line + \"\" + tabSplit [ ] ) lineAttributes = { } entrySplit = tabSplit [ ] . split ( \"\" ) ", "answer": "result = [ ]"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" ", "answer": "result . attribute_template_id = "}, {"prompt": " import os from distutils . core import setup ", "answer": "from version import VERSION"}, {"prompt": " from twisted . internet import protocol from twisted . internet import reactor import re class MyPP ( protocol . ProcessProtocol ) : def __init__ ( self , verses ) : self . verses = verses self . data = \"\" def connectionMade ( self ) : print \"\" for i in range ( self . verses ) : self . transport . write ( \"\" + \"\" + \"\" + \"\" ) self . transport . closeStdin ( ) def outReceived ( self , data ) : print \"\" % len ( data ) self . data = self . data + data def errReceived ( self , data ) : print \"\" % len ( data ) def inConnectionLost ( self ) : print \"\" def outConnectionLost ( self ) : print \"\" ( dummy , lines , words , chars , file ) = re . split ( r'' , self . data ) ", "answer": "print \"\" % lines"}, {"prompt": " from __future__ import unicode_literals from django . dispatch import receiver from reviewboard . signals import initializing @ receiver ( initializing ) def _on_initializing ( * args , ** kwargs ) : \"\"\"\"\"\" ", "answer": "from reviewboard . admin . widgets import init_widgets"}, {"prompt": " \"\"\"\"\"\" import os import shutil import tarfile import zipfile from django . utils import six class ArchiveException ( Exception ) : \"\"\"\"\"\" class UnrecognizedArchiveFormat ( ArchiveException ) : \"\"\"\"\"\" def extract ( path , to_path = '' ) : \"\"\"\"\"\" with Archive ( path ) as archive : archive . extract ( to_path ) class Archive ( object ) : \"\"\"\"\"\" def __init__ ( self , file ) : self . _archive = self . _archive_cls ( file ) ( file ) @ staticmethod def _archive_cls ( file ) : cls = None if isinstance ( file , six . string_types ) : filename = file else : try : filename = file . name except AttributeError : raise UnrecognizedArchiveFormat ( \"\" ) base , tail_ext = os . path . splitext ( filename . lower ( ) ) cls = extension_map . get ( tail_ext ) if not cls : base , ext = os . path . splitext ( base ) cls = extension_map . get ( ext ) if not cls : raise UnrecognizedArchiveFormat ( \"\" % filename ) return cls def __enter__ ( self ) : return self def __exit__ ( self , exc_type , exc_value , traceback ) : self . close ( ) def extract ( self , to_path = '' ) : self . _archive . extract ( to_path ) def list ( self ) : self . _archive . list ( ) def close ( self ) : self . _archive . close ( ) class BaseArchive ( object ) : \"\"\"\"\"\" def split_leading_dir ( self , path ) : path = str ( path ) path = path . lstrip ( '' ) . lstrip ( '' ) if '' in path and ( ( '' in path and path . find ( '' ) < path . find ( '' ) ) or '' not in path ) : return path . split ( '' , ) elif '' in path : return path . split ( '' , ) else : return path , '' ", "answer": "def has_leading_dir ( self , paths ) :"}, {"prompt": " from swgpy . object import * def create ( kernel ) : result = Tangible ( ) result . template = \"\" result . attribute_template_id = result . stfName ( \"\" , \"\" ) ", "answer": "return result "}, {"prompt": " \"\"\"\"\"\" __author__ = '' import os import shutil import sys from anvil . cache import RuleCache , FileRuleCache from anvil . context import BuildEnvironment , BuildContext from anvil . project import FileModuleResolver , Project from anvil . task import InProcessTaskExecutor , MultiProcessTaskExecutor ", "answer": "def clean_output ( cwd ) :"}, {"prompt": " import inspect import logging import os import os . path as osp import sys import gevent . monkey gevent . monkey . patch_all ( ) import gevent . pool from gevent_zeromq import zmq from . log import config_logger from . . zmq import Socket , MultiSocket , RpcServer from config . app import Configuration def job ( method ) : method . job = True return method class BaseModule ( object ) : \"\"\"\"\"\" def __init__ ( self , context = None ) : self . conf = Configuration ( ) self . name = osp . basename ( osp . dirname ( osp . abspath ( sys . argv [ ] ) ) ) self . pidfile = \"\" % self . name config_logger ( \"\" % self . name , self . conf . log_level ) self . context = context or zmq . Context . instance ( ) self . jobs = gevent . pool . Group ( ) self . rpc = RpcServer ( self , \"\" % self . name ) self . rpc . run ( ) bases = self . __class__ . __mro__ for base in bases : for func in base . __dict__ . values ( ) : if getattr ( func , '' , None ) : method = func . __get__ ( self , self . __class__ ) self . jobs . spawn ( method ) def run ( self ) : \"\"\"\"\"\" if os . access ( self . pidfile , os . F_OK ) : pid = open ( self . pidfile , '' ) . readline ( ) if osp . exists ( '' + pid ) : logging . warn ( \"\" % ( self . name , pid ) ) return else : logging . warn ( \"\" % self . name ) os . remove ( self . pidfile ) with self : try : self . jobs . join ( ) except KeyboardInterrupt : self . jobs . kill ( ) def sock ( self , name , _type = None ) : \"\"\"\"\"\" if _type : return Socket ( name , _type ) else : return Socket ( name ) def multisock ( self , name , _type = None ) : \"\"\"\"\"\" if _type : return MultiSocket ( name , _type ) else : return MultiSocket ( name ) def __enter__ ( self ) : logging . status ( \"\" % self . name ) open ( self . pidfile , '' ) . write ( str ( os . getpid ( ) ) ) return self def __exit__ ( self , type , value , traceback ) : logging . status ( \"\" % self . name ) os . remove ( self . pidfile ) return False def help ( self ) : methods = [ ] for name in dir ( self ) : obj = getattr ( self , name ) if inspect . ismethod ( obj ) : if getattr ( obj , '' , False ) : spec = inspect . getargspec ( obj ) doc = inspect . getdoc ( obj ) if doc : doc = doc . strip ( ) methods . append ( ( name , inspect . formatargspec ( * spec ) , doc ) ) else : if not name . startswith ( '' ) : methods . append ( name ) ", "answer": "return methods"}]