idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
4,400
def as_processed_list ( func ) : @ wraps ( func ) def wrapper ( * args , * * kwargs ) : func_argspec = inspect . getargspec ( func ) func_args = func_argspec . args for kw in request . args : if ( kw in func_args and kw not in RESTRICTED and not any ( request . args . get ( kw ) . startswith ( op ) for op in OPERATORS ...
A decorator used to return a JSON response of a list of model objects . It differs from as_list in that it accepts a variety of querying parameters and can use them to filter and modify the results . It expects the decorated function to return either Model Class to query or a SQLAlchemy filter which exposes a subset of...
177
89
4,401
def as_obj ( func ) : @ wraps ( func ) def wrapper ( * args , * * kwargs ) : response = func ( * args , * * kwargs ) return render_json_obj_with_requested_structure ( response ) return wrapper
A decorator used to return a JSON response with a dict representation of the model instance . It expects the decorated function to return a Model instance . It then converts the instance to dicts and serializes it into a json response
58
45
4,402
def execute ( self , interactive = False ) : url = self . _client . _build_url ( 'service_execute' , service_id = self . id ) response = self . _client . _request ( 'GET' , url , params = dict ( interactive = interactive , format = 'json' ) ) if response . status_code != requests . codes . accepted : # pragma: no cover...
Execute the service .
154
5
4,403
def edit ( self , name = None , description = None , version = None , * * kwargs ) : update_dict = { 'id' : self . id } if name : if not isinstance ( name , str ) : raise IllegalArgumentError ( "name should be provided as a string" ) update_dict . update ( { 'name' : name } ) if description : if not isinstance ( descri...
Edit Service details .
287
4
4,404
def delete ( self ) : # type: () -> None response = self . _client . _request ( 'DELETE' , self . _client . _build_url ( 'service' , service_id = self . id ) ) if response . status_code != requests . codes . no_content : # pragma: no cover raise APIError ( "Could not delete service: {} with id {}" . format ( self . nam...
Delete this service .
99
4
4,405
def get_executions ( self , * * kwargs ) : return self . _client . service_executions ( service = self . id , scope = self . scope_id , * * kwargs )
Retrieve the executions related to the current service .
46
10
4,406
def service ( self ) : if not self . _service : self . _service = self . _client . service ( id = self . service_id ) return self . _service
Retrieve the Service object to which this execution is associated .
38
12
4,407
def terminate ( self ) : url = self . _client . _build_url ( 'service_execution_terminate' , service_execution_id = self . id ) response = self . _client . _request ( 'GET' , url , params = dict ( format = 'json' ) ) if response . status_code != requests . codes . accepted : # pragma: no cover raise APIError ( "Could n...
Terminate the Service execution .
108
6
4,408
def get_log ( self , target_dir = None , log_filename = 'log.txt' ) : full_path = os . path . join ( target_dir or os . getcwd ( ) , log_filename ) url = self . _client . _build_url ( 'service_execution_log' , service_execution_id = self . id ) response = self . _client . _request ( 'GET' , url ) if response . status_c...
Retrieve the log of the service execution .
157
9
4,409
def get_notebook_url ( self ) : url = self . _client . _build_url ( 'service_execution_notebook_url' , service_execution_id = self . id ) response = self . _client . _request ( 'GET' , url , params = dict ( format = 'json' ) ) if response . status_code != requests . codes . ok : raise APIError ( "Could not retrieve not...
Get the url of the notebook if the notebook is executed in interactive mode .
139
15
4,410
def sendMessage ( self , data ) : opcode = BINARY if isinstance ( data , unicode ) : opcode = TEXT self . _sendMessage ( False , opcode , data )
Send websocket data frame to the client . If data is a unicode object then the frame is sent as Text . If the data is a bytearray object then the frame is sent as Binary .
42
42
4,411
def _shape_array ( array1 , array2 ) : if len ( array1 ) > len ( array2 ) : new_array = array2 old_array = array1 else : new_array = array1 old_array = array2 length = len ( old_array ) - len ( new_array ) for i in range ( length ) : n = new_array [ - 1 ] . copy ( ) n [ 0 : : 3 ] += 1 n [ 2 : : 3 ] = 0 new_array = np ....
Function that equalises the input arrays by zero - padding the shortest one .
144
15
4,412
def _create_txt_from_str ( in_path , channels , new_path ) : header = [ "# OpenSignals Text File Format" ] files = [ bsnb . load ( in_path ) ] with open ( in_path , encoding = "latin-1" ) as opened_p : header . append ( opened_p . readlines ( ) [ 1 ] ) header . append ( "# EndOfHeader" ) data = [ ] nr_channels = [ ] fo...
This function allows to generate a text file with synchronised signals from the input file .
455
17
4,413
def render ( self , bindings ) : out = [ ] binding = False for segment in self . segments : if segment . kind == _BINDING : if segment . literal not in bindings : raise ValidationException ( ( 'rendering error: value for key \'{}\' ' 'not provided' ) . format ( segment . literal ) ) out . extend ( PathTemplate ( bindin...
Renders a string from a path template using the provided bindings .
135
13
4,414
def match ( self , path ) : this = self . segments that = path . split ( '/' ) current_var = None bindings = { } segment_count = self . segment_count j = 0 for i in range ( 0 , len ( this ) ) : if j >= len ( that ) : break if this [ i ] . kind == _TERMINAL : if this [ i ] . literal == '*' : bindings [ current_var ] = t...
Matches a fully qualified path template string .
285
9
4,415
def parse ( self , data ) : self . binding_var_count = 0 self . segment_count = 0 segments = self . parser . parse ( data ) # Validation step: checks that there are no nested bindings. path_wildcard = False for segment in segments : if segment . kind == _TERMINAL and segment . literal == '**' : if path_wildcard : raise...
Returns a list of path template segments parsed from data .
114
11
4,416
def create ( window , root ) : notifications = { } _id = root . get_property ( "id" ) from foxpuppet . windows . browser . notifications import addons notifications . update ( addons . NOTIFICATIONS ) return notifications . get ( _id , BaseNotification ) ( window , root )
Create a notification object .
66
5
4,417
def label ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : return self . root . get_attribute ( "label" )
Provide access to the notification label .
41
8
4,418
def origin ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : return self . root . get_attribute ( "origin" )
Provide access to the notification origin .
41
8
4,419
def find_primary_button ( self ) : if self . window . firefox_version >= 67 : return self . root . find_element ( By . CLASS_NAME , "popup-notification-primary-button" ) return self . root . find_anonymous_element_by_attribute ( "anonid" , "button" )
Retrieve the primary button .
74
6
4,420
def windows ( self ) : from foxpuppet . windows import BrowserWindow return [ BrowserWindow ( self . selenium , handle ) for handle in self . selenium . window_handles ]
Return a list of all open windows .
42
8
4,421
def read_daemon ( self ) : while True : data = self . _socket . recv ( 9999 ) self . feed_parser ( data )
Read thread .
33
3
4,422
def _logic ( self , value = None ) : # type: (Any) -> Tuple[Union[bool, None], str] self . _validation_result , self . _validation_reason = None , 'No reason' return self . _validation_result , self . _validation_reason
Process the inner logic of the validator .
68
9
4,423
def get_station_board ( self , crs , rows = 17 , include_departures = True , include_arrivals = False , destination_crs = None , origin_crs = None ) : # Determine the darwn query we want to make if include_departures and include_arrivals : query_type = 'GetArrivalDepartureBoard' elif include_departures : query_type = '...
Query the darwin webservice to obtain a board for a particular station and return a StationBoard instance
311
22
4,424
def get_service_details ( self , service_id ) : service_query = self . _soap_client . service [ 'LDBServiceSoap' ] [ 'GetServiceDetails' ] try : soap_response = service_query ( serviceID = service_id ) except WebFault : raise WebServiceError return ServiceDetails ( soap_response )
Get the details of an individual service and return a ServiceDetails instance .
78
14
4,425
def render_template ( self ) : self . _parse_paths ( ) context = dict ( napp = self . _napp . __dict__ , paths = self . _paths ) self . _save ( context )
Render and save API doc in openapi . yml .
49
12
4,426
def _parse_decorated_functions ( self , code ) : matches = re . finditer ( r""" # @rest decorators (?P<decorators> (?:@rest\(.+?\)\n)+ # one or more @rest decorators inside ) # docstring delimited by 3 double quotes .+?"{3}(?P<docstring>.+?)"{3} """ , code , re . VERBOSE | re . DOTALL ) for function_match in matches : ...
Return URL rule HTTP methods and docstring .
162
9
4,427
def _parse_docstring ( self , docstring ) : match = re . match ( r""" # Following PEP 257 \s* (?P<summary>[^\n]+?) \s* # First line ( # Description and YAML are optional (\n \s*){2} # Blank line # Description (optional) ( (?!-{3,}) # Don't use YAML as description \s* (?P<description>.+?) \s* # Third line and maybe othe...
Parse the method docstring .
283
7
4,428
def _parse_methods ( cls , list_string ) : if list_string is None : return APIServer . DEFAULT_METHODS # json requires double quotes json_list = list_string . replace ( "'" , '"' ) return json . loads ( json_list )
Return HTTP method list . Use json for security reasons .
62
11
4,429
def _rule2path ( cls , rule ) : typeless = re . sub ( r'<\w+?:' , '<' , rule ) # remove Flask types return typeless . replace ( '<' , '{' ) . replace ( '>' , '}' )
Convert relative Flask rule to absolute OpenAPI path .
63
11
4,430
def property ( self , name ) : found = None if is_uuid ( name ) : found = find ( self . properties , lambda p : name == p . id ) else : found = find ( self . properties , lambda p : name == p . name ) if not found : raise NotFoundError ( "Could not find property with name or id {}" . format ( name ) ) return found
Retrieve the property belonging to this part based on its name or uuid .
84
16
4,431
def parent ( self ) : # type: () -> Any if self . parent_id : return self . _client . part ( pk = self . parent_id , category = self . category ) else : return None
Retrieve the parent of this Part .
46
8
4,432
def children ( self , * * kwargs ) : if not kwargs : # no kwargs provided is the default, we aim to cache it. if not self . _cached_children : self . _cached_children = list ( self . _client . parts ( parent = self . id , category = self . category ) ) return self . _cached_children else : # if kwargs are provided, we ...
Retrieve the children of this Part as Partset .
133
11
4,433
def siblings ( self , * * kwargs ) : # type: (Any) -> Any if self . parent_id : return self . _client . parts ( parent = self . parent_id , category = self . category , * * kwargs ) else : from pykechain . models . partset import PartSet return PartSet ( parts = [ ] )
Retrieve the siblings of this Part as Partset .
78
11
4,434
def model ( self ) : if self . category == Category . INSTANCE : model_id = self . _json_data [ 'model' ] . get ( 'id' ) return self . _client . model ( pk = model_id ) else : raise NotFoundError ( "Part {} has no model" . format ( self . name ) )
Retrieve the model of this Part as Part .
75
10
4,435
def instances ( self , * * kwargs ) : if self . category == Category . MODEL : return self . _client . parts ( model = self , category = Category . INSTANCE , * * kwargs ) else : raise NotFoundError ( "Part {} is not a model" . format ( self . name ) )
Retrieve the instances of this Part as a PartSet .
70
12
4,436
def proxy_model ( self ) : if self . category != Category . MODEL : raise IllegalArgumentError ( "Part {} is not a model, therefore it cannot have a proxy model" . format ( self ) ) if 'proxy' in self . _json_data and self . _json_data . get ( 'proxy' ) : catalog_model_id = self . _json_data [ 'proxy' ] . get ( 'id' ) ...
Retrieve the proxy model of this proxied Part as a Part .
136
14
4,437
def add ( self , model , * * kwargs ) : # type: (Part, **Any) -> Part if self . category != Category . INSTANCE : raise APIError ( "Part should be of category INSTANCE" ) return self . _client . create_part ( self , model , * * kwargs )
Add a new child instance based on a model to this part .
69
13
4,438
def add_to ( self , parent , * * kwargs ) : # type: (Part, **Any) -> Part if self . category != Category . MODEL : raise APIError ( "Part should be of category MODEL" ) return self . _client . create_part ( parent , self , * * kwargs )
Add a new instance of this model to a part .
71
11
4,439
def add_model ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Part if self . category != Category . MODEL : raise APIError ( "Part should be of category MODEL" ) return self . _client . create_model ( self , * args , * * kwargs )
Add a new child model to this model .
73
9
4,440
def add_property ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Property if self . category != Category . MODEL : raise APIError ( "Part should be of category MODEL" ) return self . _client . create_property ( self , * args , * * kwargs )
Add a new property to this model .
73
8
4,441
def update ( self , name = None , update_dict = None , bulk = True , * * kwargs ) : # dict(name=name, properties=json.dumps(update_dict))) with property ids:value action = 'bulk_update_properties' request_body = dict ( ) for prop_name_or_id , property_value in update_dict . items ( ) : if is_uuid ( prop_name_or_id ) : ...
Edit part name and property values in one go .
340
10
4,442
def add_with_properties ( self , model , name = None , update_dict = None , bulk = True , * * kwargs ) : if self . category != Category . INSTANCE : raise APIError ( "Part should be of category INSTANCE" ) name = name or model . name action = 'new_instance_with_properties' properties_update_dict = dict ( ) for prop_nam...
Add a part and update its properties in one go .
359
11
4,443
def order_properties ( self , property_list = None ) : if self . category != Category . MODEL : raise APIError ( "Part should be of category MODEL" ) if not isinstance ( property_list , list ) : raise IllegalArgumentError ( 'Expected a list of strings or Property() objects, got a {} object' . format ( type ( property_l...
Order the properties of a part model using a list of property objects or property names or property id s .
242
21
4,444
def clone ( self , * * kwargs ) : parent = self . parent ( ) return self . _client . _create_clone ( parent , self , * * kwargs )
Clone a part .
40
5
4,445
def copy ( self , target_parent , name = None , include_children = True , include_instances = True ) : if self . category == Category . MODEL and target_parent . category == Category . MODEL : # Cannot add a model under an instance or vice versa copied_model = relocate_model ( part = self , target_parent = target_paren...
Copy the Part to target parent both of them having the same category .
285
14
4,446
def move ( self , target_parent , name = None , include_children = True , include_instances = True ) : if not name : name = self . name if self . category == Category . MODEL and target_parent . category == Category . MODEL : moved_model = relocate_model ( part = self , target_parent = target_parent , name = name , inc...
Move the Part to target parent both of them the same category .
325
13
4,447
def _generate_notebook_by_difficulty_body ( notebook_object , dict_by_difficulty ) : difficulty_keys = list ( dict_by_difficulty . keys ( ) ) difficulty_keys . sort ( ) for difficulty in difficulty_keys : markdown_cell = STAR_TABLE_HEADER markdown_cell = _set_star_value ( markdown_cell , int ( difficulty ) ) for notebo...
Internal function that is used for generation of the page where notebooks are organized by difficulty level .
449
18
4,448
def _generate_dir_structure ( path ) : # ============================ Creation of the main directory ================================== current_dir = ( path + "\\opensignalsfactory_environment" ) . replace ( "\\" , "/" ) if not os . path . isdir ( current_dir ) : os . makedirs ( current_dir ) # ================== Copy ...
Internal function intended to generate the biosignalsnotebooks directories in order to the user can visualise and execute the Notebook created with notebook class in Jupyter .
403
35
4,449
def in_lamp_reach ( p ) : v1 = XYPoint ( Lime . x - Red . x , Lime . y - Red . y ) v2 = XYPoint ( Blue . x - Red . x , Blue . y - Red . y ) q = XYPoint ( p . x - Red . x , p . y - Red . y ) s = cross_product ( q , v2 ) / cross_product ( v1 , v2 ) t = cross_product ( v1 , q ) / cross_product ( v1 , v2 ) return ( s >= 0....
Check if the provided XYPoint can be recreated by a Hue lamp .
146
15
4,450
def get_closest_point_to_line ( A , B , P ) : AP = XYPoint ( P . x - A . x , P . y - A . y ) AB = XYPoint ( B . x - A . x , B . y - A . y ) ab2 = AB . x * AB . x + AB . y * AB . y ap_ab = AP . x * AB . x + AP . y * AB . y t = ap_ab / ab2 if t < 0.0 : t = 0.0 elif t > 1.0 : t = 1.0 return XYPoint ( A . x + AB . x * t , ...
Find the closest point on a line . This point will be reproducible by a Hue lamp .
156
19
4,451
def get_closest_point_to_point ( xy_point ) : pAB = get_closest_point_to_line ( Red , Lime , xy_point ) pAC = get_closest_point_to_line ( Blue , Red , xy_point ) pBC = get_closest_point_to_line ( Lime , Blue , xy_point ) # Get the distances per point and see which point is closer to our Point. dAB = get_distance_betwee...
Used to find the closest point to an unreproducible Color is unreproducible on each line in the CIE 1931 triangle .
256
28
4,452
def get_xy_from_hex ( hex_value ) : red , green , blue = struct . unpack ( 'BBB' , codecs . decode ( hex_value , 'hex' ) ) r = ( ( red + 0.055 ) / ( 1.0 + 0.055 ) ) ** 2.4 if ( red > 0.04045 ) else ( red / 12.92 ) # pragma: noqa g = ( ( green + 0.055 ) / ( 1.0 + 0.055 ) ) ** 2.4 if ( green > 0.04045 ) else ( green / 12...
Returns X Y coordinates containing the closest avilable CIE 1931 based on the hex_value provided .
382
21
4,453
def get_other_keys ( self , key , including_current = False ) : other_keys = [ ] if key in self : other_keys . extend ( self . __dict__ [ str ( type ( key ) ) ] [ key ] ) if not including_current : other_keys . remove ( key ) return other_keys
Returns list of other keys that are mapped to the same value as specified key .
71
16
4,454
def iterkeys ( self , key_type = None , return_all_keys = False ) : if ( key_type is not None ) : the_key = str ( key_type ) if the_key in self . __dict__ : for key in self . __dict__ [ the_key ] . keys ( ) : if return_all_keys : yield self . __dict__ [ the_key ] [ key ] else : yield key else : for keys in self . items...
Returns an iterator over the dictionary s keys .
112
9
4,455
def itervalues ( self , key_type = None ) : if ( key_type is not None ) : intermediate_key = str ( key_type ) if intermediate_key in self . __dict__ : for direct_key in self . __dict__ [ intermediate_key ] . values ( ) : yield self . items_dict [ direct_key ] else : for value in self . items_dict . values ( ) : yield v...
Returns an iterator over the dictionary s values .
94
9
4,456
def keys ( self , key_type = None ) : if key_type is not None : intermediate_key = str ( key_type ) if intermediate_key in self . __dict__ : return self . __dict__ [ intermediate_key ] . keys ( ) else : all_keys = { } # in order to preserve keys() type (dict_keys for python3) for keys in self . items_dict . keys ( ) : ...
Returns a copy of the dictionary s keys .
109
9
4,457
def values ( self , key_type = None ) : if ( key_type is not None ) : all_items = { } # in order to preserve keys() type (dict_values for python3) keys_used = set ( ) direct_key = str ( key_type ) if direct_key in self . __dict__ : for intermediate_key in self . __dict__ [ direct_key ] . values ( ) : if not intermediat...
Returns a copy of the dictionary s values .
151
9
4,458
def __add_item ( self , item , keys = None ) : if ( not keys or not len ( keys ) ) : raise Exception ( 'Error in %s.__add_item(%s, keys=tuple/list of items): need to specify a tuple/list containing at least one key!' % ( self . __class__ . __name__ , str ( item ) ) ) direct_key = tuple ( keys ) # put all keys in a tupl...
Internal method to add an item to the multi - key dictionary
224
12
4,459
def get ( self , key , default = None ) : if key in self : return self . items_dict [ self . __dict__ [ str ( type ( key ) ) ] [ key ] ] else : return default
Return the value at index specified as key .
46
9
4,460
def extract_translations ( self , string ) : trans = [ ] for t in Lexer ( string . decode ( "utf-8" ) , None ) . tokenize ( ) : if t . token_type == TOKEN_BLOCK : if not t . contents . startswith ( ( self . tranz_tag , self . tranzchoice_tag ) ) : continue is_tranzchoice = t . contents . startswith ( self . tranzchoice...
Extract messages from Django template string .
293
8
4,461
def next ( self ) : if self . _mode != "r" : raise UnsupportedOperation ( "not available in 'w' mode" ) self . _n += 1 if self . _n > self . _nb_markers : raise StopIteration ( ) return self . _bim . index [ self . _n - 1 ] , self . _read_current_marker ( )
Returns the next marker .
85
5
4,462
def _read_current_marker ( self ) : return self . _geno_values [ np . frombuffer ( self . _bed . read ( self . _nb_bytes ) , dtype = np . uint8 ) ] . flatten ( order = "C" ) [ : self . _nb_samples ]
Reads the current marker and returns its genotypes .
70
11
4,463
def seek ( self , n ) : if self . _mode != "r" : raise UnsupportedOperation ( "not available in 'w' mode" ) if 0 <= n < self . _nb_markers : self . _n = n self . _bed . seek ( self . _get_seek_position ( n ) ) else : # Invalid seek value raise ValueError ( "invalid position in BED: {}" . format ( n ) )
Gets to a certain marker position in the BED file .
97
13
4,464
def _read_bim ( self ) : # Reading the BIM file and setting the values bim = pd . read_csv ( self . bim_filename , delim_whitespace = True , names = [ "chrom" , "snp" , "cm" , "pos" , "a1" , "a2" ] , dtype = dict ( snp = str , a1 = str , a2 = str ) ) # Saving the index as integer bim [ "i" ] = bim . index # Checking fo...
Reads the BIM file .
702
7
4,465
def _read_fam ( self ) : # Reading the FAM file and setting the values fam = pd . read_csv ( self . fam_filename , delim_whitespace = True , names = [ "fid" , "iid" , "father" , "mother" , "gender" , "status" ] , dtype = dict ( fid = str , iid = str , father = str , mother = str ) ) # Getting the byte and bit location ...
Reads the FAM file .
199
6
4,466
def _read_bed ( self ) : # Checking if BIM and BAM files were both read if ( self . _bim is None ) or ( self . _fam is None ) : raise RuntimeError ( "no BIM or FAM file were read" ) # The number of bytes per marker self . _nb_bytes = int ( np . ceil ( self . _nb_samples / 4.0 ) ) # Checking the file is valid by looking...
Reads the BED file .
434
7
4,467
def _write_bed_header ( self ) : # Writing the first three bytes final_byte = 1 if self . _bed_format == "SNP-major" else 0 self . _bed . write ( bytearray ( ( 108 , 27 , final_byte ) ) )
Writes the BED first 3 bytes .
61
9
4,468
def iter_geno_marker ( self , markers , return_index = False ) : if self . _mode != "r" : raise UnsupportedOperation ( "not available in 'w' mode" ) # If string, we change to list if isinstance ( markers , str ) : markers = [ markers ] # Iterating over all markers if return_index : for marker in markers : geno , seek =...
Iterates over genotypes for a list of markers .
135
11
4,469
def get_geno_marker ( self , marker , return_index = False ) : if self . _mode != "r" : raise UnsupportedOperation ( "not available in 'w' mode" ) # Check if the marker exists if marker not in self . _bim . index : raise ValueError ( "{}: marker not in BIM" . format ( marker ) ) # Seeking to the correct position seek_i...
Gets the genotypes for a given marker .
146
10
4,470
def write_genotypes ( self , genotypes ) : if self . _mode != "w" : raise UnsupportedOperation ( "not available in 'r' mode" ) # Initializing the number of samples if required if self . _nb_values is None : self . _nb_values = len ( genotypes ) # Checking the expected number of samples if self . _nb_values != len ( gen...
Write genotypes to binary file .
211
7
4,471
def _read ( self , directory , filename , session , path , name , extension , spatial = None , spatialReferenceID = None , replaceParamFile = None ) : # Assign file extension attribute to file object self . fileExtension = extension timeSeries = [ ] # Open file and parse into a data structure with open ( path , 'r' ) a...
Generic Time Series Read from File Method
166
7
4,472
def _write ( self , session , openFile , replaceParamFile ) : # Retrieve all time series timeSeries = self . timeSeries # Num TimeSeries numTS = len ( timeSeries ) # Transform into list of dictionaries for pivot tool valList = [ ] for tsNum , ts in enumerate ( timeSeries ) : values = ts . values for value in values : v...
Generic Time Series Write to File Method
274
7
4,473
def as_dataframe ( self ) : time_series = { } for ts_index , ts in enumerate ( self . timeSeries ) : index = [ ] data = [ ] for value in ts . values : index . append ( value . simTime ) data . append ( value . value ) time_series [ ts_index ] = pd . Series ( data , index = index ) return pd . DataFrame ( time_series )
Return time series as pandas dataframe
94
8
4,474
def _createTimeSeriesObjects ( self , timeSeries , filename ) : try : # Determine number of value columns valColumns = len ( timeSeries [ 0 ] [ 'values' ] ) # Create List of GSSHAPY TimeSeries objects series = [ ] for i in range ( 0 , valColumns ) : ts = TimeSeries ( ) ts . timeSeriesFile = self series . append ( ts ) ...
Create GSSHAPY TimeSeries and TimeSeriesValue Objects Method
205
14
4,475
def extend ( self , * blues , memo = None ) : memo = { } if memo is None else memo for blue in blues : if isinstance ( blue , Dispatcher ) : blue = blue . blue ( memo = memo ) for method , kwargs in blue . deferred : getattr ( self , method ) ( * * kwargs ) return self
Extends deferred operations calling each operation of given Blueprints .
76
12
4,476
def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) : # Assign file extension attribute to file object self . fileExtension = extension # Open file and parse into a data structure with open ( path , 'r' ) as f : for line in f : sline = line . s...
Generic Output Location Read from File Method
157
7
4,477
def _write ( self , session , openFile , replaceParamFile ) : # Retrieve output locations locations = self . outputLocations # Write lines openFile . write ( '%s\n' % self . numLocations ) for location in locations : openFile . write ( '%s %s\n' % ( location . linkOrCellI , location . nodeOrCellJ ) )
Generic Output Location Write to File Method
84
7
4,478
def web ( self , depth = - 1 , node_data = NONE , node_function = NONE , directory = None , sites = None , run = True ) : options = { 'node_data' : node_data , 'node_function' : node_function } options = { k : v for k , v in options . items ( ) if v is not NONE } from . web import WebMap from . sol import Solution obj ...
Creates a dispatcher Flask app .
178
7
4,479
def plot ( self , workflow = None , view = True , depth = - 1 , name = NONE , comment = NONE , format = NONE , engine = NONE , encoding = NONE , graph_attr = NONE , node_attr = NONE , edge_attr = NONE , body = NONE , node_styles = NONE , node_data = NONE , node_function = NONE , edge_data = NONE , max_lines = NONE , ma...
Plots the Dispatcher with a graph in the DOT language with Graphviz .
449
18
4,480
def _api_get ( self , url , * * kwargs ) : kwargs [ 'url' ] = self . url + url kwargs [ 'auth' ] = self . auth headers = deepcopy ( self . headers ) headers . update ( kwargs . get ( 'headers' , { } ) ) kwargs [ 'headers' ] = headers return self . _get ( * * kwargs )
A convenience wrapper for _get . Adds headers auth and base url by default
92
15
4,481
def _api_put ( self , url , * * kwargs ) : kwargs [ 'url' ] = self . url + url kwargs [ 'auth' ] = self . auth headers = deepcopy ( self . headers ) headers . update ( kwargs . get ( 'headers' , { } ) ) kwargs [ 'headers' ] = headers self . _put ( * * kwargs )
A convenience wrapper for _put . Adds headers auth and base url by default
91
15
4,482
def _api_post ( self , url , * * kwargs ) : kwargs [ 'url' ] = self . url + url kwargs [ 'auth' ] = self . auth headers = deepcopy ( self . headers ) headers . update ( kwargs . get ( 'headers' , { } ) ) kwargs [ 'headers' ] = headers self . _post ( * * kwargs )
A convenience wrapper for _post . Adds headers auth and base url by default
91
15
4,483
def _api_delete ( self , url , * * kwargs ) : kwargs [ 'url' ] = self . url + url kwargs [ 'auth' ] = self . auth headers = deepcopy ( self . headers ) headers . update ( kwargs . get ( 'headers' , { } ) ) kwargs [ 'headers' ] = headers self . _delete ( * * kwargs )
A convenience wrapper for _delete . Adds headers auth and base url by default
91
15
4,484
def getAsKmlGrid ( self , session , path = None , documentName = None , colorRamp = ColorRampEnum . COLOR_RAMP_HUE , alpha = 1.0 , noDataValue = None ) : if type ( self . raster ) != type ( None ) : # Set Document Name if documentName is None : try : documentName = self . filename except AttributeError : documentName =...
Retrieve the raster as a KML document with each cell of the raster represented as a vector polygon . The result is a vector grid of raster cells . Cells with the no data value are excluded .
306
44
4,485
def getAsGrassAsciiGrid ( self , session ) : if type ( self . raster ) != type ( None ) : # Make sure the raster field is valid converter = RasterConverter ( sqlAlchemyEngineOrSession = session ) return converter . getAsGrassAsciiRaster ( tableName = self . tableName , rasterIdFieldName = 'id' , rasterId = self . id , ...
Retrieve the raster in the GRASS ASCII Grid format .
106
13
4,486
def shutdown ( url = None ) : if url is None : for host in util . hosts . values ( ) : host . shutdown ( ) global core_type core_type = None else : host = util . hosts [ url ] host . shutdown ( )
Stops the Host passed by parameter or all of them if none is specified stopping at the same time all its actors . Should be called at the end of its usage to finish correctly all the connections and threads .
53
42
4,487
def load_transport ( self , url ) : aurl = urlparse ( url ) addrl = aurl . netloc . split ( ':' ) self . addr = addrl [ 0 ] , addrl [ 1 ] self . transport = aurl . scheme self . host_url = aurl if aurl . scheme == 'http' : self . launch_actor ( 'http' , rpcactor . RPCDispatcher ( url , self , 'rpc' ) ) elif aurl . sche...
For remote communication . Sets the communication dispatcher of the host at the address and port specified .
147
18
4,488
def has_actor ( self , aid ) : url = '%s://%s/%s' % ( self . transport , self . host_url . netloc , aid ) return url in self . actors . keys ( )
Checks if the given id is used in the host by some actor .
49
15
4,489
def stop_actor ( self , aid ) : url = '%s://%s/%s' % ( self . transport , self . host_url . netloc , aid ) if url != self . url : actor = self . actors [ url ] Proxy ( actor ) . stop ( ) actor . thread . join ( ) del self . actors [ url ] del self . threads [ actor . thread ]
This method removes one actor from the Host stoping it and deleting all its references .
85
17
4,490
def lookup_url ( self , url , klass , module = None ) : if not self . alive : raise HostDownError ( ) aurl = urlparse ( url ) if self . is_local ( aurl ) : if url not in self . actors . keys ( ) : raise NotFoundError ( url ) else : return Proxy ( self . actors [ url ] ) else : try : dispatcher = self . actors [ aurl . ...
Gets a proxy reference to the actor indicated by the URL in the parameters . It can be a local reference or a remote direction to another host .
315
30
4,491
def dumps ( self , param ) : if isinstance ( param , Proxy ) : module_name = param . actor . klass . __module__ filename = sys . modules [ module_name ] . __file__ return ProxyRef ( param . actor . url , param . actor . klass . __name__ , module_name ) elif isinstance ( param , list ) : return [ self . dumps ( elem ) f...
Checks the parameters generating new proxy instances to avoid query concurrences from shared proxies and creating proxies for actors from another host .
175
26
4,492
def loads ( self , param ) : if isinstance ( param , ProxyRef ) : try : return self . lookup_url ( param . url , param . klass , param . module ) except HostError : print "Can't lookup for the actor received with the call. \ It does not exist or the url is unreachable." , param raise HostError ( param ) elif isinstance...
Checks the return parameters generating new proxy instances to avoid query concurrences from shared proxies and creating proxies for actors from another host .
182
27
4,493
def new_parallel ( self , function , * params ) : # Create a pool if not created (processes or Gevent...) if self . ppool is None : if core_type == 'thread' : from multiprocessing . pool import ThreadPool self . ppool = ThreadPool ( 500 ) else : from gevent . pool import Pool self . ppool = Pool ( 500 ) # Add the new t...
Register a new thread executing a parallel method .
106
9
4,494
def write_to_local ( self , filepath_from , filepath_to , mtime_dt = None ) : self . __log . debug ( "Writing R[%s] -> L[%s]." % ( filepath_from , filepath_to ) ) with SftpFile ( self , filepath_from , 'r' ) as sf_from : with open ( filepath_to , 'wb' ) as file_to : while 1 : part = sf_from . read ( MAX_MIRROR_WRITE_CH...
Open a remote file and write it locally .
217
9
4,495
def write_to_remote ( self , filepath_from , filepath_to , mtime_dt = None ) : self . __log . debug ( "Writing L[%s] -> R[%s]." % ( filepath_from , filepath_to ) ) with open ( filepath_from , 'rb' ) as file_from : with SftpFile ( self , filepath_to , 'w' ) as sf_to : while 1 : part = file_from . read ( MAX_MIRROR_WRITE...
Open a local file and write it remotely .
198
9
4,496
def open ( self ) : self . __sf = _sftp_open ( self . __sftp_session_int , self . __filepath , self . access_type_int , self . __create_mode ) if self . access_type_is_append is True : self . seek ( self . filesize ) return SftpFileObject ( self )
This is the only way to open a file resource .
81
11
4,497
def read ( self , size = None ) : if size is not None : return self . __sf . read ( size ) block_size = self . __class__ . __block_size b = bytearray ( ) received_bytes = 0 while 1 : partial = self . __sf . read ( block_size ) # self.__log.debug("Reading (%d) bytes. (%d) bytes returned." % # (block_size, len(partial)))...
Read a length of bytes . Return empty on EOF . If size is omitted return whole file .
165
20
4,498
def seek ( self , offset , whence = SEEK_SET ) : if whence == SEEK_SET : self . __sf . seek ( offset ) elif whence == SEEK_CUR : self . __sf . seek ( self . tell ( ) + offset ) elif whence == SEEK_END : self . __sf . seek ( self . __sf . filesize - offset )
Reposition the file pointer .
83
6
4,499
def readline ( self , size = None ) : # TODO: Add support for Unicode. ( line , nl ) = self . __buffer . read_until_nl ( self . __retrieve_data ) if self . __sf . access_type_has_universal_nl and nl is not None : self . __newlines [ nl ] = True return line
Read a single line of text with EOF .
81
10