idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
249,900
def annotate_proto ( self , text , annotators = None ) : properties = { 'annotators' : ',' . join ( annotators or self . default_annotators ) , 'outputFormat' : 'serialized' , 'serializer' : 'edu.stanford.nlp.pipeline.ProtobufAnnotationSerializer' } r = self . _request ( text , properties ) buffer = r . content # bytes...
Return a Document protocol buffer from the CoreNLP server containing annotations of the text .
145
17
249,901
def annotate ( self , text , annotators = None ) : doc_pb = self . annotate_proto ( text , annotators ) return AnnotatedDocument . from_pb ( doc_pb )
Return an AnnotatedDocument from the CoreNLP server .
45
13
249,902
def from_pb ( cls , pb ) : obj = cls . _from_pb ( pb ) obj . _pb = pb return obj
Instantiate the object from a protocol buffer .
34
9
249,903
def character_span ( self ) : begin , end = self . token_span return ( self . sentence [ begin ] . character_span [ 0 ] , self . sentence [ end - 1 ] . character_span [ - 1 ] )
Returns the character span of the token
50
7
249,904
def log_proto ( self , proto , step_num ) : self . summ_writer . add_summary ( proto , step_num ) return proto
Log a Summary protobuf to the event file .
33
11
249,905
def log ( self , key , val , step_num ) : try : ph , summ = self . summaries [ key ] except KeyError : # if we haven't defined a variable for this key, define one with self . g . as_default ( ) : ph = tf . placeholder ( tf . float32 , ( ) , name = key ) # scalar summ = tf . scalar_summary ( key , ph ) self . summaries ...
Directly log a scalar value to the event file .
142
12
249,906
def read_events ( stream ) : header_size = struct . calcsize ( '<QI' ) len_size = struct . calcsize ( '<Q' ) footer_size = struct . calcsize ( '<I' ) while True : header = stream . read ( header_size ) if len ( header ) == 0 : break elif len ( header ) < header_size : raise SummaryReaderException ( 'unexpected EOF (exp...
Read and return as a generator a sequence of Event protos from file - like object stream .
414
19
249,907
def write_events ( stream , events ) : for event in events : data = event . SerializeToString ( ) len_field = struct . pack ( '<Q' , len ( data ) ) len_crc = struct . pack ( '<I' , masked_crc ( len_field ) ) data_crc = struct . pack ( '<I' , masked_crc ( data ) ) stream . write ( len_field ) stream . write ( len_crc ) ...
Write a sequence of Event protos to file - like object stream .
121
14
249,908
def log_image ( self , step , tag , val ) : # TODO: support floating-point tensors, 4-D tensors, grayscale if len ( val . shape ) != 3 : raise ValueError ( '`log_image` value should be a 3-D tensor, instead got shape %s' % ( val . shape , ) ) if val . shape [ 2 ] != 3 : raise ValueError ( 'Last dimension of `log_image`...
Write an image event .
301
5
249,909
def log_scalar ( self , step , tag , val ) : summary = Summary ( value = [ Summary . Value ( tag = tag , simple_value = float ( np . float32 ( val ) ) ) ] ) self . _add_event ( step , summary )
Write a scalar event .
59
6
249,910
def log_histogram ( self , step , tag , val ) : hist = Histogram ( ) hist . add ( val ) summary = Summary ( value = [ Summary . Value ( tag = tag , histo = hist . encode_to_proto ( ) ) ] ) self . _add_event ( step , summary )
Write a histogram event .
69
6
249,911
def options ( allow_partial = False , read = False ) : global _options if allow_partial : opts , extras = _options_parser . parse_known_args ( ) if opts . run_dir : mkdirp ( opts . run_dir ) return opts if _options is None : # Add back in the help option (only show help and quit once arguments are finalized) _options_p...
Get the object containing the values of the parsed command line options .
312
13
249,912
def inner_products ( self , vec ) : products = self . array . dot ( vec ) return self . _word_to_score ( np . arange ( len ( products ) ) , products )
Get the inner product of a vector with every embedding .
43
12
249,913
def _word_to_score ( self , ids , scores ) : # should be 1-D vectors assert len ( ids . shape ) == 1 assert ids . shape == scores . shape w2s = { } for i in range ( len ( ids ) ) : w2s [ self . vocab . index2word ( ids [ i ] ) ] = scores [ i ] return w2s
Return a map from each word to its score .
89
10
249,914
def _init_lsh_forest ( self ) : import sklearn . neighbors lshf = sklearn . neighbors . LSHForest ( ) lshf . fit ( self . array ) return lshf
Construct an LSH forest for nearest neighbor search .
45
10
249,915
def to_dict ( self ) : d = { } for word , idx in self . vocab . iteritems ( ) : d [ word ] = self . array [ idx ] . tolist ( ) return d
Convert to dictionary .
47
5
249,916
def to_files ( self , array_file , vocab_file ) : logging . info ( 'Writing array...' ) np . save ( array_file , self . array ) logging . info ( 'Writing vocab...' ) self . vocab . to_file ( vocab_file )
Write the embedding matrix and the vocab to files .
64
12
249,917
def from_files ( cls , array_file , vocab_file ) : logging . info ( 'Loading array...' ) array = np . load ( array_file ) logging . info ( 'Loading vocab...' ) vocab = Vocab . from_file ( vocab_file ) return cls ( array , vocab )
Load the embedding matrix and the vocab from files .
73
12
249,918
def get_uuids ( ) : result = shell ( 'cl ls -w {} -u' . format ( worksheet ) ) uuids = result . split ( '\n' ) uuids = uuids [ 1 : - 1 ] # trim non uuids return uuids
List all bundle UUIDs in the worksheet .
64
11
249,919
def open_file ( uuid , path ) : # create temporary file just so we can get an unused file path f = tempfile . NamedTemporaryFile ( ) f . close ( ) # close and delete right away fname = f . name # download file to temporary path cmd = 'cl down -o {} -w {} {}/{}' . format ( fname , worksheet , uuid , path ) try : shell (...
Get the raw file content within a particular bundle at a particular path .
166
14
249,920
def load_img ( self , img_path ) : with open_file ( self . uuid , img_path ) as f : return mpimg . imread ( f )
Return an image object that can be immediately plotted with matplotlib
38
13
249,921
def output_results ( results , split_id = 'results' , output_stream = None ) : if output_stream is None : output_stream = sys . stdout output_stream . write ( '----- %s -----\n' % split_id ) for name in sorted ( results . keys ( ) ) : output_stream . write ( '%s: %s\n' % ( name , repr ( results [ name ] ) ) ) output_st...
Log results readably to output_stream with a header containing split_id .
103
16
249,922
def labels_to_onehots ( labels , num_classes ) : batch_size = labels . get_shape ( ) . as_list ( ) [ 0 ] with tf . name_scope ( "one_hot" ) : labels = tf . expand_dims ( labels , 1 ) indices = tf . expand_dims ( tf . range ( 0 , batch_size , 1 ) , 1 ) sparse_ptrs = tf . concat ( 1 , [ indices , labels ] , name = "ptrs"...
Convert a vector of integer class labels to a matrix of one - hot target vectors .
149
18
249,923
def start_task ( self , name , size ) : if len ( self . task_stack ) == 0 : self . start_time = datetime . datetime . now ( ) self . task_stack . append ( Task ( name , size , 0 ) )
Add a task to the stack . If for example name is Iteration and size is 10 progress on that task will be shown as
56
26
249,924
def progress ( self , p ) : self . task_stack [ - 1 ] = self . task_stack [ - 1 ] . _replace ( progress = p ) self . progress_report ( )
Update the current progress on the task at the top of the stack .
42
14
249,925
def end_task ( self ) : self . progress ( self . task_stack [ - 1 ] . size ) self . task_stack . pop ( )
Remove the current task from the stack .
33
8
249,926
def progress_report ( self , force = False ) : now = datetime . datetime . now ( ) if ( len ( self . task_stack ) > 1 or self . task_stack [ 0 ] > 0 ) and now - self . last_report < self . resolution and not force : return stack_printout = ', ' . join ( '%s %s of %s' % ( t . name , t . progress , t . size ) for t in se...
Print the current progress .
277
5
249,927
def write_conll ( self , fname ) : if 'label' not in self . fields : raise InvalidFieldsException ( "dataset is not in CONLL format: missing label field" ) def instance_to_conll ( inst ) : tab = [ v for k , v in inst . items ( ) if k != 'label' ] return '{}\n{}' . format ( inst [ 'label' ] , '\n' . join ( [ '\t' . join...
Serializes the dataset in CONLL format to fname
241
11
249,928
def convert ( self , converters , in_place = False ) : dataset = self if in_place else self . __class__ ( OrderedDict ( [ ( name , data [ : ] ) for name , data in self . fields . items ( ) ] ) ) for name , convert in converters . items ( ) : if name not in self . fields . keys ( ) : raise InvalidFieldsException ( 'Conv...
Applies transformations to the dataset .
138
7
249,929
def shuffle ( self ) : order = range ( len ( self ) ) random . shuffle ( order ) for name , data in self . fields . items ( ) : reindexed = [ ] for _ , i in enumerate ( order ) : reindexed . append ( data [ i ] ) self . fields [ name ] = reindexed return self
Re - indexes the dataset in random order
74
8
249,930
def pad ( cls , sequences , padding , pad_len = None ) : max_len = max ( [ len ( s ) for s in sequences ] ) pad_len = pad_len or max_len assert pad_len >= max_len , 'pad_len {} must be greater or equal to the longest sequence {}' . format ( pad_len , max_len ) for i , s in enumerate ( sequences ) : sequences [ i ] = [ ...
Pads a list of sequences such that they form a matrix .
120
13
249,931
def bleu ( eval_data , predictions , scores = 'ignored' , learner = 'ignored' ) : ref_groups = ( [ inst . output . split ( ) ] if isinstance ( inst . output , basestring ) else [ _maybe_tokenize ( r ) for r in inst . output ] for inst in eval_data ) return [ corpus_bleu ( ref_groups , [ p . split ( ) for p in predictio...
Return corpus - level BLEU score of predictions using the output field of the instances in eval_data as references . This is returned as a length - 1 list of floats .
100
36
249,932
def squared_error ( eval_data , predictions , scores = 'ignored' , learner = 'ignored' ) : return [ np . sum ( ( np . array ( pred ) - np . array ( inst . output ) ) ** 2 ) for inst , pred in zip ( eval_data , predictions ) ]
Return the squared error of each prediction in predictions with respect to the correct output in eval_data .
67
20
249,933
def encrypt_variable ( variable , build_repo , * , tld = '.org' , public_key = None , travis_token = None , * * login_kwargs ) : if not isinstance ( variable , bytes ) : raise TypeError ( "variable should be bytes" ) if not b"=" in variable : raise ValueError ( "variable should be of the form 'VARIABLE=value'" ) if not...
Encrypt an environment variable for build_repo for Travis
523
12
249,934
def encrypt_to_file ( contents , filename ) : if not filename . endswith ( '.enc' ) : raise ValueError ( "%s does not end with .enc" % filename ) key = Fernet . generate_key ( ) fer = Fernet ( key ) encrypted_file = fer . encrypt ( contents ) with open ( filename , 'wb' ) as f : f . write ( encrypted_file ) return key
Encrypts contents and writes it to filename .
90
10
249,935
def GitHub_login ( * , username = None , password = None , OTP = None , headers = None ) : if not username : username = input ( "What is your GitHub username? " ) if not password : password = getpass ( "Enter the GitHub password for {username}: " . format ( username = username ) ) headers = headers or { } if OTP : head...
Login to GitHub .
430
4
249,936
def GitHub_post ( data , url , * , auth , headers ) : r = requests . post ( url , auth = auth , headers = headers , data = json . dumps ( data ) ) GitHub_raise_for_status ( r ) return r . json ( )
POST the data data to GitHub .
57
7
249,937
def get_travis_token ( * , GitHub_token = None , * * login_kwargs ) : _headers = { 'Content-Type' : 'application/json' , 'User-Agent' : 'MyClient/1.0.0' , } headersv2 = { * * _headers , * * Travis_APIv2 } token_id = None try : if not GitHub_token : print ( green ( "I need to generate a temporary token with GitHub to au...
Generate a temporary token for authenticating with Travis
353
10
249,938
def generate_GitHub_token ( * , note = "Doctr token for pushing to gh-pages from Travis" , scopes = None , * * login_kwargs ) : if scopes is None : scopes = [ 'public_repo' ] AUTH_URL = "https://api.github.com/authorizations" data = { "scopes" : scopes , "note" : note , "note_url" : "https://github.com/drdoctr/doctr" ,...
Generate a GitHub token for pushing from Travis
148
9
249,939
def delete_GitHub_token ( token_id , * , auth , headers ) : r = requests . delete ( 'https://api.github.com/authorizations/{id}' . format ( id = token_id ) , auth = auth , headers = headers ) GitHub_raise_for_status ( r )
Delete a temporary GitHub token
70
5
249,940
def upload_GitHub_deploy_key ( deploy_repo , ssh_key , * , read_only = False , title = "Doctr deploy key for pushing to gh-pages from Travis" , * * login_kwargs ) : DEPLOY_KEY_URL = "https://api.github.com/repos/{deploy_repo}/keys" . format ( deploy_repo = deploy_repo ) data = { "title" : title , "key" : ssh_key , "rea...
Uploads a GitHub deploy key to deploy_repo .
147
12
249,941
def generate_ssh_key ( ) : key = rsa . generate_private_key ( backend = default_backend ( ) , public_exponent = 65537 , key_size = 4096 ) private_key = key . private_bytes ( serialization . Encoding . PEM , serialization . PrivateFormat . PKCS8 , serialization . NoEncryption ( ) ) public_key = key . public_key ( ) . pu...
Generates an SSH deploy public and private key .
125
10
249,942
def guess_github_repo ( ) : p = subprocess . run ( [ 'git' , 'ls-remote' , '--get-url' , 'origin' ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE , check = False ) if p . stderr or p . returncode : return False url = p . stdout . decode ( 'utf-8' ) . strip ( ) m = GIT_URL . fullmatch ( url ) if not m : retu...
Guesses the github repo for the current directory
123
9
249,943
def get_config ( ) : p = Path ( '.travis.yml' ) if not p . exists ( ) : return { } with p . open ( ) as f : travis_config = yaml . safe_load ( f . read ( ) ) config = travis_config . get ( 'doctr' , { } ) if not isinstance ( config , dict ) : raise ValueError ( 'config is not a dict: {}' . format ( config ) ) return co...
This load some configuration from the . travis . yml if file is present doctr key if present .
105
21
249,944
def decrypt_file ( file , key ) : if not file . endswith ( '.enc' ) : raise ValueError ( "%s does not end with .enc" % file ) fer = Fernet ( key ) with open ( file , 'rb' ) as f : decrypted_file = fer . decrypt ( f . read ( ) ) with open ( file [ : - 4 ] , 'wb' ) as f : f . write ( decrypted_file ) os . chmod ( file [ ...
Decrypts the file file .
115
7
249,945
def setup_deploy_key ( keypath = 'github_deploy_key' , key_ext = '.enc' , env_name = 'DOCTR_DEPLOY_ENCRYPTION_KEY' ) : key = os . environ . get ( env_name , os . environ . get ( "DOCTR_DEPLOY_ENCRYPTION_KEY" , None ) ) if not key : raise RuntimeError ( "{env_name} or DOCTR_DEPLOY_ENCRYPTION_KEY environment variable is ...
Decrypts the deploy key and configures it with ssh
573
12
249,946
def get_token ( ) : token = os . environ . get ( "GH_TOKEN" , None ) if not token : token = "GH_TOKEN environment variable not set" token = token . encode ( 'utf-8' ) return token
Get the encrypted GitHub token in Travis .
55
8
249,947
def run ( args , shell = False , exit = True ) : if "GH_TOKEN" in os . environ : token = get_token ( ) else : token = b'' if not shell : command = ' ' . join ( map ( shlex . quote , args ) ) else : command = args command = command . replace ( token . decode ( 'utf-8' ) , '~' * len ( token ) ) print ( blue ( command ) )...
Run the command args .
160
5
249,948
def get_current_repo ( ) : remote_url = subprocess . check_output ( [ 'git' , 'config' , '--get' , 'remote.origin.url' ] ) . decode ( 'utf-8' ) # Travis uses the https clone url _ , org , git_repo = remote_url . rsplit ( '.git' , 1 ) [ 0 ] . rsplit ( '/' , 2 ) return ( org + '/' + git_repo )
Get the GitHub repo name for the current directory .
106
10
249,949
def get_travis_branch ( ) : if os . environ . get ( "TRAVIS_PULL_REQUEST" , "" ) == "true" : return os . environ . get ( "TRAVIS_PULL_REQUEST_BRANCH" , "" ) else : return os . environ . get ( "TRAVIS_BRANCH" , "" )
Get the name of the branch that the PR is from .
86
12
249,950
def set_git_user_email ( ) : username = subprocess . run ( shlex . split ( 'git config user.name' ) , stdout = subprocess . PIPE ) . stdout . strip ( ) . decode ( 'utf-8' ) if not username or username == "Travis CI User" : run ( [ 'git' , 'config' , '--global' , 'user.name' , "Doctr (Travis CI)" ] ) else : print ( "Not...
Set global user and email for git user if not already present on system
289
14
249,951
def checkout_deploy_branch ( deploy_branch , canpush = True ) : # Create an empty branch with .nojekyll if it doesn't already exist create_deploy_branch ( deploy_branch , push = canpush ) remote_branch = "doctr_remote/{}" . format ( deploy_branch ) print ( "Checking out doctr working branch tracking" , remote_branch ) ...
Checkout the deploy branch creating it if it doesn t exist .
241
13
249,952
def deploy_branch_exists ( deploy_branch ) : remote_name = 'doctr_remote' branch_names = subprocess . check_output ( [ 'git' , 'branch' , '-r' ] ) . decode ( 'utf-8' ) . split ( ) return '{}/{}' . format ( remote_name , deploy_branch ) in branch_names
Check if there is a remote branch with name specified in deploy_branch .
89
16
249,953
def create_deploy_branch ( deploy_branch , push = True ) : if not deploy_branch_exists ( deploy_branch ) : print ( "Creating {} branch on doctr_remote" . format ( deploy_branch ) ) clear_working_branch ( ) run ( [ 'git' , 'checkout' , '--orphan' , DOCTR_WORKING_BRANCH ] ) # delete everything in the new ref. this is non...
If there is no remote branch with name specified in deploy_branch create one .
398
17
249,954
def find_sphinx_build_dir ( ) : build = glob . glob ( '**/*build/html' , recursive = True ) if not build : raise RuntimeError ( "Could not find Sphinx build directory automatically" ) build_folder = build [ 0 ] return build_folder
Find build subfolder within sphinx docs directory .
62
11
249,955
def copy_to_tmp ( source ) : tmp_dir = tempfile . mkdtemp ( ) # Use pathlib because os.path.basename is different depending on whether # the path ends in a / p = pathlib . Path ( source ) dirname = p . name or 'temp' new_dir = os . path . join ( tmp_dir , dirname ) if os . path . isdir ( source ) : shutil . copytree ( ...
Copies source to a temporary directory and returns the copied location .
122
13
249,956
def is_subdir ( a , b ) : a , b = map ( os . path . abspath , [ a , b ] ) return os . path . commonpath ( [ a , b ] ) == b
Return true if a is a subdirectory of b
46
10
249,957
def sync_from_log ( src , dst , log_file , exclude = ( ) ) : from os . path import join , exists , isdir exclude = [ os . path . normpath ( i ) for i in exclude ] added , removed = [ ] , [ ] if not exists ( log_file ) : # Assume this is the first run print ( "%s doesn't exist. Not removing any files." % log_file ) else...
Sync the files in src to dst .
489
8
249,958
def push_docs ( deploy_branch = 'gh-pages' , retries = 5 ) : code = 1 while code and retries : print ( "Pulling" ) code = run ( [ 'git' , 'pull' , '-s' , 'recursive' , '-X' , 'ours' , 'doctr_remote' , deploy_branch ] , exit = False ) print ( "Pushing commit" ) code = run ( [ 'git' , 'push' , '-q' , 'doctr_remote' , '{}...
Push the changes to the branch named deploy_branch .
186
12
249,959
def clean_path ( p ) : p = os . path . expanduser ( p ) p = os . path . expandvars ( p ) p = os . path . abspath ( p ) return p
Clean a path by expanding user and environment variables and ensuring absolute path .
44
14
249,960
def load_file_template ( path ) : template = StringIO ( ) if not os . path . exists ( path ) : raise ValueError ( "path does not exist: %s" % path ) with open ( clean_path ( path ) , "rb" ) as infile : # opened as binary for line in infile : template . write ( line . decode ( "utf-8" ) ) # ensure utf-8 return template
Load template from the specified filesystem path .
94
8
249,961
def load_package_template ( license , header = False ) : content = StringIO ( ) filename = 'template-%s-header.txt' if header else 'template-%s.txt' with resource_stream ( __name__ , filename % license ) as licfile : for line in licfile : content . write ( line . decode ( "utf-8" ) ) # write utf-8 string return content
Load license template distributed with package .
90
7
249,962
def extract_vars ( template ) : keys = set ( ) for match in re . finditer ( r"\{\{ (?P<key>\w+) \}\}" , template . getvalue ( ) ) : keys . add ( match . groups ( ) [ 0 ] ) return sorted ( list ( keys ) )
Extract variables from template . Variables are enclosed in double curly braces .
69
15
249,963
def generate_license ( template , context ) : out = StringIO ( ) content = template . getvalue ( ) for key in extract_vars ( template ) : if key not in context : raise ValueError ( "%s is missing from the template context" % key ) content = content . replace ( "{{ %s }}" % key , context [ key ] ) template . close ( ) #...
Generate a license by extracting variables from the template and replacing them with the corresponding values in the given context .
100
22
249,964
def get_suffix ( name ) : a = name . count ( "." ) if a : ext = name . split ( "." ) [ - 1 ] if ext in LANGS . keys ( ) : return ext return False else : return False
Check if file name have valid suffix for formatting . if have suffix return it else return False .
52
19
249,965
def _raise_for_status ( response ) : message = '' if 400 <= response . status < 500 : message = '%s Client Error: %s' % ( response . status , response . reason ) elif 500 <= response . status < 600 : message = '%s Server Error: %s' % ( response . status , response . reason ) else : return if response . status == 503 : ...
make sure that only crate . exceptions are raised that are defined in the DB - API specification
273
18
249,966
def _server_url ( server ) : if not _HTTP_PAT . match ( server ) : server = 'http://%s' % server parsed = urlparse ( server ) url = '%s://%s' % ( parsed . scheme , parsed . netloc ) return url
Normalizes a given server string to an url
61
9
249,967
def sql ( self , stmt , parameters = None , bulk_parameters = None ) : if stmt is None : return None data = _create_sql_payload ( stmt , parameters , bulk_parameters ) logger . debug ( 'Sending request to %s with payload: %s' , self . path , data ) content = self . _json_request ( 'POST' , self . path , data = data ) l...
Execute SQL stmt against the crate server .
118
10
249,968
def blob_put ( self , table , digest , data ) : response = self . _request ( 'PUT' , _blob_path ( table , digest ) , data = data ) if response . status == 201 : # blob created return True if response . status == 409 : # blob exists return False if response . status in ( 400 , 404 ) : raise BlobLocationNotFoundException...
Stores the contents of the file like
96
8
249,969
def blob_get ( self , table , digest , chunk_size = 1024 * 128 ) : response = self . _request ( 'GET' , _blob_path ( table , digest ) , stream = True ) if response . status == 404 : raise DigestNotFoundException ( table , digest ) _raise_for_status ( response ) return response . stream ( amt = chunk_size )
Returns a file like object representing the contents of the blob with the given digest .
84
16
249,970
def blob_exists ( self , table , digest ) : response = self . _request ( 'HEAD' , _blob_path ( table , digest ) ) if response . status == 200 : return True elif response . status == 404 : return False _raise_for_status ( response )
Returns true if the blob with the given digest exists under the given table .
63
15
249,971
def _request ( self , method , path , server = None , * * kwargs ) : while True : next_server = server or self . _get_server ( ) try : response = self . server_pool [ next_server ] . request ( method , path , username = self . username , password = self . password , schema = self . schema , * * kwargs ) redirect_locati...
Execute a request to the cluster
417
7
249,972
def _json_request ( self , method , path , data ) : response = self . _request ( method , path , data = data ) _raise_for_status ( response ) if len ( response . data ) > 0 : return _json_from_response ( response ) return response . data
Issue request against the crate HTTP API .
63
8
249,973
def _get_server ( self ) : with self . _lock : inactive_server_count = len ( self . _inactive_servers ) for i in range ( inactive_server_count ) : try : ts , server , message = heapq . heappop ( self . _inactive_servers ) except IndexError : pass else : if ( ts + self . retry_interval ) > time ( ) : # Not yet, put it b...
Get server to use for request . Also process inactive server list re - add them after given interval .
246
20
249,974
def _drop_server ( self , server , message ) : try : self . _active_servers . remove ( server ) except ValueError : pass else : heapq . heappush ( self . _inactive_servers , ( time ( ) , server , message ) ) logger . warning ( "Removed server %s from active pool" , server ) # if this is the last server raise exception,...
Drop server from active list and adds it to the inactive ones .
126
13
249,975
def match ( column , term , match_type = None , options = None ) : return Match ( column , term , match_type , options )
Generates match predicate for fulltext search
31
8
249,976
def put ( self , f , digest = None ) : if digest : actual_digest = digest else : actual_digest = self . _compute_digest ( f ) created = self . conn . client . blob_put ( self . container_name , actual_digest , f ) if digest : return created return actual_digest
Upload a blob
74
3
249,977
def get ( self , digest , chunk_size = 1024 * 128 ) : return self . conn . client . blob_get ( self . container_name , digest , chunk_size )
Return the contents of a blob
39
6
249,978
def delete ( self , digest ) : return self . conn . client . blob_del ( self . container_name , digest )
Delete a blob
27
3
249,979
def exists ( self , digest ) : return self . conn . client . blob_exists ( self . container_name , digest )
Check if a blob exists
28
5
249,980
def next ( self ) : if self . rows is None : raise ProgrammingError ( "No result available. " + "execute() or executemany() must be called first." ) elif not self . _closed : return next ( self . rows ) else : raise ProgrammingError ( "Cursor closed" )
Return the next row of a query result set respecting if cursor was closed .
65
15
249,981
def duration ( self ) : if self . _closed or not self . _result or "duration" not in self . _result : return - 1 return self . _result . get ( "duration" , 0 )
This read - only attribute specifies the server - side duration of a query in milliseconds .
45
17
249,982
def rewrite_update ( clauseelement , multiparams , params ) : newmultiparams = [ ] _multiparams = multiparams [ 0 ] if len ( _multiparams ) == 0 : return clauseelement , multiparams , params for _params in _multiparams : newparams = { } for key , val in _params . items ( ) : if ( not isinstance ( val , MutableDict ) or...
change the params to enable partial updates
274
7
249,983
def _get_crud_params ( compiler , stmt , * * kw ) : compiler . postfetch = [ ] compiler . insert_prefetch = [ ] compiler . update_prefetch = [ ] compiler . returning = [ ] # no parameters in the statement, no parameters in the # compiled params - return binds for all columns if compiler . column_keys is None and stmt ....
extract values from crud parameters
532
7
249,984
def get_tgt_for ( user ) : if not settings . CAS_PROXY_CALLBACK : raise CasConfigException ( "No proxy callback set in settings" ) try : return Tgt . objects . get ( username = user . username ) except ObjectDoesNotExist : logger . warning ( 'No ticket found for user {user}' . format ( user = user . username ) ) raise ...
Fetch a ticket granting ticket for a given user .
103
11
249,985
def get_proxy_ticket_for ( self , service ) : if not settings . CAS_PROXY_CALLBACK : raise CasConfigException ( "No proxy callback set in settings" ) params = { 'pgt' : self . tgt , 'targetService' : service } url = ( urljoin ( settings . CAS_SERVER_URL , 'proxy' ) + '?' + urlencode ( params ) ) page = urlopen ( url ) ...
Verifies CAS 2 . 0 + XML - based authentication ticket .
196
13
249,986
def _internal_verify_cas ( ticket , service , suffix ) : params = { 'ticket' : ticket , 'service' : service } if settings . CAS_PROXY_CALLBACK : params [ 'pgtUrl' ] = settings . CAS_PROXY_CALLBACK url = ( urljoin ( settings . CAS_SERVER_URL , suffix ) + '?' + urlencode ( params ) ) page = urlopen ( url ) username = Non...
Verifies CAS 2 . 0 and 3 . 0 XML - based authentication ticket .
467
16
249,987
def verify_proxy_ticket ( ticket , service ) : params = { 'ticket' : ticket , 'service' : service } url = ( urljoin ( settings . CAS_SERVER_URL , 'proxyValidate' ) + '?' + urlencode ( params ) ) page = urlopen ( url ) try : response = page . read ( ) tree = ElementTree . fromstring ( response ) if tree [ 0 ] . tag . en...
Verifies CAS 2 . 0 + XML - based proxy ticket .
176
13
249,988
def _get_pgtiou ( pgt ) : pgtIou = None retries_left = 5 if not settings . CAS_PGT_FETCH_WAIT : retries_left = 1 while not pgtIou and retries_left : try : return PgtIOU . objects . get ( tgt = pgt ) except PgtIOU . DoesNotExist : if settings . CAS_PGT_FETCH_WAIT : time . sleep ( 1 ) retries_left -= 1 logger . info ( 'D...
Returns a PgtIOU object given a pgt .
169
12
249,989
def gateway ( ) : if settings . CAS_GATEWAY == False : raise ImproperlyConfigured ( 'CAS_GATEWAY must be set to True' ) def wrap ( func ) : def wrapped_f ( * args ) : from cas . views import login request = args [ 0 ] try : # use callable for pre-django 2.0 is_authenticated = request . user . is_authenticated ( ) excep...
Authenticates single sign on session if ticket is available but doesn t redirect to sign in url otherwise .
315
20
249,990
def _service_url ( request , redirect_to = None , gateway = False ) : if settings . CAS_FORCE_SSL_SERVICE_URL : protocol = 'https://' else : protocol = ( 'http://' , 'https://' ) [ request . is_secure ( ) ] host = request . get_host ( ) service = protocol + host + request . path if redirect_to : if '?' in service : ser...
Generates application service URL for CAS
314
7
249,991
def proxy_callback ( request ) : pgtIou = request . GET . get ( 'pgtIou' ) tgt = request . GET . get ( 'pgtId' ) if not ( pgtIou and tgt ) : logger . info ( 'No pgtIou or tgt found in request.GET' ) return HttpResponse ( 'No pgtIOO' , content_type = "text/plain" ) try : PgtIOU . objects . create ( tgt = tgt , pgtIou = ...
Handles CAS 2 . 0 + XML - based proxy callback call . Stores the proxy granting ticket in the database for future use .
254
26
249,992
def objectify ( func ) : @ functools . wraps ( func ) def wrapper ( * args , * * kwargs ) : try : payload = func ( * args , * * kwargs ) except requests . exceptions . ConnectionError as e : raise InternetConnectionError ( e ) return EventbriteObject . create ( payload ) return wrapper
Converts the returned value from a models . Payload to a models . EventbriteObject . Used by the access methods of the client . Eventbrite object
73
33
249,993
def get_user ( self , user_id = None ) : if user_id : return self . get ( '/users/{0}/' . format ( user_id ) ) return self . get ( '/users/me/' )
Returns a user for the specified user as user .
52
10
249,994
def get_event_attendees ( self , event_id , status = None , changed_since = None ) : data = { } if status : # TODO - check the types of valid status data [ 'status' ] = status if changed_since : data [ 'changed_since' ] = changed_since return self . get ( "/events/{0}/attendees/" . format ( event_id ) , data = data )
Returns a paginated response with a key of attendees containing a list of attendee .
96
17
249,995
def webhook_to_object ( self , webhook ) : if isinstance ( webhook , string_type ) : # If still JSON, convert to a Python dict webhook = json . dumps ( webhook ) # if a flask.Request object, try to convert that to a webhook if not isinstance ( webhook , dict ) : webhook = get_webhook_from_request ( webhook ) try : webh...
Converts JSON sent by an Eventbrite Webhook to the appropriate Eventbrite object .
125
19
249,996
def get_params_from_page ( path , file_name , method_count ) : # open the rendered file. file_name = file_name . replace ( ".rst" , "" ) file_path = "{0}/../_build/html/endpoints/{1}/index.html" . format ( path , file_name ) soup = bs4 . BeautifulSoup ( open ( file_path ) ) # Pull out the relevant section section = sou...
This function accesses the rendered content . We must do this because how the params are not defined in the docs but rather the rendered HTML
255
27
249,997
def process_request ( self , request ) : # Section adjusted to restrict login to ?edit # (sing cms-toolbar-login)into DjangoCMS login. restricted_request_uri = request . path . startswith ( reverse ( 'admin:index' ) or "cms-toolbar-login" in request . build_absolute_uri ( ) ) if restricted_request_uri and request . met...
Check if the request is made form an allowed IP
312
10
249,998
def get_settings ( editor_override = None ) : flavor = getattr ( settings , "DJANGO_WYSIWYG_FLAVOR" , "yui" ) if editor_override is not None : flavor = editor_override return { "DJANGO_WYSIWYG_MEDIA_URL" : getattr ( settings , "DJANGO_WYSIWYG_MEDIA_URL" , urljoin ( settings . STATIC_URL , flavor ) + '/' ) , "DJANGO_WYS...
Utility function to retrieve settings . py values with defaults
137
11
249,999
def get_auth ( self ) : return ( self . _cfgparse . get ( self . _section , 'username' ) , self . _cfgparse . get ( self . _section , 'password' ) )
Returns username from the configfile .
46
7