idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
6,900
def add_statement ( self , statement_obj ) : if statement_obj . get_id ( ) in self . idx : raise ValueError ( "Statement with id {} already exists!" . format ( statement_obj . get_id ( ) ) ) self . node . append ( statement_obj . get_node ( ) ) self . idx [ statement_obj . get_id ( ) ] = statement_obj
Adds a statement object to the layer
89
7
6,901
def RootGroup ( self ) : return ( clc . v2 . Group ( id = self . root_group_id , alias = self . alias , session = self . session ) )
Returns group object for datacenter root group .
40
10
6,902
def LL ( n ) : if ( n <= 0 ) : return Context ( '0' ) else : LL1 = LL ( n - 1 ) r1 = C1 ( 3 ** ( n - 1 ) , 2 ** ( n - 1 ) ) - LL1 - LL1 r2 = LL1 - LL1 - LL1 return r1 + r2
constructs the LL context
76
5
6,903
def HH ( n ) : if ( n <= 0 ) : return Context ( '1' ) else : LL1 = LL ( n - 1 ) HH1 = HH ( n - 1 ) r1 = C1 ( 3 ** ( n - 1 ) , 2 ** ( n - 1 ) ) - LL1 - HH1 r2 = HH1 - HH1 - HH1 return r1 + r2
constructs the HH context
85
5
6,904
def AA ( n ) : if ( n <= 1 ) : return Context ( '10\n00' ) else : AA1 = AA ( n - 1 ) r1 = C1 ( 2 ** ( n - 1 ) , 2 ** ( n - 1 ) ) - AA1 r2 = AA1 - AA1 return r1 + r2
constructs the AA context
73
5
6,905
def BB ( n ) : if ( n <= 1 ) : return Context ( '0\n1' ) else : BB1 = BB ( n - 1 ) AA1 = AA ( n - 1 ) r1 = C1 ( ( n - 1 ) * 2 ** ( n - 2 ) , 2 ** ( n - 1 ) ) - AA1 - BB1 r2 = BB1 - C1 ( 2 ** ( n - 1 ) , 2 ** ( n - 1 ) ) - BB1 return r1 + r2
constructs the BB context
111
5
6,906
def processAndSetDefaults ( self ) : # INPUT, OUTPUT, GIVEN + BUILDABLE DEPS if not self . input : raise ValueError ( NO_INPUT_FILE ) if not self . output : # Build directory must exist, right? if not self . build_directory : File ( ) pass # Can it be built? / reference self.output_format for this else : pass # if it is not congruent with other info provided if not self . build_directory : pass # Initialize it for dependency in self . given_dependencies : pass # Check if the dependcy exists if self . output_format != self . output . getType ( ) : raise ValueError ( "" ) # Given dependencies must actually exist! # output_name must be at a lower extenion level than input_name # The build directory return
The heart of the Instruction object . This method will make sure that all fields not entered will be defaulted to a correct value . Also checks for incongruities in the data entered if it was by the user .
182
44
6,907
def greenlet ( func , args = ( ) , kwargs = None ) : if args or kwargs : def target ( ) : return func ( * args , * * ( kwargs or { } ) ) else : target = func return compat . greenlet ( target , state . mainloop )
create a new greenlet from a function and arguments
65
10
6,908
def schedule ( target = None , args = ( ) , kwargs = None ) : if target is None : def decorator ( target ) : return schedule ( target , args = args , kwargs = kwargs ) return decorator if isinstance ( target , compat . greenlet ) or target is compat . main_greenlet : glet = target else : glet = greenlet ( target , args , kwargs ) state . paused . append ( glet ) return target
insert a greenlet into the scheduler
103
8
6,909
def schedule_at ( unixtime , target = None , args = ( ) , kwargs = None ) : if target is None : def decorator ( target ) : return schedule_at ( unixtime , target , args = args , kwargs = kwargs ) return decorator if isinstance ( target , compat . greenlet ) or target is compat . main_greenlet : glet = target else : glet = greenlet ( target , args , kwargs ) state . timed_paused . insert ( unixtime , glet ) return target
insert a greenlet into the scheduler to be run at a set time
122
15
6,910
def schedule_in ( secs , target = None , args = ( ) , kwargs = None ) : return schedule_at ( time . time ( ) + secs , target , args , kwargs )
insert a greenlet into the scheduler to run after a set time
46
14
6,911
def schedule_recurring ( interval , target = None , maxtimes = 0 , starting_at = 0 , args = ( ) , kwargs = None ) : starting_at = starting_at or time . time ( ) if target is None : def decorator ( target ) : return schedule_recurring ( interval , target , maxtimes , starting_at , args , kwargs ) return decorator func = target if isinstance ( target , compat . greenlet ) or target is compat . main_greenlet : if target . dead : raise TypeError ( "can't schedule a dead greenlet" ) func = target . run def run_and_schedule_one ( tstamp , count ) : # pass in the time scheduled instead of just checking # time.time() so that delays don't add up if not maxtimes or count < maxtimes : tstamp += interval func ( * args , * * ( kwargs or { } ) ) schedule_at ( tstamp , run_and_schedule_one , args = ( tstamp , count + 1 ) ) firstrun = starting_at + interval schedule_at ( firstrun , run_and_schedule_one , args = ( firstrun , 0 ) ) return target
insert a greenlet into the scheduler to run regularly at an interval
272
14
6,912
def schedule_exception ( exception , target ) : if not isinstance ( target , compat . greenlet ) : raise TypeError ( "can only schedule exceptions for greenlets" ) if target . dead : raise ValueError ( "can't send exceptions to a dead greenlet" ) schedule ( target ) state . to_raise [ target ] = exception
schedule a greenlet to have an exception raised in it immediately
73
13
6,913
def schedule_exception_at ( unixtime , exception , target ) : if not isinstance ( target , compat . greenlet ) : raise TypeError ( "can only schedule exceptions for greenlets" ) if target . dead : raise ValueError ( "can't send exceptions to a dead greenlet" ) schedule_at ( unixtime , target ) state . to_raise [ target ] = exception
schedule a greenlet to have an exception raised at a unix timestamp
85
15
6,914
def schedule_exception_in ( secs , exception , target ) : schedule_exception_at ( time . time ( ) + secs , exception , target )
schedule a greenlet receive an exception after a number of seconds
36
13
6,915
def end ( target ) : if not isinstance ( target , compat . greenlet ) : raise TypeError ( "argument must be a greenlet" ) if not target . dead : schedule ( target ) state . to_raise [ target ] = compat . GreenletExit ( )
schedule a greenlet to be stopped immediately
58
9
6,916
def handle_exception ( klass , exc , tb , coro = None ) : if coro is None : coro = compat . getcurrent ( ) replacement = [ ] for weak in state . local_exception_handlers . get ( coro , ( ) ) : func = weak ( ) if func is None : continue try : func ( klass , exc , tb ) except Exception : continue replacement . append ( weak ) if replacement : state . local_exception_handlers [ coro ] [ : ] = replacement replacement = [ ] for weak in state . global_exception_handlers : func = weak ( ) if func is None : continue try : func ( klass , exc , tb ) except Exception : continue replacement . append ( weak ) state . global_exception_handlers [ : ] = replacement
run all the registered exception handlers
179
6
6,917
def global_exception_handler ( handler ) : if not hasattr ( handler , "__call__" ) : raise TypeError ( "exception handlers must be callable" ) log . info ( "setting a new global exception handler" ) state . global_exception_handlers . append ( weakref . ref ( handler ) ) return handler
add a callback for when an exception goes uncaught in any greenlet
74
14
6,918
def remove_global_exception_handler ( handler ) : for i , cb in enumerate ( state . global_exception_handlers ) : cb = cb ( ) if cb is not None and cb is handler : state . global_exception_handlers . pop ( i ) log . info ( "removing a global exception handler" ) return True return False
remove a callback from the list of global exception handlers
83
10
6,919
def local_exception_handler ( handler = None , coro = None ) : if handler is None : return lambda h : local_exception_handler ( h , coro ) if not hasattr ( handler , "__call__" ) : raise TypeError ( "exception handlers must be callable" ) if coro is None : coro = compat . getcurrent ( ) log . info ( "setting a new coroutine local exception handler" ) state . local_exception_handlers . setdefault ( coro , [ ] ) . append ( weakref . ref ( handler ) ) return handler
add a callback for when an exception occurs in a particular greenlet
129
13
6,920
def remove_local_exception_handler ( handler , coro = None ) : if coro is None : coro = compat . getcurrent ( ) for i , cb in enumerate ( state . local_exception_handlers . get ( coro , [ ] ) ) : cb = cb ( ) if cb is not None and cb is handler : state . local_exception_handlers [ coro ] . pop ( i ) log . info ( "removing a coroutine local exception handler" ) return True return False
remove a callback from the list of exception handlers for a coroutine
118
13
6,921
def global_hook ( handler ) : if not hasattr ( handler , "__call__" ) : raise TypeError ( "trace hooks must be callable" ) log . info ( "setting a new global hook callback" ) state . global_hooks . append ( weakref . ref ( handler ) ) return handler
add a callback to run in every switch between coroutines
67
12
6,922
def remove_global_hook ( handler ) : for i , cb in enumerate ( state . global_hooks ) : cb = cb ( ) if cb is not None and cb is handler : state . global_hooks . pop ( i ) log . info ( "removing a global hook callback" ) return True return False
remove a callback from the list of global hooks
74
9
6,923
def local_incoming_hook ( handler = None , coro = None ) : if handler is None : return lambda h : local_incoming_hook ( h , coro ) if not hasattr ( handler , "__call__" ) : raise TypeError ( "trace hooks must be callable" ) if coro is None : coro = compat . getcurrent ( ) log . info ( "setting a coroutine incoming local hook callback" ) state . local_to_hooks . setdefault ( coro , [ ] ) . append ( weakref . ref ( handler ) ) return handler
add a callback to run every time a greenlet is about to be switched to
127
16
6,924
def remove_local_incoming_hook ( handler , coro = None ) : if coro is None : coro = compat . getcurrent ( ) for i , cb in enumerate ( state . local_to_hooks . get ( coro , [ ] ) ) : cb = cb ( ) if cb is not None and cb is handler : log . info ( "removing a coroutine incoming local hook callback" ) state . local_to_hooks [ coro ] . pop ( i ) return True return False
remove a callback from the incoming hooks for a particular coro
117
12
6,925
def local_outgoing_hook ( handler = None , coro = None ) : if handler is None : return lambda h : local_outgoing_hook ( h , coro ) if not hasattr ( handler , "__call__" ) : raise TypeError ( "trace hooks must be callable" ) if coro is None : coro = compat . getcurrent ( ) log . info ( "setting a coroutine local outgoing hook callback" ) state . local_from_hooks . setdefault ( coro , [ ] ) . append ( weakref . ref ( handler ) ) return handler
add a callback to run every time a greenlet is switched away from
127
14
6,926
def remove_local_outgoing_hook ( handler , coro = None ) : if coro is None : coro = compat . getcurrent ( ) for i , cb in enumerate ( state . local_from_hooks . get ( coro , [ ] ) ) : cb = cb ( ) if cb is not None and cb is handler : log . info ( "removing a coroutine outgoing local hook callback" ) state . local_from_hooks [ coro ] . pop ( i ) return True return False
remove a callback from the outgoing hooks for a particular coro
117
12
6,927
def set_ignore_interrupts ( flag = True ) : log . info ( "setting ignore_interrupts to %r" % flag ) state . ignore_interrupts = bool ( flag )
turn off EINTR - raising from emulated syscalls on interruption by signals
44
17
6,928
def reset_poller ( poll = None ) : state . poller = poll or poller . best ( ) log . info ( "resetting fd poller, using %s" % type ( state . poller ) . __name__ )
replace the scheduler s poller throwing away any pre - existing state
53
14
6,929
def find_resource ( r , * , pkg = 'cyther' ) : file_path = pkg_resources . resource_filename ( pkg , os . path . join ( 'test' , r ) ) if not os . path . isfile ( file_path ) : msg = "Resource '{}' does not exist" raise FileNotFoundError ( msg . format ( file_path ) ) return file_path
Finds a given cyther resource in the test subdirectory in cyther package
92
16
6,930
def assert_output ( output , assert_equal ) : sorted_output = sorted ( output ) sorted_assert = sorted ( assert_equal ) if sorted_output != sorted_assert : raise ValueError ( ASSERT_ERROR . format ( sorted_output , sorted_assert ) )
Check that two outputs have the same contents as one another even if they aren t sorted yet
59
18
6,931
def write_dict_to_file ( file_path , obj ) : lines = [ ] for key , value in obj . items ( ) : lines . append ( key + ':' + repr ( value ) + '\n' ) with open ( file_path , 'w+' ) as file : file . writelines ( lines ) return None
Write a dictionary of string keys to a file
74
9
6,932
def read_dict_from_file ( file_path ) : with open ( file_path ) as file : lines = file . read ( ) . splitlines ( ) obj = { } for line in lines : key , value = line . split ( ':' , maxsplit = 1 ) obj [ key ] = eval ( value ) return obj
Read a dictionary of strings from a file
72
8
6,933
def get_input ( prompt , check , * , redo_prompt = None , repeat_prompt = False ) : if isinstance ( check , str ) : check = ( check , ) to_join = [ ] for item in check : if item : to_join . append ( str ( item ) ) else : to_join . append ( "''" ) prompt += " [{}]: " . format ( '/' . join ( to_join ) ) if repeat_prompt : redo_prompt = prompt elif not redo_prompt : redo_prompt = "Incorrect input, please choose from {}: " "" . format ( str ( check ) ) if callable ( check ) : def _checker ( r ) : return check ( r ) elif isinstance ( check , tuple ) : def _checker ( r ) : return r in check else : raise ValueError ( RESPONSES_ERROR . format ( type ( check ) ) ) response = input ( prompt ) while not _checker ( response ) : print ( response , type ( response ) ) response = input ( redo_prompt if redo_prompt else prompt ) return response
Ask the user to input something on the terminal level check their response and ask again if they didn t answer correctly
254
22
6,934
def get_choice ( prompt , choices ) : print ( ) checker = [ ] for offset , choice in enumerate ( choices ) : number = offset + 1 print ( "\t{}): '{}'\n" . format ( number , choice ) ) checker . append ( str ( number ) ) response = get_input ( prompt , tuple ( checker ) + ( '' , ) ) if not response : print ( "Exiting..." ) exit ( ) offset = int ( response ) - 1 selected = choices [ offset ] return selected
Asks for a single choice out of multiple items . Given those items and a prompt to ask the user with
115
22
6,935
def generateBatches ( tasks , givens ) : _removeGivensFromTasks ( tasks , givens ) batches = [ ] while tasks : batch = set ( ) for task , dependencies in tasks . items ( ) : if not dependencies : batch . add ( task ) if not batch : _batchErrorProcessing ( tasks ) for task in batch : del tasks [ task ] for task , dependencies in tasks . items ( ) : for item in batch : if item in dependencies : tasks [ task ] . remove ( item ) batches . append ( batch ) return batches
A function to generate a batch of commands to run in a specific order as to meet all the dependencies for each command . For example the commands with no dependencies are run first and the commands with the most deep dependencies are run last
120
45
6,936
def Get ( self , key ) : for group in self . groups : if group . id . lower ( ) == key . lower ( ) : return ( group ) elif group . name . lower ( ) == key . lower ( ) : return ( group ) elif group . description . lower ( ) == key . lower ( ) : return ( group ) raise ( clc . CLCException ( "Group not found" ) )
Get group by providing name ID description or other unique key .
90
12
6,937
def Search ( self , key ) : results = [ ] for group in self . groups : if group . id . lower ( ) . find ( key . lower ( ) ) != - 1 : results . append ( group ) elif group . name . lower ( ) . find ( key . lower ( ) ) != - 1 : results . append ( group ) elif group . description . lower ( ) . find ( key . lower ( ) ) != - 1 : results . append ( group ) return ( results )
Search group list by providing partial name ID description or other key .
106
13
6,938
def GetAll ( root_group_id , alias = None , session = None ) : if not alias : alias = clc . v2 . Account . GetAlias ( session = session ) groups = [ ] for r in clc . v2 . API . Call ( 'GET' , 'groups/%s/%s' % ( alias , root_group_id ) , { } , session = session ) [ 'groups' ] : groups . append ( Group ( id = r [ 'id' ] , alias = alias , group_obj = r , session = session ) ) return ( groups )
Gets a list of groups within a given account .
128
11
6,939
def Refresh ( self ) : self . dirty = False self . data = clc . v2 . API . Call ( 'GET' , 'groups/%s/%s' % ( self . alias , self . id ) , session = self . session ) self . data [ 'changeInfo' ] [ 'createdDate' ] = clc . v2 . time_utils . ZuluTSToSeconds ( self . data [ 'changeInfo' ] [ 'createdDate' ] ) self . data [ 'changeInfo' ] [ 'modifiedDate' ] = clc . v2 . time_utils . ZuluTSToSeconds ( self . data [ 'changeInfo' ] [ 'modifiedDate' ] )
Reloads the group object to synchronize with cloud representation .
155
13
6,940
def Defaults ( self , key ) : if not hasattr ( self , 'defaults' ) : self . defaults = clc . v2 . API . Call ( 'GET' , 'groups/%s/%s/defaults' % ( self . alias , self . id ) , session = self . session ) try : return ( self . defaults [ key ] [ 'value' ] ) except : return ( None )
Returns default configurations for resources deployed to this group .
91
10
6,941
def Subgroups ( self ) : return ( Groups ( alias = self . alias , groups_lst = self . data [ 'groups' ] , session = self . session ) )
Returns a Groups object containing all child groups .
38
9
6,942
def Servers ( self ) : return ( clc . v2 . Servers ( alias = self . alias , servers_lst = [ obj [ 'id' ] for obj in self . data [ 'links' ] if obj [ 'rel' ] == 'server' ] , session = self . session ) )
Returns a Servers object containing all servers within the group .
67
12
6,943
def List ( type = 'All' ) : r = clc . v1 . API . Call ( 'post' , 'Queue/ListQueueRequests' , { 'ItemStatusType' : Queue . item_status_type_map [ type ] } ) if int ( r [ 'StatusCode' ] ) == 0 : return ( r [ 'Requests' ] )
List of Queued requests and their current status details .
81
11
6,944
def _Load ( self , location ) : # https://api.ctl.io/v2-experimental/networks/ALIAS/WA1 for network in clc . v2 . API . Call ( 'GET' , '/v2-experimental/networks/%s/%s' % ( self . alias , location ) , { } , session = self . session ) : self . networks . append ( Network ( id = network [ 'id' ] , alias = self . alias , network_obj = network , session = self . session ) )
Load all networks associated with the given location .
120
9
6,945
def Get ( self , key ) : for network in self . networks : try : if network . id == key : return ( network ) if network . name == key : return ( network ) if network . cidr == key : return ( network ) except : # We ignore malformed records with missing attributes pass
Get network by providing name ID or other unique key .
64
11
6,946
def Create ( alias = None , location = None , session = None ) : if not alias : alias = clc . v2 . Account . GetAlias ( session = session ) if not location : location = clc . v2 . Account . GetLocation ( session = session ) return clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , '/v2-experimental/networks/%s/%s/claim' % ( alias , location ) , session = session ) , alias = alias , session = session )
Claims a new network within a given account .
120
10
6,947
def Delete ( self , location = None ) : if not location : location = clc . v2 . Account . GetLocation ( session = self . session ) return clc . v2 . API . Call ( 'POST' , '/v2-experimental/networks/%s/%s/%s/release' % ( self . alias , location , self . id ) , session = self . session )
Releases the calling network .
88
6
6,948
def Update ( self , name , description = None , location = None ) : if not location : location = clc . v2 . Account . GetLocation ( session = self . session ) payload = { 'name' : name } payload [ 'description' ] = description if description else self . description r = clc . v2 . API . Call ( 'PUT' , '/v2-experimental/networks/%s/%s/%s' % ( self . alias , location , self . id ) , payload , session = self . session ) self . name = self . data [ 'name' ] = name if description : self . data [ 'description' ] = description
Updates the attributes of a given Network via PUT .
145
12
6,949
def Refresh ( self , location = None ) : if not location : location = clc . v2 . Account . GetLocation ( session = self . session ) new_object = clc . v2 . API . Call ( 'GET' , '/v2-experimental/networks/%s/%s/%s' % ( self . alias , location , self . id ) , session = self . session ) if new_object : self . name = new_object [ 'name' ] self . data = new_object
Reloads the network object to synchronize with cloud representation .
113
13
6,950
def install_build_requires ( pkg_targets ) : def pip_install ( pkg_name , pkg_vers = None ) : pkg_name_version = '%s==%s' % ( pkg_name , pkg_vers ) if pkg_vers else pkg_name print '[WARNING] %s not found, attempting to install using a raw "pip install" call!' % pkg_name_version subprocess . Popen ( 'pip install %s' % pkg_name_version , shell = True ) . communicate ( ) def get_pkg_info ( pkg ) : """Get package name and version given a build_requires element""" pkg_name , pkg_vers = None , None if '==' in pkg : pkg_name , pkg_vers = pkg . split ( '==' ) else : pkg_name = pkg . replace ( '>' , '' ) . replace ( '<' , '' ) . split ( '=' ) [ 0 ] return pkg_name , pkg_vers for pkg in pkg_targets : pkg_name , pkg_vers = get_pkg_info ( pkg ) try : pkg_name_version = '%s==%s' % ( pkg_name , pkg_vers ) if pkg_vers else pkg_name if pkg_vers : version = getattr ( importlib . import_module ( pkg_name ) , '__version__' ) if version != pkg_vers : pip_install ( pkg_name , pkg_vers ) else : importlib . import_module ( pkg_name ) except ImportError : pip_install ( pkg_name , pkg_vers )
Iterate through build_requires list and pip install if package is not present accounting for version
389
18
6,951
def initiateCompilation ( args , file ) : ####commands = finalizeCommands(args, file) commands = makeCommands ( 0 , file ) if not args [ 'concise' ] and args [ 'print_args' ] : print_commands = bool ( args [ 'watch' ] ) response = multiCall ( * commands , print_commands = print_commands ) return response
Starts the entire compilation procedure
87
6
6,952
def run ( path , timer = False , repeat = 3 , number = 10000 , precision = 2 ) : code = extractAtCyther ( path ) if not code : output = "There was no '@cyther' code collected from the " "file '{}'\n" . format ( path ) # TODO This should use a result, right? return { 'returncode' : 0 , 'output' : output } module_directory = os . path . dirname ( path ) module_name = os . path . splitext ( os . path . basename ( path ) ) [ 0 ] setup_string = SETUP_TEMPLATE . format ( module_directory , module_name , '{}' ) if timer : string = TIMER_TEMPLATE . format ( setup_string , code , repeat , number , precision , '{}' ) else : string = setup_string + code script = os . path . join ( os . path . dirname ( __file__ ) , 'script.py' ) with open ( script , 'w+' ) as file : file . write ( string ) response = call ( [ 'python' , script ] ) return response
Extracts and runs the
256
6
6,953
def core ( args ) : args = furtherArgsProcessing ( args ) numfiles = len ( args [ 'filenames' ] ) interval = INTERVAL / numfiles files = processFiles ( args ) while True : for file in files : cytherize ( args , file ) if not args [ 'watch' ] : break else : time . sleep ( interval )
The heart of Cyther this function controls the main loop and can be used to perform any Cyther action . You can call if using Cyther from the module level
77
33
6,954
def set_timestamp ( self , timestamp = None ) : if timestamp is None : import time timestamp = time . strftime ( '%Y-%m-%dT%H:%M:%S%Z' ) self . node . set ( 'timestamp' , timestamp )
Set the timestamp of the linguistic processor set to None for the current time
62
14
6,955
def set_beginTimestamp ( self , btimestamp = None ) : if btimestamp is None : import time btimestamp = time . strftime ( '%Y-%m-%dT%H:%M:%S%Z' ) self . node . set ( 'beginTimestamp' , btimestamp )
Set the begin timestamp of the linguistic processor set to None for the current time
72
15
6,956
def set_endTimestamp ( self , etimestamp = None ) : if etimestamp is None : import time etimestamp = time . strftime ( '%Y-%m-%dT%H:%M:%S%Z' ) self . node . set ( 'endTimestamp' , etimestamp )
Set the end timestamp of the linguistic processor set to None for the current time
72
15
6,957
def set_publicId ( self , publicId ) : publicObj = self . get_public ( ) if publicObj is not None : publicObj . set_publicid ( publicId ) else : publicObj = Cpublic ( ) publicObj . set_publicid ( publicId ) self . set_public ( publicObj )
Sets the publicId to the public object
69
9
6,958
def set_uri ( self , uri ) : publicObj = self . get_public ( ) if publicObj is not None : publicObj . set_uri ( uri ) else : publicObj = Cpublic ( ) publicObj . set_uri ( uri ) self . set_public ( publicObj )
Sets the uri to the public object
66
9
6,959
def remove_lp ( self , layer ) : for this_node in self . node . findall ( 'linguisticProcessors' ) : if this_node . get ( 'layer' ) == layer : self . node . remove ( this_node ) break
Removes the linguistic processors for a given layer
56
9
6,960
def add_linguistic_processor ( self , layer , my_lp ) : ## Locate the linguisticProcessor element for taht layer found_lp_obj = None for this_lp in self . node . findall ( 'linguisticProcessors' ) : lp_obj = ClinguisticProcessors ( this_lp ) if lp_obj . get_layer ( ) == layer : found_lp_obj = lp_obj break if found_lp_obj is None : #Not found found_lp_obj = ClinguisticProcessors ( ) found_lp_obj . set_layer ( layer ) self . add_linguistic_processors ( found_lp_obj ) found_lp_obj . add_linguistic_processor ( my_lp )
Adds a linguistic processor to a certain layer
171
8
6,961
def get_fileDesc ( self ) : node = self . node . find ( 'fileDesc' ) if node is not None : return CfileDesc ( node = node ) else : return None
Returns the fileDesc object or None if there is no such element
41
13
6,962
def get_public ( self ) : node = self . node . find ( 'public' ) if node is not None : return Cpublic ( node = node ) else : return None
Returns the public object or None if there is no such element
38
12
6,963
def GetPackages ( classification , visibility ) : r = clc . v1 . API . Call ( 'post' , 'Blueprint/GetPackages' , { 'Classification' : Blueprint . classification_stoi [ classification ] , 'Visibility' : Blueprint . visibility_stoi [ visibility ] } ) if int ( r [ 'StatusCode' ] ) == 0 : return ( r [ 'Packages' ] )
Gets a list of Blueprint Packages filtered by classification and visibility .
91
14
6,964
def GetAllPackages ( classification ) : packages = [ ] for visibility in Blueprint . visibility_stoi . keys ( ) : try : for r in Blueprint . GetPackages ( classification , visibility ) : packages . append ( dict ( r . items ( ) + { 'Visibility' : visibility } . items ( ) ) ) except : pass if len ( packages ) : return ( packages )
Gets a list of all Blueprint Packages with a given classification .
82
14
6,965
def PackageUpload ( package , ftp_url ) : #o = urlparse.urlparse(ftp_url) # Very weak URL checking #if o.scheme.lower() != "ftp": # clc.v1.output.Status('ERROR',2,'Invalid FTP URL') # return # Confirm file exists if not os . path . isfile ( package ) : clc . v1 . output . Status ( 'ERROR' , 2 , 'Package file (%s) not found' % ( package ) ) return m = re . search ( "ftp://(?P<user>.+?):(?P<passwd>.+?)@(?P<host>.+)" , ftp_url ) try : ftp = ftplib . FTP ( m . group ( 'host' ) , m . group ( 'user' ) , m . group ( 'passwd' ) ) file = open ( package , 'rb' ) filename = re . sub ( ".*/" , "" , package ) ftp . storbinary ( "STOR %s" % ( filename ) , file ) file . close ( ) ftp . quit ( ) clc . v1 . output . Status ( 'SUCCESS' , 2 , 'Blueprint package %s Uploaded' % ( filename ) ) except Exception as e : clc . v1 . output . Status ( 'ERROR' , 2 , 'FTP error %s: %s' % ( ftp_url , str ( e ) ) ) return ( { } )
Uploads specified zip package to cloud endpoint .
332
9
6,966
def PackagePublish ( package , classification , visibility , os ) : r = clc . v1 . API . Call ( 'post' , 'Blueprint/PublishPackage' , { 'Classification' : Blueprint . classification_stoi [ classification ] , 'Name' : package , 'OperatingSystems' : os , 'Visibility' : Blueprint . visibility_stoi [ visibility ] } ) if int ( r [ 'StatusCode' ] ) == 0 : return ( r )
Publishes a Blueprint Package for use within the Blueprint Designer .
104
12
6,967
def PackagePublishUI ( package , type , visibility ) : # fetch OS list linux_lst = { 'L' : { 'selected' : False , 'Description' : 'All Linux' } } windows_lst = { 'W' : { 'selected' : False , 'Description' : 'All Windows' } } for r in clc . v1 . Server . GetTemplates ( ) : r [ 'selected' ] = False if re . search ( "Windows" , r [ 'Description' ] ) : windows_lst [ str ( r [ 'OperatingSystem' ] ) ] = r elif re . search ( "CentOS|RedHat|Ubuntu" , r [ 'Description' ] ) : linux_lst [ str ( r [ 'OperatingSystem' ] ) ] = r # Get selections if os . name == 'posix' : scr = curses . initscr ( ) curses . cbreak ( ) while True : if os . name == 'posix' : c = Blueprint . _DrawPublishPackageUIPosix ( scr , linux_lst , windows_lst ) else : c = Blueprint . _DrawPublishPackageUI ( linux_lst , windows_lst ) if c . lower ( ) == 'q' : break elif c . lower ( ) == 'l' : for l in linux_lst : linux_lst [ l ] [ 'selected' ] = not linux_lst [ l ] [ 'selected' ] elif c . lower ( ) == 'w' : for l in windows_lst : windows_lst [ l ] [ 'selected' ] = not windows_lst [ l ] [ 'selected' ] elif c in linux_lst : linux_lst [ c ] [ 'selected' ] = not linux_lst [ c ] [ 'selected' ] elif c in windows_lst : windows_lst [ c ] [ 'selected' ] = not windows_lst [ c ] [ 'selected' ] if os . name == 'posix' : curses . nocbreak ( ) curses . echo ( ) curses . endwin ( ) # Extract selections ids = [ ] for l in dict ( linux_lst . items ( ) + windows_lst . items ( ) ) . values ( ) : if l [ 'selected' ] and 'OperatingSystem' in l : ids . append ( str ( l [ 'OperatingSystem' ] ) ) clc . v1 . output . Status ( 'SUCCESS' , 2 , 'Selected operating system IDs: %s' % ( " " . join ( ids ) ) ) return ( Blueprint . PackagePublish ( package , type , visibility , ids ) )
Publishes a Blueprint Package for use within the Blueprint Designer after interactive OS selection .
595
16
6,968
def getmembers ( self ) : if self . _members is None : self . _members = _members = [ ] g = self . data_file magic = g . read ( 2 ) while magic : if magic == b'07' : magic += g . read ( 4 ) member = RPMInfo . _read ( magic , g ) if member . name == 'TRAILER!!!' : break if not member . isdir : _members . append ( member ) magic = g . read ( 2 ) return _members return self . _members
Return the members of the archive as a list of RPMInfo objects . The list has the same order as the members in the archive .
115
27
6,969
def getmember ( self , name ) : members = self . getmembers ( ) for m in members [ : : - 1 ] : if m . name == name : return m raise KeyError ( "member %s could not be found" % name )
Return an RPMInfo object for member name . If name can not be found in the archive KeyError is raised . If a member occurs more than once in the archive its last occurrence is assumed to be the most up - to - date version .
53
49
6,970
def data_file ( self ) : if self . _data_file is None : fileobj = _SubFile ( self . _fileobj , self . data_offset ) if self . headers [ "archive_compression" ] == b"xz" : if not getattr ( sys . modules [ __name__ ] , 'lzma' , False ) : raise NoLZMAModuleError ( 'lzma module not present' ) self . _data_file = lzma . LZMAFile ( fileobj ) else : self . _data_file = gzip . GzipFile ( fileobj = fileobj ) return self . _data_file
Return the uncompressed raw CPIO data of the RPM archive .
146
13
6,971
def load_input ( definition ) : if isinstance ( definition , ( str , io . TextIOWrapper ) ) : try : definition = yaml . safe_load ( definition ) except Exception as exc : raise ParsingInputError ( "Unable to parse input: %s" % str ( exc ) ) return definition
Load and parse input if needed .
69
7
6,972
def any2sql ( func , definition_dict = None , * * definition_kwargs ) : if definition_dict and definition_kwargs : raise InputError ( "Cannot process dict and kwargs input at the same time" ) definition = load_input ( definition_dict or definition_kwargs ) if definition . get ( 'returning' , '' ) == '*' : definition [ 'returning' ] = mosql_raw ( '*' ) try : result = func ( * * definition ) except ( TypeError , AttributeError ) as exc : raise ClauseError ( "Clause definition error: %s" % str ( exc ) ) from exc except Exception as exc : import json2sql . errors as json2sql_errors if exc . __class__ . __name__ not in json2sql_errors . __dict__ . keys ( ) : raise json2sql_errors . Json2SqlInternalError ( "Unhandled error: %s" % str ( exc ) ) from exc raise return result
Handle general to SQL conversion .
220
6
6,973
def _expand_join ( join_definition ) : join_table_name = join_definition . pop ( 'table' ) join_func = getattr ( mosql_query , join_definition . pop ( 'join_type' , 'join' ) ) return join_func ( join_table_name , * * join_definition )
Expand join definition to join call .
74
8
6,974
def _construct_select_query ( * * filter_definition ) : table_name = filter_definition . pop ( 'table' ) distinct = filter_definition . pop ( 'distinct' , False ) select_count = filter_definition . pop ( 'count' , False ) if distinct and select_count : raise UnsupportedDefinitionError ( 'SELECT (DISTINCT ...) is not supported' ) if select_count and 'select' in filter_definition : raise UnsupportedDefinitionError ( 'SELECT COUNT(columns) is not supported' ) if 'joins' in filter_definition : join_definitions = filter_definition . pop ( 'joins' ) if not isinstance ( join_definitions , ( tuple , list ) ) : join_definitions = ( join_definitions , ) filter_definition [ 'joins' ] = [ ] for join_def in join_definitions : filter_definition [ 'joins' ] . append ( _expand_join ( join_def ) ) if 'where' in filter_definition : for key , value in filter_definition [ 'where' ] . items ( ) : if is_filter_query ( value ) : # We can do it recursively here sub_query = value . pop ( DEFAULT_FILTER_KEY ) if value : raise ParsingInputError ( "Unknown keys for sub-query provided: %s" % value ) filter_definition [ 'where' ] [ key ] = mosql_raw ( '( {} )' . format ( _construct_select_query ( * * sub_query ) ) ) elif isinstance ( value , str ) and value . startswith ( '$' ) and QUERY_REFERENCE . fullmatch ( value [ 1 : ] ) : # Make sure we construct correct query with escaped table name and escaped column for sub-queries filter_definition [ 'where' ] [ key ] = mosql_raw ( '"{}"' . format ( '"."' . join ( value [ 1 : ] . split ( '.' ) ) ) ) raw_select = select ( table_name , * * filter_definition ) if distinct : # Note that we want to limit replace to the current SELECT, not affect nested ones raw_select = raw_select . replace ( 'SELECT' , 'SELECT DISTINCT' , 1 ) if select_count : # Note that we want to limit replace to the current SELECT, not affect nested ones raw_select = raw_select . replace ( 'SELECT *' , 'SELECT COUNT(*)' , 1 ) return raw_select
Return SELECT statement that will be used as a filter .
558
11
6,975
def connect ( self , address ) : address = _dns_resolve ( self , address ) with self . _registered ( 'we' ) : while 1 : err = self . _sock . connect_ex ( address ) if not self . _blocking or err not in _BLOCKING_OP : if err not in ( 0 , errno . EISCONN ) : raise socket . error ( err , errno . errorcode [ err ] ) return if self . _writable . wait ( self . gettimeout ( ) ) : raise socket . timeout ( "timed out" ) if scheduler . state . interrupted : raise IOError ( errno . EINTR , "interrupted system call" )
initiate a new connection to a remote socket bound to an address
152
14
6,976
def getsockopt ( self , level , optname , * args , * * kwargs ) : return self . _sock . getsockopt ( level , optname , * args , * * kwargs )
get the value of a given socket option
47
8
6,977
def makefile ( self , mode = 'r' , bufsize = - 1 ) : f = SocketFile ( self . _sock , mode ) f . _sock . settimeout ( self . gettimeout ( ) ) return f
create a file - like object that wraps the socket
50
10
6,978
def recvfrom ( self , bufsize , flags = 0 ) : with self . _registered ( 're' ) : while 1 : if self . _closed : raise socket . error ( errno . EBADF , "Bad file descriptor" ) try : return self . _sock . recvfrom ( bufsize , flags ) except socket . error , exc : if not self . _blocking or exc [ 0 ] not in _BLOCKING_OP : raise sys . exc_clear ( ) if self . _readable . wait ( self . gettimeout ( ) ) : raise socket . timeout ( "timed out" ) if scheduler . state . interrupted : raise IOError ( errno . EINTR , "interrupted system call" )
receive data on a socket that isn t necessarily a 1 - 1 connection
158
15
6,979
def send ( self , data , flags = 0 ) : with self . _registered ( 'we' ) : while 1 : try : return self . _sock . send ( data ) except socket . error , exc : if exc [ 0 ] not in _CANT_SEND or not self . _blocking : raise if self . _writable . wait ( self . gettimeout ( ) ) : raise socket . timeout ( "timed out" ) if scheduler . state . interrupted : raise IOError ( errno . EINTR , "interrupted system call" )
send data over the socket connection
120
6
6,980
def sendall ( self , data , flags = 0 ) : sent = self . send ( data , flags ) while sent < len ( data ) : sent += self . send ( data [ sent : ] , flags )
send data over the connection and keep sending until it all goes
45
12
6,981
def setsockopt ( self , level , optname , value ) : return self . _sock . setsockopt ( level , optname , value )
set the value of a given socket option
33
8
6,982
def settimeout ( self , timeout ) : if timeout is not None : timeout = float ( timeout ) self . _timeout = timeout
set the timeout for this specific socket
27
7
6,983
def get_version ( ) : if not INSTALLED : try : with open ( 'version.txt' , 'r' ) as v_fh : return v_fh . read ( ) except Exception : warnings . warn ( 'Unable to resolve package version until installed' , UserWarning ) return '0.0.0' #can't parse version without stuff installed return p_version . get_version ( HERE )
find current version information
91
4
6,984
def add_span ( self , term_span ) : new_span = Cspan ( ) new_span . create_from_ids ( term_span ) self . node . append ( new_span . get_node ( ) )
Adds a list of term ids a new span in the references
50
13
6,985
def remove_span ( self , span ) : this_node = span . get_node ( ) self . node . remove ( this_node )
Removes a specific span from the coref object
31
10
6,986
def to_kaf ( self ) : if self . type == 'NAF' : for node_coref in self . __get_corefs_nodes ( ) : node_coref . set ( 'coid' , node_coref . get ( 'id' ) ) del node_coref . attrib [ 'id' ]
Converts the coreference layer to KAF
75
9
6,987
def to_naf ( self ) : if self . type == 'KAF' : for node_coref in self . __get_corefs_nodes ( ) : node_coref . set ( 'id' , node_coref . get ( 'coid' ) ) del node_coref . attrib [ 'coid' ]
Converts the coreference layer to NAF
76
9
6,988
def remove_coreference ( self , coid ) : for this_node in self . node . findall ( 'coref' ) : if this_node . get ( 'id' ) == coid : self . node . remove ( this_node ) break
Removes the coreference with specific identifier
56
8
6,989
def vt2esofspy ( vesseltree , outputfilename = "tracer.txt" , axisorder = [ 0 , 1 , 2 ] ) : if ( type ( vesseltree ) == str ) and os . path . isfile ( vesseltree ) : import io3d vt = io3d . misc . obj_from_file ( vesseltree ) else : vt = vesseltree print ( vt [ 'general' ] ) print ( vt . keys ( ) ) vtgm = vt [ 'graph' ] [ 'microstructure' ] lines = [ ] vs = vt [ 'general' ] [ 'voxel_size_mm' ] sh = vt [ 'general' ] [ 'shape_px' ] # switch axis ax = axisorder lines . append ( "#Tracer+\n" ) lines . append ( "#voxelsize mm %f %f %f\n" % ( vs [ ax [ 0 ] ] , vs [ ax [ 1 ] ] , vs [ ax [ 2 ] ] ) ) lines . append ( "#shape %i %i %i\n" % ( sh [ ax [ 0 ] ] , sh [ ax [ 1 ] ] , sh [ ax [ 2 ] ] ) ) lines . append ( str ( len ( vtgm ) * 2 ) + "\n" ) i = 1 for id in vtgm : # edge[''] try : nda = vtgm [ id ] [ 'nodeA_ZYX' ] ndb = vtgm [ id ] [ 'nodeB_ZYX' ] lines . append ( "%i\t%i\t%i\t%i\n" % ( nda [ ax [ 0 ] ] , nda [ ax [ 1 ] ] , nda [ ax [ 2 ] ] , i ) ) lines . append ( "%i\t%i\t%i\t%i\n" % ( ndb [ ax [ 0 ] ] , ndb [ ax [ 1 ] ] , ndb [ ax [ 2 ] ] , i ) ) i += 1 except : pass lines . append ( "%i\t%i\t%i\t%i" % ( 0 , 0 , 0 , 0 ) ) lines [ 3 ] = str ( i - 1 ) + "\n" with open ( outputfilename , 'wt' ) as f : f . writelines ( lines )
exports vesseltree to esofspy format
521
10
6,990
def constq_grun ( v , v0 , gamma0 , q ) : x = v / v0 return gamma0 * np . power ( x , q )
calculate Gruneisen parameter for constant q
36
10
6,991
def constq_debyetemp ( v , v0 , gamma0 , q , theta0 ) : gamma = constq_grun ( v , v0 , gamma0 , q ) if isuncertainties ( [ v , v0 , gamma0 , q , theta0 ] ) : theta = theta0 * unp . exp ( ( gamma0 - gamma ) / q ) else : theta = theta0 * np . exp ( ( gamma0 - gamma ) / q ) return theta
calculate Debye temperature for constant q
110
9
6,992
def constq_pth ( v , temp , v0 , gamma0 , q , theta0 , n , z , t_ref = 300. , three_r = 3. * constants . R ) : v_mol = vol_uc2mol ( v , z ) # x = v / v0 gamma = constq_grun ( v , v0 , gamma0 , q ) theta = constq_debyetemp ( v , v0 , gamma0 , q , theta0 ) xx = theta / temp debye = debye_E ( xx ) if t_ref == 0. : debye0 = 0. else : xx0 = theta / t_ref debye0 = debye_E ( xx0 ) Eth0 = three_r * n * t_ref * debye0 Eth = three_r * n * temp * debye delEth = Eth - Eth0 p_th = ( gamma / v_mol * delEth ) * 1.e-9 return p_th
calculate thermal pressure for constant q
222
8
6,993
def getValidReff ( self , urn , inventory = None , level = None ) : return self . call ( { "inv" : inventory , "urn" : urn , "level" : level , "request" : "GetValidReff" } )
Retrieve valid urn - references for a text
57
10
6,994
def getPassage ( self , urn , inventory = None , context = None ) : return self . call ( { "inv" : inventory , "urn" : urn , "context" : context , "request" : "GetPassage" } )
Retrieve a passage
55
4
6,995
def getPassagePlus ( self , urn , inventory = None , context = None ) : return self . call ( { "inv" : inventory , "urn" : urn , "context" : context , "request" : "GetPassagePlus" } )
Retrieve a passage and information about it
57
8
6,996
def parse_intervals ( diff_report ) : for patch in diff_report . patch_set : try : old_pf = diff_report . old_file ( patch . source_file ) new_pf = diff_report . new_file ( patch . target_file ) except InvalidPythonFile : continue for hunk in patch : for line in hunk : if line . line_type == LINE_TYPE_ADDED : idx = line . target_line_no yield ContextInterval ( new_pf . filename , new_pf . context ( idx ) ) elif line . line_type == LINE_TYPE_REMOVED : idx = line . source_line_no yield ContextInterval ( old_pf . filename , old_pf . context ( idx ) ) elif line . line_type in ( LINE_TYPE_EMPTY , LINE_TYPE_CONTEXT ) : pass else : raise AssertionError ( "Unexpected line type: %s" % line )
Parse a diff into an iterator of Intervals .
221
11
6,997
def string_literal ( content ) : if '"' in content and "'" in content : # there is no way to escape string literal characters in XPath raise ValueError ( "Cannot represent this string in XPath" ) if '"' in content : # if it contains " wrap it in ' content = "'%s'" % content else : # wrap it in " content = '"%s"' % content return content
Choose a string literal that can wrap our string .
89
10
6,998
def element_id_by_label ( browser , label ) : label = ElementSelector ( browser , str ( '//label[contains(., %s)]' % string_literal ( label ) ) ) if not label : return False return label . get_attribute ( 'for' )
The ID of an element referenced by a label s for attribute . The label must be visible .
63
19
6,999
def find_button ( browser , value ) : field_types = ( 'submit' , 'reset' , 'button-element' , 'button' , 'image' , 'button-role' , ) return reduce ( operator . add , ( find_field_with_value ( browser , field_type , value ) for field_type in field_types ) )
Find a button with the given value .
78
8