idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
34,000
def cmd ( f ) : @ wraps ( f ) def wrapper ( * args , ** kwargs ) : return f ( * args , ** kwargs ) setattr ( wrapper , executors . EXECUTOR_ATTR , executors . CMD ) return wrapper
wrapper for easily exposing a function as a CLI command . including help message arguments help and type .
34,001
def main ( func = None , argv = None , input_stream = stdin , output_stream = stdout , error_stream = stderr , exit = True ) : executor = executors . get_func_executor ( func ) exitcode = executor ( func , argv , input_stream , output_stream , error_stream ) if exit : sys . exit ( exitcode ) return exitcode
runs a function as a command . runs a function as a command - reading input from input_stream writing output into output_stream and providing arguments from argv .
34,002
def _parse_docstring ( docstring ) : params = { } if not docstring : return None , params try : help_msg = _DOCSTRING_REGEX . search ( docstring ) . group ( ) help_msg = _strip_lines ( help_msg ) except AttributeError : help_msg = None for param in _DOCSTRING_PARAM_REGEX . finditer ( docstring ) : param_definition = pa...
parses docstring into its help message and params
34,003
def error2str ( e ) : out = StringIO ( ) traceback . print_exception ( None , e , e . __traceback__ , file = out ) out . seek ( 0 ) return out . read ( )
returns the formatted stacktrace of the exception e .
34,004
def get_runner ( worker_type , max_workers = None , workers_window = None ) : worker_func = _runners_mapping [ worker_type ] return partial ( worker_func , max_workers = max_workers , workers_window = workers_window )
returns a runner callable .
34,005
def get_inline_func ( inline_str , modules = None , ** stream_kwargs ) : if not _is_compilable ( inline_str ) : raise ValueError ( 'cannot compile the inline expression - "%s"' % inline_str ) inline_globals = _import_inline_modules ( modules ) func = _inline2func ( inline_str , inline_globals , ** stream_kwargs ) retur...
returns a function decorated by cbox . stream decorator .
34,006
def setmode ( mode ) : if hasattr ( mode , '__getitem__' ) : set_custom_pin_mappings ( mode ) mode = CUSTOM assert mode in [ BCM , BOARD , SUNXI , CUSTOM ] global _mode _mode = mode
You must call this method prior to using all other calls .
34,007
def setup ( channel , direction , initial = None , pull_up_down = None ) : if _mode is None : raise RuntimeError ( "Mode has not been set" ) if pull_up_down is not None : if _gpio_warnings : warnings . warn ( "Pull up/down setting are not (yet) fully supported, continuing anyway. Use GPIO.setwarnings(False) to disable ...
You need to set up every channel you are using as an input or an output .
34,008
def input ( channel ) : _check_configured ( channel ) pin = get_gpio_pin ( _mode , channel ) return sysfs . input ( pin )
Read the value of a GPIO pin .
34,009
def output ( channel , state ) : if isinstance ( channel , list ) : for ch in channel : output ( ch , state ) else : _check_configured ( channel , direction = OUT ) pin = get_gpio_pin ( _mode , channel ) return sysfs . output ( pin , state )
Set the output state of a GPIO pin .
34,010
def wait_for_edge ( channel , trigger , timeout = - 1 ) : _check_configured ( channel , direction = IN ) pin = get_gpio_pin ( _mode , channel ) if event . blocking_wait_for_edge ( pin , trigger , timeout ) is not None : return channel
This function is designed to block execution of your program until an edge is detected .
34,011
def is_swapped ( app_label , model ) : default_model = join ( app_label , model ) setting = swappable_setting ( app_label , model ) value = getattr ( settings , setting , default_model ) if value != default_model : return value else : return False
Returns the value of the swapped setting or False if the model hasn t been swapped .
34,012
def get_model_names ( app_label , models ) : return dict ( ( model , get_model_name ( app_label , model ) ) for model in models )
Map model names to their swapped equivalents for the given app
34,013
def update ( self , entries = { } , * args , ** kwargs ) : if isinstance ( entries , dict ) : entries = self . _reject_reserved_keys ( entries ) for key , value in dict ( entries , * args , ** kwargs ) . items ( ) : if isinstance ( value , dict ) : self . __dict__ [ key ] = AttributeDict ( value ) else : self . __dict_...
Update dictionary .
34,014
def read_table ( filename , usecols = ( 0 , 1 ) , sep = '\t' , comment = '#' , encoding = 'utf-8' , skip = 0 ) : with io . open ( filename , 'r' , encoding = encoding ) as f : for _ in range ( skip ) : next ( f ) lines = ( line for line in f if not line . startswith ( comment ) ) d = dict ( ) for line in lines : column...
Parse data files from the data directory
34,015
def build_index ( ) : nationalities = read_table ( get_data_path ( 'nationalities.txt' ) , sep = ':' ) countries = read_table ( get_data_path ( 'countryInfo.txt' ) , usecols = [ 4 , 0 ] , skip = 1 ) cities = read_table ( get_data_path ( 'cities15000.txt' ) , usecols = [ 1 , 8 ] ) city_patches = read_table ( get_data_pa...
Load information from the data directory
34,016
def _find_executables ( name ) : exe_name = name + '.exe' * sys . platform . startswith ( 'win' ) env_path = os . environ . get ( name . upper ( ) + '_PATH' , '' ) possible_locations = [ ] def add ( * dirs ) : for d in dirs : if d and d not in possible_locations and os . path . isdir ( d ) : possible_locations . append...
Try to find an executable .
34,017
def get_elastix_exes ( ) : if EXES : if EXES [ 0 ] : return EXES else : raise RuntimeError ( 'No Elastix executable.' ) elastix , ver = _find_executables ( 'elastix' ) if elastix : base , ext = os . path . splitext ( elastix ) base = os . path . dirname ( base ) transformix = os . path . join ( base , 'transformix' + e...
Get the executables for elastix and transformix . Raises an error if they cannot be found .
34,018
def _clear_dir ( dirName ) : for fname in os . listdir ( dirName ) : try : os . remove ( os . path . join ( dirName , fname ) ) except Exception : pass try : os . rmdir ( dirName ) except Exception : pass
Remove a directory and it contents . Ignore any failures .
34,019
def get_tempdir ( ) : tempdir = os . path . join ( tempfile . gettempdir ( ) , 'pyelastix' ) if not os . path . isdir ( tempdir ) : os . makedirs ( tempdir ) for fname in os . listdir ( tempdir ) : dirName = os . path . join ( tempdir , fname ) if not ( os . path . isdir ( dirName ) and fname . startswith ( 'id_' ) ) :...
Get the temporary directory where pyelastix stores its temporary files . The directory is specific to the current process and the calling thread . Generally the user does not need this ; directories are automatically cleaned up . Though Elastix log files are also written here .
34,020
def _clear_temp_dir ( ) : tempdir = get_tempdir ( ) for fname in os . listdir ( tempdir ) : try : os . remove ( os . path . join ( tempdir , fname ) ) except Exception : pass
Clear the temporary directory .
34,021
def _get_image_paths ( im1 , im2 ) : paths = [ ] for im in [ im1 , im2 ] : if im is None : paths . append ( paths [ 0 ] ) continue if isinstance ( im , str ) : if os . path . isfile ( im1 ) : paths . append ( im ) else : raise ValueError ( 'Image location does not exist.' ) elif isinstance ( im , np . ndarray ) : id = ...
If the images are paths to a file checks whether the file exist and return the paths . If the images are numpy arrays writes them to disk and returns the paths of the new files .
34,022
def _system3 ( cmd , verbose = False ) : interrupted = False if verbose > 0 : progress = Progress ( ) stdout = [ ] def poll_process ( p ) : while not interrupted : msg = p . stdout . readline ( ) . decode ( ) if msg : stdout . append ( msg ) if 'error' in msg . lower ( ) : print ( msg . rstrip ( ) ) if verbose == 1 : p...
Execute the given command in a subprocess and wait for it to finish . A thread is run that prints output of the process if verbose is True .
34,023
def _get_dtype_maps ( ) : tmp = [ ( np . float32 , 'MET_FLOAT' ) , ( np . float64 , 'MET_DOUBLE' ) , ( np . uint8 , 'MET_UCHAR' ) , ( np . int8 , 'MET_CHAR' ) , ( np . uint16 , 'MET_USHORT' ) , ( np . int16 , 'MET_SHORT' ) , ( np . uint32 , 'MET_UINT' ) , ( np . int32 , 'MET_INT' ) , ( np . uint64 , 'MET_ULONG' ) , ( n...
Get dictionaries to map numpy data types to ITK types and the other way around .
34,024
def _read_image_data ( mhd_file ) : tempdir = get_tempdir ( ) fname = tempdir + '/' + mhd_file des = open ( fname , 'r' ) . read ( ) match = re . findall ( 'ElementDataFile = (.+?)\n' , des ) fname = tempdir + '/' + match [ 0 ] data = open ( fname , 'rb' ) . read ( ) match = re . findall ( 'ElementType = (.+?)\n' , des...
Read the resulting image data and return it as a numpy array .
34,025
def _get_fixed_params ( im ) : p = Parameters ( ) if not isinstance ( im , np . ndarray ) : return p p . FixedImageDimension = im . ndim p . MovingImageDimension = im . ndim p . WriteResultImage = True tmp = DTYPE_NP2ITK [ im . dtype . name ] p . ResultImagePixelType = tmp . split ( '_' ) [ - 1 ] . lower ( ) p . Result...
Parameters that the user has no influence on . Mostly chosen bases on the input images .
34,026
def get_advanced_params ( ) : p = Parameters ( ) p . FixedInternalImagePixelType = "float" p . MovingInternalImagePixelType = "float" p . UseDirectionCosines = True p . Registration = 'MultiResolutionRegistration' p . FixedImagePyramid = "FixedRecursiveImagePyramid" p . MovingImagePyramid = "MovingRecursiveImagePyramid...
Get Parameters struct with parameters that most users do not want to think about .
34,027
def _write_parameter_file ( params ) : path = os . path . join ( get_tempdir ( ) , 'params.txt' ) def valToStr ( val ) : if val in [ True , False ] : return '"%s"' % str ( val ) . lower ( ) elif isinstance ( val , int ) : return str ( val ) elif isinstance ( val , float ) : tmp = str ( val ) if not '.' in tmp : tmp += ...
Write the parameter file in the format that elaxtix likes .
34,028
def _highlight ( html ) : formatter = pygments . formatters . HtmlFormatter ( nowrap = True ) code_expr = re . compile ( r'<pre><code class="language-(?P<lang>.+?)">(?P<code>.+?)' r'</code></pre>' , re . DOTALL ) def replacer ( match ) : try : lang = match . group ( 'lang' ) lang = _LANG_ALIASES . get ( lang , lang ) l...
Syntax - highlights HTML - rendered Markdown .
34,029
def check_restructuredtext ( self ) : Command . warn ( self , "This command has been deprecated. Use `twine check` instead: " "https://packaging.python.org/guides/making-a-pypi-friendly-readme" "#validating-restructuredtext-markup" ) data = self . distribution . get_long_description ( ) content_type = getattr ( self . ...
Checks if the long string fields are reST - compliant .
34,030
def render_code ( code , filetype , pygments_style ) : if filetype : lexer = pygments . lexers . get_lexer_by_name ( filetype ) formatter = pygments . formatters . HtmlFormatter ( style = pygments_style ) return pygments . highlight ( code , lexer , formatter ) else : return "<pre><code>{}</code></pre>" . format ( code...
Renders a piece of code into HTML . Highlights syntax if filetype is specfied
34,031
def fql ( self , query , args = None , post_args = None ) : args = args or { } if self . access_token : if post_args is not None : post_args [ "access_token" ] = self . access_token else : args [ "access_token" ] = self . access_token post_data = None if post_args is None else urllib . urlencode ( post_args ) if not is...
FQL query .
34,032
def _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value ( lb , ub ) : if lb is None and ub is None : raise Exception ( "Free constraint ..." ) elif lb is None : sense = '<' rhs = float ( ub ) range_value = 0. elif ub is None : sense = '>' rhs = float ( lb ) range_value = 0. elif lb == ub : sense = '=' rhs = float...
Helper function used by Constraint and Model
34,033
def parse_optimization_expression ( obj , linear = True , quadratic = False , expression = None , ** kwargs ) : if expression is None : expression = obj . expression if not ( linear or quadratic ) : if obj . is_Linear : linear = True elif obj . is_Quadratic : quadratic = True else : raise ValueError ( "Expression is no...
Function for parsing the expression of a Constraint or Objective object .
34,034
def _parse_quadratic_expression ( expression , expanded = False ) : linear_coefficients = { } quadratic_coefficients = { } offset = 0 if expression . is_Number : return float ( expression ) , linear_coefficients , quadratic_coefficients if expression . is_Mul : terms = ( expression , ) elif expression . is_Add : terms ...
Parse a quadratic expression . It is assumed that the expression is known to be quadratic or linear .
34,035
def clone ( cls , variable , ** kwargs ) : return cls ( variable . name , lb = variable . lb , ub = variable . ub , type = variable . type , ** kwargs )
Make a copy of another variable . The variable being copied can be of the same type or belong to a different solver interface .
34,036
def set_bounds ( self , lb , ub ) : if lb is not None and ub is not None and lb > ub : raise ValueError ( "The provided lower bound {} is larger than the provided upper bound {}" . format ( lb , ub ) ) self . _lb = lb self . _ub = ub if self . problem is not None : self . problem . _pending_modifications . var_lb . app...
Change the lower and upper bounds of a variable .
34,037
def to_json ( self ) : json_obj = { "name" : self . name , "lb" : self . lb , "ub" : self . ub , "type" : self . type } return json_obj
Returns a json - compatible object from the Variable that can be saved using the json module .
34,038
def clone ( cls , constraint , model = None , ** kwargs ) : return cls ( cls . _substitute_variables ( constraint , model = model ) , lb = constraint . lb , ub = constraint . ub , indicator_variable = constraint . indicator_variable , active_when = constraint . active_when , name = constraint . name , sloppy = True , *...
Make a copy of another constraint . The constraint being copied can be of the same type or belong to a different solver interface .
34,039
def to_json ( self ) : if self . indicator_variable is None : indicator = None else : indicator = self . indicator_variable . name json_obj = { "name" : self . name , "expression" : expr_to_json ( self . expression ) , "lb" : self . lb , "ub" : self . ub , "indicator_variable" : indicator , "active_when" : self . activ...
Returns a json - compatible object from the constraint that can be saved using the json module .
34,040
def clone ( cls , objective , model = None , ** kwargs ) : return cls ( cls . _substitute_variables ( objective , model = model ) , name = objective . name , direction = objective . direction , sloppy = True , ** kwargs )
Make a copy of an objective . The objective being copied can be of the same type or belong to a different solver interface .
34,041
def to_json ( self ) : json_obj = { "name" : self . name , "expression" : expr_to_json ( self . expression ) , "direction" : self . direction } return json_obj
Returns a json - compatible object from the objective that can be saved using the json module .
34,042
def from_json ( cls , json_obj , variables = None ) : if variables is None : variables = { } expression = parse_expr ( json_obj [ "expression" ] , variables ) return cls ( expression , direction = json_obj [ "direction" ] , name = json_obj [ "name" ] )
Constructs an Objective from the provided json - object .
34,043
def clone ( cls , model , use_json = True , use_lp = False ) : model . update ( ) interface = sys . modules [ cls . __module__ ] if use_lp : warnings . warn ( "Cloning with LP formats can change variable and constraint ID's." ) new_model = cls . from_lp ( model . to_lp ( ) ) new_model . configuration = interface . Conf...
Make a copy of a model . The model being copied can be of the same type or belong to a different solver interface . This is the preferred way of copying models .
34,044
def add ( self , stuff , sloppy = False ) : if self . _pending_modifications . toggle == 'remove' : self . update ( ) self . _pending_modifications . toggle = 'add' if isinstance ( stuff , collections . Iterable ) : for elem in stuff : self . add ( elem , sloppy = sloppy ) elif isinstance ( stuff , Variable ) : if stuf...
Add variables and constraints .
34,045
def remove ( self , stuff ) : if self . _pending_modifications . toggle == 'add' : self . update ( ) self . _pending_modifications . toggle = 'remove' if isinstance ( stuff , str ) : try : variable = self . variables [ stuff ] self . _pending_modifications . rm_var . append ( variable ) except KeyError : try : constrai...
Remove variables and constraints .
34,046
def update ( self , callback = int ) : add_var = self . _pending_modifications . add_var if len ( add_var ) > 0 : self . _add_variables ( add_var ) self . _pending_modifications . add_var = [ ] callback ( ) add_constr = self . _pending_modifications . add_constr if len ( add_constr ) > 0 : self . _add_constraints ( add...
Process all pending model modifications .
34,047
def optimize ( self ) : self . update ( ) status = self . _optimize ( ) if status != OPTIMAL and self . configuration . presolve == "auto" : self . configuration . presolve = True status = self . _optimize ( ) self . configuration . presolve = "auto" self . _status = status return status
Solve the optimization problem using the relevant solver back - end . The status returned by this method tells whether an optimal solution was found if the problem is infeasible etc . Consult optlang . statuses for more elaborate explanations of each status .
34,048
def to_json ( self ) : json_obj = { "name" : self . name , "variables" : [ var . to_json ( ) for var in self . variables ] , "constraints" : [ const . to_json ( ) for const in self . constraints ] , "objective" : self . objective . to_json ( ) } return json_obj
Returns a json - compatible object from the model that can be saved using the json module . Variables constraints and objective contained in the model will be saved . Configurations will not be saved .
34,049
def solve_with_glpsol ( glp_prob ) : from swiglpk import glp_get_row_name , glp_get_col_name , glp_write_lp , glp_get_num_rows , glp_get_num_cols row_ids = [ glp_get_row_name ( glp_prob , i ) for i in range ( 1 , glp_get_num_rows ( glp_prob ) + 1 ) ] col_ids = [ glp_get_col_name ( glp_prob , i ) for i in range ( 1 , gl...
Solve glpk problem with glpsol commandline solver . Mainly for testing purposes .
34,050
def glpk_read_cplex ( path ) : from swiglpk import glp_create_prob , glp_read_lp problem = glp_create_prob ( ) glp_read_lp ( problem , None , path ) return problem
Reads cplex file and returns glpk problem .
34,051
def expr_to_json ( expr ) : if isinstance ( expr , symbolics . Mul ) : return { "type" : "Mul" , "args" : [ expr_to_json ( arg ) for arg in expr . args ] } elif isinstance ( expr , symbolics . Add ) : return { "type" : "Add" , "args" : [ expr_to_json ( arg ) for arg in expr . args ] } elif isinstance ( expr , symbolics...
Converts a Sympy expression to a json - compatible tree - structure .
34,052
def parse_expr ( expr , local_dict = None ) : if local_dict is None : local_dict = { } if expr [ "type" ] == "Add" : return add ( [ parse_expr ( arg , local_dict ) for arg in expr [ "args" ] ] ) elif expr [ "type" ] == "Mul" : return mul ( [ parse_expr ( arg , local_dict ) for arg in expr [ "args" ] ] ) elif expr [ "ty...
Parses a json - object created with expr_to_json into a Sympy expression .
34,053
def set_variable_bounds ( self , name , lower , upper ) : self . bounds [ name ] = ( lower , upper ) self . _reset_solution ( )
Set the bounds of a variable
34,054
def add_constraint ( self , name , coefficients = { } , ub = 0 ) : if name in self . _constraints : raise ValueError ( "A constraint named " + name + " already exists." ) self . _constraints [ name ] = len ( self . _constraints ) self . upper_bounds = np . append ( self . upper_bounds , ub ) new_row = np . array ( [ [ ...
Add a constraint to the problem . The constrain is formulated as a dictionary of variable names to linear coefficients . The constraint can only have an upper bound . To make a constraint with a lower bound multiply all coefficients by - 1 .
34,055
def remove_variable ( self , name ) : index = self . _get_var_index ( name ) self . _A = np . delete ( self . A , index , 1 ) del self . bounds [ name ] del self . _variables [ name ] self . _update_variable_indices ( ) self . _reset_solution ( )
Remove a variable from the problem .
34,056
def remove_constraint ( self , name ) : index = self . _get_constraint_index ( name ) self . _A = np . delete ( self . A , index , 0 ) self . upper_bounds = np . delete ( self . upper_bounds , index ) del self . _constraints [ name ] self . _update_constraint_indices ( ) self . _reset_solution ( )
Remove a constraint from the problem
34,057
def set_constraint_bound ( self , name , value ) : index = self . _get_constraint_index ( name ) self . upper_bounds [ index ] = value self . _reset_solution ( )
Set the upper bound of a constraint .
34,058
def get_var_primal ( self , name ) : if self . _var_primals is None : return None else : index = self . _get_var_index ( name ) return self . _var_primals [ index ]
Get the primal value of a variable . Returns None if the problem has not bee optimized .
34,059
def get_constraint_slack ( self , name ) : if self . _slacks is None : return None else : index = self . _get_constraint_index ( name ) return self . _slacks [ index ]
Get the value of the slack variable of a constraint .
34,060
def optimize ( self , method = "simplex" , verbosity = False , tolerance = 1e-9 , ** kwargs ) : c = np . array ( [ self . objective . get ( name , 0 ) for name in self . _variables ] ) if self . direction == "max" : c *= - 1 bounds = list ( six . itervalues ( self . bounds ) ) solution = linprog ( c , self . A , self ....
Run the linprog function on the problem . Returns None .
34,061
def objective_value ( self ) : if self . _f is None : raise RuntimeError ( "Problem has not been optimized yet" ) if self . direction == "max" : return - self . _f + self . offset else : return self . _f + self . offset
Returns the optimal objective value
34,062
def install ( application , io_loop = None , ** kwargs ) : if getattr ( application , 'amqp' , None ) is not None : LOGGER . warning ( 'AMQP is already installed' ) return False kwargs . setdefault ( 'io_loop' , io_loop ) for prefix in { 'AMQP' , 'RABBITMQ' } : key = '{}_URL' . format ( prefix ) if os . environ . get (...
Call this to install AMQP for the Tornado application . Additional keyword arguments are passed through to the constructor of the AMQP object .
34,063
def amqp_publish ( self , exchange , routing_key , body , properties = None ) : properties = properties or { } if hasattr ( self , 'correlation_id' ) and getattr ( self , 'correlation_id' ) : properties . setdefault ( 'correlation_id' , self . correlation_id ) return self . application . amqp . publish ( exchange , rou...
Publish a message to RabbitMQ
34,064
def publish ( self , exchange , routing_key , body , properties = None ) : future = concurrent . Future ( ) properties = properties or { } properties . setdefault ( 'app_id' , self . default_app_id ) properties . setdefault ( 'message_id' , str ( uuid . uuid4 ( ) ) ) properties . setdefault ( 'timestamp' , int ( time ....
Publish a message to RabbitMQ . If the RabbitMQ connection is not established or is blocked attempt to wait until sending is possible .
34,065
def on_delivery_confirmation ( self , method_frame ) : confirmation_type = method_frame . method . NAME . split ( '.' ) [ 1 ] . lower ( ) LOGGER . debug ( 'Received %s for delivery tag: %i' , confirmation_type , method_frame . method . delivery_tag ) if method_frame . method . multiple : confirmed = sorted ( [ msg for ...
Invoked by pika when RabbitMQ responds to a Basic . Publish RPC command passing in either a Basic . Ack or Basic . Nack frame with the delivery tag of the message that was published . The delivery tag is an integer counter indicating the message number that was sent on the channel via Basic . Publish . Here we re just ...
34,066
def close ( self ) : if not self . closable : LOGGER . warning ( 'Closed called while %s' , self . state_description ) raise ConnectionStateError ( self . state_description ) self . state = self . STATE_CLOSING LOGGER . info ( 'Closing RabbitMQ connection' ) self . connection . close ( )
Cleanly shutdown the connection to RabbitMQ
34,067
def _reconnect ( self ) : if self . idle or self . closed : LOGGER . debug ( 'Attempting RabbitMQ reconnect in %s seconds' , self . reconnect_delay ) self . io_loop . call_later ( self . reconnect_delay , self . connect ) return LOGGER . warning ( 'Reconnect called while %s' , self . state_description )
Schedule the next connection attempt if the class is not currently closing .
34,068
def on_connection_open ( self , connection ) : LOGGER . debug ( 'Connection opened' ) connection . add_on_connection_blocked_callback ( self . on_connection_blocked ) connection . add_on_connection_unblocked_callback ( self . on_connection_unblocked ) connection . add_backpressure_callback ( self . on_back_pressure_det...
This method is called by pika once the connection to RabbitMQ has been established .
34,069
def on_connection_open_error ( self , connection , error ) : LOGGER . critical ( 'Could not connect to RabbitMQ (%s): %r' , connection , error ) self . state = self . STATE_CLOSED self . _reconnect ( )
Invoked if the connection to RabbitMQ can not be made .
34,070
def on_connection_blocked ( self , method_frame ) : LOGGER . warning ( 'Connection blocked: %s' , method_frame ) self . state = self . STATE_BLOCKED if self . on_unavailable : self . on_unavailable ( self )
This method is called by pika if RabbitMQ sends a connection blocked method to let us know we need to throttle our publishing .
34,071
def on_connection_closed ( self , connection , reply_code , reply_text ) : start_state = self . state self . state = self . STATE_CLOSED if self . on_unavailable : self . on_unavailable ( self ) self . connection = None self . channel = None if start_state != self . STATE_CLOSING : LOGGER . warning ( '%s closed while %...
This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly . Since it is unexpected we will reconnect to RabbitMQ if it disconnects .
34,072
def on_basic_return ( self , _channel , method , properties , body ) : if self . on_return : self . on_return ( method , properties , body ) else : LOGGER . critical ( '%s message %s published to %s (CID %s) returned: %s' , method . exchange , properties . message_id , method . routing_key , properties . correlation_id...
Invoke a registered callback or log the returned message .
34,073
def on_channel_closed ( self , channel , reply_code , reply_text ) : for future in self . messages . values ( ) : future . set_exception ( AMQPException ( reply_code , reply_text ) ) self . messages = { } if self . closing : LOGGER . debug ( 'Channel %s was intentionally closed (%s) %s' , channel , reply_code , reply_t...
Invoked by pika when RabbitMQ unexpectedly closes the channel .
34,074
def object_to_json ( obj ) : if isinstance ( obj , ( datetime . datetime , datetime . date , datetime . time ) ) : return obj . isoformat ( ) return str ( obj )
Convert object that cannot be natively serialized by python to JSON representation .
34,075
def from_response ( cls , response_data ) : identity = lambda x : x return Mail ( ** _transform_dict ( response_data , { 'guid' : ( 'mail_id' , identity ) , 'subject' : ( 'mail_subject' , identity ) , 'sender' : ( 'mail_from' , identity ) , 'datetime' : ( 'mail_timestamp' , lambda x : datetime . utcfromtimestamp ( int ...
Factory method to create a Mail instance from a Guerrillamail response dict .
34,076
def grad_f ( xy ) : return np . array ( [ grad_fx ( xy [ 0 ] , xy [ 1 ] ) , grad_fy ( xy [ 0 ] , xy [ 1 ] ) ] )
Gradient of f
34,077
def prox_circle ( xy , step ) : center = np . array ( [ 0 , 0 ] ) dxy = xy - center radius = 0.5 if 1 : phi = np . arctan2 ( dxy [ 1 ] , dxy [ 0 ] ) return center + radius * np . array ( [ np . cos ( phi ) , np . sin ( phi ) ] ) else : return xy
Projection onto circle
34,078
def prox_xline ( x , step ) : if not np . isscalar ( x ) : x = x [ 0 ] if x > 0.5 : return np . array ( [ 0.5 ] ) else : return np . array ( [ x ] )
Projection onto line in x
34,079
def prox_yline ( y , step ) : if not np . isscalar ( y ) : y = y [ 0 ] if y > - 0.75 : return np . array ( [ - 0.75 ] ) else : return np . array ( [ y ] )
Projection onto line in y
34,080
def prox_line ( xy , step ) : return np . concatenate ( ( prox_xline ( xy [ 0 ] , step ) , prox_yline ( xy [ 1 ] , step ) ) )
2D projection onto 2 lines
34,081
def prox_lim ( xy , step , boundary = None ) : if boundary == "circle" : return prox_circle ( xy , step ) if boundary == "line" : return prox_line ( xy , step ) return xy
Proximal projection operator
34,082
def prox_gradf12 ( x , step , j = None , Xs = None ) : if j == 0 : return x - step * grad_fx ( Xs [ 0 ] [ 0 ] , Xs [ 1 ] [ 0 ] ) if j == 1 : y = x return y - step * grad_fy ( Xs [ 0 ] [ 0 ] , Xs [ 1 ] [ 0 ] ) raise NotImplementedError
1D gradient operator for x or y
34,083
def prox_gradf_lim12 ( x , step , j = None , Xs = None , boundary = None ) : if j == 0 : x -= step * grad_fx ( Xs [ 0 ] [ 0 ] , Xs [ 1 ] [ 0 ] ) if j == 1 : y = x y -= step * grad_fy ( Xs [ 0 ] [ 0 ] , Xs [ 1 ] [ 0 ] ) return prox_lim12 ( x , step , j = j , Xs = Xs , boundary = boundary )
1D projection operator
34,084
def pgm ( X , prox_f , step_f , accelerated = False , relax = None , e_rel = 1e-6 , max_iter = 1000 , traceback = None ) : stepper = utils . NesterovStepper ( accelerated = accelerated ) if relax is not None : assert relax > 0 and relax < 1.5 if traceback is not None : traceback . update_history ( 0 , X = X , step_f = ...
Proximal Gradient Method
34,085
def admm ( X , prox_f , step_f , prox_g = None , step_g = None , L = None , e_rel = 1e-6 , e_abs = 0 , max_iter = 1000 , traceback = None ) : _L = utils . MatrixAdapter ( L ) if prox_g is not None and step_g is None : step_g = utils . get_step_g ( step_f , _L . spectral_norm ) Z , U = utils . initZU ( X , _L ) it = 0 i...
Alternating Direction Method of Multipliers
34,086
def bpgm ( X , proxs_f , steps_f_cb , update_order = None , accelerated = False , relax = None , max_iter = 1000 , e_rel = 1e-6 , traceback = None ) : N = len ( X ) if np . isscalar ( e_rel ) : e_rel = [ e_rel ] * N if relax is not None : assert relax > 0 and relax < 1.5 if update_order is None : update_order = range (...
Block Proximal Gradient Method .
34,087
def get_step_f ( step_f , lR2 , lS2 ) : mu , tau = 10 , 2 if lR2 > mu * lS2 : return step_f * tau elif lS2 > mu * lR2 : return step_f / tau return step_f
Update the stepsize of given the primal and dual errors .
34,088
def update_variables ( X , Z , U , prox_f , step_f , prox_g , step_g , L ) : if not hasattr ( prox_g , '__iter__' ) : if prox_g is not None : dX = step_f / step_g * L . T . dot ( L . dot ( X ) - Z + U ) X [ : ] = prox_f ( X - dX , step_f ) LX , R , S = do_the_mm ( X , step_f , Z , U , prox_g , step_g , L ) else : S = -...
Update the primal and dual variables
34,089
def get_variable_errors ( X , L , LX , Z , U , step_g , e_rel , e_abs = 0 ) : n = X . size p = Z . size e_pri2 = np . sqrt ( p ) * e_abs / L . spectral_norm + e_rel * np . max ( [ l2 ( LX ) , l2 ( Z ) ] ) if step_g is not None : e_dual2 = np . sqrt ( n ) * e_abs / L . spectral_norm + e_rel * l2 ( L . T . dot ( U ) / st...
Get the errors in a single multiplier method step
34,090
def check_constraint_convergence ( X , L , LX , Z , U , R , S , step_f , step_g , e_rel , e_abs ) : if isinstance ( L , list ) : M = len ( L ) convergence = True errors = [ ] for i in range ( M ) : c , e = check_constraint_convergence ( X , L [ i ] , LX [ i ] , Z [ i ] , U [ i ] , R [ i ] , S [ i ] , step_f , step_g [ ...
Calculate if all constraints have converged .
34,091
def check_convergence ( newX , oldX , e_rel ) : new_old = newX * oldX old2 = oldX ** 2 norms = [ np . sum ( new_old ) , np . sum ( old2 ) ] convergent = norms [ 0 ] >= ( 1 - e_rel ** 2 ) * norms [ 1 ] return convergent , norms
Check that the algorithm converges using Langville 2014 criteria
34,092
def _store_variable ( self , j , key , m , value ) : if hasattr ( value , 'copy' ) : v = value . copy ( ) else : v = value self . history [ j ] [ key ] [ m ] . append ( v )
Store a copy of the variable in the history
34,093
def update_history ( self , it , j = 0 , M = None , ** kwargs ) : if not np . any ( [ k in self . history [ j ] for k in kwargs ] ) : for k in kwargs : if M is None or M == 0 : self . history [ j ] [ k ] = [ [ ] ] else : self . history [ j ] [ k ] = [ [ ] for m in range ( M ) ] for k , v in kwargs . items ( ) : if M is...
Add the current state for all kwargs to the history
34,094
def generateComponent ( m ) : freq = 25 * np . random . random ( ) phase = 2 * np . pi * np . random . random ( ) x = np . arange ( m ) return np . cos ( x / freq - phase ) ** 2
Creates oscillating components to be mixed
34,095
def generateAmplitudes ( k ) : res = np . array ( [ np . random . random ( ) for i in range ( k ) ] ) return res / res . sum ( )
Makes mixing coefficients
34,096
def add_noise ( Y , sigma ) : return Y + np . random . normal ( 0 , sigma , Y . shape )
Adds noise to Y
34,097
def nmf ( Y , A , S , W = None , prox_A = operators . prox_plus , prox_S = operators . prox_plus , proxs_g = None , steps_g = None , Ls = None , slack = 0.9 , update_order = None , steps_g_update = 'steps_f' , max_iter = 1000 , e_rel = 1e-3 , e_abs = 0 , traceback = None ) : if W is not None : WA = normalizeMatrix ( W ...
Non - negative matrix factorization .
34,098
def prox_zero ( X , step ) : return np . zeros ( X . shape , dtype = X . dtype )
Proximal operator to project onto zero
34,099
def prox_unity ( X , step , axis = 0 ) : return X / np . sum ( X , axis = axis , keepdims = True )
Projection onto sum = 1 along an axis