idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
249,100
def iter_module_paths ( modules = None ) : modules = modules or list ( sys . modules . values ( ) ) for module in modules : try : filename = module . __file__ except ( AttributeError , ImportError ) : # pragma: no cover continue if filename is not None : abs_filename = os . path . abspath ( filename ) if os . path . is...
Yield paths of all imported modules .
94
8
249,101
def update_paths ( self ) : new_paths = [ ] with self . lock : for path in expand_source_paths ( iter_module_paths ( ) ) : if path not in self . paths : self . paths . add ( path ) new_paths . append ( path ) if new_paths : self . watch_paths ( new_paths )
Check sys . modules for paths to add to our path set .
84
13
249,102
def search_traceback ( self , tb ) : new_paths = [ ] with self . lock : for filename , line , funcname , txt in traceback . extract_tb ( tb ) : path = os . path . abspath ( filename ) if path not in self . paths : self . paths . add ( path ) new_paths . append ( path ) if new_paths : self . watch_paths ( new_paths )
Inspect a traceback for new paths to add to our path set .
101
15
249,103
def args_from_interpreter_flags ( ) : flag_opt_map = { 'debug' : 'd' , 'dont_write_bytecode' : 'B' , 'no_user_site' : 's' , 'no_site' : 'S' , 'ignore_environment' : 'E' , 'verbose' : 'v' , 'bytes_warning' : 'b' , 'quiet' : 'q' , 'optimize' : 'O' , } args = [ ] for flag , opt in flag_opt_map . items ( ) : v = getattr ( ...
Return a list of command - line arguments reproducing the current settings in sys . flags and sys . warnoptions .
180
23
249,104
def spawn ( spec , kwargs , pass_fds = ( ) ) : r , w = os . pipe ( ) for fd in [ r ] + list ( pass_fds ) : set_inheritable ( fd , True ) preparation_data = get_preparation_data ( ) r_handle = get_handle ( r ) args , env = get_command_line ( pipe_handle = r_handle ) process = subprocess . Popen ( args , env = env , clos...
Invoke a python function in a subprocess .
165
10
249,105
def get_watchman_sockpath ( binpath = 'watchman' ) : path = os . getenv ( 'WATCHMAN_SOCK' ) if path : return path cmd = [ binpath , '--output-encoding=json' , 'get-sockname' ] result = subprocess . check_output ( cmd ) result = json . loads ( result ) return result [ 'sockname' ]
Find the watchman socket or raise .
91
8
249,106
def start_reloader ( worker_path , reload_interval = 1 , shutdown_interval = default , verbose = 1 , logger = None , monitor_factory = None , worker_args = None , worker_kwargs = None , ignore_files = None , ) : if is_active ( ) : return get_reloader ( ) if logger is None : logger = DefaultLogger ( verbose ) if monitor...
Start a monitor and then fork a worker process which starts by executing the importable function at worker_path .
212
22
249,107
def run ( self ) : self . _capture_signals ( ) self . _start_monitor ( ) try : while True : if not self . _run_worker ( ) : self . _wait_for_changes ( ) time . sleep ( self . reload_interval ) except KeyboardInterrupt : pass finally : self . _stop_monitor ( ) self . _restore_signals ( ) sys . exit ( 1 )
Execute the reloader forever blocking the current thread .
93
11
249,108
def run_once ( self ) : self . _capture_signals ( ) self . _start_monitor ( ) try : self . _run_worker ( ) except KeyboardInterrupt : return finally : self . _stop_monitor ( ) self . _restore_signals ( )
Execute the worker once .
62
6
249,109
def malloc ( self , key , shape , dtype ) : if key not in self . _memory or self . _memory [ key ] . shape != shape or self . _memory [ key ] . dtype != dtype : self . _memory [ key ] = Shmem ( key , shape , dtype , self . _uuid ) return self . _memory [ key ] . np_array
Allocates a block of shared memory and returns a numpy array whose data corresponds with that block .
85
21
249,110
def package_info ( pkg_name ) : indent = " " for config , _ in _iter_packages ( ) : if pkg_name == config [ "name" ] : print ( "Package:" , pkg_name ) print ( indent , "Platform:" , config [ "platform" ] ) print ( indent , "Version:" , config [ "version" ] ) print ( indent , "Path:" , config [ "path" ] ) print ( indent...
Prints the information of a package .
140
8
249,111
def world_info ( world_name , world_config = None , initial_indent = "" , next_indent = " " ) : if world_config is None : for config , _ in _iter_packages ( ) : for world in config [ "maps" ] : if world [ "name" ] == world_name : world_config = world if world_config is None : raise HolodeckException ( "Couldn't find wo...
Gets and prints the information of a world .
296
10
249,112
def install ( package_name ) : holodeck_path = util . get_holodeck_path ( ) binary_website = "https://s3.amazonaws.com/holodeckworlds/" if package_name not in packages : raise HolodeckException ( "Unknown package name " + package_name ) package_url = packages [ package_name ] print ( "Installing " + package_name + " at...
Installs a holodeck package .
189
8
249,113
def remove ( package_name ) : if package_name not in packages : raise HolodeckException ( "Unknown package name " + package_name ) for config , path in _iter_packages ( ) : if config [ "name" ] == package_name : shutil . rmtree ( path )
Removes a holodeck package .
65
8
249,114
def make ( world_name , gl_version = GL_VERSION . OPENGL4 , window_res = None , cam_res = None , verbose = False ) : holodeck_worlds = _get_worlds_map ( ) if world_name not in holodeck_worlds : raise HolodeckException ( "Invalid World Name" ) param_dict = copy ( holodeck_worlds [ world_name ] ) param_dict [ "start_worl...
Creates a holodeck environment using the supplied world name .
251
13
249,115
def unlink ( self ) : if os . name == "posix" : self . __linux_unlink__ ( ) elif os . name == "nt" : self . __windows_unlink__ ( ) else : raise HolodeckException ( "Currently unsupported os: " + os . name )
unlinks the shared memory
66
5
249,116
def add_number_parameters ( self , number ) : if isinstance ( number , list ) : for x in number : self . add_number_parameters ( x ) return self . _parameters . append ( "{ \"value\": " + str ( number ) + " }" )
Add given number parameters to the internal list .
62
9
249,117
def add_string_parameters ( self , string ) : if isinstance ( string , list ) : for x in string : self . add_string_parameters ( x ) return self . _parameters . append ( "{ \"value\": \"" + string + "\" }" )
Add given string parameters to the internal list .
61
9
249,118
def set_type ( self , weather_type ) : weather_type . lower ( ) exists = self . has_type ( weather_type ) if exists : self . add_string_parameters ( weather_type )
Set the weather type .
47
5
249,119
def uav_example ( ) : env = holodeck . make ( "UrbanCity" ) # This changes the control scheme for the uav env . set_control_scheme ( "uav0" , ControlSchemes . UAV_ROLL_PITCH_YAW_RATE_ALT ) for i in range ( 10 ) : env . reset ( ) # This command tells the UAV to not roll or pitch, but to constantly yaw left at 10m altitu...
A basic example of how to use the UAV agent .
180
12
249,120
def sphere_example ( ) : env = holodeck . make ( "MazeWorld" ) # This command is to constantly rotate to the right command = 2 for i in range ( 10 ) : env . reset ( ) for _ in range ( 1000 ) : state , reward , terminal , _ = env . step ( command ) # To access specific sensor data: pixels = state [ Sensors . PIXEL_CAMER...
A basic example of how to use the sphere agent .
106
11
249,121
def android_example ( ) : env = holodeck . make ( "AndroidPlayground" ) # The Android's command is a 94 length vector representing torques to be applied at each of his joints command = np . ones ( 94 ) * 10 for i in range ( 10 ) : env . reset ( ) for j in range ( 1000 ) : if j % 50 == 0 : command *= - 1 state , reward ...
A basic example of how to use the android agent .
136
11
249,122
def multi_agent_example ( ) : env = holodeck . make ( "UrbanCity" ) cmd0 = np . array ( [ 0 , 0 , - 2 , 10 ] ) cmd1 = np . array ( [ 0 , 0 , 5 , 10 ] ) for i in range ( 10 ) : env . reset ( ) # This will queue up a new agent to spawn into the environment, given that the coordinates are not blocked. sensors = [ Sensors ...
A basic example of using multiple agents
344
7
249,123
def world_command_examples ( ) : env = holodeck . make ( "MazeWorld" ) # This is the unaltered MazeWorld for _ in range ( 300 ) : _ = env . tick ( ) env . reset ( ) # The set_day_time_command sets the hour between 0 and 23 (military time). This example sets it to 6 AM. env . set_day_time ( 6 ) for _ in range ( 300 ) : ...
A few examples to showcase commands for manipulating the worlds .
395
11
249,124
def editor_example ( ) : sensors = [ Sensors . PIXEL_CAMERA , Sensors . LOCATION_SENSOR , Sensors . VELOCITY_SENSOR ] agent = AgentDefinition ( "uav0" , agents . UavAgent , sensors ) env = HolodeckEnvironment ( agent , start_world = False ) env . agents [ "uav0" ] . set_control_scheme ( 1 ) command = [ 0 , 0 , 10 , 50 ...
This editor example shows how to interact with holodeck worlds while they are being built in the Unreal Engine . Most people that use holodeck will not need this .
143
34
249,125
def editor_multi_agent_example ( ) : agent_definitions = [ AgentDefinition ( "uav0" , agents . UavAgent , [ Sensors . PIXEL_CAMERA , Sensors . LOCATION_SENSOR ] ) , AgentDefinition ( "uav1" , agents . UavAgent , [ Sensors . LOCATION_SENSOR , Sensors . VELOCITY_SENSOR ] ) ] env = HolodeckEnvironment ( agent_definitions ...
This editor example shows how to interact with holodeck worlds that have multiple agents . This is specifically for when working with UE4 directly and not a prebuilt binary .
248
34
249,126
def get_holodeck_path ( ) : if "HOLODECKPATH" in os . environ and os . environ [ "HOLODECKPATH" ] != "" : return os . environ [ "HOLODECKPATH" ] if os . name == "posix" : return os . path . expanduser ( "~/.local/share/holodeck" ) elif os . name == "nt" : return os . path . expanduser ( "~\\AppData\\Local\\holodeck" ) ...
Gets the path of the holodeck environment
137
10
249,127
def convert_unicode ( value ) : if isinstance ( value , dict ) : return { convert_unicode ( key ) : convert_unicode ( value ) for key , value in value . iteritems ( ) } elif isinstance ( value , list ) : return [ convert_unicode ( item ) for item in value ] elif isinstance ( value , unicode ) : return value . encode ( ...
Resolves python 2 issue with json loading in unicode instead of string
97
14
249,128
def info ( self ) : result = list ( ) result . append ( "Agents:\n" ) for agent in self . _all_agents : result . append ( "\tName: " ) result . append ( agent . name ) result . append ( "\n\tType: " ) result . append ( type ( agent ) . __name__ ) result . append ( "\n\t" ) result . append ( "Sensors:\n" ) for sensor in...
Returns a string with specific information about the environment . This information includes which agents are in the environment and which sensors they have .
154
25
249,129
def reset ( self ) : self . _reset_ptr [ 0 ] = True self . _commands . clear ( ) for _ in range ( self . _pre_start_steps + 1 ) : self . tick ( ) return self . _default_state_fn ( )
Resets the environment and returns the state . If it is a single agent environment it returns that state for that agent . Otherwise it returns a dict from agent name to state .
59
35
249,130
def step ( self , action ) : self . _agent . act ( action ) self . _handle_command_buffer ( ) self . _client . release ( ) self . _client . acquire ( ) return self . _get_single_state ( )
Supplies an action to the main agent and tells the environment to tick once . Primary mode of interaction for single agent environments .
54
25
249,131
def teleport ( self , agent_name , location = None , rotation = None ) : self . agents [ agent_name ] . teleport ( location * 100 , rotation ) # * 100 to convert m to cm self . tick ( )
Teleports the target agent to any given location and applies a specific rotation .
48
15
249,132
def tick ( self ) : self . _handle_command_buffer ( ) self . _client . release ( ) self . _client . acquire ( ) return self . _get_full_state ( )
Ticks the environment once . Normally used for multi - agent environments .
43
14
249,133
def add_state_sensors ( self , agent_name , sensors ) : if isinstance ( sensors , list ) : for sensor in sensors : self . add_state_sensors ( agent_name , sensor ) else : if agent_name not in self . _sensor_map : self . _sensor_map [ agent_name ] = dict ( ) self . _sensor_map [ agent_name ] [ sensors ] = self . _client...
Adds a sensor to a particular agent . This only works if the world you are running also includes that particular sensor on the agent .
136
26
249,134
def spawn_agent ( self , agent_definition , location ) : self . _should_write_to_command_buffer = True self . _add_agents ( agent_definition ) command_to_send = SpawnAgentCommand ( location , agent_definition . name , agent_definition . type ) self . _commands . add_command ( command_to_send )
Queues a spawn agent command . It will be applied when tick or step is called next . The agent won t be able to be used until the next frame .
79
33
249,135
def set_fog_density ( self , density ) : if density < 0 or density > 1 : raise HolodeckException ( "Fog density should be between 0 and 1" ) self . _should_write_to_command_buffer = True command_to_send = ChangeFogDensityCommand ( density ) self . _commands . add_command ( command_to_send )
Queue up a change fog density command . It will be applied when tick or step is called next . By the next tick the exponential height fog in the world will have the new density . If there is no fog in the world it will be automatically created with the given density .
85
55
249,136
def set_day_time ( self , hour ) : self . _should_write_to_command_buffer = True command_to_send = DayTimeCommand ( hour % 24 ) self . _commands . add_command ( command_to_send )
Queue up a change day time command . It will be applied when tick or step is called next . By the next tick the lighting and the skysphere will be updated with the new hour . If there is no skysphere or directional light in the world the command will not function properly but will not cause a crash .
56
67
249,137
def start_day_cycle ( self , day_length ) : if day_length <= 0 : raise HolodeckException ( "The given day length should be between above 0!" ) self . _should_write_to_command_buffer = True command_to_send = DayCycleCommand ( True ) command_to_send . set_day_length ( day_length ) self . _commands . add_command ( command...
Queue up a day cycle command to start the day cycle . It will be applied when tick or step is called next . The sky sphere will now update each tick with an updated sun angle as it moves about the sky . The length of a day will be roughly equivalent to the number of minutes given .
98
60
249,138
def stop_day_cycle ( self ) : self . _should_write_to_command_buffer = True command_to_send = DayCycleCommand ( False ) self . _commands . add_command ( command_to_send )
Queue up a day cycle command to stop the day cycle . It will be applied when tick or step is called next . By the next tick day cycle will stop where it is .
53
36
249,139
def teleport_camera ( self , location , rotation ) : self . _should_write_to_command_buffer = True command_to_send = TeleportCameraCommand ( location , rotation ) self . _commands . add_command ( command_to_send )
Queue up a teleport camera command to stop the day cycle . By the next tick the camera s location and rotation will be updated
57
25
249,140
def set_control_scheme ( self , agent_name , control_scheme ) : if agent_name not in self . agents : print ( "No such agent %s" % agent_name ) else : self . agents [ agent_name ] . set_control_scheme ( control_scheme )
Set the control scheme for a specific agent .
67
9
249,141
def _handle_command_buffer ( self ) : if self . _should_write_to_command_buffer : self . _write_to_command_buffer ( self . _commands . to_json ( ) ) self . _should_write_to_command_buffer = False self . _commands . clear ( )
Checks if we should write to the command buffer writes all of the queued commands to the buffer and then clears the contents of the self . _commands list
71
33
249,142
def _write_to_command_buffer ( self , to_write ) : # TODO(mitch): Handle the edge case of writing too much data to the buffer. np . copyto ( self . _command_bool_ptr , True ) to_write += '0' # The gason JSON parser in holodeck expects a 0 at the end of the file. input_bytes = str . encode ( to_write ) for index , val i...
Write input to the command buffer . Reformat input string to the correct format .
118
16
249,143
def teleport ( self , location = None , rotation = None ) : val = 0 if location is not None : val += 1 np . copyto ( self . _teleport_buffer , location ) if rotation is not None : np . copyto ( self . _rotation_buffer , rotation ) val += 2 self . _teleport_bool_buffer [ 0 ] = val
Teleports the agent to a specific location with a specific rotation .
79
13
249,144
def url ( self , request = "" ) : if request . startswith ( "/" ) : request = request [ 1 : ] return "{}://{}/{}" . format ( self . scheme , self . host , request )
Build the url with the appended request if provided .
50
11
249,145
def object_url ( self , object_t , object_id = None , relation = None , * * kwargs ) : if object_t not in self . objects_types : raise TypeError ( "{} is not a valid type" . format ( object_t ) ) request_items = ( str ( item ) for item in [ object_t , object_id , relation ] if item is not None ) request = "/" . join ( ...
Helper method to build the url to query to access the object passed as parameter
251
15
249,146
def get_album ( self , object_id , relation = None , * * kwargs ) : return self . get_object ( "album" , object_id , relation = relation , * * kwargs )
Get the album with the provided id
47
7
249,147
def get_artist ( self , object_id , relation = None , * * kwargs ) : return self . get_object ( "artist" , object_id , relation = relation , * * kwargs )
Get the artist with the provided id
47
7
249,148
def search ( self , query , relation = None , index = 0 , limit = 25 , * * kwargs ) : return self . get_object ( "search" , relation = relation , q = query , index = index , limit = limit , * * kwargs )
Search track album artist or user
59
6
249,149
def advanced_search ( self , terms , relation = None , index = 0 , limit = 25 , * * kwargs ) : assert isinstance ( terms , dict ) , "terms must be a dict" # terms are sorted (for consistent tests between Python < 3.7 and >= 3.7) query = " " . join ( sorted ( [ '{}:"{}"' . format ( k , v ) for ( k , v ) in terms . items...
Advanced search of track album or artist .
136
8
249,150
def asdict ( self ) : result = { } for key in self . _fields : value = getattr ( self , key ) if isinstance ( value , list ) : value = [ i . asdict ( ) if isinstance ( i , Resource ) else i for i in value ] if isinstance ( value , Resource ) : value = value . asdict ( ) result [ key ] = value return result
Convert resource to dictionary
86
5
249,151
def get_relation ( self , relation , * * kwargs ) : # pylint: disable=E1101 return self . client . get_object ( self . type , self . id , relation , self , * * kwargs )
Generic method to load the relation from any resource .
53
10
249,152
def iter_relation ( self , relation , * * kwargs ) : # pylint: disable=E1101 index = 0 while 1 : items = self . get_relation ( relation , index = index , * * kwargs ) for item in items : yield ( item ) if len ( items ) == 0 : break index += len ( items )
Generic method to iterate relation from any resource .
76
10
249,153
def run ( graph , save_on_github = False , main_entity = None ) : try : ontology = graph . all_ontologies [ 0 ] uri = ontology . uri except : ontology = None uri = ";" . join ( [ s for s in graph . sources ] ) # ontotemplate = open("template.html", "r") ontotemplate = open ( ONTODOCS_VIZ_TEMPLATES + "sigmajs.html" , "r...
2016 - 11 - 30
667
5
249,154
def _debugGraph ( self ) : print ( "Len of graph: " , len ( self . rdflib_graph ) ) for x , y , z in self . rdflib_graph : print ( x , y , z )
internal util to print out contents of graph
53
8
249,155
def load_uri ( self , uri ) : # if self.verbose: printDebug("----------") if self . verbose : printDebug ( "Reading: <%s>" % uri , fg = "green" ) success = False sorted_fmt_opts = try_sort_fmt_opts ( self . rdf_format_opts , uri ) for f in sorted_fmt_opts : if self . verbose : printDebug ( ".. trying rdf serialization:...
Load a single resource into the graph for this object .
329
11
249,156
def print_summary ( self ) : if self . sources_valid : printDebug ( "----------\nLoaded %d triples.\n----------" % len ( self . rdflib_graph ) , fg = 'white' ) printDebug ( "RDF sources loaded successfully: %d of %d." % ( len ( self . sources_valid ) , len ( self . sources_valid ) + len ( self . sources_invalid ) ) , f...
print out stats about loading operation
248
6
249,157
def loading_failed ( self , rdf_format_opts , uri = "" ) : if uri : uri = " <%s>" % str ( uri ) printDebug ( "----------\nFatal error parsing graph%s\n(using RDF serializations: %s)" % ( uri , str ( rdf_format_opts ) ) , "red" ) printDebug ( "----------\nTIP: You can try one of the following RDF validation services\n<h...
default message if we need to abort loading
159
8
249,158
def _build_qname ( self , uri = None , namespaces = None ) : if not uri : uri = self . uri if not namespaces : namespaces = self . namespaces return uri2niceString ( uri , namespaces )
extracts a qualified name for a uri
57
10
249,159
def ancestors ( self , cl = None , noduplicates = True ) : if not cl : cl = self if cl . parents ( ) : bag = [ ] for x in cl . parents ( ) : if x . uri != cl . uri : # avoid circular relationships bag += [ x ] + self . ancestors ( x , noduplicates ) else : bag += [ x ] # finally: if noduplicates : return remove_duplica...
returns all ancestors in the taxonomy
110
8
249,160
def descendants ( self , cl = None , noduplicates = True ) : if not cl : cl = self if cl . children ( ) : bag = [ ] for x in cl . children ( ) : if x . uri != cl . uri : # avoid circular relationships bag += [ x ] + self . descendants ( x , noduplicates ) else : bag += [ x ] # finally: if noduplicates : return remove_d...
returns all descendants in the taxonomy
110
8
249,161
def annotations ( self , qname = True ) : if qname : return sorted ( [ ( uri2niceString ( x , self . namespaces ) ) , ( uri2niceString ( y , self . namespaces ) ) , z ] for x , y , z in self . triples ) else : return sorted ( self . triples )
wrapper that returns all triples for an onto . By default resources URIs are transformed into qnames
75
20
249,162
def printStats ( self ) : printDebug ( "----------------" ) printDebug ( "Parents......: %d" % len ( self . parents ( ) ) ) printDebug ( "Children.....: %d" % len ( self . children ( ) ) ) printDebug ( "Ancestors....: %d" % len ( self . ancestors ( ) ) ) printDebug ( "Descendants..: %d" % len ( self . descendants ( ) )...
shortcut to pull out useful info for interactive use
164
10
249,163
def load_sparql ( self , sparql_endpoint , verbose = False , hide_base_schemas = True , hide_implicit_types = True , hide_implicit_preds = True , credentials = None ) : try : # graph = rdflib.Graph('SPARQLStore') # graph = rdflib.ConjunctiveGraph('SPARQLStore') graph = rdflib . ConjunctiveGraph ( 'SPARQLUpdateStore' ) ...
Set up a SPARQLStore backend as a virtual ontospy graph
295
15
249,164
def build_all ( self , verbose = False , hide_base_schemas = True , hide_implicit_types = True , hide_implicit_preds = True ) : if verbose : printDebug ( "Scanning entities..." , "green" ) printDebug ( "----------" , "comment" ) self . build_ontologies ( ) if verbose : printDebug ( "Ontologies.........: %d" % len ( sel...
Extract all ontology entities from an RDF graph and construct Python representations of them .
429
18
249,165
def build_ontologies ( self , exclude_BNodes = False , return_string = False ) : out = [ ] qres = self . sparqlHelper . getOntology ( ) if qres : # NOTE: SPARQL returns a list of rdflib.query.ResultRow (~ tuples..) for candidate in qres : if isBlankNode ( candidate [ 0 ] ) : if exclude_BNodes : continue else : checkDC_...
Extract ontology instances info from the graph then creates python objects for them .
461
16
249,166
def build_entity_from_uri ( self , uri , ontospyClass = None ) : if not ontospyClass : ontospyClass = RDF_Entity elif not issubclass ( ontospyClass , RDF_Entity ) : click . secho ( "Error: <%s> is not a subclass of ontospy.RDF_Entity" % str ( ontospyClass ) ) return None else : pass qres = self . sparqlHelper . entityT...
Extract RDF statements having a URI as subject then instantiate the RDF_Entity Python object so that it can be queried further .
231
29
249,167
def printClassTree ( self , element = None , showids = False , labels = False , showtype = False ) : TYPE_MARGIN = 11 # length for owl:class etc.. if not element : # first time for x in self . toplayer_classes : printGenericTree ( x , 0 , showids , labels , showtype , TYPE_MARGIN ) else : printGenericTree ( element , 0...
Print nicely into stdout the class tree of an ontology
104
12
249,168
def printPropertyTree ( self , element = None , showids = False , labels = False , showtype = False ) : TYPE_MARGIN = 18 # length for owl:AnnotationProperty etc.. if not element : # first time for x in self . toplayer_properties : printGenericTree ( x , 0 , showids , labels , showtype , TYPE_MARGIN ) else : printGeneri...
Print nicely into stdout the property tree of an ontology
106
12
249,169
def add ( self , text = "" , default_continuousAdd = True ) : if not text and default_continuousAdd : self . continuousAdd ( ) else : pprefix = "" for x , y in self . rdflib_graph . namespaces ( ) : pprefix += "@prefix %s: <%s> . \n" % ( x , y ) # add final . if missing if text and ( not text . strip ( ) . endswith ( "...
add some turtle text
177
4
249,170
def rdf_source ( self , aformat = "turtle" ) : if aformat and aformat not in self . SUPPORTED_FORMATS : return "Sorry. Allowed formats are %s" % str ( self . SUPPORTED_FORMATS ) if aformat == "dot" : return self . __serializedDot ( ) else : # use stardard rdf serializations return self . rdflib_graph . serialize ( form...
Serialize graph using the format required
102
7
249,171
def omnigraffle ( self ) : temp = self . rdf_source ( "dot" ) try : # try to put in the user/tmp folder from os . path import expanduser home = expanduser ( "~" ) filename = home + "/tmp/turtle_sketch.dot" f = open ( filename , "w" ) except : filename = "turtle_sketch.dot" f = open ( filename , "w" ) f . write ( temp )...
tries to open an export directly in omnigraffle
136
13
249,172
def main ( ) : print ( "Ontospy " + VERSION ) Shell ( ) . _clear_screen ( ) print ( Style . BRIGHT + "** Ontospy Interactive Ontology Browser " + VERSION + " **" + Style . RESET_ALL ) # manager.get_or_create_home_repo() Shell ( ) . cmdloop ( ) raise SystemExit ( 1 )
standalone line script
86
4
249,173
def _print ( self , ms , style = "TIP" ) : styles1 = { 'IMPORTANT' : Style . BRIGHT , 'TIP' : Style . DIM , 'URI' : Style . BRIGHT , 'TEXT' : Fore . GREEN , 'MAGENTA' : Fore . MAGENTA , 'BLUE' : Fore . BLUE , 'GREEN' : Fore . GREEN , 'RED' : Fore . RED , 'DEFAULT' : Style . DIM , } try : print ( styles1 [ style ] + ms ...
abstraction for managing color printing
148
7
249,174
def _printM ( self , messages ) : if len ( messages ) == 2 : print ( Style . BRIGHT + messages [ 0 ] + Style . RESET_ALL + Fore . BLUE + messages [ 1 ] + Style . RESET_ALL ) else : print ( "Not implemented" )
print a list of strings - for the mom used only by stats printout
63
15
249,175
def _printDescription ( self , hrlinetop = True ) : if hrlinetop : self . _print ( "----------------" ) NOTFOUND = "[not found]" if self . currentEntity : obj = self . currentEntity [ 'object' ] label = obj . bestLabel ( ) or NOTFOUND description = obj . bestDescription ( ) or NOTFOUND print ( Style . BRIGHT + "OBJECT ...
generic method to print out a description
506
7
249,176
def _next_ontology ( self ) : currentfile = self . current [ 'file' ] try : idx = self . all_ontologies . index ( currentfile ) return self . all_ontologies [ idx + 1 ] except : return self . all_ontologies [ 0 ]
Dynamically retrieves the next ontology in the list
63
12
249,177
def _load_ontology ( self , filename , preview_mode = False ) : if not preview_mode : fullpath = self . LOCAL_MODELS + filename g = manager . get_pickled_ontology ( filename ) if not g : g = manager . do_pickle_ontology ( filename ) else : fullpath = filename filename = os . path . basename ( os . path . normpath ( ful...
Loads an ontology
151
5
249,178
def _select_property ( self , line ) : g = self . current [ 'graph' ] if not line : out = g . all_properties using_pattern = False else : using_pattern = True if line . isdigit ( ) : line = int ( line ) out = g . get_property ( line ) if out : if type ( out ) == type ( [ ] ) : choice = self . _selectFromList ( out , us...
try to match a property and load it
210
8
249,179
def _select_concept ( self , line ) : g = self . current [ 'graph' ] if not line : out = g . all_skos_concepts using_pattern = False else : using_pattern = True if line . isdigit ( ) : line = int ( line ) out = g . get_skos ( line ) if out : if type ( out ) == type ( [ ] ) : choice = self . _selectFromList ( out , usin...
try to match a class and load it
215
8
249,180
def do_visualize ( self , line ) : if not self . current : self . _help_noontology ( ) return line = line . split ( ) try : # from ..viz.builder import action_visualize from . . ontodocs . builder import action_visualize except : self . _print ( "This command requires the ontodocs package: `pip install ontodocs`" ) ret...
Visualize an ontology - ie wrapper for export command
130
11
249,181
def do_import ( self , line ) : line = line . split ( ) if line and line [ 0 ] == "starter-pack" : actions . action_bootstrap ( ) elif line and line [ 0 ] == "uri" : self . _print ( "------------------\nEnter a valid graph URI: (e.g. http://www.w3.org/2009/08/skos-reference/skos.rdf)" ) var = input ( ) if var : if var ...
Import an ontology
322
4
249,182
def do_file ( self , line ) : opts = self . FILE_OPTS if not self . all_ontologies : self . _help_nofiles ( ) return line = line . split ( ) if not line or line [ 0 ] not in opts : self . help_file ( ) return if line [ 0 ] == "rename" : self . _rename_file ( ) elif line [ 0 ] == "delete" : self . _delete_file ( ) else ...
PErform some file operation
109
6
249,183
def do_serialize ( self , line ) : opts = self . SERIALIZE_OPTS if not self . current : self . _help_noontology ( ) return line = line . split ( ) g = self . current [ 'graph' ] if not line : line = [ 'turtle' ] if line [ 0 ] not in opts : self . help_serialize ( ) return elif self . currentEntity : self . currentEntit...
Serialize an entity into an RDF flavour
135
9
249,184
def do_back ( self , line ) : if self . currentEntity : self . currentEntity = None self . prompt = _get_prompt ( self . current [ 'file' ] ) else : self . current = None self . prompt = _get_prompt ( )
Go back one step . From entity = > ontology ; from ontology = > ontospy top level .
59
23
249,185
def do_zen ( self , line ) : _quote = random . choice ( QUOTES ) # print(_quote['source']) print ( Style . DIM + unicode ( _quote [ 'text' ] ) ) print ( Style . BRIGHT + unicode ( _quote [ 'source' ] ) + Style . RESET_ALL )
Inspiring quotes for the working ontologist
74
8
249,186
def complete_get ( self , text , line , begidx , endidx ) : options = self . GET_OPTS if not text : completions = options else : completions = [ f for f in options if f . startswith ( text ) ] return completions
completion for find command
60
5
249,187
def complete_info ( self , text , line , begidx , endidx ) : opts = self . INFO_OPTS if not text : completions = opts else : completions = [ f for f in opts if f . startswith ( text ) ] return completions
completion for info command
63
5
249,188
def build_D3treeStandard ( old , MAX_DEPTH , level = 1 , toplayer = None ) : out = [ ] if not old : old = toplayer for x in old : d = { } # print "*" * level, x.label d [ 'qname' ] = x . qname d [ 'name' ] = x . bestLabel ( quotes = False ) . replace ( "_" , " " ) d [ 'objid' ] = x . id if x . children ( ) and level < ...
For d3s examples all we need is a json with name children and size .. eg
221
18
249,189
def build_D3bubbleChart ( old , MAX_DEPTH , level = 1 , toplayer = None ) : out = [ ] if not old : old = toplayer for x in old : d = { } # print "*" * level, x.label d [ 'qname' ] = x . qname d [ 'name' ] = x . bestLabel ( quotes = False ) . replace ( "_" , " " ) d [ 'objid' ] = x . id if x . children ( ) and level < M...
Similar to standar d3 but nodes with children need to be duplicated otherwise they are not depicted explicitly but just color coded
294
25
249,190
def infer_best_title ( self ) : if self . ontospy_graph . all_ontologies : return self . ontospy_graph . all_ontologies [ 0 ] . uri elif self . ontospy_graph . sources : return self . ontospy_graph . sources [ 0 ] else : return "Untitled"
Selects something usable as a title for an ontospy graph
74
13
249,191
def build ( self , output_path = "" ) : self . output_path = self . checkOutputPath ( output_path ) self . _buildStaticFiles ( ) self . final_url = self . _buildTemplates ( ) printDebug ( "Done." , "comment" ) printDebug ( "=> %s" % ( self . final_url ) , "comment" ) return self . final_url
method that should be inherited by all vis classes
88
9
249,192
def _buildTemplates ( self ) : # in this case we only have one contents = self . _renderTemplate ( self . template_name , extraContext = None ) # the main url used for opening viz f = self . main_file_name main_url = self . _save2File ( contents , f , self . output_path ) return main_url
do all the things necessary to build the viz should be adapted to work for single - file viz or multi - files etc .
78
25
249,193
def _build_basic_context ( self ) : # printDebug(str(self.ontospy_graph.toplayer_classes)) topclasses = self . ontospy_graph . toplayer_classes [ : ] if len ( topclasses ) < 3 : # massage the toplayer! for topclass in self . ontospy_graph . toplayer_classes : for child in topclass . children ( ) : if child not in topcl...
Return a standard dict used in django as a template context
383
12
249,194
def checkOutputPath ( self , output_path ) : if not output_path : # output_path = self.output_path_DEFAULT output_path = os . path . join ( self . output_path_DEFAULT , slugify ( unicode ( self . title ) ) ) if os . path . exists ( output_path ) : shutil . rmtree ( output_path ) os . makedirs ( output_path ) return out...
Create or clean up output path
99
6
249,195
def highlight_code ( self , ontospy_entity ) : try : pygments_code = highlight ( ontospy_entity . rdf_source ( ) , TurtleLexer ( ) , HtmlFormatter ( ) ) pygments_code_css = HtmlFormatter ( ) . get_style_defs ( '.highlight' ) return { "pygments_code" : pygments_code , "pygments_code_css" : pygments_code_css } except Exc...
produce an html version of Turtle code with syntax highlighted using Pygments CSS
129
15
249,196
def query ( self , q , format = "" , convert = True ) : lines = [ "PREFIX %s: <%s>" % ( k , r ) for k , r in self . prefixes . iteritems ( ) ] lines . extend ( q . split ( "\n" ) ) query = "\n" . join ( lines ) if self . verbose : print ( query , "\n\n" ) return self . __doQuery ( query , format , convert )
Generic SELECT query structure . q is the main body of the query .
103
14
249,197
def describe ( self , uri , format = "" , convert = True ) : lines = [ "PREFIX %s: <%s>" % ( k , r ) for k , r in self . prefixes . iteritems ( ) ] if uri . startswith ( "http://" ) : lines . extend ( [ "DESCRIBE <%s>" % uri ] ) else : # it's a shortened uri lines . extend ( [ "DESCRIBE %s" % uri ] ) query = "\n" . joi...
A simple DESCRIBE query with no where arguments . uri is the resource you want to describe .
151
22
249,198
def __doQuery ( self , query , format , convert ) : self . __getFormat ( format ) self . sparql . setQuery ( query ) if convert : results = self . sparql . query ( ) . convert ( ) else : results = self . sparql . query ( ) return results
Inner method that does the actual query
63
8
249,199
def get_default_preds ( ) : g = ontospy . Ontospy ( rdfsschema , text = True , verbose = False , hide_base_schemas = False ) classes = [ ( x . qname , x . bestDescription ( ) ) for x in g . all_classes ] properties = [ ( x . qname , x . bestDescription ( ) ) for x in g . all_properties ] commands = [ ( 'exit' , 'exits ...
dynamically build autocomplete options based on an external file
138
13