idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
28,200 | def next_items ( self , n ) : items = [ ] while len ( items ) < n : if self . _line_ptr >= len ( self . _line ) : line = next ( self . _file ) . strip ( ) while not line or line [ 0 ] == "#" : line = next ( self . _file ) . strip ( ) self . _line = self . _re_delimiter . split ( line ) self . _line_ptr = 0 n_read = min... | Returns the next n items . |
28,201 | def get_param_map ( word , required_keys = None ) : if required_keys is None : required_keys = [ ] words = word . split ( "," ) param_map = { } for wordi in words : if "=" not in wordi : key = wordi . strip ( ) value = None else : sword = wordi . split ( "=" ) assert len ( sword ) == 2 , sword key = sword [ 0 ] . strip... | get the optional arguments on a line |
28,202 | def get_parameters_by_path ( self , path , with_decryption , recursive , filters = None ) : result = [ ] path = path . rstrip ( '/' ) + '/' for param in self . _parameters : if path != '/' and not param . startswith ( path ) : continue if '/' in param [ len ( path ) + 1 : ] and not recursive : continue if not self . _m... | Implement the get - parameters - by - path - API in the backend . |
28,203 | def _match_filters ( parameter , filters = None ) : for filter_obj in ( filters or [ ] ) : key = filter_obj [ 'Key' ] option = filter_obj . get ( 'Option' , 'Equals' ) values = filter_obj . get ( 'Values' , [ ] ) what = None if key == 'Type' : what = parameter . type elif key == 'KeyId' : what = parameter . keyid if op... | Return True if the given parameter matches all the filters |
28,204 | def initialize_service ( service , operation , api_protocol ) : lib_dir = get_lib_dir ( service ) test_dir = get_test_dir ( service ) print_progress ( 'Initializing service' , service , 'green' ) client = boto3 . client ( service ) service_class = client . __class__ . __name__ endpoint_prefix = client . _service_model ... | create lib and test dirs if not exist |
28,205 | def get_response_query_template ( service , operation ) : client = boto3 . client ( service ) aws_operation_name = to_upper_camel_case ( operation ) op_model = client . _service_model . operation_model ( aws_operation_name ) result_wrapper = op_model . output_shape . serialization [ 'resultWrapper' ] response_wrapper =... | refers to definition of API in botocore and autogenerates template Assume that response format is xml when protocol is query |
28,206 | def camelcase_to_underscores ( argument ) : result = '' prev_char_title = True if not argument : return argument for index , char in enumerate ( argument ) : try : next_char_title = argument [ index + 1 ] . istitle ( ) except IndexError : next_char_title = True upper_to_lower = char . istitle ( ) and not next_char_titl... | Converts a camelcase param like theNewAttribute to the equivalent python underscore variable like the_new_attribute |
28,207 | def underscores_to_camelcase ( argument ) : result = '' previous_was_underscore = False for char in argument : if char != '_' : if previous_was_underscore : result += char . upper ( ) else : result += char previous_was_underscore = char == '_' return result | Converts a camelcase param like the_new_attribute to the equivalent camelcase version like theNewAttribute . Note that the first letter is NOT capitalized by this function |
28,208 | def convert_regex_to_flask_path ( url_path ) : for token in [ "$" ] : url_path = url_path . replace ( token , "" ) def caller ( reg ) : match_name , match_pattern = reg . groups ( ) return '<regex("{0}"):{1}>' . format ( match_pattern , match_name ) url_path = re . sub ( "\(\?P<(.*?)>(.*?)\)" , caller , url_path ) if u... | Converts a regex matching url to one that can be used with flask |
28,209 | def generate_boto3_response ( operation ) : def _boto3_request ( method ) : @ wraps ( method ) def f ( self , * args , ** kwargs ) : rendered = method ( self , * args , ** kwargs ) if 'json' in self . headers . get ( 'Content-Type' , [ ] ) : self . response_headers . update ( { 'x-amzn-requestid' : '2690d7eb-ed86-11dd-... | The decorator to convert an XML response to JSON if the request is determined to be from boto3 . Pass the API action as a parameter . |
28,210 | def describe_repositories ( self , registry_id = None , repository_names = None ) : if repository_names : for repository_name in repository_names : if repository_name not in self . repositories : raise RepositoryNotFoundException ( repository_name , registry_id or DEFAULT_REGISTRY_ID ) repositories = [ ] for repository... | maxResults and nextToken not implemented |
28,211 | def list_images ( self , repository_name , registry_id = None ) : repository = None found = False if repository_name in self . repositories : repository = self . repositories [ repository_name ] if registry_id : if repository . registry_id == registry_id : found = True else : found = True if not found : raise Repositor... | maxResults and filtering not implemented |
28,212 | def httprettified ( test ) : "A decorator tests that use HTTPretty" def decorate_class ( klass ) : for attr in dir ( klass ) : if not attr . startswith ( 'test_' ) : continue attr_value = getattr ( klass , attr ) if not hasattr ( attr_value , "__call__" ) : continue setattr ( klass , attr , decorate_callable ( attr_val... | A decorator tests that use HTTPretty |
28,213 | def get_next_entry ( self , method , info , request ) : if method not in self . current_entries : self . current_entries [ method ] = 0 entries_for_method = [ e for e in self . entries if e . method == method ] if self . current_entries [ method ] >= len ( entries_for_method ) : self . current_entries [ method ] = - 1 ... | Cycle through available responses but only once . Any subsequent requests will receive the last response |
28,214 | def mock_xray_client ( f ) : @ wraps ( f ) def _wrapped ( * args , ** kwargs ) : print ( "Starting X-Ray Patch" ) old_xray_context_var = os . environ . get ( 'AWS_XRAY_CONTEXT_MISSING' ) os . environ [ 'AWS_XRAY_CONTEXT_MISSING' ] = 'LOG_ERROR' old_xray_context = aws_xray_sdk . core . xray_recorder . _context old_xray_... | Mocks the X - Ray sdk by pwning its evil singleton with our methods |
28,215 | def to_description_dict ( self ) : return { 'certificateArn' : self . arn , 'certificateId' : self . certificate_id , 'status' : self . status , 'certificatePem' : self . certificate_pem , 'ownedBy' : self . owner , 'creationDate' : self . creation_date , 'lastModifiedDate' : self . last_modified_date , 'transferData' ... | You might need keys below in some situation - caCertificateId - previousOwnedBy |
28,216 | def start ( self ) : if self . instance is None : reservation = self . ec2_backend . add_instances ( image_id = self . ami_id , count = 1 , user_data = "" , security_group_names = [ ] , security_group_ids = self . security_group_ids , instance_type = self . instance_type , key_name = self . ssh_keyname , ebs_optimized ... | create an ec2 reservation if one doesn t already exist and call start_instance . Update instance attributes to the newly created instance attributes |
28,217 | def flatten_json_request_body ( prefix , dict_body , spec ) : if len ( spec ) == 1 and 'type' in spec : return { prefix : to_str ( dict_body , spec ) } flat = { } for key , value in dict_body . items ( ) : node_type = spec [ key ] [ 'type' ] if node_type == 'list' : for idx , v in enumerate ( value , 1 ) : pref = key +... | Convert a JSON request body into query params . |
28,218 | def xml_to_json_response ( service_spec , operation , xml , result_node = None ) : def transform ( value , spec ) : if len ( spec ) == 1 : return from_str ( value , spec ) od = OrderedDict ( ) for k , v in value . items ( ) : if k . startswith ( '@' ) : continue if k not in spec : log . warning ( 'Field %s is not defin... | Convert rendered XML response to JSON for use with boto3 . |
28,219 | def get_current_user ( self ) : if 'Authorization' in self . headers : match = self . access_key_regex . search ( self . headers [ 'Authorization' ] ) if match : return match . group ( 1 ) if self . querystring . get ( 'AWSAccessKeyId' ) : return self . querystring . get ( 'AWSAccessKeyId' ) else : return '111122223333... | Returns the access key id used in this request as the current user id |
28,220 | def delete_alias ( self , alias_name ) : for aliases in self . key_to_aliases . values ( ) : if alias_name in aliases : aliases . remove ( alias_name ) | Delete the alias . |
28,221 | def compare ( self , range_comparison , range_objs ) : range_values = [ obj . value for obj in range_objs ] comparison_func = get_comparison_func ( range_comparison ) return comparison_func ( self . value , * range_values ) | Compares this type against comparison filters |
28,222 | def paginate ( limit , start_arg = "next_token" , limit_arg = "max_results" ) : default_start = 0 def outer_wrapper ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : start = int ( default_start if kwargs . get ( start_arg ) is None else kwargs [ start_arg ] ) lim = int ( limit if kwargs . get... | Returns a limited result list and an offset into list of remaining items |
28,223 | def _url_matches ( self , url , other , match_querystring = False ) : if not match_querystring : other = other . split ( '?' , 1 ) [ 0 ] if responses . _is_string ( url ) : if responses . _has_unicode ( url ) : url = responses . _clean_unicode ( url ) if not isinstance ( other , six . text_type ) : other = other . enco... | Need to override this so we can fix querystrings breaking regex matching |
28,224 | def urls ( self ) : url_bases = self . _url_module . url_bases unformatted_paths = self . _url_module . url_paths urls = { } for url_base in url_bases : for url_path , handler in unformatted_paths . items ( ) : url = url_path . format ( url_base ) urls [ url ] = handler return urls | A dictionary of the urls to be mocked with this service and the handlers that should be called in their place |
28,225 | def url_paths ( self ) : unformatted_paths = self . _url_module . url_paths paths = { } for unformatted_path , handler in unformatted_paths . items ( ) : path = unformatted_path . format ( "" ) paths [ path ] = handler return paths | A dictionary of the paths of the urls to be mocked with this service and the handlers that should be called in their place |
28,226 | def flask_paths ( self ) : paths = { } for url_path , handler in self . url_paths . items ( ) : url_path = convert_regex_to_flask_path ( url_path ) paths [ url_path ] = handler return paths | The url paths that will be used for the flask server |
28,227 | def yaml_tag_constructor ( loader , tag , node ) : def _f ( loader , tag , node ) : if tag == '!GetAtt' : return node . value . split ( '.' ) elif type ( node ) == yaml . SequenceNode : return loader . construct_sequence ( node ) else : return node . value if tag == '!Ref' : key = 'Ref' else : key = 'Fn::{}' . format (... | convert shorthand intrinsic function to full name |
28,228 | def get_endpoint_name ( self , headers ) : match = headers . get ( 'x-amz-target' ) or headers . get ( 'X-Amz-Target' ) if match : return match . split ( "." ) [ 1 ] | Parses request headers and extracts part od the X - Amz - Target that corresponds to a method of DynamoHandler |
28,229 | def get_reservations_by_instance_ids ( self , instance_ids , filters = None ) : reservations = [ ] for reservation in self . all_reservations ( ) : reservation_instance_ids = [ instance . id for instance in reservation . instances ] matching_reservation = any ( instance_id in reservation_instance_ids for instance_id in... | Go through all of the reservations and filter to only return those associated with the given instance_ids . |
28,230 | def list_task_definitions ( self ) : task_arns = [ ] for task_definition_list in self . task_definitions . values ( ) : task_arns . extend ( [ task_definition . arn for task_definition in task_definition_list ] ) return task_arns | Filtering not implemented |
28,231 | def create_from_previous_version ( cls , previous_shadow , payload ) : version , previous_payload = ( previous_shadow . version + 1 , previous_shadow . to_dict ( include_delta = False ) ) if previous_shadow else ( 1 , { } ) if payload is None : shadow = FakeShadow ( None , None , None , version , deleted = True ) retur... | set None to payload when you want to delete shadow |
28,232 | def to_dict ( self , include_delta = True ) : if self . deleted : return { 'timestamp' : self . timestamp , 'version' : self . version } delta = self . parse_payload ( self . desired , self . reported ) payload = { } if self . desired is not None : payload [ 'desired' ] = self . desired if self . reported is not None :... | returning nothing except for just top - level keys for now . |
28,233 | def delete_thing_shadow ( self , thing_name ) : thing = iot_backends [ self . region_name ] . describe_thing ( thing_name ) if thing . thing_shadow is None : raise ResourceNotFoundException ( ) payload = None new_shadow = FakeShadow . create_from_previous_version ( thing . thing_shadow , payload ) thing . thing_shadow ... | after deleting get_thing_shadow will raise ResourceNotFound . But version of the shadow keep increasing ... |
28,234 | def _get_arn_from_idempotency_token ( self , token ) : now = datetime . datetime . now ( ) if token in self . _idempotency_tokens : if self . _idempotency_tokens [ token ] [ 'expires' ] < now : del self . _idempotency_tokens [ token ] return None else : return self . _idempotency_tokens [ token ] [ 'arn' ] return None | If token doesnt exist return None later it will be set with an expiry and arn . |
28,235 | def _validate_tag_key ( self , tag_key , exception_param = 'tags.X.member.key' ) : if len ( tag_key ) > 128 : raise TagKeyTooBig ( tag_key , param = exception_param ) match = re . findall ( r'[\w\s_.:/=+\-@]+' , tag_key ) if not len ( match ) or len ( match [ 0 ] ) < len ( tag_key ) : raise InvalidTagCharacters ( tag_k... | Validates the tag key . |
28,236 | def enable_mfa_device ( self , user_name , serial_number , authentication_code_1 , authentication_code_2 ) : user = self . get_user ( user_name ) if serial_number in user . mfa_devices : raise IAMConflictException ( "EntityAlreadyExists" , "Device {0} already exists" . format ( serial_number ) ) user . enable_mfa_devic... | Enable MFA Device for user . |
28,237 | def deactivate_mfa_device ( self , user_name , serial_number ) : user = self . get_user ( user_name ) if serial_number not in user . mfa_devices : raise IAMNotFoundException ( "Device {0} not found" . format ( serial_number ) ) user . deactivate_mfa_device ( serial_number ) | Deactivate and detach MFA Device from user if device exists . |
28,238 | def delete ( self , * args , ** kwargs ) : hosted_zone = route53_backend . get_hosted_zone_by_name ( self . hosted_zone_name ) if not hosted_zone : hosted_zone = route53_backend . get_hosted_zone ( self . hosted_zone_id ) hosted_zone . delete_rrset_by_name ( self . name ) | Not exposed as part of the Route 53 API - used for CloudFormation . args are ignored |
28,239 | def last_requestline ( sent_data ) : for line in reversed ( sent_data ) : try : parse_requestline ( decode_utf8 ( line ) ) except ValueError : pass else : return line | Find the last line in sent_data that can be parsed with parse_requestline |
28,240 | def attribute_md5 ( self ) : def utf8 ( str ) : if isinstance ( str , six . string_types ) : return str . encode ( 'utf-8' ) return str md5 = hashlib . md5 ( ) struct_format = "!I" . encode ( 'ascii' ) for name in sorted ( self . message_attributes . keys ( ) ) : attr = self . message_attributes [ name ] data_type = at... | The MD5 of all attributes is calculated by first generating a utf - 8 string from each attribute and MD5 - ing the concatenation of them all . Each attribute is encoded with some bytes that describe the length of each part and the type of attribute . |
28,241 | def mark_received ( self , visibility_timeout = None ) : if visibility_timeout : visibility_timeout = int ( visibility_timeout ) else : visibility_timeout = 0 if not self . approximate_first_receive_timestamp : self . approximate_first_receive_timestamp = int ( unix_time_millis ( ) ) self . approximate_receive_count +=... | When a message is received we will set the first receive timestamp tap the approximate_receive_count and the visible_at time . |
28,242 | def receive_messages ( self , queue_name , count , wait_seconds_timeout , visibility_timeout ) : queue = self . get_queue ( queue_name ) result = [ ] previous_result_count = len ( result ) polling_end = unix_time ( ) + wait_seconds_timeout while True : if result or ( wait_seconds_timeout and unix_time ( ) > polling_end... | Attempt to retrieve visible messages from a queue . |
28,243 | def get_table_keys_name ( self , table_name , keys ) : table = self . tables . get ( table_name ) if not table : return None , None else : if len ( keys ) == 1 : for key in keys : if key in table . hash_key_names : return key , None potential_hash , potential_range = None , None for key in set ( keys ) : if key in tabl... | Given a set of keys extracts the key and range key |
28,244 | def metadata_response ( self , request , full_url , headers ) : parsed_url = urlparse ( full_url ) tomorrow = datetime . datetime . utcnow ( ) + datetime . timedelta ( days = 1 ) credentials = dict ( AccessKeyId = "test-key" , SecretAccessKey = "test-secret-key" , Token = "test-session-token" , Expiration = tomorrow . ... | Mock response for localhost metadata |
28,245 | def _list_element_starts_with ( items , needle ) : for item in items : if item . startswith ( needle ) : return True return False | True of any of the list elements starts with needle |
28,246 | def _validate_compute_resources ( self , cr ) : for param in ( 'instanceRole' , 'maxvCpus' , 'minvCpus' , 'instanceTypes' , 'securityGroupIds' , 'subnets' , 'type' ) : if param not in cr : raise InvalidParameterValueException ( 'computeResources must contain {0}' . format ( param ) ) if self . iam_backend . get_role_by... | Checks contents of sub dictionary for managed clusters |
28,247 | def find_min_instances_to_meet_vcpus ( instance_types , target ) : instance_vcpus = [ ] instances = [ ] for instance_type in instance_types : if instance_type == 'optimal' : instance_type = 'm4.4xlarge' instance_vcpus . append ( ( EC2_INSTANCE_TYPES [ instance_type ] [ 'vcpus' ] , instance_type ) ) instance_vcpus = sor... | Finds the minimum needed instances to meed a vcpu target |
28,248 | def create_job_queue ( self , queue_name , priority , state , compute_env_order ) : for variable , var_name in ( ( queue_name , 'jobQueueName' ) , ( priority , 'priority' ) , ( state , 'state' ) , ( compute_env_order , 'computeEnvironmentOrder' ) ) : if variable is None : raise ClientException ( '{0} must be provided' ... | Create a job queue |
28,249 | def update_job_queue ( self , queue_name , priority , state , compute_env_order ) : if queue_name is None : raise ClientException ( 'jobQueueName must be provided' ) job_queue = self . get_job_queue ( queue_name ) if job_queue is None : raise ClientException ( 'Job queue {0} does not exist' . format ( queue_name ) ) if... | Update a job queue |
28,250 | def toFilename ( url ) : urlp = urlparse ( url ) path = urlp . path if not path : path = "file_{}" . format ( int ( time . time ( ) ) ) value = re . sub ( r'[^\w\s\.\-]' , '-' , path ) . strip ( ) . lower ( ) return re . sub ( r'[-\s]+' , '-' , value ) . strip ( "-" ) [ - 200 : ] | gets url and returns filename |
28,251 | def main ( argv = None ) : global Verbose global EncodeUtf8 global csvOutput if argv is None : argv = sys . argv if ( len ( argv ) < 3 and not ( ( '-h' in argv ) or ( '--help' in argv ) ) ) : log . exception ( 'Bad args' ) raise TikaException ( 'Bad args' ) try : opts , argv = getopt . getopt ( argv [ 1 : ] , 'hi:s:o:p... | Run Tika from command line according to USAGE . |
28,252 | def from_file ( filename , mime = False ) : m = _get_magic_type ( mime ) return m . from_file ( filename ) | Accepts a filename and returns the detected filetype . Return value is the mimetype if mime = True otherwise a human readable name . |
28,253 | def from_buffer ( buffer , mime = False ) : m = _get_magic_type ( mime ) return m . from_buffer ( buffer ) | Accepts a binary string and returns the detected filetype . Return value is the mimetype if mime = True otherwise a human readable name . |
28,254 | def desaturate ( color , prop ) : if not 0 <= prop <= 1 : raise ValueError ( "prop must be between 0 and 1" ) rgb = mplcol . colorConverter . to_rgb ( color ) h , l , s = colorsys . rgb_to_hls ( * rgb ) s *= prop new_color = colorsys . hls_to_rgb ( h , l , s ) return new_color | Decrease the saturation channel of a color by some percent . |
28,255 | def color_palette ( name = None , n_colors = 6 , desat = None ) : seaborn_palettes = dict ( deep = [ "#4C72B0" , "#55A868" , "#C44E52" , "#8172B2" , "#CCB974" , "#64B5CD" ] , muted = [ "#4878CF" , "#6ACC65" , "#D65F5F" , "#B47CC7" , "#C4AD66" , "#77BEDB" ] , pastel = [ "#92C6FF" , "#97F0AA" , "#FF9F9A" , "#D0BBFF" , "#... | Return a list of colors defining a color palette . |
28,256 | def mpl_palette ( name , n_colors = 6 ) : brewer_qual_pals = { "Accent" : 8 , "Dark2" : 8 , "Paired" : 12 , "Pastel1" : 9 , "Pastel2" : 8 , "Set1" : 9 , "Set2" : 8 , "Set3" : 12 } if name . endswith ( "_d" ) : pal = [ "#333333" ] pal . extend ( color_palette ( name . replace ( "_d" , "_r" ) , 2 ) ) cmap = blend_palette... | Return discrete colors from a matplotlib palette . |
28,257 | def dark_palette ( color , n_colors = 6 , reverse = False , as_cmap = False ) : gray = "#222222" colors = [ color , gray ] if reverse else [ gray , color ] return blend_palette ( colors , n_colors , as_cmap ) | Make a palette that blends from a deep gray to color . |
28,258 | def blend_palette ( colors , n_colors = 6 , as_cmap = False ) : name = "-" . join ( map ( str , colors ) ) pal = mpl . colors . LinearSegmentedColormap . from_list ( name , colors ) if not as_cmap : pal = pal ( np . linspace ( 0 , 1 , n_colors ) ) return pal | Make a palette that blends between a list of colors . |
28,259 | def xkcd_palette ( colors ) : palette = [ xkcd_rgb [ name ] for name in colors ] return color_palette ( palette , len ( palette ) ) | Make a palette with color names from the xkcd color survey . |
28,260 | def cubehelix_palette ( n_colors = 6 , start = 0 , rot = .4 , gamma = 1.0 , hue = 0.8 , light = .85 , dark = .15 , reverse = False , as_cmap = False ) : cdict = mpl . _cm . cubehelix ( gamma , start , rot , hue ) cmap = mpl . colors . LinearSegmentedColormap ( "cubehelix" , cdict ) x = np . linspace ( light , dark , n_... | Make a sequential palette from the cubehelix system . |
28,261 | def get_args ( stream_spec , overwrite_output = False ) : nodes = get_stream_spec_nodes ( stream_spec ) args = [ ] sorted_nodes , outgoing_edge_maps = topo_sort ( nodes ) input_nodes = [ node for node in sorted_nodes if isinstance ( node , InputNode ) ] output_nodes = [ node for node in sorted_nodes if isinstance ( nod... | Build command - line arguments to be passed to ffmpeg . |
28,262 | def compile ( stream_spec , cmd = 'ffmpeg' , overwrite_output = False ) : if isinstance ( cmd , basestring ) : cmd = [ cmd ] elif type ( cmd ) != list : cmd = list ( cmd ) return cmd + get_args ( stream_spec , overwrite_output = overwrite_output ) | Build command - line for invoking ffmpeg . |
28,263 | def run_async ( stream_spec , cmd = 'ffmpeg' , pipe_stdin = False , pipe_stdout = False , pipe_stderr = False , quiet = False , overwrite_output = False ) : args = compile ( stream_spec , cmd , overwrite_output = overwrite_output ) stdin_stream = subprocess . PIPE if pipe_stdin else None stdout_stream = subprocess . PI... | Asynchronously invoke ffmpeg for the supplied node graph . |
28,264 | def run ( stream_spec , cmd = 'ffmpeg' , capture_stdout = False , capture_stderr = False , input = None , quiet = False , overwrite_output = False ) : process = run_async ( stream_spec , cmd , pipe_stdin = input is not None , pipe_stdout = capture_stdout , pipe_stderr = capture_stderr , quiet = quiet , overwrite_output... | Invoke ffmpeg for the supplied node graph . |
28,265 | def output ( * streams_and_filename , ** kwargs ) : streams_and_filename = list ( streams_and_filename ) if 'filename' not in kwargs : if not isinstance ( streams_and_filename [ - 1 ] , basestring ) : raise ValueError ( 'A filename must be provided' ) kwargs [ 'filename' ] = streams_and_filename . pop ( - 1 ) streams =... | Output file URL |
28,266 | def _do_watch_progress ( filename , sock , handler ) : connection , client_address = sock . accept ( ) data = b'' try : while True : more_data = connection . recv ( 16 ) if not more_data : break data += more_data lines = data . split ( b'\n' ) for line in lines [ : - 1 ] : line = line . decode ( ) parts = line . split ... | Function to run in a separate gevent greenlet to read progress events from a unix - domain socket . |
28,267 | def _watch_progress ( handler ) : with _tmpdir_scope ( ) as tmpdir : socket_filename = os . path . join ( tmpdir , 'sock' ) sock = socket . socket ( socket . AF_UNIX , socket . SOCK_STREAM ) with contextlib . closing ( sock ) : sock . bind ( socket_filename ) sock . listen ( 1 ) child = gevent . spawn ( _do_watch_progr... | Context manager for creating a unix - domain socket and listen for ffmpeg progress events . |
28,268 | def show_progress ( total_duration ) : with tqdm ( total = round ( total_duration , 2 ) ) as bar : def handler ( key , value ) : if key == 'out_time_ms' : time = round ( float ( value ) / 1000000. , 2 ) bar . update ( time - bar . n ) elif key == 'progress' and value == 'end' : bar . update ( bar . total - bar . n ) wi... | Create a unix - domain socket to watch progress and render tqdm progress bar . |
28,269 | def probe ( filename , cmd = 'ffprobe' , ** kwargs ) : args = [ cmd , '-show_format' , '-show_streams' , '-of' , 'json' ] args += convert_kwargs_to_cmd_line_args ( kwargs ) args += [ filename ] p = subprocess . Popen ( args , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) out , err = p . communicate ( ) if p... | Run ffprobe on the specified file and return a JSON representation of the output . |
28,270 | def filter_multi_output ( stream_spec , filter_name , * args , ** kwargs ) : return FilterNode ( stream_spec , filter_name , args = args , kwargs = kwargs , max_inputs = None ) | Apply custom filter with one or more outputs . |
28,271 | def filter ( stream_spec , filter_name , * args , ** kwargs ) : return filter_multi_output ( stream_spec , filter_name , * args , ** kwargs ) . stream ( ) | Apply custom filter . |
28,272 | def filter_ ( stream_spec , filter_name , * args , ** kwargs ) : return filter ( stream_spec , filter_name , * args , ** kwargs ) | Alternate name for filter so as to not collide with the built - in python filter operator . |
28,273 | def trim ( stream , ** kwargs ) : return FilterNode ( stream , trim . __name__ , kwargs = kwargs ) . stream ( ) | Trim the input so that the output contains one continuous subpart of the input . |
28,274 | def overlay ( main_parent_node , overlay_parent_node , eof_action = 'repeat' , ** kwargs ) : kwargs [ 'eof_action' ] = eof_action return FilterNode ( [ main_parent_node , overlay_parent_node ] , overlay . __name__ , kwargs = kwargs , max_inputs = 2 ) . stream ( ) | Overlay one video on top of another . |
28,275 | def crop ( stream , x , y , width , height , ** kwargs ) : return FilterNode ( stream , crop . __name__ , args = [ width , height , x , y ] , kwargs = kwargs ) . stream ( ) | Crop the input video . |
28,276 | def drawbox ( stream , x , y , width , height , color , thickness = None , ** kwargs ) : if thickness : kwargs [ 't' ] = thickness return FilterNode ( stream , drawbox . __name__ , args = [ x , y , width , height , color ] , kwargs = kwargs ) . stream ( ) | Draw a colored box on the input image . |
28,277 | def drawtext ( stream , text = None , x = 0 , y = 0 , escape_text = True , ** kwargs ) : if text is not None : if escape_text : text = escape_chars ( text , '\\\'%' ) kwargs [ 'text' ] = text if x != 0 : kwargs [ 'x' ] = x if y != 0 : kwargs [ 'y' ] = y return filter ( stream , drawtext . __name__ , ** kwargs ) | Draw a text string or text from a specified file on top of a video using the libfreetype library . |
28,278 | def concat ( * streams , ** kwargs ) : video_stream_count = kwargs . get ( 'v' , 1 ) audio_stream_count = kwargs . get ( 'a' , 0 ) stream_count = video_stream_count + audio_stream_count if len ( streams ) % stream_count != 0 : raise ValueError ( 'Expected concat input streams to have length multiple of {} (v={}, a={});... | Concatenate audio and video streams joining them together one after the other . |
28,279 | def zoompan ( stream , ** kwargs ) : return FilterNode ( stream , zoompan . __name__ , kwargs = kwargs ) . stream ( ) | Apply Zoom & Pan effect . |
28,280 | def colorchannelmixer ( stream , * args , ** kwargs ) : return FilterNode ( stream , colorchannelmixer . __name__ , kwargs = kwargs ) . stream ( ) | Adjust video input frames by re - mixing color channels . |
28,281 | def _recursive_repr ( item ) : if isinstance ( item , basestring ) : result = str ( item ) elif isinstance ( item , list ) : result = '[{}]' . format ( ', ' . join ( [ _recursive_repr ( x ) for x in item ] ) ) elif isinstance ( item , dict ) : kv_pairs = [ '{}: {}' . format ( _recursive_repr ( k ) , _recursive_repr ( i... | Hack around python repr to deterministically represent dictionaries . |
28,282 | def escape_chars ( text , chars ) : text = str ( text ) chars = list ( set ( chars ) ) if '\\' in chars : chars . remove ( '\\' ) chars . insert ( 0 , '\\' ) for ch in chars : text = text . replace ( ch , '\\' + ch ) return text | Helper function to escape uncomfortable characters . |
28,283 | def convert_kwargs_to_cmd_line_args ( kwargs ) : args = [ ] for k in sorted ( kwargs . keys ( ) ) : v = kwargs [ k ] args . append ( '-{}' . format ( k ) ) if v is not None : args . append ( '{}' . format ( v ) ) return args | Helper function to build command line arguments out of dict . |
28,284 | def stream ( self , label = None , selector = None ) : return self . __outgoing_stream_type ( self , label , upstream_selector = selector ) | Create an outgoing stream originating from this node . |
28,285 | def _tffunc ( * argtypes ) : placeholders = list ( map ( tf . placeholder , argtypes ) ) def wrap ( f ) : out = f ( * placeholders ) def wrapper ( * args , ** kw ) : return out . eval ( dict ( zip ( placeholders , args ) ) , session = kw . get ( 'session' ) ) return wrapper return wrap | Helper that transforms TF - graph generating function into a regular one . See _resize function below . |
28,286 | def _base_resize ( img , size ) : img = tf . expand_dims ( img , 0 ) return tf . image . resize_bilinear ( img , size ) [ 0 , : , : , : ] | Helper function that uses TF to resize an image |
28,287 | def _calc_grad_tiled ( self , img , t_grad , tile_size = 512 ) : sz = tile_size h , w = img . shape [ : 2 ] sx , sy = np . random . randint ( sz , size = 2 ) img_shift = np . roll ( np . roll ( img , sx , 1 ) , sy , 0 ) grad = np . zeros_like ( img ) for y in range ( 0 , max ( h - sz // 2 , sz ) , sz ) : for x in range... | Compute the value of tensor t_grad over the image in a tiled way . Random shifts are applied to the image to blur tile boundaries over multiple iterations . |
28,288 | def collect ( self ) : if libvirt is None : self . log . error ( 'Unable to import either libvirt' ) return { } conn = libvirt . openReadOnly ( None ) conninfo = conn . getInfo ( ) memallocated = 0 coresallocated = 0 totalcores = 0 results = { } domIds = conn . listDomainsID ( ) if 0 in domIds : domU = conn . lookupByI... | Collect libvirt data |
28,289 | def publish_delayed_metric ( self , name , value , timestamp , raw_value = None , precision = 0 , metric_type = 'GAUGE' , instance = None ) : path = self . get_metric_path ( name , instance ) ttl = float ( self . config [ 'interval' ] ) * float ( self . config [ 'ttl_multiplier' ] ) metric = Metric ( path , value , raw... | Metrics may not be immediately available when querying cloudwatch . Hence allow the ability to publish a metric from some the past given its timestamp . |
28,290 | def agr_busy ( self ) : c1 = { } c2 = { } disk_results = { } agr_results = { } names = [ 'disk_busy' , 'base_for_disk_busy' , 'raid_name' , 'base_for_disk_busy' , 'instance_uuid' ] netapp_api = NaElement ( 'perf-object-get-instances' ) netapp_api . child_add_string ( 'objectname' , 'disk' ) disk_1 = self . get_netapp_e... | Collector for average disk busyness per aggregate |
28,291 | def consistency_point ( self ) : cp_delta = { } xml_path = 'instances/instance-data/counters' netapp_api = NaElement ( 'perf-object-get-instances' ) netapp_api . child_add_string ( 'objectname' , 'wafl' ) instance = NaElement ( 'instances' ) instance . child_add_string ( 'instance' , 'wafl' ) counter = NaElement ( 'cou... | Collector for getting count of consistancy points |
28,292 | def zero_disk ( self , disk_xml = None ) : troubled_disks = 0 for filer_disk in disk_xml : raid_state = filer_disk . find ( 'raid-state' ) . text if not raid_state == 'spare' : continue is_zeroed = filer_disk . find ( 'is-zeroed' ) . text if is_zeroed == 'false' : troubled_disks += 1 self . push ( 'not_zeroed' , 'disk'... | Collector and publish not zeroed disk metrics |
28,293 | def spare_disk ( self , disk_xml = None ) : spare_disk = { } disk_types = set ( ) for filer_disk in disk_xml : disk_types . add ( filer_disk . find ( 'effective-disk-type' ) . text ) if not filer_disk . find ( 'raid-state' ) . text == 'spare' : continue disk_type = filer_disk . find ( 'effective-disk-type' ) . text if ... | Number of spare disk per type . |
28,294 | def get_netapp_elem ( self , netapp_api = None , sub_element = None ) : netapp_data = self . server . invoke_elem ( netapp_api ) if netapp_data . results_status ( ) == 'failed' : self . log . error ( 'While using netapp API failed to retrieve ' 'disk-list-info for netapp filer %s' % self . device ) print ( netapp_data ... | Retrieve netapp elem |
28,295 | def _netapp_login ( self ) : self . server = NaServer ( self . ip , 1 , 3 ) self . server . set_transport_type ( 'HTTPS' ) self . server . set_style ( 'LOGIN' ) self . server . set_admin_user ( self . netapp_user , self . netapp_password ) | Login to our netapp filer |
28,296 | def _get_socket_paths ( self ) : socket_pattern = os . path . join ( self . config [ 'socket_path' ] , ( self . config [ 'socket_prefix' ] + '*.' + self . config [ 'socket_ext' ] ) ) return glob . glob ( socket_pattern ) | Return a sequence of paths to sockets for communicating with ceph daemons . |
28,297 | def _get_counter_prefix_from_socket_name ( self , name ) : base = os . path . splitext ( os . path . basename ( name ) ) [ 0 ] if base . startswith ( self . config [ 'socket_prefix' ] ) : base = base [ len ( self . config [ 'socket_prefix' ] ) : ] return 'ceph.' + base | Given the name of a UDS socket return the prefix for counters coming from that source . |
28,298 | def _get_stats_from_socket ( self , name ) : try : json_blob = subprocess . check_output ( [ self . config [ 'ceph_binary' ] , '--admin-daemon' , name , 'perf' , 'dump' , ] ) except subprocess . CalledProcessError as err : self . log . info ( 'Could not get stats from %s: %s' , name , err ) self . log . exception ( 'Co... | Return the parsed JSON data returned when ceph is told to dump the stats from the named socket . |
28,299 | def _publish_stats ( self , counter_prefix , stats ) : for stat_name , stat_value in flatten_dictionary ( stats , prefix = counter_prefix , ) : self . publish_gauge ( stat_name , stat_value ) | Given a stats dictionary from _get_stats_from_socket publish the individual values . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.