idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
244,100
def handle_path ( backend_inst , path , * * kwargs ) : if callable ( getattr ( backend_inst , 'handle_path' , None ) ) : # Prefer handle_path() if present. LOGGER . debug ( "using handle_path" ) return backend_inst . handle_path ( path ) elif callable ( getattr ( backend_inst , 'handle_fobj' , None ) ) : # Fallback to ...
Handle a path .
180
4
244,101
def handle_fobj ( backend , f , * * kwargs ) : if not is_binary ( f ) : raise AssertionError ( 'File must be opened in binary mode.' ) if callable ( getattr ( backend , 'handle_fobj' , None ) ) : # Prefer handle_fobj() if present. LOGGER . debug ( "using handle_fobj" ) return backend . handle_fobj ( f ) elif callable (...
Handle a file - like object .
257
7
244,102
def backend_from_mime ( mime ) : try : mod_name = MIMETYPE_TO_BACKENDS [ mime ] except KeyError : msg = "No handler for %r, defaulting to %r" % ( mime , DEFAULT_MIME ) if 'FULLTEXT_TESTING' in os . environ : warn ( msg ) else : LOGGER . debug ( msg ) mod_name = MIMETYPE_TO_BACKENDS [ DEFAULT_MIME ] mod = import_mod ( m...
Determine backend module object from a mime string .
126
12
244,103
def backend_from_fname ( name ) : ext = splitext ( name ) [ 1 ] try : mime = EXTS_TO_MIMETYPES [ ext ] except KeyError : try : f = open ( name , 'rb' ) except IOError as e : # The file may not exist, we are being asked to determine it's type # from it's name. Other errors are unexpected. if e . errno != errno . ENOENT ...
Determine backend module object from a file name .
239
11
244,104
def backend_from_fobj ( f ) : if magic is None : warn ( "magic lib is not installed; assuming mime type %r" % ( DEFAULT_MIME ) ) return backend_from_mime ( DEFAULT_MIME ) else : offset = f . tell ( ) try : f . seek ( 0 ) chunk = f . read ( MAGIC_BUFFER_SIZE ) mime = magic . from_buffer ( chunk , mime = True ) return ba...
Determine backend module object from a file object .
121
11
244,105
def backend_inst_from_mod ( mod , encoding , encoding_errors , kwargs ) : kw = dict ( encoding = encoding , encoding_errors = encoding_errors , kwargs = kwargs ) try : klass = getattr ( mod , "Backend" ) except AttributeError : raise AttributeError ( "%r mod does not define any backend class" % mod ) inst = klass ( * *...
Given a mod and a set of opts return an instantiated Backend class .
199
17
244,106
def get ( path_or_file , default = SENTINAL , mime = None , name = None , backend = None , encoding = None , encoding_errors = None , kwargs = None , _wtitle = False ) : try : text , title = _get ( path_or_file , default = default , mime = mime , name = name , backend = backend , kwargs = kwargs , encoding = encoding ,...
Get document full text .
150
5
244,107
def hilite ( s , ok = True , bold = False ) : if not term_supports_colors ( ) : return s attr = [ ] if ok is None : # no color pass elif ok : # green attr . append ( '32' ) else : # red attr . append ( '31' ) if bold : attr . append ( '1' ) return '\x1b[%sm%s\x1b[0m' % ( ';' . join ( attr ) , s )
Return an highlighted version of string .
117
7
244,108
def fobj_to_tempfile ( f , suffix = '' ) : with tempfile . NamedTemporaryFile ( dir = TEMPDIR , suffix = suffix , delete = False ) as t : shutil . copyfileobj ( f , t ) try : yield t . name finally : os . remove ( t . name )
Context manager which copies a file object to disk and return its name . When done the file is deleted .
70
21
244,109
def rm ( pattern ) : paths = glob . glob ( pattern ) for path in paths : if path . startswith ( '.git/' ) : continue if os . path . isdir ( path ) : def onerror ( fun , path , excinfo ) : exc = excinfo [ 1 ] if exc . errno != errno . ENOENT : raise safe_print ( "rmdir -f %s" % path ) shutil . rmtree ( path , onerror = ...
Recursively remove a file or dir by pattern .
128
11
244,110
def help ( ) : safe_print ( 'Run "make [-p <PYTHON>] <target>" where <target> is one of:' ) for name in sorted ( _cmds ) : safe_print ( " %-20s %s" % ( name . replace ( '_' , '-' ) , _cmds [ name ] or '' ) ) sys . exit ( 1 )
Print this help
85
3
244,111
def clean ( ) : rm ( "$testfn*" ) rm ( "*.bak" ) rm ( "*.core" ) rm ( "*.egg-info" ) rm ( "*.orig" ) rm ( "*.pyc" ) rm ( "*.pyd" ) rm ( "*.pyo" ) rm ( "*.rej" ) rm ( "*.so" ) rm ( "*.~" ) rm ( "*__pycache__" ) rm ( ".coverage" ) rm ( ".tox" ) rm ( ".coverage" ) rm ( "build" ) rm ( "dist" ) rm ( "docs/_build" ) rm ( "ht...
Deletes dev files
162
4
244,112
def lint ( ) : py_files = subprocess . check_output ( "git ls-files" ) if PY3 : py_files = py_files . decode ( ) py_files = [ x for x in py_files . split ( ) if x . endswith ( '.py' ) ] py_files = ' ' . join ( py_files ) sh ( "%s -m flake8 %s" % ( PYTHON , py_files ) , nolog = True )
Run flake8 against all py files
110
8
244,113
def coverage ( ) : # Note: coverage options are controlled by .coveragerc file install ( ) test_setup ( ) sh ( "%s -m coverage run %s" % ( PYTHON , TEST_SCRIPT ) ) sh ( "%s -m coverage report" % PYTHON ) sh ( "%s -m coverage html" % PYTHON ) sh ( "%s -m webbrowser -t htmlcov/index.html" % PYTHON )
Run coverage tests .
104
4
244,114
def venv ( ) : try : import virtualenv # NOQA except ImportError : sh ( "%s -m pip install virtualenv" % PYTHON ) if not os . path . isdir ( "venv" ) : sh ( "%s -m virtualenv venv" % PYTHON ) sh ( "venv\\Scripts\\pip install -r %s" % ( REQUIREMENTS_TXT ) )
Install venv + deps .
95
7
244,115
def compute_header_hmac_hash ( context ) : return hmac . new ( hashlib . sha512 ( b'\xff' * 8 + hashlib . sha512 ( context . _ . header . value . dynamic_header . master_seed . data + context . transformed_key + b'\x01' ) . digest ( ) ) . digest ( ) , context . _ . header . data , hashlib . sha256 ) . digest ( )
Compute HMAC - SHA256 hash of header . Used to prevent header tampering .
101
17
244,116
def compute_payload_block_hash ( this ) : return hmac . new ( hashlib . sha512 ( struct . pack ( '<Q' , this . _index ) + hashlib . sha512 ( this . _ . _ . header . value . dynamic_header . master_seed . data + this . _ . transformed_key + b'\x01' ) . digest ( ) ) . digest ( ) , struct . pack ( '<Q' , this . _index ) +...
Compute hash of each payload block . Used to prevent payload corruption and tampering .
144
16
244,117
def decrypt ( self , block ) : if len ( block ) % 16 : raise ValueError ( "block size must be a multiple of 16" ) plaintext = b'' while block : a , b , c , d = struct . unpack ( "<4L" , block [ : 16 ] ) temp = [ a , b , c , d ] decrypt ( self . context , temp ) plaintext += struct . pack ( "<4L" , * temp ) block = bloc...
Decrypt blocks .
107
4
244,118
def encrypt ( self , block ) : if len ( block ) % 16 : raise ValueError ( "block size must be a multiple of 16" ) ciphertext = b'' while block : a , b , c , d = struct . unpack ( "<4L" , block [ 0 : 16 ] ) temp = [ a , b , c , d ] encrypt ( self . context , temp ) ciphertext += struct . pack ( "<4L" , * temp ) block = ...
Encrypt blocks .
108
4
244,119
def aes_kdf ( key , rounds , password = None , keyfile = None ) : cipher = AES . new ( key , AES . MODE_ECB ) key_composite = compute_key_composite ( password = password , keyfile = keyfile ) # get the number of rounds from the header and transform the key_composite transformed_key = key_composite for _ in range ( 0 , ...
Set up a context for AES128 - ECB encryption to find transformed_key
125
15
244,120
def compute_key_composite ( password = None , keyfile = None ) : # hash the password if password : password_composite = hashlib . sha256 ( password . encode ( 'utf-8' ) ) . digest ( ) else : password_composite = b'' # hash the keyfile if keyfile : # try to read XML keyfile try : with open ( keyfile , 'r' ) as f : tree ...
Compute composite key . Used in header verification and payload decryption .
375
14
244,121
def compute_master ( context ) : # combine the transformed key with the header master seed to find the master_key master_key = hashlib . sha256 ( context . _ . header . value . dynamic_header . master_seed . data + context . transformed_key ) . digest ( ) return master_key
Computes master key from transformed key and master seed . Used in payload decryption .
67
17
244,122
def Unprotect ( protected_stream_id , protected_stream_key , subcon ) : return Switch ( protected_stream_id , { 'arcfourvariant' : ARCFourVariantStream ( protected_stream_key , subcon ) , 'salsa20' : Salsa20Stream ( protected_stream_key , subcon ) , 'chacha20' : ChaCha20Stream ( protected_stream_key , subcon ) , } , de...
Select stream cipher based on protected_stream_id
103
10
244,123
def encrypt ( self , plaintext , n = '' ) : #self.ed = 'e' if chain is encrypting, 'd' if decrypting, # None if nothing happened with the chain yet #assert self.ed in ('e',None) # makes sure you don't encrypt with a cipher that has started decrypting self . ed = 'e' if self . mode == MODE_XTS : # data sequence number (...
Encrypt some plaintext
138
5
244,124
def decrypt ( self , ciphertext , n = '' ) : #self.ed = 'e' if chain is encrypting, 'd' if decrypting, # None if nothing happened with the chain yet #assert self.ed in ('d',None) # makes sure you don't decrypt with a cipher that has started encrypting self . ed = 'd' if self . mode == MODE_XTS : # data sequence number ...
Decrypt some ciphertext
138
5
244,125
def final ( self , style = 'pkcs7' ) : # TODO: after calling final, reset the IV? so the cipher is as good as new? assert self . mode not in ( MODE_XTS , MODE_CMAC ) # finalizing (=padding) doesn't make sense when in XTS or CMAC mode if self . ed == b'e' : # when the chain is in encryption mode, finalizing will pad the...
Finalizes the encryption by padding the cache
282
8
244,126
def _datetime_to_utc ( self , dt ) : if not dt . tzinfo : dt = dt . replace ( tzinfo = tz . gettz ( ) ) return dt . astimezone ( tz . gettz ( 'UTC' ) )
Convert naive datetimes to UTC
64
7
244,127
def _encode_time ( self , value ) : if self . _kp . version >= ( 4 , 0 ) : diff_seconds = int ( ( self . _datetime_to_utc ( value ) - datetime ( year = 1 , month = 1 , day = 1 , tzinfo = tz . gettz ( 'UTC' ) ) ) . total_seconds ( ) ) return base64 . b64encode ( struct . pack ( '<Q' , diff_seconds ) ) . decode ( 'utf-8'...
Convert datetime to base64 or plaintext string
139
11
244,128
def _decode_time ( self , text ) : if self . _kp . version >= ( 4 , 0 ) : # decode KDBX4 date from b64 format try : return ( datetime ( year = 1 , month = 1 , day = 1 , tzinfo = tz . gettz ( 'UTC' ) ) + timedelta ( seconds = struct . unpack ( '<Q' , base64 . b64decode ( text ) ) [ 0 ] ) ) except BinasciiError : return ...
Convert base64 time or plaintext time to datetime
171
12
244,129
def fromrdd ( rdd , dims = None , nrecords = None , dtype = None , labels = None , ordered = False ) : from . images import Images from bolt . spark . array import BoltArraySpark if dims is None or dtype is None : item = rdd . values ( ) . first ( ) dtype = item . dtype dims = item . shape if nrecords is None : nrecord...
Load images from a Spark RDD .
189
8
244,130
def fromarray ( values , labels = None , npartitions = None , engine = None ) : from . images import Images import bolt if isinstance ( values , bolt . spark . array . BoltArraySpark ) : return Images ( values ) values = asarray ( values ) if values . ndim < 2 : raise ValueError ( 'Array for images must have at least 2...
Load images from an array .
308
6
244,131
def fromlist ( items , accessor = None , keys = None , dims = None , dtype = None , labels = None , npartitions = None , engine = None ) : if spark and isinstance ( engine , spark ) : nrecords = len ( items ) if keys : items = zip ( keys , items ) else : keys = [ ( i , ) for i in range ( nrecords ) ] items = zip ( keys...
Load images from a list of items using the given accessor .
212
13
244,132
def frompath ( path , accessor = None , ext = None , start = None , stop = None , recursive = False , npartitions = None , dims = None , dtype = None , labels = None , recount = False , engine = None , credentials = None ) : from thunder . readers import get_parallel_reader reader = get_parallel_reader ( path ) ( engin...
Load images from a path using the given accessor .
296
11
244,133
def fromtif ( path , ext = 'tif' , start = None , stop = None , recursive = False , nplanes = None , npartitions = None , labels = None , engine = None , credentials = None , discard_extra = False ) : from tifffile import TiffFile if nplanes is not None and nplanes <= 0 : raise ValueError ( 'nplanes must be positive if...
Loads images from single or multi - page TIF files .
463
13
244,134
def frompng ( path , ext = 'png' , start = None , stop = None , recursive = False , npartitions = None , labels = None , engine = None , credentials = None ) : from scipy . misc import imread def getarray ( idx_buffer_filename ) : idx , buf , _ = idx_buffer_filename fbuf = BytesIO ( buf ) yield ( idx , ) , imread ( fbu...
Load images from PNG files .
147
6
244,135
def fromrandom ( shape = ( 10 , 50 , 50 ) , npartitions = 1 , seed = 42 , engine = None ) : seed = hash ( seed ) def generate ( v ) : random . seed ( seed + v ) return random . randn ( * shape [ 1 : ] ) return fromlist ( range ( shape [ 0 ] ) , accessor = generate , npartitions = npartitions , engine = engine )
Generate random image data .
91
6
244,136
def fromexample ( name = None , engine = None ) : datasets = [ 'mouse' , 'fish' ] if name is None : print ( 'Availiable example image datasets' ) for d in datasets : print ( '- ' + d ) return check_options ( name , datasets ) path = 's3n://thunder-sample-data/images/' + name if name == 'mouse' : data = frombinary ( pat...
Load example image data .
162
5
244,137
def unchunk ( self ) : if self . padding != len ( self . shape ) * ( 0 , ) : shape = self . values . shape arr = empty ( shape , dtype = object ) for inds in product ( * [ arange ( s ) for s in shape ] ) : slices = [ ] for i , p , n in zip ( inds , self . padding , shape ) : start = None if ( i == 0 or p == 0 ) else p ...
Reconstitute the chunked array back into a full ndarray .
168
16
244,138
def chunk ( arr , chunk_size = "150" , padding = None ) : plan , _ = LocalChunks . getplan ( chunk_size , arr . shape [ 1 : ] , arr . dtype ) plan = r_ [ arr . shape [ 0 ] , plan ] if padding is None : pad = arr . ndim * ( 0 , ) elif isinstance ( padding , int ) : pad = ( 0 , ) + ( arr . ndim - 1 ) * ( padding , ) else...
Created a chunked array from a full array and a chunk size .
466
14
244,139
def filter ( self , func ) : if self . mode == 'local' : reshaped = self . _align ( self . baseaxes ) filtered = asarray ( list ( filter ( func , reshaped ) ) ) if self . labels is not None : mask = asarray ( list ( map ( func , reshaped ) ) ) if self . mode == 'spark' : sort = False if self . labels is None else True ...
Filter array along an axis .
282
6
244,140
def map ( self , func , value_shape = None , dtype = None , with_keys = False ) : axis = self . baseaxes if self . mode == 'local' : axes = sorted ( tupleize ( axis ) ) key_shape = [ self . shape [ axis ] for axis in axes ] reshaped = self . _align ( axes , key_shape = key_shape ) if with_keys : keys = zip ( * unravel_...
Apply an array - > array function across an axis .
363
11
244,141
def _reduce ( self , func , axis = 0 ) : if self . mode == 'local' : axes = sorted ( tupleize ( axis ) ) # if the function is a ufunc, it can automatically handle reducing over multiple axes if isinstance ( func , ufunc ) : inshape ( self . shape , axes ) reduced = func . reduce ( self , axis = tuple ( axes ) ) else : ...
Reduce an array along an axis .
243
8
244,142
def element_wise ( self , other , op ) : if not isscalar ( other ) and not self . shape == other . shape : raise ValueError ( "shapes %s and %s must be equal" % ( self . shape , other . shape ) ) if not isscalar ( other ) and isinstance ( other , Data ) and not self . mode == other . mode : raise NotImplementedError if...
Apply an elementwise operation to data .
324
8
244,143
def clip ( self , min = None , max = None ) : return self . _constructor ( self . values . clip ( min = min , max = max ) ) . __finalize__ ( self )
Clip values above and below .
44
7
244,144
def fromrdd ( rdd , nrecords = None , shape = None , index = None , labels = None , dtype = None , ordered = False ) : from . series import Series from bolt . spark . array import BoltArraySpark if index is None or dtype is None : item = rdd . values ( ) . first ( ) if index is None : index = range ( len ( item ) ) if ...
Load series data from a Spark RDD .
251
9
244,145
def fromarray ( values , index = None , labels = None , npartitions = None , engine = None ) : from . series import Series import bolt if isinstance ( values , bolt . spark . array . BoltArraySpark ) : return Series ( values ) values = asarray ( values ) if values . ndim < 2 : values = expand_dims ( values , 0 ) if ind...
Load series data from an array .
241
7
244,146
def fromlist ( items , accessor = None , index = None , labels = None , dtype = None , npartitions = None , engine = None ) : if spark and isinstance ( engine , spark ) : if dtype is None : dtype = accessor ( items [ 0 ] ) . dtype if accessor else items [ 0 ] . dtype nrecords = len ( items ) keys = map ( lambda k : ( k...
Load series data from a list with an optional accessor function .
226
13
244,147
def fromtext ( path , ext = 'txt' , dtype = 'float64' , skip = 0 , shape = None , index = None , labels = None , npartitions = None , engine = None , credentials = None ) : from thunder . readers import normalize_scheme , get_parallel_reader path = normalize_scheme ( path , ext ) if spark and isinstance ( engine , spar...
Loads series data from text files .
365
8
244,148
def frombinary ( path , ext = 'bin' , conf = 'conf.json' , dtype = None , shape = None , skip = 0 , index = None , labels = None , engine = None , credentials = None ) : shape , dtype = _binaryconfig ( path , conf , dtype , shape , credentials ) from thunder . readers import normalize_scheme , get_parallel_reader path ...
Load series data from flat binary files .
528
8
244,149
def _binaryconfig ( path , conf , dtype = None , shape = None , credentials = None ) : import json from thunder . readers import get_file_reader , FileNotFoundError reader = get_file_reader ( path ) ( credentials = credentials ) try : buf = reader . read ( path , filename = conf ) params = json . loads ( str ( buf . de...
Collects parameters to use for binary series loading .
201
10
244,150
def fromexample ( name = None , engine = None ) : import os import tempfile import shutil from boto . s3 . connection import S3Connection datasets = [ 'iris' , 'mouse' , 'fish' ] if name is None : print ( 'Availiable example series datasets' ) for d in datasets : print ( '- ' + d ) return check_options ( name , dataset...
Load example series data .
285
5
244,151
def tobinary ( series , path , prefix = 'series' , overwrite = False , credentials = None ) : from six import BytesIO from thunder . utils import check_path from thunder . writers import get_parallel_writer if not overwrite : check_path ( path , credentials = credentials ) overwrite = True def tobuffer ( kv ) : firstke...
Writes out data to binary format .
353
8
244,152
def write_config ( path , shape = None , dtype = None , name = "conf.json" , overwrite = True , credentials = None ) : import json from thunder . writers import get_file_writer writer = get_file_writer ( path ) conf = { 'shape' : shape , 'dtype' : str ( dtype ) } confwriter = writer ( path , name , overwrite = overwrit...
Write a conf . json file with required information to load Series binary data .
136
15
244,153
def toblocks ( self , chunk_size = 'auto' , padding = None ) : from thunder . blocks . blocks import Blocks from thunder . blocks . local import LocalChunks if self . mode == 'spark' : if chunk_size is 'auto' : chunk_size = str ( max ( [ int ( 1e5 / self . shape [ 0 ] ) , 1 ] ) ) chunks = self . values . chunk ( chunk_...
Convert to blocks which represent subdivisions of the images data .
165
13
244,154
def toseries ( self , chunk_size = 'auto' ) : from thunder . series . series import Series if chunk_size is 'auto' : chunk_size = str ( max ( [ int ( 1e5 / self . shape [ 0 ] ) , 1 ] ) ) n = len ( self . shape ) - 1 index = arange ( self . shape [ 0 ] ) if self . mode == 'spark' : return Series ( self . values . swap (...
Converts to series data .
165
6
244,155
def tospark ( self , engine = None ) : from thunder . images . readers import fromarray if self . mode == 'spark' : logging . getLogger ( 'thunder' ) . warn ( 'images already in spark mode' ) pass if engine is None : raise ValueError ( 'Must provide a SparkContext' ) return fromarray ( self . toarray ( ) , engine = eng...
Convert to distributed spark mode .
86
7
244,156
def foreach ( self , func ) : if self . mode == 'spark' : self . values . tordd ( ) . map ( lambda kv : ( kv [ 0 ] [ 0 ] , kv [ 1 ] ) ) . foreach ( func ) else : [ func ( kv ) for kv in enumerate ( self . values ) ]
Execute a function on each image .
78
8
244,157
def sample ( self , nsamples = 100 , seed = None ) : if nsamples < 1 : raise ValueError ( "Number of samples must be larger than 0, got '%g'" % nsamples ) if seed is None : seed = random . randint ( 0 , 2 ** 32 ) if self . mode == 'spark' : result = asarray ( self . values . tordd ( ) . values ( ) . takeSample ( False ...
Extract a random sample of images .
158
8
244,158
def var ( self ) : return self . _constructor ( self . values . var ( axis = 0 , keepdims = True ) )
Compute the variance across images .
30
7
244,159
def std ( self ) : return self . _constructor ( self . values . std ( axis = 0 , keepdims = True ) )
Compute the standard deviation across images .
30
8
244,160
def squeeze ( self ) : axis = tuple ( range ( 1 , len ( self . shape ) - 1 ) ) if prod ( self . shape [ 1 : ] ) == 1 else None return self . map ( lambda x : x . squeeze ( axis = axis ) )
Remove single - dimensional axes from images .
56
8
244,161
def max_projection ( self , axis = 2 ) : if axis >= size ( self . value_shape ) : raise Exception ( 'Axis for projection (%s) exceeds ' 'image dimensions (%s-%s)' % ( axis , 0 , size ( self . value_shape ) - 1 ) ) new_value_shape = list ( self . value_shape ) del new_value_shape [ axis ] return self . map ( lambda x : ...
Compute maximum projections of images along a dimension .
114
10
244,162
def max_min_projection ( self , axis = 2 ) : if axis >= size ( self . value_shape ) : raise Exception ( 'Axis for projection (%s) exceeds ' 'image dimensions (%s-%s)' % ( axis , 0 , size ( self . value_shape ) - 1 ) ) new_value_shape = list ( self . value_shape ) del new_value_shape [ axis ] return self . map ( lambda ...
Compute maximum - minimum projection along a dimension .
124
10
244,163
def subsample ( self , factor ) : value_shape = self . value_shape ndims = len ( value_shape ) if not hasattr ( factor , '__len__' ) : factor = [ factor ] * ndims factor = [ int ( sf ) for sf in factor ] if any ( ( sf <= 0 for sf in factor ) ) : raise ValueError ( 'All sampling factors must be positive; got ' + str ( f...
Downsample images by an integer factor .
205
8
244,164
def gaussian_filter ( self , sigma = 2 , order = 0 ) : from scipy . ndimage . filters import gaussian_filter return self . map ( lambda v : gaussian_filter ( v , sigma , order ) , value_shape = self . value_shape )
Spatially smooth images with a gaussian filter .
64
11
244,165
def _image_filter ( self , filter = None , size = 2 ) : from numpy import isscalar from scipy . ndimage . filters import median_filter , uniform_filter FILTERS = { 'median' : median_filter , 'uniform' : uniform_filter } func = FILTERS [ filter ] mode = self . mode value_shape = self . value_shape ndims = len ( value_sh...
Generic function for maping a filtering operation over images .
252
11
244,166
def localcorr ( self , size = 2 ) : from thunder . images . readers import fromarray , fromrdd from numpy import corrcoef , concatenate nimages = self . shape [ 0 ] # spatially average the original image set over the specified neighborhood blurred = self . uniform_filter ( size ) # union the averaged images with the or...
Correlate every pixel in an image sequence to the average of its local neighborhood .
251
17
244,167
def subtract ( self , val ) : if isinstance ( val , ndarray ) : if val . shape != self . value_shape : raise Exception ( 'Cannot subtract image with dimensions %s ' 'from images with dimension %s' % ( str ( val . shape ) , str ( self . value_shape ) ) ) return self . map ( lambda x : x - val , value_shape = self . valu...
Subtract a constant value or an image from all images .
92
13
244,168
def topng ( self , path , prefix = 'image' , overwrite = False ) : from thunder . images . writers import topng # TODO add back colormap and vmin/vmax topng ( self , path , prefix = prefix , overwrite = overwrite )
Write 2d images as PNG files .
57
8
244,169
def map_as_series ( self , func , value_size = None , dtype = None , chunk_size = 'auto' ) : blocks = self . toblocks ( chunk_size = chunk_size ) if value_size is not None : dims = list ( blocks . blockshape ) dims [ 0 ] = value_size else : dims = None def f ( block ) : return apply_along_axis ( func , 0 , block ) retu...
Efficiently apply a function to images as series data .
124
12
244,170
def count ( self ) : if self . mode == 'spark' : return self . tordd ( ) . count ( ) if self . mode == 'local' : return prod ( self . values . values . shape )
Explicit count of the number of items .
48
9
244,171
def collect_blocks ( self ) : if self . mode == 'spark' : return self . values . tordd ( ) . sortByKey ( ) . values ( ) . collect ( ) if self . mode == 'local' : return self . values . values . flatten ( ) . tolist ( )
Collect the blocks in a list
67
6
244,172
def map ( self , func , value_shape = None , dtype = None ) : mapped = self . values . map ( func , value_shape = value_shape , dtype = dtype ) return self . _constructor ( mapped ) . __finalize__ ( self , noprop = ( 'dtype' , ) )
Apply an array - > array function to each block
72
10
244,173
def toimages ( self ) : from thunder . images . images import Images if self . mode == 'spark' : values = self . values . values_to_keys ( ( 0 , ) ) . unchunk ( ) if self . mode == 'local' : values = self . values . unchunk ( ) return Images ( values )
Convert blocks to images .
71
6
244,174
def toseries ( self ) : from thunder . series . series import Series if self . mode == 'spark' : values = self . values . values_to_keys ( tuple ( range ( 1 , len ( self . shape ) ) ) ) . unchunk ( ) if self . mode == 'local' : values = self . values . unchunk ( ) values = rollaxis ( values , 0 , values . ndim ) return...
Converts blocks to series .
95
6
244,175
def toarray ( self ) : if self . mode == 'spark' : return self . values . unchunk ( ) . toarray ( ) if self . mode == 'local' : return self . values . unchunk ( )
Convert blocks to local ndarray
49
8
244,176
def flatten ( self ) : size = prod ( self . shape [ : - 1 ] ) return self . reshape ( size , self . shape [ - 1 ] )
Reshape all dimensions but the last into a single dimension
36
12
244,177
def tospark ( self , engine = None ) : from thunder . series . readers import fromarray if self . mode == 'spark' : logging . getLogger ( 'thunder' ) . warn ( 'images already in local mode' ) pass if engine is None : raise ValueError ( 'Must provide SparkContext' ) return fromarray ( self . toarray ( ) , index = self ....
Convert to spark mode .
97
6
244,178
def sample ( self , n = 100 , seed = None ) : if n < 1 : raise ValueError ( "Number of samples must be larger than 0, got '%g'" % n ) if seed is None : seed = random . randint ( 0 , 2 ** 32 ) if self . mode == 'spark' : result = asarray ( self . values . tordd ( ) . values ( ) . takeSample ( False , n , seed ) ) else :...
Extract random sample of records .
199
7
244,179
def map ( self , func , index = None , value_shape = None , dtype = None , with_keys = False ) : # if new index is given, can infer missing value_shape if value_shape is None and index is not None : value_shape = len ( index ) if isinstance ( value_shape , int ) : values_shape = ( value_shape , ) new = super ( Series ,...
Map an array - > array function over each record .
171
11
244,180
def mean ( self ) : return self . _constructor ( self . values . mean ( axis = self . baseaxes , keepdims = True ) )
Compute the mean across records
34
6
244,181
def sum ( self ) : return self . _constructor ( self . values . sum ( axis = self . baseaxes , keepdims = True ) )
Compute the sum across records .
34
7
244,182
def max ( self ) : return self . _constructor ( self . values . max ( axis = self . baseaxes , keepdims = True ) )
Compute the max across records .
34
7
244,183
def min ( self ) : return self . _constructor ( self . values . min ( axis = self . baseaxes , keepdims = True ) )
Compute the min across records .
34
7
244,184
def reshape ( self , * shape ) : if prod ( self . shape ) != prod ( shape ) : raise ValueError ( "Reshaping must leave the number of elements unchanged" ) if self . shape [ - 1 ] != shape [ - 1 ] : raise ValueError ( "Reshaping cannot change the size of the constituent series (last dimension)" ) if self . labels is not...
Reshape the Series object
153
6
244,185
def between ( self , left , right ) : crit = lambda x : left <= x < right return self . select ( crit )
Select subset of values within the given index range .
27
10
244,186
def select ( self , crit ) : import types # handle lists, strings, and ints if not isinstance ( crit , types . FunctionType ) : # set("foo") -> {"f", "o"}; wrap in list to prevent: if isinstance ( crit , string_types ) : critlist = set ( [ crit ] ) else : try : critlist = set ( crit ) except TypeError : # typically mea...
Select subset of values that match a given index criterion .
386
11
244,187
def center ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : x - mean ( x ) ) elif axis == 0 : meanval = self . mean ( ) . toarray ( ) return self . map ( lambda x : x - meanval ) else : raise Exception ( 'Axis must be 0 or 1' )
Subtract the mean either within or across records .
77
11
244,188
def standardize ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : x / std ( x ) ) elif axis == 0 : stdval = self . std ( ) . toarray ( ) return self . map ( lambda x : x / stdval ) else : raise Exception ( 'Axis must be 0 or 1' )
Divide by standard deviation either within or across records .
78
11
244,189
def zscore ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : ( x - mean ( x ) ) / std ( x ) ) elif axis == 0 : meanval = self . mean ( ) . toarray ( ) stdval = self . std ( ) . toarray ( ) return self . map ( lambda x : ( x - meanval ) / stdval ) else : raise Exception ( 'Axis must be 0 or 1' )
Subtract the mean and divide by standard deviation within or across records .
103
15
244,190
def squelch ( self , threshold ) : func = lambda x : zeros ( x . shape ) if max ( x ) < threshold else x return self . map ( func )
Set all records that do not exceed the given threhsold to 0 .
38
16
244,191
def correlate ( self , signal ) : s = asarray ( signal ) if s . ndim == 1 : if size ( s ) != self . shape [ - 1 ] : raise ValueError ( "Length of signal '%g' does not match record length '%g'" % ( size ( s ) , self . shape [ - 1 ] ) ) return self . map ( lambda x : corrcoef ( x , s ) [ 0 , 1 ] , index = [ 1 ] ) elif s ...
Correlate records against one or many one - dimensional arrays .
238
13
244,192
def _check_panel ( self , length ) : n = len ( self . index ) if divmod ( n , length ) [ 1 ] != 0 : raise ValueError ( "Panel length '%g' must evenly divide length of series '%g'" % ( length , n ) ) if n == length : raise ValueError ( "Panel length '%g' cannot be length of series '%g'" % ( length , n ) )
Check that given fixed panel length evenly divides index .
93
10
244,193
def mean_by_panel ( self , length ) : self . _check_panel ( length ) func = lambda v : v . reshape ( - 1 , length ) . mean ( axis = 0 ) newindex = arange ( length ) return self . map ( func , index = newindex )
Compute the mean across fixed sized panels of each record .
63
12
244,194
def _makemasks ( self , index = None , level = 0 ) : if index is None : index = self . index try : dims = len ( array ( index ) . shape ) if dims == 1 : index = array ( index , ndmin = 2 ) . T except : raise TypeError ( 'A multi-index must be convertible to a numpy ndarray' ) try : index = index [ : , level ] except : ...
Internal function for generating masks for selecting values based on multi - index values .
247
15
244,195
def _map_by_index ( self , function , level = 0 ) : if type ( level ) is int : level = [ level ] masks , ind = self . _makemasks ( index = self . index , level = level ) nMasks = len ( masks ) newindex = array ( ind ) if len ( newindex [ 0 ] ) == 1 : newindex = ravel ( newindex ) return self . map ( lambda v : asarray ...
An internal function for maping a function to groups of values based on a multi - index
129
18
244,196
def aggregate_by_index ( self , function , level = 0 ) : result = self . _map_by_index ( function , level = level ) return result . map ( lambda v : array ( v ) , index = result . index )
Aggregrate data in each record grouping by index values .
52
13
244,197
def gramian ( self ) : if self . mode == 'spark' : rdd = self . values . tordd ( ) from pyspark . accumulators import AccumulatorParam class MatrixAccumulator ( AccumulatorParam ) : def zero ( self , value ) : return zeros ( shape ( value ) ) def addInPlace ( self , val1 , val2 ) : val1 += val2 return val1 global mat i...
Compute gramian of a distributed matrix .
218
9
244,198
def times ( self , other ) : if isinstance ( other , ScalarType ) : other = asarray ( other ) index = self . index else : if isinstance ( other , list ) : other = asarray ( other ) if isinstance ( other , ndarray ) and other . ndim < 2 : other = expand_dims ( other , 1 ) if not self . shape [ 1 ] == other . shape [ 0 ]...
Multiply a matrix by another one .
366
9
244,199
def _makewindows ( self , indices , window ) : div = divmod ( window , 2 ) before = div [ 0 ] after = div [ 0 ] + div [ 1 ] index = asarray ( self . index ) indices = asarray ( indices ) if where ( index == max ( indices ) ) [ 0 ] [ 0 ] + after > len ( index ) : raise ValueError ( "Maximum requested index %g, with wind...
Make masks used by windowing functions
216
7