idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
49,000
def create_organization ( self , auth , owner_name , org_name , full_name = None , description = None , website = None , location = None ) : data = { "username" : org_name , "full_name" : full_name , "description" : description , "website" : website , "location" : location } url = "/admin/users/{u}/orgs" . format ( u =...
Creates a new organization and returns the created organization .
49,001
def create_organization_team ( self , auth , org_name , name , description = None , permission = "read" ) : data = { "name" : name , "description" : description , "permission" : permission } url = "/admin/orgs/{o}/teams" . format ( o = org_name ) response = self . post ( url , auth = auth , data = data ) return GogsTea...
Creates a new team of the organization .
49,002
def add_team_membership ( self , auth , team_id , username ) : url = "/admin/teams/{t}/members/{u}" . format ( t = team_id , u = username ) self . put ( url , auth = auth )
Add user to team .
49,003
def remove_team_membership ( self , auth , team_id , username ) : url = "/admin/teams/{t}/members/{u}" . format ( t = team_id , u = username ) self . delete ( url , auth = auth )
Remove user from team .
49,004
def add_repo_to_team ( self , auth , team_id , repo_name ) : url = "/admin/teams/{t}/repos/{r}" . format ( t = team_id , r = repo_name ) self . put ( url , auth = auth )
Add or update repo from team .
49,005
def list_deploy_keys ( self , auth , username , repo_name ) : response = self . get ( "/repos/{u}/{r}/keys" . format ( u = username , r = repo_name ) , auth = auth ) return [ GogsRepo . DeployKey . from_json ( key_json ) for key_json in response . json ( ) ]
List deploy keys for the specified repo .
49,006
def get_deploy_key ( self , auth , username , repo_name , key_id ) : response = self . get ( "/repos/{u}/{r}/keys/{k}" . format ( u = username , r = repo_name , k = key_id ) , auth = auth ) return GogsRepo . DeployKey . from_json ( response . json ( ) )
Get a deploy key for the specified repo .
49,007
def add_deploy_key ( self , auth , username , repo_name , title , key_content ) : data = { "title" : title , "key" : key_content } response = self . post ( "/repos/{u}/{r}/keys" . format ( u = username , r = repo_name ) , auth = auth , data = data ) return GogsRepo . DeployKey . from_json ( response . json ( ) )
Add a deploy key to the specified repo .
49,008
def delete_deploy_key ( self , auth , username , repo_name , key_id ) : self . delete ( "/repos/{u}/{r}/keys/{k}" . format ( u = username , r = repo_name , k = key_id ) , auth = auth )
Remove deploy key for the specified repo .
49,009
def delete ( self , path , auth = None , ** kwargs ) : return self . _check_ok ( self . _delete ( path , auth = auth , ** kwargs ) )
Manually make a DELETE request .
49,010
def get ( self , path , auth = None , ** kwargs ) : return self . _check_ok ( self . _get ( path , auth = auth , ** kwargs ) )
Manually make a GET request .
49,011
def patch ( self , path , auth = None , ** kwargs ) : return self . _check_ok ( self . _patch ( path , auth = auth , ** kwargs ) )
Manually make a PATCH request .
49,012
def post ( self , path , auth = None , ** kwargs ) : return self . _check_ok ( self . _post ( path , auth = auth , ** kwargs ) )
Manually make a POST request .
49,013
def put ( self , path , auth = None , ** kwargs ) : return self . _check_ok ( self . _put ( path , auth = auth , ** kwargs ) )
Manually make a PUT request .
49,014
def _fail ( response ) : message = "Status code: {}-{}, url: {}" . format ( response . status_code , response . reason , response . url ) try : message += ", message:{}" . format ( response . json ( ) [ "message" ] ) except ( ValueError , KeyError ) : pass raise ApiFailure ( message , response . status_code )
Raise an ApiFailure pertaining to the given response
49,015
def Printer ( open_file = sys . stdout , closing = False ) : try : while True : logstr = ( yield ) open_file . write ( logstr ) open_file . write ( '\n' ) except GeneratorExit : if closing : try : open_file . close ( ) except : pass
Prints items with a timestamp .
49,016
def FilePrinter ( filename , mode = 'a' , closing = True ) : path = os . path . abspath ( os . path . expanduser ( filename ) ) f = open ( path , mode ) return Printer ( f , closing )
Opens the given file and returns a printer to it .
49,017
def Emailer ( recipients , sender = None ) : import smtplib hostname = socket . gethostname ( ) if not sender : sender = 'lggr@{0}' . format ( hostname ) smtp = smtplib . SMTP ( 'localhost' ) try : while True : logstr = ( yield ) try : smtp . sendmail ( sender , recipients , logstr ) except smtplib . SMTPException : pa...
Sends messages as emails to the given list of recipients .
49,018
def GMailer ( recipients , username , password , subject = 'Log message from lggr.py' ) : import smtplib srvr = smtplib . SMTP ( 'smtp.gmail.com' , 587 ) srvr . ehlo ( ) srvr . starttls ( ) srvr . ehlo ( ) srvr . login ( username , password ) if not ( isinstance ( recipients , list ) or isinstance ( recipients , tuple ...
Sends messages as emails to the given list of recipients from a GMail account .
49,019
def add ( self , levels , logger ) : if isinstance ( levels , ( list , tuple ) ) : for lvl in levels : self . config [ lvl ] . add ( logger ) else : self . config [ levels ] . add ( logger )
Given a list or tuple of logging levels add a logger instance to each .
49,020
def remove ( self , level , logger ) : self . config [ level ] . discard ( logger ) logger . close ( )
Given a level remove a given logger function if it is a member of that level closing the logger function either way .
49,021
def clear ( self , level ) : for item in self . config [ level ] : item . close ( ) self . config [ level ] . clear ( )
Remove all logger functions from a given level .
49,022
def _log ( self , level , fmt , args = None , extra = None , exc_info = None , inc_stackinfo = False , inc_multiproc = False ) : if not self . enabled : return log_record = self . _make_record ( level , fmt , args , extra , exc_info , inc_stackinfo , inc_multiproc ) logstr = log_record [ 'defaultfmt' ] . format ( ** lo...
Send a log message to all of the logging functions for a given level as well as adding the message to this logger instance s history .
49,023
def log ( self , * args , ** kwargs ) : if self . suppress_errors : try : self . _log ( * args , ** kwargs ) return True except : return False else : self . _log ( * args , ** kwargs ) return True
Do logging but handle error suppression .
49,024
def debug ( self , msg , * args , ** kwargs ) : kwargs . setdefault ( 'inc_stackinfo' , True ) self . log ( DEBUG , msg , args , ** kwargs )
Log a message with DEBUG level . Automatically includes stack info unless it is specifically not included .
49,025
def error ( self , msg , * args , ** kwargs ) : kwargs . setdefault ( 'inc_stackinfo' , True ) kwargs . setdefault ( 'inc_multiproc' , True ) self . log ( ERROR , msg , args , ** kwargs )
Log a message with ERROR level . Automatically includes stack and process info unless they are specifically not included .
49,026
def critical ( self , msg , * args , ** kwargs ) : kwargs . setdefault ( 'inc_stackinfo' , True ) kwargs . setdefault ( 'inc_multiproc' , True ) self . log ( CRITICAL , msg , args , ** kwargs )
Log a message with CRITICAL level . Automatically includes stack and process info unless they are specifically not included .
49,027
def multi ( self , lvl_list , msg , * args , ** kwargs ) : for level in lvl_list : self . log ( level , msg , args , ** kwargs )
Log a message at multiple levels
49,028
def all ( self , msg , * args , ** kwargs ) : self . multi ( ALL , msg , args , ** kwargs )
Log a message at every known log level
49,029
def _map_value ( self , value ) : if isinstance ( value , list ) : out = [ ] for c in value : out . append ( self . _map_value ( c ) ) return out elif isinstance ( value , dict ) and 'metadata' in value and 'labels' in value [ 'metadata' ] and 'self' in value : return neo4j . Node ( ustr ( value [ 'metadata' ] [ 'id' ]...
Maps a raw deserialized row to proper types
49,030
def get_deprecated_gene_ids ( filename ) : deprecated = { } with open ( filename ) as handle : for line in handle : line = line . strip ( ) . split ( ) old = line [ 0 ] new = line [ 1 ] deprecated [ old ] = new return deprecated
gets a dict of the gene IDs used during in DDD datasets that have been deprecated in favour of other gene IDs
49,031
def required_from_env ( key ) : val = os . environ . get ( key ) if not val : raise ValueError ( "Required argument '{}' not supplied and not found in environment variables" . format ( key ) ) return val
Retrieve a required variable from the current environment variables .
49,032
def get ( self , url ) : logger . debug ( 'Making GET request to %s' , url ) return self . oauth_session . get ( url )
Make a HTTP GET request to the Reader API .
49,033
def post ( self , url , post_params = None ) : params = urlencode ( post_params ) logger . debug ( 'Making POST request to %s with body %s' , url , params ) return self . oauth_session . post ( url , data = params )
Make a HTTP POST request to the Reader API .
49,034
def delete ( self , url ) : logger . debug ( 'Making DELETE request to %s' , url ) return self . oauth_session . delete ( url )
Make a HTTP DELETE request to the Readability API .
49,035
def get_article ( self , article_id ) : url = self . _generate_url ( 'articles/{0}' . format ( article_id ) ) return self . get ( url )
Get a single article represented by article_id .
49,036
def get_bookmarks ( self , ** filters ) : filter_dict = filter_args_to_dict ( filters , ACCEPTED_BOOKMARK_FILTERS ) url = self . _generate_url ( 'bookmarks' , query_params = filter_dict ) return self . get ( url )
Get Bookmarks for the current user .
49,037
def get_bookmark ( self , bookmark_id ) : url = self . _generate_url ( 'bookmarks/{0}' . format ( bookmark_id ) ) return self . get ( url )
Get a single bookmark represented by bookmark_id .
49,038
def add_bookmark ( self , url , favorite = False , archive = False , allow_duplicates = True ) : rdb_url = self . _generate_url ( 'bookmarks' ) params = { "url" : url , "favorite" : int ( favorite ) , "archive" : int ( archive ) , "allow_duplicates" : int ( allow_duplicates ) } return self . post ( rdb_url , params )
Adds given bookmark to the authenticated user .
49,039
def update_bookmark ( self , bookmark_id , favorite = None , archive = None , read_percent = None ) : rdb_url = self . _generate_url ( 'bookmarks/{0}' . format ( bookmark_id ) ) params = { } if favorite is not None : params [ 'favorite' ] = 1 if favorite == True else 0 if archive is not None : params [ 'archive' ] = 1 ...
Updates given bookmark . The requested bookmark must belong to the current user .
49,040
def delete_bookmark ( self , bookmark_id ) : url = self . _generate_url ( 'bookmarks/{0}' . format ( bookmark_id ) ) return self . delete ( url )
Delete a single bookmark represented by bookmark_id .
49,041
def get_bookmark_tags ( self , bookmark_id ) : url = self . _generate_url ( 'bookmarks/{0}/tags' . format ( bookmark_id ) ) return self . get ( url )
Retrieve tags that have been applied to a bookmark .
49,042
def add_tags_to_bookmark ( self , bookmark_id , tags ) : url = self . _generate_url ( 'bookmarks/{0}/tags' . format ( bookmark_id ) ) params = dict ( tags = tags ) return self . post ( url , params )
Add tags to to a bookmark .
49,043
def delete_tag_from_bookmark ( self , bookmark_id , tag_id ) : url = self . _generate_url ( 'bookmarks/{0}/tags/{1}' . format ( bookmark_id , tag_id ) ) return self . delete ( url )
Remove a single tag from a bookmark .
49,044
def get_tag ( self , tag_id ) : url = self . _generate_url ( 'tags/{0}' . format ( tag_id ) ) return self . get ( url )
Get a single tag represented by tag_id .
49,045
def post ( self , url , post_params = None ) : post_params [ 'token' ] = self . token params = urlencode ( post_params ) logger . debug ( 'Making POST request to %s with body %s' , url , params ) return requests . post ( url , data = params )
Make an HTTP POST request to the Parser API .
49,046
def _generate_url ( self , resource , query_params = None ) : resource = '{resource}?token={token}' . format ( resource = resource , token = self . token ) if query_params : resource += "&{}" . format ( urlencode ( query_params ) ) return self . base_url_template . format ( resource )
Build the url to resource .
49,047
def get_article ( self , url = None , article_id = None , max_pages = 25 ) : query_params = { } if url is not None : query_params [ 'url' ] = url if article_id is not None : query_params [ 'article_id' ] = article_id query_params [ 'max_pages' ] = max_pages url = self . _generate_url ( 'parser' , query_params = query_p...
Send a GET request to the parser endpoint of the parser API to get back the representation of an article .
49,048
def post_article_content ( self , content , url , max_pages = 25 ) : params = { 'doc' : content , 'max_pages' : max_pages } url = self . _generate_url ( 'parser' , { "url" : url } ) return self . post ( url , post_params = params )
POST content to be parsed to the Parser API .
49,049
def get_article_status ( self , url = None , article_id = None ) : query_params = { } if url is not None : query_params [ 'url' ] = url if article_id is not None : query_params [ 'article_id' ] = article_id url = self . _generate_url ( 'parser' , query_params = query_params ) return self . head ( url )
Send a HEAD request to the parser endpoint to the parser API to get the articles status .
49,050
def get_confidence ( self , url = None , article_id = None ) : query_params = { } if url is not None : query_params [ 'url' ] = url if article_id is not None : query_params [ 'article_id' ] = article_id url = self . _generate_url ( 'confidence' , query_params = query_params ) return self . get ( url )
Send a GET request to the confidence endpoint of the Parser API .
49,051
def save ( f , arr , vocab ) : itr = iter ( vocab ) word , idx = next ( itr ) _write_line ( f , arr [ idx ] , word ) for word , idx in itr : f . write ( b'\n' ) _write_line ( f , arr [ idx ] , word )
Save word embedding file .
49,052
def convert ( outputfile , inputfile , to_format , from_format ) : emb = word_embedding . WordEmbedding . load ( inputfile , format = _input_choices [ from_format ] [ 1 ] , binary = _input_choices [ from_format ] [ 2 ] ) emb . save ( outputfile , format = _output_choices [ to_format ] [ 1 ] , binary = _output_choices [...
Convert pretrained word embedding file in one format to another .
49,053
def check_format ( inputfile ) : t = word_embedding . classify_format ( inputfile ) if t == word_embedding . _glove : _echo_format_result ( 'glove' ) elif t == word_embedding . _word2vec_bin : _echo_format_result ( 'word2vec-binary' ) elif t == word_embedding . _word2vec_text : _echo_format_result ( 'word2vec-text' ) e...
Check format of inputfile .
49,054
def list ( ) : choice_len = max ( map ( len , _input_choices . keys ( ) ) ) tmpl = " {:<%d}: {}\n" % choice_len text = '' . join ( map ( lambda k_v : tmpl . format ( k_v [ 0 ] , k_v [ 1 ] [ 0 ] ) , six . iteritems ( _input_choices ) ) ) click . echo ( text )
List available format .
49,055
def main ( ) : from twitter . cmdline import Action , OPTIONS twitter = Twitter . from_oauth_file ( ) Action ( ) ( twitter , OPTIONS )
Do the default action of twitter command .
49,056
def from_oauth_file ( cls , filepath = None ) : if filepath is None : home = os . environ . get ( 'HOME' , os . environ . get ( 'USERPROFILE' , '' ) ) filepath = os . path . join ( home , '.twitter_oauth' ) oauth_token , oauth_token_secret = read_token_file ( filepath ) twitter = cls ( auth = OAuth ( oauth_token , oaut...
Get an object bound to the Twitter API using your own credentials .
49,057
def get_version ( filepath = 'src/birding/version.py' ) : with open ( get_abspath ( filepath ) ) as version_file : return re . search ( r , version_file . read ( ) ) . group ( 'version' )
Get version without import which avoids dependency issues .
49,058
def search ( self , q , ** kw ) : url = '{base_url}/search/{stream}' . format ( ** vars ( self ) ) params = { 'q' : q , } params . update ( self . params ) params . update ( kw ) response = self . session . get ( url , params = params ) response . raise_for_status ( ) return response . json ( )
Search Gnip for given query returning deserialized response .
49,059
def dump ( result ) : if isinstance ( result , dict ) : statuses = result [ 'results' ] else : statuses = result status_str_list = [ ] for status in statuses : status_str_list . append ( textwrap . dedent ( u ) . strip ( ) . format ( screen_name = status [ 'actor' ] [ 'preferredUsername' ] , text = status [ 'body' ] ) ...
Dump result into a string useful for debugging .
49,060
def shelf_from_config ( config , ** default_init ) : shelf_cls = import_name ( config [ 'shelf_class' ] , default_ns = 'birding.shelf' ) init = { } init . update ( default_init ) init . update ( config [ 'shelf_init' ] ) shelf = shelf_cls ( ** init ) if hasattr ( shelf , 'set_expiration' ) and 'shelf_expiration' in con...
Get a Shelf instance dynamically based on config .
49,061
def unpack ( self , key , value ) : value , freshness = value if not self . is_fresh ( freshness ) : raise KeyError ( '{} (stale)' . format ( key ) ) return value
Unpack and return value only if it is fresh .
49,062
def is_fresh ( self , freshness ) : if self . expire_after is None : return True return self . freshness ( ) - freshness <= self . expire_after
Return False if given freshness value has expired else True .
49,063
def is_first_instance_aws ( ) : try : instance_details = requests . get ( 'http://169.254.169.254/latest/dynamic/instance-identity/document' , timeout = 5 ) . json ( ) instance_id = instance_details [ 'instanceId' ] instance_region = instance_details [ 'region' ] except ( requests . RequestException , ValueError , KeyE...
Returns True if the current instance is the first instance in the ASG group sorted by instance_id .
49,064
def is_first_instance_k8s ( current_pod_name = None ) : current_pod_name = current_pod_name or os . environ . get ( 'POD_NAME' ) if not current_pod_name : raise StackInterrogationException ( 'Pod name not known' ) namespace = 'money-to-prisoners-%s' % settings . ENVIRONMENT try : load_incluster_config ( ) except Config...
Returns True if the current pod is the first replica in Kubernetes cluster .
49,065
def splitarg ( args ) : if not args : return args split = list ( ) for arg in args : if ',' in arg : split . extend ( [ x for x in arg . split ( ',' ) if x ] ) elif arg : split . append ( arg ) return split
This function will split arguments separated by spaces or commas to be backwards compatible with the original ArcGet command line tool
49,066
def logout ( request , template_name = None , next_page = None , redirect_field_name = REDIRECT_FIELD_NAME , current_app = None , extra_context = None ) : auth_logout ( request ) if next_page is not None : next_page = resolve_url ( next_page ) if ( redirect_field_name in request . POST or redirect_field_name in request...
Logs out the user .
49,067
def get_config ( filepath = None , default_loader = None , on_missing = None ) : cache_key = ( filepath , default_loader , on_missing ) if CACHE . get ( cache_key ) is not None : return CACHE . get ( cache_key ) logger = logging . getLogger ( 'birding' ) if filepath is None : filepath = BIRDING_CONF if default_loader i...
Get a dict for the current birding configuration .
49,068
def get_defaults_file ( * a , ** kw ) : fd = StringIO ( ) fd . write ( get_defaults_str ( * a , ** kw ) ) fd . seek ( 0 ) return fd
Get a file object with YAML data of configuration defaults .
49,069
def get_defaults_str ( raw = None , after = 'Defaults::' ) : if raw is None : raw = __doc__ return unicode ( textwrap . dedent ( raw . split ( after ) [ - 1 ] ) . strip ( ) )
Get the string YAML representation of configuration defaults .
49,070
def overlay ( upper , lower ) : result = { } for key in upper : if is_mapping ( upper [ key ] ) : lower_value = lower . get ( key , { } ) if not is_mapping ( lower_value ) : msg = 'Attempting to overlay a mapping on a non-mapping: {}' raise ValueError ( msg . format ( key ) ) result [ key ] = overlay ( upper [ key ] , ...
Return the overlay of upper dict onto lower dict .
49,071
def import_name ( name , default_ns = None ) : if '.' not in name : if default_ns is None : return importlib . import_module ( name ) else : name = default_ns + '.' + name module_name , object_name = name . rsplit ( '.' , 1 ) module = importlib . import_module ( module_name ) return getattr ( module , object_name )
Import an object based on the dotted string .
49,072
def follow_topic_from_config ( ) : config = get_config ( ) [ 'ResultTopicBolt' ] kafka_class = import_name ( config [ 'kafka_class' ] ) return follow_topic ( kafka_class , config [ 'topic' ] , ** config [ 'kafka_init' ] )
Read kafka config then dispatch to follow_topic .
49,073
def follow_topic ( kafka_class , name , retry_interval = 1 , ** kafka_init ) : while True : try : client = kafka_class ( ** kafka_init ) topic = client . topics [ name ] consumer = topic . get_simple_consumer ( reset_offset_on_start = True ) except Exception as e : if not should_try_kafka_again ( e ) : raise with flush...
Dump each message from kafka topic to stdio .
49,074
def follow_fd ( fd ) : dump = Dump ( ) for line in fd : if not line . strip ( ) : continue with flushing ( sys . stdout , sys . stderr ) : status = load ( line ) if status : dump ( status )
Dump each line of input to stdio .
49,075
def should_try_kafka_again ( error ) : msg = 'Unable to retrieve' return isinstance ( error , KafkaException ) and str ( error ) . startswith ( msg )
Determine if the error means to retry or fail True to retry .
49,076
def check_valid ( line0 , line1 ) : data = line0 . strip ( ) . split ( b' ' ) if len ( data ) <= 2 : return False try : map ( float , data [ 2 : ] ) except : return False return True
Check if a file is valid Glove format .
49,077
def load_with_vocab ( fin , vocab , dtype = np . float32 ) : arr = None for line in fin : try : token , v = _parse_line ( line , dtype ) except ( ValueError , IndexError ) : raise ParseError ( b'Parsing error in line: ' + line ) if token in vocab : if arr is None : arr = np . empty ( ( len ( vocab ) , len ( v ) ) , dty...
Load word embedding file with predefined vocabulary
49,078
def load ( fin , dtype = np . float32 , max_vocab = None ) : vocab = { } arr = None i = 0 for line in fin : if max_vocab is not None and i >= max_vocab : break try : token , v = _parse_line ( line , dtype ) except ( ValueError , IndexError ) : raise ParseError ( b'Parsing error in line: ' + line ) if token in vocab : p...
Load word embedding file .
49,079
def set_version ( context : Context , version = None , bump = False ) : if bump and version : raise TaskError ( 'You cannot bump and set a specific version' ) if bump : from mtp_common import VERSION version = list ( VERSION ) version [ - 1 ] += 1 else : try : version = list ( map ( int , version . split ( '.' ) ) ) as...
Updates the version of MTP - common
49,080
def docs ( context : Context ) : try : from sphinx . application import Sphinx except ImportError : context . pip_command ( 'install' , 'Sphinx' ) from sphinx . application import Sphinx context . shell ( 'cp' , 'README.rst' , 'docs/README.rst' ) app = Sphinx ( 'docs' , 'docs' , 'docs/build' , 'docs/build/.doctrees' , ...
Generates static documentation
49,081
def authenticate ( self , username = None , password = None ) : data = api_client . authenticate ( username , password ) if not data : return return User ( data . get ( 'pk' ) , data . get ( 'token' ) , data . get ( 'user_data' ) )
Returns a valid MojUser if the authentication is successful or None if the credentials were wrong .
49,082
def get_client_token ( ) : if getattr ( settings , 'NOMIS_API_CLIENT_TOKEN' , '' ) : return settings . NOMIS_API_CLIENT_TOKEN global client_token if not client_token or client_token [ 'expires' ] and client_token [ 'expires' ] - now ( ) < datetime . timedelta ( days = 1 ) : session = None try : session = api_client . g...
Requests and stores the NOMIS API client token from mtp - api
49,083
def include ( self , * fields , ** kwargs ) : clone = self . _clone ( ) if self . query . filter_is_sticky : clone . query . filter_is_sticky = True clone . _include_limit = kwargs . pop ( 'limit_includes' , None ) assert not kwargs , '"limit_includes" is the only accepted kwargs. Eat your heart out 2.7' if fields == (...
Return a new QuerySet instance that will include related objects .
49,084
def revoke_token ( access_token ) : response = requests . post ( get_revoke_token_url ( ) , data = { 'token' : access_token , 'client_id' : settings . API_CLIENT_ID , 'client_secret' : settings . API_CLIENT_SECRET , } , timeout = 15 ) return response . status_code == 200
Instructs the API to delete this access token and associated refresh token
49,085
def lru_cache ( fn ) : @ wraps ( fn ) def memoized_fn ( * args ) : pargs = pickle . dumps ( args ) if pargs not in memoized_fn . cache : memoized_fn . cache [ pargs ] = fn ( * args ) return memoized_fn . cache [ pargs ] for attr , value in iter ( fn . __dict__ . items ( ) ) : setattr ( memoized_fn , attr , value ) memo...
Memoization wrapper that can handle function attributes mutable arguments and can be applied either as a decorator or at runtime .
49,086
def auth ( alias = None , url = None , cfg = "~/.xnat_auth" ) : if not alias and not url : raise ValueError ( 'you must provide an alias or url argument' ) if alias and url : raise ValueError ( 'cannot provide both alias and url arguments' ) cfg = os . path . expanduser ( cfg ) if not os . path . exists ( cfg ) : raise...
Read connection details from an xnat_auth XML file
49,087
def accession ( auth , label , project = None ) : return list ( experiments ( auth , label , project ) ) [ 0 ] . id
Get the Accession ID for any Experiment label .
49,088
def extract ( zf , content , out_dir = '.' ) : previous_header_offset = 0 compensation = Namespace ( value = 2 ** 32 , factor = 0 ) for i , member in enumerate ( zf . infolist ( ) ) : if i == 0 : concat = member . header_offset member . header_offset -= concat if previous_header_offset > member . header_offset : compen...
Extracting a Java 1 . 6 XNAT ZIP archive in Python .
49,089
def __quick_validate ( r , check = ( 'ResultSet' , 'Result' , 'totalRecords' ) ) : if 'ResultSet' in check and 'ResultSet' not in r : raise ResultSetError ( 'no ResultSet in server response' ) if 'Result' in check and 'Result' not in r [ 'ResultSet' ] : raise ResultSetError ( 'no Result in server response' ) if 'totalR...
Quick validation of JSON result set returned by XNAT .
49,090
def scansearch ( auth , label , filt , project = None , aid = None ) : if not aid : aid = accession ( auth , label , project ) url = "%s/data/experiments/%s/scans?format=csv" % ( auth . url . rstrip ( '/' ) , aid ) logger . debug ( "issuing http request %s" , url ) r = requests . get ( url , auth = ( auth . username , ...
Search for scans by supplying a set of SQL - based conditionals .
49,091
def scans ( auth , label = None , scan_ids = None , project = None , experiment = None ) : if experiment and ( label or project ) : raise ValueError ( 'cannot supply experiment with label or project' ) if experiment : label , project = experiment . label , experiment . project aid = accession ( auth , label , project )...
Get scan information for a MR Session as a sequence of dictionaries .
49,092
def extendedboldqc ( auth , label , scan_ids = None , project = None , aid = None ) : if not aid : aid = accession ( auth , label , project ) path = '/data/experiments' params = { 'xsiType' : 'neuroinfo:extendedboldqc' , 'columns' : ',' . join ( extendedboldqc . columns . keys ( ) ) } if project : params [ 'project' ] ...
Get ExtendedBOLDQC data as a sequence of dictionaries .
49,093
def _autobox ( content , format ) : if format == Format . JSON : return json . loads ( content ) elif format == Format . XML : return etree . fromstring ( content ) elif format == Format . CSV : try : return csv . reader ( io . BytesIO ( content ) ) except TypeError : def unicode_csv_reader ( unicode_csv_data , dialect...
Autobox response content .
49,094
def get_user ( request ) : if not hasattr ( request , '_cached_user' ) : request . _cached_user = auth_get_user ( request ) return request . _cached_user
Returns a cached copy of the user if it exists or calls auth_get_user otherwise .
49,095
def ensure_compatible_admin ( view ) : def wrapper ( request , * args , ** kwargs ) : user_roles = request . user . user_data . get ( 'roles' , [ ] ) if len ( user_roles ) != 1 : context = { 'message' : 'I need to be able to manage user accounts. ' 'My username is %s' % request . user . username } return render ( reque...
Ensures that the user is in exactly one role . Other checks could be added such as requiring one prison if in prison - clerk role .
49,096
def fault_barrier ( fn ) : @ functools . wraps ( fn ) def process ( self , tup ) : try : return fn ( self , tup ) except Exception as e : if isinstance ( e , KeyboardInterrupt ) : return print ( str ( e ) , file = sys . stderr ) self . fail ( tup ) return process
Method decorator to catch and log errors then send fail message .
49,097
def search_manager_from_config ( config , ** default_init ) : manager_cls = import_name ( config [ 'class' ] , default_ns = 'birding.search' ) init = { } init . update ( default_init ) init . update ( config [ 'init' ] ) manager = manager_cls ( ** init ) return manager
Get a SearchManager instance dynamically based on config .
49,098
def bids_from_config ( sess , scans_metadata , config , out_base ) : _item = next ( iter ( scans_metadata ) ) session , subject = _item [ 'session_label' ] , _item [ 'subject_label' ] sourcedata_base = os . path . join ( out_base , 'sourcedata' , 'sub-{0}' . format ( legal . sub ( '' , subject ) ) , 'ses-{0}' . format ...
Create a BIDS output directory from configuration file
49,099
def proc_anat ( config , args ) : refs = dict ( ) for scan in iterconfig ( config , 'anat' ) : ref = scan . get ( 'id' , None ) templ = 'sub-${sub}_ses-${ses}' if 'acquisition' in scan : templ += '_acq-${acquisition}' if 'run' in scan : templ += '_run-${run}' templ += '_${modality}' templ = string . Template ( templ ) ...
Download anatomical data and convert to BIDS