idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
28,800 | def get_parent ( parent ) : if isinstance ( parent , Interface ) : return parent . id elif isinstance ( parent , int ) : return parent else : raise TypeError ( "parent must be an Interface or int, not %s" % ( type ( parent ) . __name__ ) ) | Get the parent to send to the handler . |
28,801 | async def save ( self ) : if set ( self . tags ) != set ( self . _orig_data [ 'tags' ] ) : self . _changed_data [ 'tags' ] = ',' . join ( self . tags ) elif 'tags' in self . _changed_data : del self . _changed_data [ 'tags' ] orig_params = self . _orig_data [ 'params' ] if not isinstance ( orig_params , dict ) : orig_p... | Save this interface . |
28,802 | async def disconnect ( self ) : self . _data = await self . _handler . disconnect ( system_id = self . node . system_id , id = self . id ) | Disconnect this interface . |
28,803 | async def delete ( self ) : interface = self . _data [ 'interface' ] data = await interface . _handler . unlink_subnet ( system_id = interface . node . system_id , id = interface . id , _id = self . id ) interface . _data [ 'links' ] = list ( data [ 'links' ] ) interface . _orig_data [ 'links' ] = copy . deepcopy ( int... | Delete this interface link . |
28,804 | async def set_as_default_gateway ( self ) : interface = self . _data [ 'interface' ] await interface . _handler . set_default_gateway ( system_id = interface . node . system_id , id = interface . id , link_id = self . id ) | Set this link as the default gateway for the node . |
28,805 | async def create ( cls , interface : Interface , mode : LinkMode , subnet : Union [ Subnet , int ] = None , ip_address : str = None , force : bool = False , default_gateway : bool = False ) : if not isinstance ( interface , Interface ) : raise TypeError ( "interface must be an Interface, not %s" % type ( interface ) . ... | Create a link on Interface in MAAS . |
28,806 | async def create ( cls , node : Union [ Node , str ] , cache_device : Union [ BlockDevice , Partition ] ) : params = { } if isinstance ( node , str ) : params [ 'system_id' ] = node elif isinstance ( node , Node ) : params [ 'system_id' ] = node . system_id else : raise TypeError ( 'node must be a Node or str, not %s' ... | Create a BcacheCacheSet on a Node . |
28,807 | def render ( self , target , data ) : rows = self . get_rows ( target , data ) rows = self . _filter_rows ( rows ) renderer = getattr ( self , "_render_%s" % target . name , None ) if renderer is None : raise ValueError ( "Cannot render %r for %s." % ( self . value , target ) ) else : return renderer ( rows ) | Render the table . |
28,808 | async def get_default ( cls ) : data = await cls . _handler . read ( id = cls . _default_fabric_id ) return cls ( data ) | Get the default Fabric for the MAAS . |
28,809 | async def delete ( self ) : if self . id == self . _origin . Fabric . _default_fabric_id : raise CannotDelete ( "Default fabric cannot be deleted." ) await self . _handler . delete ( id = self . id ) | Delete this Fabric . |
28,810 | def dir_class ( cls ) : for name , value in vars_class ( cls ) . items ( ) : if isinstance ( value , ObjectMethod ) : if value . has_classmethod : yield name elif isinstance ( value , Disabled ) : pass else : yield name for name , value in vars_class ( type ( cls ) ) . items ( ) : if name == "mro" : pass elif isinstanc... | Return a list of names available on cls . |
28,811 | def dir_instance ( inst ) : for name , value in vars_class ( type ( inst ) ) . items ( ) : if isinstance ( value , ObjectMethod ) : if value . has_instancemethod : yield name elif isinstance ( value , Disabled ) : pass elif isinstance ( value , ( classmethod , staticmethod ) ) : pass else : yield name | Return a list of names available on inst . |
28,812 | def is_pk_descriptor ( descriptor , include_alt = False ) : if descriptor . pk is True or type ( descriptor . pk ) is int : return True if include_alt : return descriptor . alt_pk is True or type ( descriptor . alt_pk ) is int else : return False | Return true if descriptor is a primary key . |
28,813 | def get_pk_descriptors ( cls ) : pk_fields = { name : descriptor for name , descriptor in vars_class ( cls ) . items ( ) if isinstance ( descriptor , ObjectField ) and is_pk_descriptor ( descriptor ) } alt_pk_fields = defaultdict ( list ) for name , descriptor in vars_class ( cls ) . items ( ) : if isinstance ( descrip... | Return tuple of tuples with attribute name and descriptor on the cls that is defined as the primary keys . |
28,814 | def ManagedCreate ( super_cls ) : @ wraps ( super_cls . create ) async def _create ( self , * args , ** kwargs ) : cls = type ( self ) manager = getattr ( cls , '_manager' , None ) manager_field = getattr ( cls , '_manager_field' , None ) if manager is not None and manager_field is not None : args = ( manager , ) + arg... | Dynamically creates a create method for a ObjectSet . Managed class that calls the super_cls . create . |
28,815 | def mapping_of ( cls ) : def mapper ( data ) : if not isinstance ( data , Mapping ) : raise TypeError ( "data must be a mapping, not %s" % type ( data ) . __name__ ) return { key : cls ( value ) for key , value in data . items ( ) } return mapper | Expects a mapping from some key to data for cls instances . |
28,816 | def find_objects ( modules ) : return { subclass . __name__ : subclass for subclass in chain ( get_all_subclasses ( Object ) , get_all_subclasses ( ObjectSet ) , ) if subclass . __module__ in modules } | Find subclasses of Object and ObjectSet in the given modules . |
28,817 | def bind ( cls , origin , handler , * , name = None ) : name = cls . __name__ if name is None else name attrs = { "_origin" : origin , "_handler" : handler , "__module__" : "origin" , } return type ( name , ( cls , ) , attrs ) | Bind this object to the given origin and handler . |
28,818 | async def refresh ( self ) : cls = type ( self ) if hasattr ( cls , 'read' ) : descriptors , alt_descriptors = get_pk_descriptors ( cls ) if len ( descriptors ) == 1 : try : obj = await cls . read ( getattr ( self , descriptors [ 0 ] [ 0 ] ) ) except AttributeError : found = False for alt_name , _ in alt_descriptors [ ... | Refresh the object from MAAS . |
28,819 | async def save ( self ) : if hasattr ( self . _handler , "update" ) : if self . _changed_data : update_data = dict ( self . _changed_data ) update_data . update ( { key : self . _orig_data [ key ] for key in self . _handler . params } ) self . _data = await self . _handler . update ( ** update_data ) else : raise Attri... | Save the object in MAAS . |
28,820 | def Managed ( cls , manager , field , items ) : attrs = { "_manager" : manager , "_manager_field" : field , } if hasattr ( cls , "create" ) : attrs [ 'create' ] = ManagedCreate ( cls ) cls = type ( "%s.Managed#%s" % ( cls . __name__ , manager . __class__ . __name__ ) , ( cls , ) , attrs ) return cls ( items ) | Create a custom ObjectSet that is managed by a related Object . |
28,821 | def Checked ( cls , name , datum_to_value = None , value_to_datum = None , ** other ) : attrs = { } if datum_to_value is not None : @ wraps ( datum_to_value ) def datum_to_value_method ( instance , datum ) : return datum_to_value ( datum ) attrs [ "datum_to_value" ] = staticmethod ( datum_to_value_method ) if value_to_... | Create a custom ObjectField that validates values and datums . |
28,822 | def value_to_datum ( self , instance , value ) : if value is None : return None bound = getattr ( instance . _origin , self . cls ) if type ( value ) is bound : if self . use_data_setter : return value . _data else : descriptors , alt_descriptors = get_pk_descriptors ( bound ) if len ( descriptors ) == 1 : return getat... | Convert a given Python - side value to a MAAS - side datum . |
28,823 | async def fromURL ( cls , url , * , credentials = None , insecure = False ) : session = await bones . SessionAPI . fromURL ( url , credentials = credentials , insecure = insecure ) return cls ( session ) | Return an Origin for a given MAAS instance . |
28,824 | def fromProfile ( cls , profile ) : session = bones . SessionAPI . fromProfile ( profile ) return cls ( session ) | Return an Origin from a given configuration profile . |
28,825 | def fromProfileName ( cls , name ) : session = bones . SessionAPI . fromProfileName ( name ) return cls ( session ) | Return an Origin from a given configuration profile name . |
28,826 | async def login ( cls , url , * , username = None , password = None , insecure = False ) : profile , session = await bones . SessionAPI . login ( url = url , username = username , password = password , insecure = insecure ) return profile , cls ( session ) | Make an Origin by logging - in with a username and password . |
28,827 | async def connect ( cls , url , * , apikey = None , insecure = False ) : profile , session = await bones . SessionAPI . connect ( url = url , apikey = apikey , insecure = insecure ) return profile , cls ( session ) | Make an Origin by connecting with an apikey . |
28,828 | def facade ( factory ) : wrapper = FacadeDescriptor ( factory . __name__ , factory ) return update_wrapper ( wrapper , factory ) | Declare a method as a facade factory . |
28,829 | async def delete ( self ) : await self . _handler . delete ( system_id = self . block_device . node . system_id , device_id = self . block_device . id , id = self . id ) | Delete this partition . |
28,830 | async def unformat ( self ) : self . _data = await self . _handler . unformat ( system_id = self . block_device . node . system_id , device_id = self . block_device . id , id = self . id ) | Unformat this partition . |
28,831 | async def mount ( self , mount_point , * , mount_options = None ) : self . _data = await self . _handler . mount ( system_id = self . block_device . node . system_id , device_id = self . block_device . id , id = self . id , mount_point = mount_point , mount_options = mount_options ) | Mount this partition . |
28,832 | async def umount ( self ) : self . _data = await self . _handler . unmount ( system_id = self . block_device . node . system_id , device_id = self . block_device . id , id = self . id ) | Unmount this partition . |
28,833 | async def read ( cls , node , block_device ) : if isinstance ( node , str ) : system_id = node elif isinstance ( node , Node ) : system_id = node . system_id else : raise TypeError ( "node must be a Node or str, not %s" % type ( node ) . __name__ ) if isinstance ( block_device , int ) : block_device = block_device elif... | Get list of Partitions s for node and block_device . |
28,834 | async def create ( cls , block_device : BlockDevice , size : int ) : params = { } if isinstance ( block_device , BlockDevice ) : params [ 'system_id' ] = block_device . node . system_id params [ 'device_id' ] = block_device . id else : raise TypeError ( 'block_device must be a BlockDevice, not %s' % ( type ( block_devi... | Create a partition on a block device . |
28,835 | def asynchronous ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : eventloop = get_event_loop ( ) result = func ( * args , ** kwargs ) if not eventloop . is_running ( ) : while isawaitable ( result ) : result = eventloop . run_until_complete ( result ) return result return wrapper | Return func in a smart asynchronous - aware wrapper . |
28,836 | def _maybe_wrap ( attribute ) : if iscoroutinefunction ( attribute ) : return asynchronous ( attribute ) if isinstance ( attribute , ( classmethod , staticmethod ) ) : if iscoroutinefunction ( attribute . __func__ ) : return attribute . __class__ ( asynchronous ( attribute . __func__ ) ) return attribute | Helper for Asynchronous . |
28,837 | async def create ( cls , cidr : str , vlan : Union [ Vlan , int ] = None , * , name : str = None , description : str = None , gateway_ip : str = None , rdns_mode : RDNSMode = None , dns_servers : Union [ Sequence [ str ] , str ] = None , managed : bool = None ) : params = { "cidr" : cidr } if isinstance ( vlan , int ) ... | Create a Subnet in MAAS . |
28,838 | async def save ( self ) : if 'vlan' in self . _changed_data and self . _changed_data [ 'vlan' ] : self . _changed_data [ 'vlan' ] = self . _changed_data [ 'vlan' ] [ 'id' ] if ( self . _orig_data [ 'vlan' ] and 'id' in self . _orig_data [ 'vlan' ] and self . _changed_data [ 'vlan' ] == ( self . _orig_data [ 'vlan' ] [ ... | Save this subnet . |
28,839 | def urlencode ( data ) : def dec ( string ) : if isinstance ( string , bytes ) : string = string . decode ( "utf-8" ) return quote_plus ( string ) return "&" . join ( "%s=%s" % ( dec ( name ) , dec ( value ) ) for name , value in data ) | A version of urllib . urlencode that isn t insane . |
28,840 | def sign ( uri , headers , credentials ) : consumer_key , token_key , token_secret = credentials auth = OAuthSigner ( token_key , token_secret , consumer_key , "" ) auth . sign_request ( uri , method = "GET" , body = None , headers = headers ) | Sign the URI and headers . |
28,841 | def parse_docstring ( thing ) : assert not isinstance ( thing , bytes ) doc = cleandoc ( thing ) if isinstance ( thing , str ) else getdoc ( thing ) doc = empty if doc is None else doc assert not isinstance ( doc , bytes ) parts = docstring_split ( doc ) if len ( parts ) == 2 : title , body = parts [ 0 ] , parts [ 1 ] ... | Parse a Python docstring or the docstring found on thing . |
28,842 | def api_url ( string ) : url = urlparse ( string ) url = url . _replace ( path = ensure_trailing_slash ( url . path ) ) if re . search ( "/api/[0-9.]+/?$" , url . path ) is None : url = url . _replace ( path = url . path + "api/2.0/" ) return url . geturl ( ) | Ensure that string looks like a URL to the API . |
28,843 | def vars_class ( cls ) : return dict ( chain . from_iterable ( vars ( cls ) . items ( ) for cls in reversed ( cls . __mro__ ) ) ) | Return a dict of vars for the given class including all ancestors . |
28,844 | def remove_None ( params : dict ) : return { key : value for key , value in params . items ( ) if value is not None } | Remove all keys in params that have the value of None . |
28,845 | def sign_request ( self , url , method , body , headers ) : client = oauth1 . Client ( self . consumer_key , self . consumer_secret , self . token_key , self . token_secret , signature_method = oauth1 . SIGNATURE_PLAINTEXT , realm = self . realm ) body = None if body is None or len ( body ) == 0 else body uri , signed_... | Sign a request . |
28,846 | def print ( self , * args , ** kwargs ) : clear_len = max ( len ( self . _prev_msg ) , len ( self . msg ) ) + 4 self . spinner . stream . write ( "%s\r" % ( ' ' * clear_len ) ) print ( * args , file = self . spinner . stream , flush = True , ** kwargs ) | Print inside of the spinner context . |
28,847 | async def create ( cls , node : Union [ Node , str ] , level : Union [ RaidLevel , str ] , devices : Iterable [ Union [ BlockDevice , Partition ] ] , * , name : str = None , uuid : str = None , spare_devices : Iterable [ Union [ BlockDevice , Partition ] ] ) : if isinstance ( level , RaidLevel ) : level = level . value... | Create a RAID on a Node . |
28,848 | async def create ( cls , destination : Union [ int , Subnet ] , source : Union [ int , Subnet ] , gateway_ip : str , metric : int ) : params = { "gateway_ip" : gateway_ip , "metric" : metric , } if isinstance ( source , Subnet ) : params [ "source" ] = source . id elif isinstance ( source , int ) : params [ "source" ] ... | Create a StaticRoute in MAAS . |
28,849 | def fetch_build_egg ( self , req ) : from setuptools . command . easy_install import easy_install dist = Distribution ( { 'script_args' : [ 'easy_install' ] } ) dist . parse_config_files ( ) opts = dist . get_option_dict ( 'easy_install' ) keep = ( 'find_links' , 'site_dirs' , 'index_url' , 'optimize' , 'site_dirs' , '... | Specialized version of Distribution . fetch_build_egg that respects respects allow_hosts and index_url . |
28,850 | def _caching ( self , disk_or_memory , cache_directory = None ) : if disk_or_memory not in ( 'disk' , 'memory' ) : raise ValueError ( 'Accepted values are "disk" or "memory"' ) get_methods_id = [ 0 ] def memoize ( func ) : _global_cache_dir = '' if disk_or_memory == 'disk' : if cache_directory : if sys . version_info [... | Decorator that allows caching the outputs of the BaseClient get methods . Cache can be either disk - or memory - based . Disk - based cache is reloaded automatically between runs if the same cache directory is specified . Cache is kept per each unique uid . |
28,851 | def set_subresources ( self , ** kwargs ) : for attribute_name , resource in self . _subresource_map . items ( ) : sub_attr = kwargs . get ( attribute_name ) if sub_attr is None : value = None elif isinstance ( sub_attr , list ) : value = [ resource ( ** x ) for x in sub_attr ] else : value = resource ( ** sub_attr ) s... | Same logic as the original except for the first if clause . |
28,852 | def build_url_base ( host , port , is_https ) : base = "http" if is_https : base += 's' base += "://" base += host if port : base += ":" base += str ( port ) return base | Make base of url based on config |
28,853 | def is_motion_detection_enabled ( self ) : response = requests . get ( self . motion_url , auth = HTTPBasicAuth ( self . _username , self . _password ) ) _LOGGING . debug ( 'Response: %s' , response . text ) if response . status_code != 200 : _LOGGING . error ( "There was an error connecting to %s" , self . motion_url ... | Get current state of Motion Detection |
28,854 | def put_motion_detection_xml ( self , xml ) : _LOGGING . debug ( 'xml:' ) _LOGGING . debug ( "%s" , xml ) headers = DEFAULT_HEADERS headers [ 'Content-Length' ] = len ( xml ) headers [ 'Host' ] = self . _host response = requests . put ( self . motion_url , auth = HTTPBasicAuth ( self . _username , self . _password ) , ... | Put request with xml Motion Detection |
28,855 | def _apply_common_rules ( self , part , maxlength ) : part = part . strip ( ) if self . fix : part = part . strip ( '.' ) if not part : return part , 'It cannot be empty.' if len ( part ) > maxlength : return part , 'It cannot be longer than %i chars.' % maxlength if part [ 0 ] == '.' : return part , 'It cannot start w... | This method contains the rules that must be applied to both the domain and the local part of the e - mail address . |
28,856 | def mime ( self ) : author = self . author sender = self . sender if not author : raise ValueError ( "You must specify an author." ) if not self . subject : raise ValueError ( "You must specify a subject." ) if len ( self . recipients ) == 0 : raise ValueError ( "You must specify at least one recipient." ) if not self ... | Produce the final MIME message . |
28,857 | def attach ( self , name , data = None , maintype = None , subtype = None , inline = False , filename = None , filename_charset = '' , filename_language = '' , encoding = None ) : self . _dirty = True if not maintype : maintype , guessed_encoding = guess_type ( name ) encoding = encoding or guessed_encoding if not main... | Attach a file to this message . |
28,858 | def embed ( self , name , data = None ) : if data is None : with open ( name , 'rb' ) as fp : data = fp . read ( ) name = os . path . basename ( name ) elif isinstance ( data , bytes ) : pass elif hasattr ( data , 'read' ) : data = data . read ( ) else : raise TypeError ( "Unable to read image contents" ) subtype = img... | Attach an image file and prepare for HTML embedding . |
28,859 | def deliver ( self , message ) : config = self . config success = config . success failure = config . failure exhaustion = config . exhaustion if getattr ( message , 'die' , False ) : 1 / 0 if failure : chance = random . randint ( 0 , 100001 ) / 100000.0 if chance < failure : raise TransportFailedException ( "Mock fail... | Concrete message delivery . |
28,860 | def startup ( self ) : log . info ( "Immediate delivery manager starting." ) log . debug ( "Initializing transport queue." ) self . transport . startup ( ) log . info ( "Immediate delivery manager started." ) | Perform startup actions . This just chains down to the transport layer . |
28,861 | def string_addresses ( self , encoding = None ) : if not encoding : encoding = self . encoding return [ Address ( i . address ) . encode ( encoding ) . decode ( encoding ) for i in self ] | Return a list of string representations of the addresses suitable for usage in an SMTP transaction . |
28,862 | def run ( self ) : while True : self . connect_lock . acquire ( ) if self . stopped ( ) : return self . __connect ( ) self . connect_lock . release ( ) self . ws . run_forever ( ) | If the connection drops then run_forever will terminate and a reconnection attempt will be made . |
28,863 | def send ( self , data ) : while not self . stopped ( ) : try : self . ws . send ( data ) return except websocket . WebSocketConnectionClosedException : time . sleep ( 0.1 ) | This method keeps trying to send a message relying on the run method to reopen the websocket in case it was closed . |
28,864 | def __create_channel_run ( self , channel , username , token ) : data = { 'channel_id' : channel . get_node_id ( ) . hex , 'chef_name' : self . __get_chef_name ( ) , 'ricecooker_version' : __version__ , 'started_by_user' : username , 'started_by_user_token' : token , 'content_server' : config . DOMAIN , } try : respons... | Sends a post request to create the channel run . |
28,865 | def run ( self ) : while True : self . open_lock . acquire ( ) if self . stopped ( ) : return self . __open ( ) self . open_lock . release ( ) | This override threading . Thread to open socket and wait for messages . |
28,866 | def filter_filenames ( filenames ) : filenames_cleaned = [ ] for filename in filenames : keep = True for pattern in FILE_EXCLUDE_EXTENTIONS : if filename . endswith ( pattern ) : keep = False for pattern in FILE_SKIP_PATTENRS : if pattern in filename : keep = False if keep : filenames_cleaned . append ( filename ) retu... | Skip files with extentions in FILE_EXCLUDE_EXTENTIONS and filenames that contain FILE_SKIP_PATTENRS . |
28,867 | def filter_thumbnail_files ( chan_path , filenames , metadata_provider ) : thumbnail_files_to_skip = metadata_provider . get_thumbnail_paths ( ) filenames_cleaned = [ ] for filename in filenames : keep = True chan_filepath = os . path . join ( chan_path , filename ) chan_filepath_tuple = path_to_tuple ( chan_filepath )... | We don t want to create ContentNode from thumbnail files . |
28,868 | def keep_folder ( raw_path ) : keep = True for pattern in DIR_EXCLUDE_PATTERNS : if pattern in raw_path : LOGGER . debug ( 'rejecting' , raw_path ) keep = False return keep | Keep only folders that don t contain patterns in DIR_EXCLUDE_PATTERNS . |
28,869 | def process_folder ( channel , rel_path , filenames , metadata_provider ) : LOGGER . debug ( 'IN process_folder ' + str ( rel_path ) + ' ' + str ( filenames ) ) if not keep_folder ( rel_path ) : return chan_path = chan_path_from_rel_path ( rel_path , metadata_provider . channeldir ) chan_path_tuple = path_to_tuple ... | Create ContentNode s from each file in this folder and the node to channel under the path rel_path . |
28,870 | def build_ricecooker_json_tree ( args , options , metadata_provider , json_tree_path ) : LOGGER . info ( 'Starting to build the ricecooker_json_tree' ) channeldir = args [ 'channeldir' ] if channeldir . endswith ( os . path . sep ) : channeldir . rstrip ( os . path . sep ) channelparentdir , channeldirname = os . path ... | Download all categories subpages modules and resources from open . edu . |
28,871 | def construct_channel ( self , * args , ** kwargs ) : channel = self . get_channel ( * args , ** kwargs ) exampletopic = TopicNode ( source_id = "topic-1" , title = "Example Topic" ) channel . add_child ( exampletopic ) examplesubtopic = TopicNode ( source_id = "topic-1a" , title = "Example Subtopic" ) exampletopic . a... | This method is reponsible for creating a ChannelNode object from the info in channel_info and populating it with TopicNode and ContentNode children . |
28,872 | def read_tree_from_json ( srcpath ) : with open ( srcpath ) as infile : json_tree = json . load ( infile ) if json_tree is None : raise ValueError ( 'Could not find ricecooker json tree' ) return json_tree | Load ricecooker json tree data from json file at srcpath . |
28,873 | def get_channel_node_from_json ( json_tree ) : channel = ChannelNode ( title = json_tree [ 'title' ] , description = json_tree [ 'description' ] , source_domain = json_tree [ 'source_domain' ] , source_id = json_tree [ 'source_id' ] , language = json_tree [ 'language' ] , thumbnail = json_tree . get ( 'thumbnail' , Non... | Build ChannelNode from json data provided in json_tree . |
28,874 | def get_channel ( self , ** kwargs ) : if self . compatibility_mode : if hasattr ( self . chef_module , 'get_channel' ) : config . LOGGER . info ( "Calling get_channel... " ) channel = self . chef_module . get_channel ( ** kwargs ) if hasattr ( self . chef_module , 'create_channel' ) : config . LOGGER . info ( "Calling... | Call chef script s get_channel method in compatibility mode ... or ... Create a ChannelNode from the Chef s channel_info class attribute . |
28,875 | def construct_channel ( self , ** kwargs ) : channel = self . get_channel ( ** kwargs ) json_tree_path = self . get_json_tree_path ( ** kwargs ) json_tree = read_tree_from_json ( json_tree_path ) build_tree_from_json ( channel , json_tree [ 'children' ] ) raise_for_invalid_channel ( channel ) return channel | Build the channel tree by adding TopicNodes and ContentNode children . |
28,876 | def pre_run ( self , args , options ) : if 'generate' in args and args [ 'generate' ] : self . metadata_provider = CsvMetadataProvider ( args [ 'channeldir' ] , channelinfo = args [ 'channelinfo' ] , contentinfo = args [ 'contentinfo' ] , exercisesinfo = args [ 'exercisesinfo' ] , questionsinfo = args [ 'questionsinfo'... | This function is called before run in order to build the json tree . |
28,877 | def calculate_relative_url ( url , filename = None , baseurl = None , subpath = None ) : if isinstance ( subpath , str ) : subpath = subpath . strip ( "/" ) . split ( "/" ) elif subpath is None : subpath = [ ] if baseurl : baseurl = urllib . parse . urljoin ( baseurl , "." ) assert url . startswith ( baseurl ) , "URL m... | Calculate the relative path for a URL relative to a base URL possibly also injecting in a subpath prefix . |
28,878 | def download_file ( url , destpath , filename = None , baseurl = None , subpath = None , middleware_callbacks = None , middleware_kwargs = None , request_fn = sess . get ) : relative_file_url , subpath , filename = calculate_relative_url ( url , filename = filename , baseurl = baseurl , subpath = subpath ) fulldestpath... | Download a file from a URL into a destination folder with optional use of relative paths and middleware processors . |
28,879 | def set_language ( self , language ) : if isinstance ( language , str ) : language_obj = languages . getlang ( language ) if language_obj : self . language = language_obj . code else : raise TypeError ( "Language code {} not found" . format ( language ) ) if isinstance ( language , languages . Language ) : self . langu... | Set self . language to internal lang . repr . code from str or Language object . |
28,880 | def get_thumbnail_preset ( self ) : if isinstance ( self , ChannelNode ) : return format_presets . CHANNEL_THUMBNAIL elif isinstance ( self , TopicNode ) : return format_presets . TOPIC_THUMBNAIL elif isinstance ( self , VideoNode ) : return format_presets . VIDEO_THUMBNAIL elif isinstance ( self , AudioNode ) : return... | Returns the format preset corresponding to this Node s type or None if the node doesn t have a format preset . |
28,881 | def open ( self , update = False ) : filename = os . path . basename ( self . source_path ) folder , _ext = os . path . splitext ( filename ) self . path = os . path . sep . join ( [ self . directory , folder , filename ] ) if not os . path . exists ( os . path . dirname ( self . path ) ) : os . makedirs ( os . path . ... | Opens pdf file to read from . |
28,882 | def get_toc ( self , subchapters = False ) : self . check_path ( ) chapters = [ ] index = 0 for dest in self . pdf . getOutlines ( ) : if isinstance ( dest , CustomDestination ) and not isinstance ( dest [ '/Page' ] , NullObject ) : page_num = self . pdf . getDestinationPageNumber ( dest ) chapter_pagerange = { "title"... | Returns table - of - contents information extracted from the PDF doc . When subchapters = False the output is a list of this form |
28,883 | def get_metadata_file_path ( channeldir , filename ) : channelparentdir , channeldirname = os . path . split ( channeldir ) return os . path . join ( channelparentdir , filename ) | Return the path to the metadata file named filename that is a sibling of channeldir . |
28,884 | def _read_csv_lines ( path ) : csv_file = open ( path , 'r' ) csv_lines_raw = csv_file . readlines ( ) csv_lines_clean = [ line for line in csv_lines_raw if len ( line . strip ( ) ) > 0 ] return csv_lines_clean | Opens CSV file path and returns list of rows . Pass output of this function to csv . DictReader for reading data . |
28,885 | def _clean_dict ( row ) : row_cleaned = { } for key , val in row . items ( ) : if val is None or val == '' : row_cleaned [ key ] = None else : row_cleaned [ key ] = val return row_cleaned | Transform empty strings values of dict row to None . |
28,886 | def get ( self , path_tuple ) : if path_tuple in self . contentcache : metadata = self . contentcache [ path_tuple ] else : LOGGER . warning ( 'No metadata found for path_tuple ' + str ( path_tuple ) ) metadata = dict ( filepath = os . path . sep . join ( path_tuple ) , title = os . path . sep . join ( path_tuple ) ) r... | Returns metadata dict for path in path_tuple . |
28,887 | def get_channel_info ( self ) : csv_filename = get_metadata_file_path ( channeldir = self . channeldir , filename = self . channelinfo ) csv_lines = _read_csv_lines ( csv_filename ) dict_reader = csv . DictReader ( csv_lines ) channel_csvs_list = list ( dict_reader ) channel_csv = channel_csvs_list [ 0 ] if len ( chann... | Returns the first data row from Channel . csv |
28,888 | def get_thumbnail_paths ( self ) : thumbnail_path_tuples = [ ] channel_info = self . get_channel_info ( ) chthumbnail_path = channel_info . get ( 'thumbnail_chan_path' , None ) if chthumbnail_path : chthumbnail_path_tuple = path_to_tuple ( chthumbnail_path , windows = self . winpaths ) thumbnail_path_tuples . append ( ... | Helper function used to avoid processing thumbnail files during os . walk . |
28,889 | def _map_exercise_row_to_dict ( self , row ) : row_cleaned = _clean_dict ( row ) license_id = row_cleaned [ CONTENT_LICENSE_ID_KEY ] if license_id : license_dict = dict ( license_id = row_cleaned [ CONTENT_LICENSE_ID_KEY ] , description = row_cleaned . get ( CONTENT_LICENSE_DESCRIPTION_KEY , None ) , copyright_holder =... | Convert dictionary keys from raw CSV Exercise format to ricecooker keys . |
28,890 | def _map_exercise_question_row_to_dict ( self , row ) : row_cleaned = _clean_dict ( row ) all_answers = [ ] ansA = row_cleaned [ EXERCISE_QUESTIONS_OPTION_A_KEY ] all_answers . append ( ansA ) ansB = row_cleaned . get ( EXERCISE_QUESTIONS_OPTION_B_KEY , None ) if ansB : all_answers . append ( ansB ) ansC = row_cleaned ... | Convert dictionary keys from raw CSV Exercise Question format to ricecooker keys . |
28,891 | def validate_headers ( self ) : super ( ) . validate ( ) self . validate_header ( self . channeldir , self . channelinfo , CHANNEL_INFO_HEADER ) self . validate_header ( self . channeldir , self . contentinfo , CONTENT_INFO_HEADER ) if self . has_exercises ( ) : self . validate_header ( self . channeldir , self . exerc... | Check if CSV metadata files have the right format . |
28,892 | def validate_header ( self , channeldir , filename , expected_header ) : expected = set ( expected_header ) csv_filename = get_metadata_file_path ( channeldir , filename ) csv_lines = _read_csv_lines ( csv_filename ) dict_reader = csv . DictReader ( csv_lines ) actual = set ( dict_reader . fieldnames ) if not actual ==... | Check if CSV metadata file filename have the expected header format . |
28,893 | def generate_contentinfo_from_channeldir ( self , args , options ) : LOGGER . info ( 'Generating Content.csv rows folders and file in channeldir' ) file_path = get_metadata_file_path ( self . channeldir , self . contentinfo ) with open ( file_path , 'a' ) as csv_file : csvwriter = csv . DictWriter ( csv_file , CONTENT_... | Create rows in Content . csv for each folder and file in self . channeldir . |
28,894 | def generate_contentinfo_from_folder ( self , csvwriter , rel_path , filenames ) : LOGGER . debug ( 'IN process_folder ' + str ( rel_path ) + ' ' + str ( filenames ) ) from ricecooker . utils . linecook import filter_filenames , filter_thumbnail_files , chan_path_from_rel_path topicrow = self . channeldir_node_to_r... | Create a topic node row in Content . csv for the folder at rel_path and add content node rows for all the files in the rel_path folder . |
28,895 | def channeldir_node_to_row ( self , path_tuple ) : row = dict ( ) for key in CONTENT_INFO_HEADER : row [ key ] = None row [ CONTENT_PATH_KEY ] = "/" . join ( path_tuple ) title = path_tuple [ - 1 ] . replace ( '_' , ' ' ) for ext in content_kinds . MAPPING . keys ( ) : if title . endswith ( ext ) : title = title . repl... | Return a dict with keys corresponding to Content . csv columns . |
28,896 | def generate_templates ( self , exercise_questions = False ) : self . generate_template ( channeldir = self . channeldir , filename = self . channelinfo , header = CHANNEL_INFO_HEADER ) self . generate_template ( channeldir = self . channeldir , filename = self . contentinfo , header = CONTENT_INFO_HEADER ) if exercise... | Create empty . csv files with the right headers and place them in the Will place files as siblings of directory channeldir . |
28,897 | def generate_template ( self , channeldir , filename , header ) : file_path = get_metadata_file_path ( channeldir , filename ) if not os . path . exists ( file_path ) : with open ( file_path , 'w' ) as csv_file : csvwriter = csv . DictWriter ( csv_file , header ) csvwriter . writeheader ( ) | Create empty template . csv file called filename as siblings of the directory channeldir with header fields specified in header . |
28,898 | def authenticate_user ( token ) : config . SESSION . headers . update ( { "Authorization" : "Token {0}" . format ( token ) } ) try : response = config . SESSION . post ( config . authentication_url ( ) ) response . raise_for_status ( ) user = json . loads ( response . _content . decode ( "utf-8" ) ) config . LOGGER . i... | Add the content curation Authorizatino token header to config . SESSION . |
28,899 | def residue_distances ( res_1_num , res_1_chain , res_2_num , res_2_chain , model ) : res1 = model [ res_1_chain ] [ res_1_num ] . child_list [ - 1 ] res2 = model [ res_2_chain ] [ res_2_num ] . child_list [ - 1 ] distance = res1 - res2 return distance | Distance between the last atom of 2 residues |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.