query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Similarity scores for sentences with title in descending order
def _title_similarity_score ( full_text , title ) : sentences = sentence_tokenizer ( full_text ) norm = _normalize ( [ title ] + sentences ) similarity_matrix = pairwise_kernels ( norm , metric = 'cosine' ) return sorted ( zip ( similarity_matrix [ 0 , 1 : ] , range ( len ( similarity_matrix ) ) , sentences ) , key = lambda tup : tup [ 0 ] , reverse = True )
8,300
https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/core.py#L77-L91
[ "def", "group_toggle", "(", "self", ",", "addr", ",", "use_cache", "=", "True", ")", ":", "data", "=", "self", ".", "group_read", "(", "addr", ",", "use_cache", ")", "if", "len", "(", "data", ")", "!=", "1", ":", "problem", "=", "\"Can't toggle a {}-octet group address {}\"", ".", "format", "(", "len", "(", "data", ")", ",", "addr", ")", "logging", ".", "error", "(", "problem", ")", "raise", "KNXException", "(", "problem", ")", "if", "data", "[", "0", "]", "==", "0", ":", "self", ".", "group_write", "(", "addr", ",", "[", "1", "]", ")", "elif", "data", "[", "0", "]", "==", "1", ":", "self", ".", "group_write", "(", "addr", ",", "[", "0", "]", ")", "else", ":", "problem", "=", "\"Can't toggle group address {} as value is {}\"", ".", "format", "(", "addr", ",", "data", "[", "0", "]", ")", "logging", ".", "error", "(", "problem", ")", "raise", "KNXException", "(", "problem", ")" ]
rerank the two vectors by min aggregrate rank reorder
def _aggregrate_scores ( its , tss , num_sentences ) : final = [ ] for i , el in enumerate ( its ) : for j , le in enumerate ( tss ) : if el [ 2 ] == le [ 2 ] : assert el [ 1 ] == le [ 1 ] final . append ( ( el [ 1 ] , i + j , el [ 2 ] ) ) _final = sorted ( final , key = lambda tup : tup [ 1 ] ) [ : num_sentences ] return sorted ( _final , key = lambda tup : tup [ 0 ] )
8,301
https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/core.py#L102-L112
[ "def", "create_silence", "(", "length", ")", ":", "data", "=", "bytearray", "(", "length", ")", "i", "=", "0", "while", "i", "<", "length", ":", "data", "[", "i", "]", "=", "128", "i", "+=", "1", "return", "data" ]
some crude heuristics for now most are implemented on bot - side with domain whitelists
def _eval_meta_as_summary ( meta ) : if meta == '' : return False if len ( meta ) > 500 : return False if 'login' in meta . lower ( ) : return False return True
8,302
https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/core.py#L115-L126
[ "def", "_wait_for_async", "(", "conn", ",", "request_id", ")", ":", "count", "=", "0", "log", ".", "debug", "(", "'Waiting for asynchronous operation to complete'", ")", "result", "=", "conn", ".", "get_operation_status", "(", "request_id", ")", "while", "result", ".", "status", "==", "'InProgress'", ":", "count", "=", "count", "+", "1", "if", "count", ">", "120", ":", "raise", "ValueError", "(", "'Timed out waiting for asynchronous operation to complete.'", ")", "time", ".", "sleep", "(", "5", ")", "result", "=", "conn", ".", "get_operation_status", "(", "request_id", ")", "if", "result", ".", "status", "!=", "'Succeeded'", ":", "raise", "AzureException", "(", "'Operation failed. {message} ({code})'", ".", "format", "(", "message", "=", "result", ".", "error", ".", "message", ",", "code", "=", "result", ".", "error", ".", "code", ")", ")" ]
Return a list of subscriptions currently active for this WVA device
def get_subscriptions ( self ) : # Example: {'subscriptions': ['subscriptions/TripDistance~sub', 'subscriptions/FuelRate~sub', ]} subscriptions = [ ] for uri in self . get_http_client ( ) . get ( "subscriptions" ) . get ( 'subscriptions' ) : subscriptions . append ( self . get_subscription ( uri . split ( "/" ) [ - 1 ] ) ) return subscriptions
8,303
https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/core.py#L90-L100
[ "def", "fetch_and_create_image", "(", "self", ",", "url", ",", "image_title", ")", ":", "context", "=", "{", "\"file_url\"", ":", "url", ",", "\"foreign_title\"", ":", "image_title", ",", "}", "try", ":", "image_file", "=", "requests", ".", "get", "(", "url", ")", "local_image", "=", "Image", "(", "title", "=", "image_title", ",", "file", "=", "ImageFile", "(", "BytesIO", "(", "image_file", ".", "content", ")", ",", "name", "=", "image_title", ")", ")", "local_image", ".", "save", "(", ")", "return", "(", "local_image", ",", "context", ")", "except", "Exception", "as", "e", ":", "context", ".", "update", "(", "{", "\"exception\"", ":", "e", ",", "}", ")", "raise", "ImageCreationFailed", "(", "context", ",", "None", ")" ]
Get the event stream associated with this WVA
def get_event_stream ( self ) : if self . _event_stream is None : self . _event_stream = WVAEventStream ( self . _http_client ) return self . _event_stream
8,304
https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/core.py#L102-L112
[ "def", "crypto_config_from_kwargs", "(", "fallback", ",", "*", "*", "kwargs", ")", ":", "try", ":", "crypto_config", "=", "kwargs", ".", "pop", "(", "\"crypto_config\"", ")", "except", "KeyError", ":", "try", ":", "fallback_kwargs", "=", "{", "\"table_name\"", ":", "kwargs", "[", "\"TableName\"", "]", "}", "except", "KeyError", ":", "fallback_kwargs", "=", "{", "}", "crypto_config", "=", "fallback", "(", "*", "*", "fallback_kwargs", ")", "return", "crypto_config", ",", "kwargs" ]
Call the C - code that actually populates the histogram
def _populateHistogram ( self ) : try : buildHistogram . populate1DHist ( self . _data , self . histogram , self . minValue , self . maxValue , self . binWidth ) except : if ( ( self . _data . max ( ) - self . _data . min ( ) ) < self . binWidth ) : raise ValueError ( "In histogram1d class, the binWidth is " "greater than the data range of the array " "object." ) else : raise SystemError ( "An error processing the array object " "information occured in the buildHistogram " "module of histogram1d." )
8,305
https://github.com/spacetelescope/stsci.imagestats/blob/d7fc9fe9783f7ed3dc9e4af47acd357a5ccd68e3/stsci/imagestats/histogram1d.py#L55-L68
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_stopped", "=", "True", "threads", "=", "[", "self", ".", "_accept_thread", "]", "threads", ".", "extend", "(", "self", ".", "_server_threads", ")", "self", ".", "_listening_sock", ".", "close", "(", ")", "for", "sock", "in", "list", "(", "self", ".", "_server_socks", ")", ":", "try", ":", "sock", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "except", "socket", ".", "error", ":", "pass", "try", ":", "sock", ".", "close", "(", ")", "except", "socket", ".", "error", ":", "pass", "with", "self", ".", "_unlock", "(", ")", ":", "for", "thread", "in", "threads", ":", "thread", ".", "join", "(", "10", ")", "if", "self", ".", "_uds_path", ":", "try", ":", "os", ".", "unlink", "(", "self", ".", "_uds_path", ")", "except", "OSError", ":", "pass" ]
Returns histogram s centers .
def getCenters ( self ) : return np . arange ( self . histogram . size ) * self . binWidth + self . minValue
8,306
https://github.com/spacetelescope/stsci.imagestats/blob/d7fc9fe9783f7ed3dc9e4af47acd357a5ccd68e3/stsci/imagestats/histogram1d.py#L70-L72
[ "def", "create", "(", "self", ",", "user_id", ",", "media_id", ",", "item_type", ",", "token", ",", "data", ")", ":", "final_dict", "=", "{", "\"data\"", ":", "{", "\"type\"", ":", "\"libraryEntries\"", ",", "\"attributes\"", ":", "data", ",", "\"relationships\"", ":", "{", "\"user\"", ":", "{", "\"data\"", ":", "{", "\"id\"", ":", "user_id", ",", "\"type\"", ":", "\"users\"", "}", "}", ",", "\"media\"", ":", "{", "\"data\"", ":", "{", "\"id\"", ":", "media_id", ",", "\"type\"", ":", "item_type", "}", "}", "}", "}", "}", "final_headers", "=", "self", ".", "header", "final_headers", "[", "'Authorization'", "]", "=", "\"Bearer {}\"", ".", "format", "(", "token", ")", "r", "=", "requests", ".", "post", "(", "self", ".", "apiurl", "+", "\"/library-entries\"", ",", "json", "=", "final_dict", ",", "headers", "=", "final_headers", ")", "if", "r", ".", "status_code", "!=", "201", ":", "raise", "ConnectionError", "(", "r", ".", "text", ")", "jsd", "=", "r", ".", "json", "(", ")", "return", "jsd", "[", "'data'", "]", "[", "'id'", "]" ]
Book a reservation given the session id the room id as an integer and the start and end time as datetimes .
def book_reservation ( self , sessionid , roomid , start , end ) : duration = int ( ( end - start ) . seconds / 60 ) format = "%Y-%m-%dT%H:%M:%S-{}" . format ( self . get_dst_gmt_timezone ( ) ) booking_url = "{}/reserve/{}/{}/?d={}" . format ( BASE_URL , roomid , start . strftime ( format ) , duration ) resp = requests . get ( booking_url , cookies = { "sessionid" : sessionid } ) if resp . status_code == 403 : return { "success" : False , "error" : "Your account does not have permission to book Wharton GSRs!" } resp . raise_for_status ( ) csrfheader = re . search ( r"csrftoken=(.*?);" , resp . headers [ "Set-Cookie" ] ) . group ( 1 ) csrftoken = re . search ( r"<input name=\"csrfmiddlewaretoken\" type=\"hidden\" value=\"(.*?)\"/>" , resp . content . decode ( "utf8" ) ) . group ( 1 ) start_string = start . strftime ( "%I:%M %p" ) if start_string [ 0 ] == "0" : start_string = start_string [ 1 : ] resp = requests . post ( booking_url , cookies = { "sessionid" : sessionid , "csrftoken" : csrfheader } , headers = { "Referer" : booking_url } , data = { "csrfmiddlewaretoken" : csrftoken , "room" : roomid , "start_time" : start_string , "end_time" : end . strftime ( "%a %b %d %H:%M:%S %Y" ) , "date" : start . strftime ( "%B %d, %Y" ) } ) resp . raise_for_status ( ) content = resp . content . decode ( "utf8" ) if "errorlist" in content : error_msg = re . search ( r"class=\"errorlist\"><li>(.*?)</li>" , content ) . group ( 1 ) return { "success" : False , "error" : error_msg } return { "success" : True }
8,307
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L53-L90
[ "def", "make_certificate_authority", "(", "*", "*", "name", ")", ":", "key", "=", "make_pkey", "(", ")", "csr", "=", "make_certificate_signing_request", "(", "key", ",", "*", "*", "name", ")", "crt", "=", "make_certificate", "(", "csr", ",", "key", ",", "csr", ",", "make_serial", "(", ")", ",", "0", ",", "10", "*", "365", "*", "24", "*", "60", "*", "60", ",", "exts", "=", "[", "crypto", ".", "X509Extension", "(", "b'basicConstraints'", ",", "True", ",", "b'CA:TRUE'", ")", "]", ")", "return", "key", ",", "crt" ]
Deletes a Wharton GSR Booking for a given booking and session id .
def delete_booking ( self , sessionid , booking_id ) : url = "{}{}{}/" . format ( BASE_URL , "/delete/" , booking_id ) cookies = dict ( sessionid = sessionid ) try : resp = requests . get ( url , cookies = cookies , headers = { 'Referer' : '{}{}' . format ( BASE_URL , "/reservations/" ) } ) except resp . exceptions . HTTPError as error : raise APIError ( "Server Error: {}" . format ( error ) ) if resp . status_code == 404 : raise APIError ( "Booking could not be found on server." ) html = resp . content . decode ( "utf8" ) if "https://weblogin.pennkey.upenn.edu" in html : raise APIError ( "Wharton Auth Failed. Session ID is not valid." ) resp . raise_for_status ( ) soup = BeautifulSoup ( html , "html5lib" ) middleware_token = soup . find ( "input" , { 'name' : "csrfmiddlewaretoken" } ) . get ( 'value' ) csrftoken = resp . cookies [ 'csrftoken' ] cookies2 = { 'sessionid' : sessionid , 'csrftoken' : csrftoken } headers = { 'Referer' : url } payload = { 'csrfmiddlewaretoken' : middleware_token } try : resp2 = requests . post ( url , cookies = cookies2 , data = payload , headers = headers ) except resp2 . exceptions . HTTPError as error : raise APIError ( "Server Error: {}" . format ( error ) ) return { "success" : True }
8,308
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L92-L124
[ "def", "intermediary_to_markdown", "(", "tables", ",", "relationships", ",", "output", ")", ":", "er_markup", "=", "_intermediary_to_markdown", "(", "tables", ",", "relationships", ")", "with", "open", "(", "output", ",", "\"w\"", ")", "as", "file_out", ":", "file_out", ".", "write", "(", "er_markup", ")" ]
Make a request to retrieve Wharton GSR listings .
def get_wharton_gsrs ( self , sessionid , date = None ) : if date : date += " {}" . format ( self . get_dst_gmt_timezone ( ) ) else : date = datetime . datetime . utcnow ( ) . strftime ( "%Y-%m-%d %H:%S" ) resp = requests . get ( 'https://apps.wharton.upenn.edu/gsr/api/app/grid_view/' , params = { 'search_time' : date } , cookies = { 'sessionid' : sessionid } ) if resp . status_code == 200 : return resp . json ( ) else : raise APIError ( 'Remote server returned status code {}.' . format ( resp . status_code ) )
8,309
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L126-L140
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_connection", "is", "None", ":", "return", "if", "self", ".", "_transaction", "is", "not", "None", ":", "await", "self", ".", "_transaction", ".", "rollback", "(", ")", "self", ".", "_transaction", "=", "None", "# don't close underlying connection, it can be reused by pool", "# conn.close()", "self", ".", "_engine", ".", "release", "(", "self", ")", "self", ".", "_connection", "=", "None", "self", ".", "_engine", "=", "None" ]
Convert the Wharton GSR format into the studyspaces API format .
def switch_format ( self , gsr ) : if "error" in gsr : return gsr categories = { "cid" : 1 , "name" : "Huntsman Hall" , "rooms" : [ ] } for time in gsr [ "times" ] : for entry in time : entry [ "name" ] = entry [ "room_number" ] del entry [ "room_number" ] start_time_str = entry [ "start_time" ] end_time = datetime . datetime . strptime ( start_time_str [ : - 6 ] , '%Y-%m-%dT%H:%M:%S' ) + datetime . timedelta ( minutes = 30 ) end_time_str = end_time . strftime ( "%Y-%m-%dT%H:%M:%S" ) + "-{}" . format ( self . get_dst_gmt_timezone ( ) ) time = { "available" : not entry [ "reserved" ] , "start" : entry [ "start_time" ] , "end" : end_time_str , } exists = False for room in categories [ "rooms" ] : if room [ "name" ] == entry [ "name" ] : room [ "times" ] . append ( time ) exists = True if not exists : del entry [ "booked_by_user" ] del entry [ "building" ] if "reservation_id" in entry : del entry [ "reservation_id" ] entry [ "lid" ] = 1 entry [ "gid" ] = 1 entry [ "capacity" ] = 5 entry [ "room_id" ] = int ( entry [ "id" ] ) del entry [ "id" ] entry [ "times" ] = [ time ] del entry [ "reserved" ] del entry [ "end_time" ] del entry [ "start_time" ] categories [ "rooms" ] . append ( entry ) return { "categories" : [ categories ] , "rooms" : categories [ "rooms" ] }
8,310
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L142-L184
[ "def", "dump", "(", "self", ")", ":", "assert", "self", ".", "database", "is", "not", "None", "cmd", "=", "\"SELECT count from {} WHERE rowid={}\"", "self", ".", "_execute", "(", "cmd", ".", "format", "(", "self", ".", "STATE_INFO_TABLE", ",", "self", ".", "STATE_INFO_ROW", ")", ")", "ret", "=", "self", ".", "_fetchall", "(", ")", "assert", "len", "(", "ret", ")", "==", "1", "assert", "len", "(", "ret", "[", "0", "]", ")", "==", "1", "count", "=", "self", ".", "_from_sqlite", "(", "ret", "[", "0", "]", "[", "0", "]", ")", "+", "self", ".", "inserts", "if", "count", ">", "self", ".", "row_limit", ":", "msg", "=", "\"cleaning up state, this might take a while.\"", "logger", ".", "warning", "(", "msg", ")", "delete", "=", "count", "-", "self", ".", "row_limit", "delete", "+=", "int", "(", "self", ".", "row_limit", "*", "(", "self", ".", "row_cleanup_quota", "/", "100.0", ")", ")", "cmd", "=", "(", "\"DELETE FROM {} WHERE timestamp IN (\"", "\"SELECT timestamp FROM {} ORDER BY timestamp ASC LIMIT {});\"", ")", "self", ".", "_execute", "(", "cmd", ".", "format", "(", "self", ".", "STATE_TABLE", ",", "self", ".", "STATE_TABLE", ",", "delete", ")", ")", "self", ".", "_vacuum", "(", ")", "cmd", "=", "\"SELECT COUNT(*) FROM {}\"", "self", ".", "_execute", "(", "cmd", ".", "format", "(", "self", ".", "STATE_TABLE", ")", ")", "ret", "=", "self", ".", "_fetchall", "(", ")", "assert", "len", "(", "ret", ")", "==", "1", "assert", "len", "(", "ret", "[", "0", "]", ")", "==", "1", "count", "=", "ret", "[", "0", "]", "[", "0", "]", "cmd", "=", "\"UPDATE {} SET count = {} WHERE rowid = {}\"", "self", ".", "_execute", "(", "cmd", ".", "format", "(", "self", ".", "STATE_INFO_TABLE", ",", "self", ".", "_to_sqlite", "(", "count", ")", ",", "self", ".", "STATE_INFO_ROW", ",", ")", ")", "self", ".", "_update_cache_directory_state", "(", ")", "self", ".", "database", ".", "commit", "(", ")", "self", ".", "cursor", ".", "close", "(", ")", "self", ".", "database", ".", "close", "(", ")", "self", ".", "database", "=", "None", "self", ".", "cursor", "=", "None", "self", ".", "inserts", "=", "0" ]
Return the wharton GSR listing formatted in studyspaces format .
def get_wharton_gsrs_formatted ( self , sessionid , date = None ) : gsrs = self . get_wharton_gsrs ( sessionid , date ) return self . switch_format ( gsrs )
8,311
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L186-L189
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_connection", "is", "None", ":", "return", "if", "self", ".", "_transaction", "is", "not", "None", ":", "await", "self", ".", "_transaction", ".", "rollback", "(", ")", "self", ".", "_transaction", "=", "None", "# don't close underlying connection, it can be reused by pool", "# conn.close()", "self", ".", "_engine", ".", "release", "(", "self", ")", "self", ".", "_connection", "=", "None", "self", ".", "_engine", "=", "None" ]
Collect all the options info from the other modules .
def get_options ( ) : options = collections . defaultdict ( list ) for opt_class in config_factory . get_options ( ) : if not issubclass ( opt_class , config_base . Options ) : continue config_options = opt_class ( None ) options [ config_options . group_name ] . extend ( config_options . list ( ) ) return [ ( key , value ) for key , value in options . items ( ) ]
8,312
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/config/options.py#L26-L34
[ "def", "face_index", "(", "vertices", ")", ":", "new_verts", "=", "[", "]", "face_indices", "=", "[", "]", "for", "wall", "in", "vertices", ":", "face_wall", "=", "[", "]", "for", "vert", "in", "wall", ":", "if", "new_verts", ":", "if", "not", "np", ".", "isclose", "(", "vert", ",", "new_verts", ")", ".", "all", "(", "axis", "=", "1", ")", ".", "any", "(", ")", ":", "new_verts", ".", "append", "(", "vert", ")", "else", ":", "new_verts", ".", "append", "(", "vert", ")", "face_index", "=", "np", ".", "where", "(", "np", ".", "isclose", "(", "vert", ",", "new_verts", ")", ".", "all", "(", "axis", "=", "1", ")", ")", "[", "0", "]", "[", "0", "]", "face_wall", ".", "append", "(", "face_index", ")", "face_indices", ".", "append", "(", "face_wall", ")", "return", "np", ".", "array", "(", "new_verts", ")", ",", "np", ".", "array", "(", "face_indices", ")" ]
Returns True if the wash alert web interface seems to be working properly or False otherwise .
def check_is_working ( self ) : try : r = requests . post ( "http://{}/" . format ( LAUNDRY_DOMAIN ) , timeout = 60 , data = { "locationid" : "5faec7e9-a4aa-47c2-a514-950c03fac460" , "email" : "pennappslabs@gmail.com" , "washers" : 0 , "dryers" : 0 , "locationalert" : "OK" } ) r . raise_for_status ( ) return "The transaction log for database 'QuantumCoin' is full due to 'LOG_BACKUP'." not in r . text except requests . exceptions . HTTPError : return False
8,313
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/laundry.py#L153-L170
[ "def", "LOAD", "(", "target_reg", ",", "region_name", ",", "offset_reg", ")", ":", "return", "ClassicalLoad", "(", "unpack_classical_reg", "(", "target_reg", ")", ",", "region_name", ",", "unpack_classical_reg", "(", "offset_reg", ")", ")" ]
Returns the average usage of laundry machines every hour for a given hall .
def machine_usage ( self , hall_no ) : try : num = int ( hall_no ) except ValueError : raise ValueError ( "Room Number must be integer" ) r = requests . get ( USAGE_BASE_URL + str ( num ) , timeout = 60 ) parsed = BeautifulSoup ( r . text , 'html5lib' ) usage_table = parsed . find_all ( 'table' , width = '504px' ) [ 0 ] rows = usage_table . find_all ( 'tr' ) usages = { } for i , row in enumerate ( rows ) : day = [ ] hours = row . find_all ( 'td' ) for hour in hours : day . append ( self . busy_dict [ str ( hour [ 'class' ] [ 0 ] ) ] ) usages [ self . days [ i ] ] = day return usages
8,314
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/laundry.py#L172-L202
[ "def", "createAlignment", "(", "self", ",", "resultFormat", "=", "dict", ")", ":", "table", "=", "self", ".", "_initialise", "(", ")", "alignment", "=", "self", ".", "_fillAndTraceback", "(", "table", ")", "output", "=", "alignment", "[", "0", "]", "if", "output", "[", "0", "]", "==", "''", "or", "output", "[", "2", "]", "==", "''", ":", "result", "=", "None", "else", ":", "indexes", "=", "alignment", "[", "1", "]", "result", "=", "{", "'cigar'", ":", "self", ".", "_cigarString", "(", "output", ")", ",", "'sequence1Start'", ":", "indexes", "[", "'min_col'", "]", ",", "'sequence1End'", ":", "indexes", "[", "'max_col'", "]", ",", "'sequence2Start'", ":", "indexes", "[", "'min_row'", "]", ",", "'sequence2End'", ":", "indexes", "[", "'max_row'", "]", ",", "'text'", ":", "self", ".", "_formatAlignment", "(", "output", ",", "indexes", ")", ",", "}", "return", "self", ".", "_alignmentToStr", "(", "result", ")", "if", "resultFormat", "is", "str", "else", "result" ]
Create message object for sending email
def create_message ( from_addr , to_addr , subject , body , encoding = None ) : if encoding == "None" : encoding = None if not encoding : encoding = 'utf-8' msg = MIMEText ( body . encode ( encoding ) , 'plain' , encoding ) msg [ 'Subject' ] = Header ( subject . encode ( encoding ) , encoding ) msg [ 'From' ] = from_addr msg [ 'To' ] = to_addr msg [ 'Date' ] = formatdate ( ) return msg
8,315
https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/mailer.py#L11-L42
[ "def", "from_overlays", "(", "overlays", ")", ":", "jc", "=", "JobConfig", "(", ")", "jc", ".", "comment", "=", "overlays", ".", "get", "(", "'comment'", ")", "if", "'jobConfigOverlays'", "in", "overlays", ":", "if", "len", "(", "overlays", "[", "'jobConfigOverlays'", "]", ")", ">=", "1", ":", "jco", "=", "copy", ".", "deepcopy", "(", "overlays", "[", "'jobConfigOverlays'", "]", "[", "0", "]", ")", "# Now extract the logical information", "if", "'jobConfig'", "in", "jco", ":", "_jc", "=", "jco", "[", "'jobConfig'", "]", "jc", ".", "job_name", "=", "_jc", ".", "pop", "(", "'jobName'", ",", "None", ")", "jc", ".", "job_group", "=", "_jc", ".", "pop", "(", "'jobGroup'", ",", "None", ")", "jc", ".", "preload", "=", "_jc", ".", "pop", "(", "'preloadApplicationBundles'", ",", "False", ")", "jc", ".", "data_directory", "=", "_jc", ".", "pop", "(", "'dataDirectory'", ",", "None", ")", "jc", ".", "tracing", "=", "_jc", ".", "pop", "(", "'tracing'", ",", "None", ")", "for", "sp", "in", "_jc", ".", "pop", "(", "'submissionParameters'", ",", "[", "]", ")", ":", "jc", ".", "submission_parameters", "[", "sp", "[", "'name'", "]", "]", "=", "sp", "[", "'value'", "]", "if", "not", "_jc", ":", "del", "jco", "[", "'jobConfig'", "]", "if", "'deploymentConfig'", "in", "jco", ":", "_dc", "=", "jco", "[", "'deploymentConfig'", "]", "if", "'manual'", "==", "_dc", ".", "get", "(", "'fusionScheme'", ")", ":", "if", "'fusionTargetPeCount'", "in", "_dc", ":", "jc", ".", "target_pe_count", "=", "_dc", ".", "pop", "(", "'fusionTargetPeCount'", ")", "if", "len", "(", "_dc", ")", "==", "1", ":", "del", "jco", "[", "'deploymentConfig'", "]", "if", "jco", ":", "jc", ".", "raw_overlay", "=", "jco", "return", "jc" ]
Obtain an auth token from client id and client secret .
def _obtain_token ( self ) : # don't renew token if hasn't expired yet if self . expiration and self . expiration > datetime . datetime . now ( ) : return resp = requests . post ( "{}/1.1/oauth/token" . format ( API_URL ) , data = { "client_id" : self . client_id , "client_secret" : self . client_secret , "grant_type" : "client_credentials" } ) . json ( ) if "error" in resp : raise APIError ( "LibCal Auth Failed: {}, {}" . format ( resp [ "error" ] , resp . get ( "error_description" ) ) ) self . expiration = datetime . datetime . now ( ) + datetime . timedelta ( seconds = resp [ "expires_in" ] ) self . token = resp [ "access_token" ] print ( self . token )
8,316
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L30-L48
[ "def", "reindex_multifiles", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Reindexing Multifiles ...\"", ")", "brains", "=", "api", ".", "search", "(", "dict", "(", "portal_type", "=", "\"Multifile\"", ")", ",", "\"bika_setup_catalog\"", ")", "total", "=", "len", "(", "brains", ")", "for", "num", ",", "brain", "in", "enumerate", "(", "brains", ")", ":", "if", "num", "%", "100", "==", "0", ":", "logger", ".", "info", "(", "\"Reindexing Multifile: {0}/{1}\"", ".", "format", "(", "num", ",", "total", ")", ")", "obj", "=", "api", ".", "get_object", "(", "brain", ")", "obj", ".", "reindexObject", "(", ")" ]
Make a signed request to the libcal API .
def _request ( self , * args , * * kwargs ) : if not self . token : self . _obtain_token ( ) headers = { "Authorization" : "Bearer {}" . format ( self . token ) } # add authorization headers if "headers" in kwargs : kwargs [ "headers" ] . update ( headers ) else : kwargs [ "headers" ] = headers # add api site to url args = list ( args ) if not args [ 1 ] . startswith ( "http" ) : args [ 1 ] = "{}{}" . format ( API_URL , args [ 1 ] ) has_no_token = kwargs . get ( "no_token" ) if has_no_token : del kwargs [ "no_token" ] resp = requests . request ( * args , * * kwargs ) if resp . status_code == 401 and not has_no_token : self . _obtain_token ( ) kwargs [ "no_token" ] = True self . _request ( * args , * * kwargs ) return resp
8,317
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L50-L78
[ "def", "get_description_metadata", "(", "self", ")", ":", "metadata", "=", "dict", "(", "self", ".", "_mdata", "[", "'description'", "]", ")", "metadata", ".", "update", "(", "{", "'existing_string_values'", ":", "self", ".", "_my_map", "[", "'description'", "]", "[", "'text'", "]", "}", ")", "return", "Metadata", "(", "*", "*", "metadata", ")" ]
Returns a list of rooms and their availabilities grouped by category .
def get_rooms ( self , lid , start = None , end = None ) : range_str = "availability" if start : start_datetime = datetime . datetime . combine ( datetime . datetime . strptime ( start , "%Y-%m-%d" ) . date ( ) , datetime . datetime . min . time ( ) ) range_str += "=" + start if end and not start == end : range_str += "," + end else : start_datetime = None resp = self . _request ( "GET" , "/1.1/space/categories/{}" . format ( lid ) ) . json ( ) if "error" in resp : raise APIError ( resp [ "error" ] ) output = { "id" : lid , "categories" : [ ] } # if there aren't any rooms associated with this location, return if len ( resp ) < 1 : return output if "error" in resp [ 0 ] : raise APIError ( resp [ 0 ] [ "error" ] ) if "categories" not in resp [ 0 ] : return output categories = resp [ 0 ] [ "categories" ] id_to_category = { i [ "cid" ] : i [ "name" ] for i in categories } categories = "," . join ( [ str ( x [ "cid" ] ) for x in categories ] ) resp = self . _request ( "GET" , "/1.1/space/category/{}" . format ( categories ) ) for category in resp . json ( ) : cat_out = { "cid" : category [ "cid" ] , "name" : id_to_category [ category [ "cid" ] ] , "rooms" : [ ] } # ignore equipment categories if cat_out [ "name" ] . endswith ( "Equipment" ) : continue items = category [ "items" ] items = "," . join ( [ str ( x ) for x in items ] ) resp = self . _request ( "GET" , "/1.1/space/item/{}?{}" . format ( items , range_str ) ) for room in resp . json ( ) : if room [ "id" ] in ROOM_BLACKLIST : continue # prepend protocol to urls if "image" in room and room [ "image" ] : if not room [ "image" ] . startswith ( "http" ) : room [ "image" ] = "https:" + room [ "image" ] # convert html descriptions to text if "description" in room : description = room [ "description" ] . replace ( u'\xa0' , u' ' ) room [ "description" ] = BeautifulSoup ( description , "html.parser" ) . text . strip ( ) # remove extra fields if "formid" in room : del room [ "formid" ] # enforce date filter # API returns dates outside of the range, fix this manually if start_datetime : out_times = [ ] for time in room [ "availability" ] : parsed_start = datetime . datetime . strptime ( time [ "from" ] [ : - 6 ] , "%Y-%m-%dT%H:%M:%S" ) if parsed_start >= start_datetime : out_times . append ( time ) room [ "availability" ] = out_times cat_out [ "rooms" ] . append ( room ) if cat_out [ "rooms" ] : output [ "categories" ] . append ( cat_out ) return output
8,318
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L93-L167
[ "def", "GenerateFile", "(", "self", ",", "input_filename", "=", "None", ",", "output_filename", "=", "None", ")", ":", "if", "input_filename", "is", "None", ":", "input_filename", "=", "output_filename", "+", "\".in\"", "if", "output_filename", "[", "-", "3", ":", "]", "==", "\".in\"", ":", "output_filename", "=", "output_filename", "[", ":", "-", "3", "]", "logging", ".", "debug", "(", "\"Generating file %s from %s\"", ",", "output_filename", ",", "input_filename", ")", "with", "io", ".", "open", "(", "input_filename", ",", "\"r\"", ")", "as", "fd", ":", "data", "=", "fd", ".", "read", "(", ")", "with", "io", ".", "open", "(", "output_filename", ",", "\"w\"", ")", "as", "fd", ":", "fd", ".", "write", "(", "config", ".", "CONFIG", ".", "InterpolateValue", "(", "data", ",", "context", "=", "self", ".", "context", ")", ")" ]
Books a room given the required information .
def book_room ( self , item , start , end , fname , lname , email , nickname , custom = { } , test = False ) : data = { "start" : start , "fname" : fname , "lname" : lname , "email" : email , "nickname" : nickname , "bookings" : [ { "id" : item , "to" : end } ] , "test" : test } data . update ( custom ) resp = self . _request ( "POST" , "/1.1/space/reserve" , json = data ) out = resp . json ( ) if "errors" in out and "error" not in out : errors = out [ "errors" ] if isinstance ( errors , list ) : errors = " " . join ( errors ) out [ "error" ] = BeautifulSoup ( errors . replace ( "\n" , " " ) , "html.parser" ) . text . strip ( ) del out [ "errors" ] if "results" not in out : if "error" not in out : out [ "error" ] = None out [ "results" ] = True else : out [ "results" ] = False return out
8,319
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L169-L231
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "source_cache", "=", "self", ".", "get_source_cache", "(", ")", "# First, delete any related thumbnails.", "self", ".", "delete_thumbnails", "(", "source_cache", ")", "# Next, delete the source image.", "super", "(", "ThumbnailerFieldFile", ",", "self", ")", ".", "delete", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Finally, delete the source cache entry.", "if", "source_cache", "and", "source_cache", ".", "pk", "is", "not", "None", ":", "source_cache", ".", "delete", "(", ")" ]
Cancel a room given a booking id .
def cancel_room ( self , booking_id ) : resp = self . _request ( "POST" , "/1.1/space/cancel/{}" . format ( booking_id ) ) return resp . json ( )
8,320
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L233-L240
[ "def", "create_onvif_service", "(", "self", ",", "name", ",", "from_template", "=", "True", ",", "portType", "=", "None", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "xaddr", ",", "wsdl_file", "=", "self", ".", "get_definition", "(", "name", ")", "with", "self", ".", "services_lock", ":", "svt", "=", "self", ".", "services_template", ".", "get", "(", "name", ")", "# Has a template, clone from it. Faster.", "if", "svt", "and", "from_template", "and", "self", ".", "use_services_template", ".", "get", "(", "name", ")", ":", "service", "=", "ONVIFService", ".", "clone", "(", "svt", ",", "xaddr", ",", "self", ".", "user", ",", "self", ".", "passwd", ",", "wsdl_file", ",", "self", ".", "cache_location", ",", "self", ".", "cache_duration", ",", "self", ".", "encrypt", ",", "self", ".", "daemon", ",", "no_cache", "=", "self", ".", "no_cache", ",", "portType", "=", "portType", ",", "dt_diff", "=", "self", ".", "dt_diff", ")", "# No template, create new service from wsdl document.", "# A little time-comsuming", "else", ":", "service", "=", "ONVIFService", "(", "xaddr", ",", "self", ".", "user", ",", "self", ".", "passwd", ",", "wsdl_file", ",", "self", ".", "cache_location", ",", "self", ".", "cache_duration", ",", "self", ".", "encrypt", ",", "self", ".", "daemon", ",", "no_cache", "=", "self", ".", "no_cache", ",", "portType", "=", "portType", ",", "dt_diff", "=", "self", ".", "dt_diff", ")", "self", ".", "services", "[", "name", "]", "=", "service", "setattr", "(", "self", ",", "name", ",", "service", ")", "if", "not", "self", ".", "services_template", ".", "get", "(", "name", ")", ":", "self", ".", "services_template", "[", "name", "]", "=", "service", "return", "service" ]
Gets reservations for a given email .
def get_reservations ( self , email , date , timeout = None ) : try : resp = self . _request ( "GET" , "/1.1/space/bookings?email={}&date={}&limit=100" . format ( email , date ) , timeout = timeout ) except resp . exceptions . HTTPError as error : raise APIError ( "Server Error: {}" . format ( error ) ) except requests . exceptions . ConnectTimeout : raise APIError ( "Timeout Error" ) return resp . json ( )
8,321
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L242-L254
[ "def", "_set_cdn_access", "(", "self", ",", "container", ",", "public", ",", "ttl", "=", "None", ")", ":", "headers", "=", "{", "\"X-Cdn-Enabled\"", ":", "\"%s\"", "%", "public", "}", "if", "public", "and", "ttl", ":", "headers", "[", "\"X-Ttl\"", "]", "=", "ttl", "self", ".", "api", ".", "cdn_request", "(", "\"/%s\"", "%", "utils", ".", "get_name", "(", "container", ")", ",", "method", "=", "\"PUT\"", ",", "headers", "=", "headers", ")" ]
Gets booking information for a given list of booking ids .
def get_reservations_for_booking_ids ( self , booking_ids ) : try : resp = self . _request ( "GET" , "/1.1/space/booking/{}" . format ( booking_ids ) ) except resp . exceptions . HTTPError as error : raise APIError ( "Server Error: {}" . format ( error ) ) return resp . json ( )
8,322
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L256-L266
[ "def", "stop", "(", "name", ",", "kill", "=", "False", ",", "path", "=", "None", ",", "use_vt", "=", "None", ")", ":", "_ensure_exists", "(", "name", ",", "path", "=", "path", ")", "orig_state", "=", "state", "(", "name", ",", "path", "=", "path", ")", "if", "orig_state", "==", "'frozen'", "and", "not", "kill", ":", "# Gracefully stopping a frozen container is slower than unfreezing and", "# then stopping it (at least in my testing), so if we're not", "# force-stopping the container, unfreeze it first.", "unfreeze", "(", "name", ",", "path", "=", "path", ")", "cmd", "=", "'lxc-stop'", "if", "kill", ":", "cmd", "+=", "' -k'", "ret", "=", "_change_state", "(", "cmd", ",", "name", ",", "'stopped'", ",", "use_vt", "=", "use_vt", ",", "path", "=", "path", ")", "ret", "[", "'state'", "]", "[", "'old'", "]", "=", "orig_state", "return", "ret" ]
Gets room information for a given list of ids .
def get_room_info ( self , room_ids ) : try : resp = self . _request ( "GET" , "/1.1/space/item/{}" . format ( room_ids ) ) rooms = resp . json ( ) for room in rooms : if not room [ "image" ] . startswith ( "http" ) : room [ "image" ] = "https:" + room [ "image" ] if "description" in room : description = room [ "description" ] . replace ( u'\xa0' , u' ' ) room [ "description" ] = BeautifulSoup ( description , "html.parser" ) . text . strip ( ) except resp . exceptions . HTTPError as error : raise APIError ( "Server Error: {}" . format ( error ) ) return rooms
8,323
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L268-L286
[ "def", "create_search_index", "(", "self", ",", "index", ",", "schema", "=", "None", ",", "n_val", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "yz_wm_index", ":", "raise", "NotImplementedError", "(", "\"Search 2.0 administration is not \"", "\"supported for this version\"", ")", "url", "=", "self", ".", "search_index_path", "(", "index", ")", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "content_dict", "=", "dict", "(", ")", "if", "schema", ":", "content_dict", "[", "'schema'", "]", "=", "schema", "if", "n_val", ":", "content_dict", "[", "'n_val'", "]", "=", "n_val", "if", "timeout", ":", "content_dict", "[", "'timeout'", "]", "=", "timeout", "content", "=", "json", ".", "dumps", "(", "content_dict", ")", "# Run the request...", "status", ",", "_", ",", "_", "=", "self", ".", "_request", "(", "'PUT'", ",", "url", ",", "headers", ",", "content", ")", "if", "status", "!=", "204", ":", "raise", "RiakError", "(", "'Error setting Search 2.0 index.'", ")", "return", "True" ]
Reconstructs ancestral states for the given character on the given tree .
def reconstruct_ancestral_states ( tree , character , states , prediction_method = MPPA , model = F81 , params = None , avg_br_len = None , num_nodes = None , num_tips = None , force_joint = True ) : logging . getLogger ( 'pastml' ) . debug ( 'ACR settings for {}:\n\tMethod:\t{}{}.' . format ( character , prediction_method , '\n\tModel:\t{}' . format ( model ) if model and is_ml ( prediction_method ) else '' ) ) if COPY == prediction_method : return { CHARACTER : character , STATES : states , METHOD : prediction_method } if not num_nodes : num_nodes = sum ( 1 for _ in tree . traverse ( ) ) if not num_tips : num_tips = len ( tree ) if is_ml ( prediction_method ) : if avg_br_len is None : avg_br_len = np . mean ( n . dist for n in tree . traverse ( ) if n . dist ) freqs , sf , kappa = None , None , None if params is not None : freqs , sf , kappa = _parse_pastml_parameters ( params , states ) return ml_acr ( tree = tree , character = character , prediction_method = prediction_method , model = model , states = states , avg_br_len = avg_br_len , num_nodes = num_nodes , num_tips = num_tips , freqs = freqs , sf = sf , kappa = kappa , force_joint = force_joint ) if is_parsimonious ( prediction_method ) : return parsimonious_acr ( tree , character , prediction_method , states , num_nodes , num_tips ) raise ValueError ( 'Method {} is unknown, should be one of ML ({}), one of MP ({}) or {}' . format ( prediction_method , ', ' . join ( ML_METHODS ) , ', ' . join ( MP_METHODS ) , COPY ) )
8,324
https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/acr.py#L137-L197
[ "def", "verify_registration", "(", "request", ")", ":", "user", "=", "process_verify_registration_data", "(", "request", ".", "data", ")", "extra_data", "=", "None", "if", "registration_settings", ".", "REGISTER_VERIFICATION_AUTO_LOGIN", ":", "extra_data", "=", "perform_login", "(", "request", ",", "user", ")", "return", "get_ok_response", "(", "'User verified successfully'", ",", "extra_data", "=", "extra_data", ")" ]
Reconstructs ancestral states for the given tree and all the characters specified as columns of the given annotation dataframe .
def acr ( tree , df , prediction_method = MPPA , model = F81 , column2parameters = None , force_joint = True ) : for c in df . columns : df [ c ] = df [ c ] . apply ( lambda _ : '' if pd . isna ( _ ) else _ . encode ( 'ASCII' , 'replace' ) . decode ( ) ) columns = preannotate_tree ( df , tree ) name_tree ( tree ) collapse_zero_branches ( tree , features_to_be_merged = df . columns ) avg_br_len , num_nodes , num_tips = get_tree_stats ( tree ) logging . getLogger ( 'pastml' ) . debug ( '\n=============ACR===============================' ) column2parameters = column2parameters if column2parameters else { } def _work ( args ) : return reconstruct_ancestral_states ( * args , avg_br_len = avg_br_len , num_nodes = num_nodes , num_tips = num_tips , force_joint = force_joint ) prediction_methods = value2list ( len ( columns ) , prediction_method , MPPA ) models = value2list ( len ( columns ) , model , F81 ) def get_states ( method , model , column ) : df_states = [ _ for _ in df [ column ] . unique ( ) if pd . notnull ( _ ) and _ != '' ] if not is_ml ( method ) or model not in { HKY , JTT } : return np . sort ( df_states ) states = HKY_STATES if HKY == model else JTT_STATES if not set ( df_states ) & set ( states ) : raise ValueError ( 'The allowed states for model {} are {}, ' 'but your annotation file specifies {} as states in column {}.' . format ( model , ', ' . join ( states ) , ', ' . join ( df_states ) , column ) ) state_set = set ( states ) df [ column ] = df [ column ] . apply ( lambda _ : _ if _ in state_set else '' ) return states with ThreadPool ( ) as pool : acr_results = pool . map ( func = _work , iterable = ( ( tree , column , get_states ( method , model , column ) , method , model , column2parameters [ column ] if column in column2parameters else None ) for ( column , method , model ) in zip ( columns , prediction_methods , models ) ) ) result = [ ] for acr_res in acr_results : if isinstance ( acr_res , list ) : result . extend ( acr_res ) else : result . append ( acr_res ) return result
8,325
https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/acr.py#L200-L276
[ "def", "get_max_bitlen", "(", "self", ")", ":", "payload_max_bitlen", "=", "self", ".", "max_size", "*", "self", ".", "value_type", ".", "get_max_bitlen", "(", ")", "return", "{", "self", ".", "MODE_DYNAMIC", ":", "payload_max_bitlen", "+", "self", ".", "max_size", ".", "bit_length", "(", ")", ",", "self", ".", "MODE_STATIC", ":", "payload_max_bitlen", "}", "[", "self", ".", "mode", "]" ]
Compute correction factors for 2D rhizotron geometries following Weigand and Kemna 2017 Biogeosciences
def compute_correction_factors ( data , true_conductivity , elem_file , elec_file ) : settings = { 'rho' : 100 , 'pha' : 0 , 'elem' : 'elem.dat' , 'elec' : 'elec.dat' , '2D' : True , 'sink_node' : 100 , } K = geometric_factors . compute_K_numerical ( data , settings = settings ) data = geometric_factors . apply_K ( data , K ) data = fixK . fix_sign_with_K ( data ) frequency = 100 data_onef = data . query ( 'frequency == {}' . format ( frequency ) ) rho_measured = data_onef [ 'r' ] * data_onef [ 'k' ] rho_true = 1 / true_conductivity * 1e4 correction_factors = rho_true / rho_measured collection = np . hstack ( ( data_onef [ [ 'a' , 'b' , 'm' , 'n' ] ] . values , np . abs ( correction_factors ) [ : , np . newaxis ] ) ) return collection
8,326
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/eit_fzj_utils.py#L12-L62
[ "def", "should_audit", "(", "instance", ")", ":", "# do not audit any model listed in UNREGISTERED_CLASSES", "for", "unregistered_class", "in", "UNREGISTERED_CLASSES", ":", "if", "isinstance", "(", "instance", ",", "unregistered_class", ")", ":", "return", "False", "# only audit models listed in REGISTERED_CLASSES (if it's set)", "if", "len", "(", "REGISTERED_CLASSES", ")", ">", "0", ":", "for", "registered_class", "in", "REGISTERED_CLASSES", ":", "if", "isinstance", "(", "instance", ",", "registered_class", ")", ":", "break", "else", ":", "return", "False", "# all good", "return", "True" ]
Map the RDF format to the approproate suffix
def rdf_suffix ( fmt : str ) -> str : for k , v in SUFFIX_FORMAT_MAP . items ( ) : if fmt == v : return k return 'rdf'
8,327
https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/generate_shexj.py#L143-L148
[ "def", "from_parmed", "(", "cls", ",", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "st", "=", "parmed", ".", "load_file", "(", "path", ",", "structure", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", "box", "=", "kwargs", ".", "pop", "(", "'box'", ",", "getattr", "(", "st", ",", "'box'", ",", "None", ")", ")", "velocities", "=", "kwargs", ".", "pop", "(", "'velocities'", ",", "getattr", "(", "st", ",", "'velocities'", ",", "None", ")", ")", "positions", "=", "kwargs", ".", "pop", "(", "'positions'", ",", "getattr", "(", "st", ",", "'positions'", ",", "None", ")", ")", "return", "cls", "(", "master", "=", "st", ",", "topology", "=", "st", ".", "topology", ",", "positions", "=", "positions", ",", "box", "=", "box", ",", "velocities", "=", "velocities", ",", "path", "=", "path", ",", "*", "*", "kwargs", ")" ]
Export to unified data format used in pyGIMLi & BERT .
def export_bert ( data , electrodes , filename ) : # Check for multiple timesteps if has_multiple_timesteps ( data ) : for i , timestep in enumerate ( split_timesteps ( data ) ) : export_bert ( timestep , electrodes , filename . replace ( "." , "_%.3d." % i ) ) # TODO: Make ABMN consistent # index_full = ert.data.groupby(list("abmn")).groups.keys() # g = ert.data.groupby('timestep') # q = ert.data.pivot_table(values='r', index=list("abmn"), columns="timestep", dropna=True) # ert.data.reset_index(list("abmn")) f = open ( filename , 'w' ) f . write ( "%d\n" % len ( electrodes ) ) f . write ( "# " ) # Make temporary copies for renaming electrodes = electrodes . copy ( ) data = data . copy ( ) electrodes . columns = electrodes . columns . str . lower ( ) data . columns = data . columns . str . lower ( ) # Remove unnecessary columns and rename according to bert conventions # https://gitlab.com/resistivity-net/bert#the-unified-data-format cols_to_export = [ "a" , "b" , "m" , "n" , "u" , "i" , "r" , "rho_a" , "error" ] data . drop ( data . columns . difference ( cols_to_export ) , 1 , inplace = True ) data . rename ( columns = { "rho_a" : "rhoa" , "error" : "err" } , inplace = True ) for key in electrodes . keys ( ) : f . write ( "%s " % key ) f . write ( "\n" ) for row in electrodes . itertuples ( index = False ) : for val in row : f . write ( "%5.3f " % val ) f . write ( "\n" ) f . write ( "%d\n" % len ( data ) ) f . write ( "# " ) # Make sure that a, b, m, n are the first 4 columns columns = data . columns . tolist ( ) for c in "abmn" : columns . remove ( c ) columns = list ( "abmn" ) + columns data = data [ columns ] for key in data . keys ( ) : f . write ( "%s " % key ) f . write ( "\n" ) for row in data . itertuples ( index = False ) : for i , val in enumerate ( row ) : if i < 4 : f . write ( "%d " % val ) else : f . write ( "%E " % val ) f . write ( "\n" ) f . close ( )
8,328
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/exporters/bert.py#L4-L73
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_stopped", "=", "True", "for", "result", "in", "self", ".", "_results", ":", "result", ".", "_set_result", "(", "Failure", "(", "ReactorStopped", "(", ")", ")", ")" ]
Reset the points for the specified index position . If no index is specified reset points for all point handlers .
def reset ( self , index = None ) : points_handler_count = len ( self . registration_view . points ) if index is None : indexes = range ( points_handler_count ) else : indexes = [ index ] indexes = [ i for i in indexes if i < points_handler_count ] for i in indexes : self . registration_view . points [ i ] . reset ( ) if indexes : self . registration_view . update_transform ( )
8,329
https://github.com/cfobel/webcam-recorder/blob/ffeb57c9044033fbea6372b3e642b83fd42dea87/webcam_recorder/view.py#L102-L118
[ "def", "_compare_acl", "(", "current", ",", "desired", ",", "region", ",", "key", ",", "keyid", ",", "profile", ")", ":", "ocid", "=", "_get_canonical_id", "(", "region", ",", "key", ",", "keyid", ",", "profile", ")", "return", "__utils__", "[", "'boto3.json_objs_equal'", "]", "(", "current", ",", "_acl_to_grant", "(", "desired", ",", "ocid", ")", ")" ]
Read a res2dinv - file and return the header
def _read_file ( filename ) : # read data with open ( filename , 'r' ) as fid2 : abem_data_orig = fid2 . read ( ) fid = StringIO ( ) fid . write ( abem_data_orig ) fid . seek ( 0 ) # determine type of array fid . readline ( ) fid . readline ( ) file_type = int ( fid . readline ( ) . strip ( ) ) # reset file pointer fid . seek ( 0 ) return file_type , fid
8,330
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/res2dinv.py#L15-L46
[ "def", "create", "(", "self", ",", "path", ")", ":", "path", "=", "self", ".", "_sanitize_path", "(", "path", ")", "hive", ",", "subpath", "=", "self", ".", "_parse_path", "(", "path", ")", "handle", "=", "win32", ".", "RegCreateKey", "(", "hive", ",", "subpath", ")", "return", "RegistryKey", "(", "path", ",", "handle", ")" ]
Read a RES2DINV - style file produced by the ABEM export program .
def add_dat_file ( filename , settings , container = None , * * kwargs ) : # each type is read by a different function importers = { # general array type 11 : _read_general_type , } file_type , content = _read_file ( filename ) if file_type not in importers : raise Exception ( 'type of RES2DINV data file not recognized: {0}' . format ( file_type ) ) header , data = importers [ file_type ] ( content , settings ) timestep = settings . get ( 'timestep' , 0 ) # add timestep column data [ 'timestep' ] = timestep if container is None : container = ERT ( data ) else : container . data = pd . concat ( ( container . data , data ) ) return container
8,331
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/res2dinv.py#L142-L170
[ "def", "add", "(", "self", ",", "watch_key", ",", "tensor_value", ")", ":", "if", "watch_key", "not", "in", "self", ".", "_tensor_data", ":", "self", ".", "_tensor_data", "[", "watch_key", "]", "=", "_WatchStore", "(", "watch_key", ",", "mem_bytes_limit", "=", "self", ".", "_watch_mem_bytes_limit", ")", "self", ".", "_tensor_data", "[", "watch_key", "]", ".", "add", "(", "tensor_value", ")" ]
Get user input value from stdin
def console_input ( default , validation = None , allow_empty = False ) : value = raw_input ( "> " ) or default if value == "" and not allow_empty : print "Invalid: Empty value is not permitted." return console_input ( default , validation ) if validation : try : return validation ( value ) except ValidationError , e : print "Invalid: " , e return console_input ( default , validation ) return value
8,332
https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/wizard.py#L22-L49
[ "def", "json_engine", "(", "self", ",", "req", ")", ":", "# pylint: disable=R0201,W0613", "try", ":", "return", "stats", ".", "engine_data", "(", "config", ".", "engine", ")", "except", "(", "error", ".", "LoggableError", ",", "xmlrpc", ".", "ERRORS", ")", "as", "torrent_exc", ":", "raise", "exc", ".", "HTTPInternalServerError", "(", "str", "(", "torrent_exc", ")", ")" ]
Compute weC from weT aeT
def correct ( self , calib , temp , we_t , ae_t ) : if not A4TempComp . in_range ( temp ) : return None if self . __algorithm == 1 : return self . __eq1 ( temp , we_t , ae_t ) if self . __algorithm == 2 : return self . __eq2 ( temp , we_t , ae_t , calib . we_cal_mv , calib . ae_cal_mv ) if self . __algorithm == 3 : return self . __eq3 ( temp , we_t , ae_t , calib . we_cal_mv , calib . ae_cal_mv ) if self . __algorithm == 4 : return self . __eq4 ( temp , we_t , calib . we_cal_mv ) raise ValueError ( "A4TempComp.conv: unrecognised algorithm: %d." % self . __algorithm )
8,333
https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/a4_temp_comp.py#L82-L101
[ "def", "connection", "(", "cls", ")", ":", "local", "=", "cls", ".", "_threadlocal", "if", "not", "getattr", "(", "local", ",", "'connection'", ",", "None", ")", ":", "# Make sure these variables are no longer affected by other threads.", "local", ".", "user", "=", "cls", ".", "user", "local", ".", "password", "=", "cls", ".", "password", "local", ".", "site", "=", "cls", ".", "site", "local", ".", "timeout", "=", "cls", ".", "timeout", "local", ".", "headers", "=", "cls", ".", "headers", "local", ".", "format", "=", "cls", ".", "format", "local", ".", "version", "=", "cls", ".", "version", "local", ".", "url", "=", "cls", ".", "url", "if", "cls", ".", "site", "is", "None", ":", "raise", "ValueError", "(", "\"No shopify session is active\"", ")", "local", ".", "connection", "=", "ShopifyConnection", "(", "cls", ".", "site", ",", "cls", ".", "user", ",", "cls", ".", "password", ",", "cls", ".", "timeout", ",", "cls", ".", "format", ")", "return", "local", ".", "connection" ]
Compute the linear - interpolated temperature compensation factor .
def cf_t ( self , temp ) : index = int ( ( temp - A4TempComp . __MIN_TEMP ) // A4TempComp . __INTERVAL ) # index of start of interval # on boundary... if temp % A4TempComp . __INTERVAL == 0 : return self . __values [ index ] # all others... y1 = self . __values [ index ] # y value at start of interval y2 = self . __values [ index + 1 ] # y value at end of interval delta_y = y2 - y1 delta_x = float ( temp % A4TempComp . __INTERVAL ) / A4TempComp . __INTERVAL # proportion of interval cf_t = y1 + ( delta_y * delta_x ) # print("A4TempComp.cf_t: alg:%d, temp:%f y1:%f y2:%f delta_y:%f delta_x:%f cf_t:%f " % # (self.__algorithm, temp, y1, y2, delta_y, delta_x, cf_t), file=sys.stderr) return cf_t
8,334
https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/a4_temp_comp.py#L152-L175
[ "def", "do_opt", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "if", "not", "args", ":", "largest", "=", "0", "keys", "=", "[", "key", "for", "key", "in", "self", ".", "conf", "if", "not", "key", ".", "startswith", "(", "\"_\"", ")", "]", "for", "key", "in", "keys", ":", "largest", "=", "max", "(", "largest", ",", "len", "(", "key", ")", ")", "for", "key", "in", "keys", ":", "print", "(", "\"%s : %s\"", "%", "(", "key", ".", "rjust", "(", "largest", ")", ",", "self", ".", "conf", "[", "key", "]", ")", ")", "return", "option", "=", "args", ".", "pop", "(", "0", ")", "if", "not", "args", "and", "not", "kwargs", ":", "method", "=", "getattr", "(", "self", ",", "\"getopt_\"", "+", "option", ",", "None", ")", "if", "method", "is", "None", ":", "self", ".", "getopt_default", "(", "option", ")", "else", ":", "method", "(", ")", "else", ":", "method", "=", "getattr", "(", "self", ",", "\"opt_\"", "+", "option", ",", "None", ")", "if", "method", "is", "None", ":", "print", "(", "\"Unrecognized option %r\"", "%", "option", ")", "else", ":", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "save_config", "(", ")" ]
A memoization decorator whose purpose is to cache calls .
def run_once ( function , state = { } , errors = { } ) : @ six . wraps ( function ) def _wrapper ( * args , * * kwargs ) : if function in errors : # Deliberate use of LBYL. six . reraise ( * errors [ function ] ) try : return state [ function ] except KeyError : try : state [ function ] = result = function ( * args , * * kwargs ) return result except Exception : errors [ function ] = sys . exc_info ( ) raise return _wrapper
8,335
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/utils.py#L187-L204
[ "def", "find_stream", "(", "cls", ",", "fileobj", ",", "max_bytes", ")", ":", "r", "=", "BitReader", "(", "fileobj", ")", "stream", "=", "cls", "(", "r", ")", "if", "stream", ".", "sync", "(", "max_bytes", ")", ":", "stream", ".", "offset", "=", "(", "r", ".", "get_position", "(", ")", "-", "12", ")", "//", "8", "return", "stream" ]
The current session used by the client .
def _session ( self ) : if self . _http_session is None : self . _http_session = requests . Session ( ) self . _http_session . headers . update ( self . _get_headers ( ) ) self . _http_session . verify = self . _verify_https_request ( ) if all ( self . _credentials ) : username , password = self . _credentials self . _http_session . auth = requests_ntlm . HttpNtlmAuth ( username = username , password = password ) return self . _http_session
8,336
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/utils.py#L59-L79
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "BaseTagDetail", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", "[", "'tag'", "]", "=", "self", ".", "tag", "return", "context" ]
Getting the required information from the API .
def get_resource ( self , path ) : response = self . _http_request ( path ) try : return response . json ( ) except ValueError : raise exception . ServiceException ( "Invalid service response." )
8,337
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/utils.py#L164-L170
[ "def", "n_weekends", "(", "self", ")", "->", "int", ":", "startdate", "=", "self", ".", "start", ".", "date", "(", ")", "enddate", "=", "self", ".", "end", ".", "date", "(", ")", "ndays", "=", "(", "enddate", "-", "startdate", ")", ".", "days", "+", "1", "in_weekend", "=", "False", "n_weekends", "=", "0", "for", "i", "in", "range", "(", "ndays", ")", ":", "date", "=", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "i", ")", "if", "not", "in_weekend", "and", "is_weekend", "(", "date", ")", ":", "in_weekend", "=", "True", "n_weekends", "+=", "1", "elif", "in_weekend", "and", "not", "is_weekend", "(", "date", ")", ":", "in_weekend", "=", "False", "return", "n_weekends" ]
Update the required resource .
def update_resource ( self , path , data , if_match = None ) : response = self . _http_request ( resource = path , method = "PUT" , body = data , if_match = if_match ) try : return response . json ( ) except ValueError : raise exception . ServiceException ( "Invalid service response." )
8,338
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/utils.py#L172-L179
[ "def", "setMaxDaysBack", "(", "self", ",", "maxDaysBack", ")", ":", "assert", "isinstance", "(", "maxDaysBack", ",", "int", ")", ",", "\"maxDaysBack value has to be a positive integer\"", "assert", "maxDaysBack", ">=", "1", "self", ".", "topicPage", "[", "\"maxDaysBack\"", "]", "=", "maxDaysBack" ]
Convert all of the values to their max values . This form is used to represent the summary level
def summarize ( self ) : s = str ( self . allval ( ) ) return self . parse ( s [ : 2 ] + '' . join ( [ 'Z' ] * len ( s [ 2 : ] ) ) )
8,339
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/civick.py#L41-L46
[ "def", "get_broker_id", "(", "data_path", ")", ":", "# Path to the meta.properties file. This is used to read the automatic broker id", "# if the given broker id is -1", "META_FILE_PATH", "=", "\"{data_path}/meta.properties\"", "if", "not", "data_path", ":", "raise", "ValueError", "(", "\"You need to specify the data_path if broker_id == -1\"", ")", "meta_properties_path", "=", "META_FILE_PATH", ".", "format", "(", "data_path", "=", "data_path", ")", "return", "_read_generated_broker_id", "(", "meta_properties_path", ")" ]
Filter Schlumberger configurations
def _filter_schlumberger ( configs ) : # sort configs configs_sorted = np . hstack ( ( np . sort ( configs [ : , 0 : 2 ] , axis = 1 ) , np . sort ( configs [ : , 2 : 4 ] , axis = 1 ) , ) ) . astype ( int ) # determine unique voltage dipoles MN = configs_sorted [ : , 2 : 4 ] . copy ( ) MN_unique = np . unique ( MN . view ( MN . dtype . descr * 2 ) ) MN_unique_reshape = MN_unique . view ( MN . dtype ) . reshape ( - 1 , 2 ) schl_indices_list = [ ] for mn in MN_unique_reshape : # check if there are more than one associated current injections nr_current_binary = ( ( configs_sorted [ : , 2 ] == mn [ 0 ] ) & ( configs_sorted [ : , 3 ] == mn [ 1 ] ) ) if len ( np . where ( nr_current_binary ) [ 0 ] ) < 2 : continue # now which of these configurations have current electrodes on both # sides of the voltage dipole nr_left_right = ( ( configs_sorted [ : , 0 ] < mn [ 0 ] ) & ( configs_sorted [ : , 1 ] > mn [ 0 ] ) & nr_current_binary ) # now check that the left/right distances are equal distance_left = np . abs ( configs_sorted [ nr_left_right , 0 ] - mn [ 0 ] ) . squeeze ( ) distance_right = np . abs ( configs_sorted [ nr_left_right , 1 ] - mn [ 1 ] ) . squeeze ( ) nr_equal_distances = np . where ( distance_left == distance_right ) [ 0 ] indices = np . where ( nr_left_right ) [ 0 ] [ nr_equal_distances ] if indices . size > 2 : schl_indices_list . append ( indices ) # set Schlumberger configs to nan if len ( schl_indices_list ) == 0 : return configs , { 0 : np . array ( [ ] ) } else : schl_indices = np . hstack ( schl_indices_list ) . squeeze ( ) configs [ schl_indices , : ] = np . nan return configs , { 0 : schl_indices }
8,340
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/filter_config_types.py#L17-L97
[ "def", "experimental", "(", "message", ")", ":", "def", "f__", "(", "f", ")", ":", "def", "f_", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "message", ",", "category", "=", "ExperimentalWarning", ",", "stacklevel", "=", "2", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "f_", ".", "__name__", "=", "f", ".", "__name__", "f_", ".", "__doc__", "=", "f", ".", "__doc__", "f_", ".", "__dict__", ".", "update", "(", "f", ".", "__dict__", ")", "return", "f_", "return", "f__" ]
Filter dipole - dipole configurations
def _filter_dipole_dipole ( configs ) : # check that dipoles have equal size dist_ab = np . abs ( configs [ : , 0 ] - configs [ : , 1 ] ) dist_mn = np . abs ( configs [ : , 2 ] - configs [ : , 3 ] ) distances_equal = ( dist_ab == dist_mn ) # check that they are not overlapping not_overlapping = ( # either a,b < m,n ( ( configs [ : , 0 ] < configs [ : , 2 ] ) & ( configs [ : , 1 ] < configs [ : , 2 ] ) & ( configs [ : , 0 ] < configs [ : , 3 ] ) & ( configs [ : , 1 ] < configs [ : , 3 ] ) ) | # or m,n < a,b ( ( configs [ : , 2 ] < configs [ : , 0 ] ) & ( configs [ : , 3 ] < configs [ : , 0 ] ) & ( configs [ : , 2 ] < configs [ : , 1 ] ) & ( configs [ : , 3 ] < configs [ : , 1 ] ) ) ) is_dipole_dipole = ( distances_equal & not_overlapping ) dd_indices = np . where ( is_dipole_dipole ) [ 0 ] dd_indices_sorted = _sort_dd_skips ( configs [ dd_indices , : ] , dd_indices ) # set all dd configs to nan configs [ dd_indices , : ] = np . nan return configs , dd_indices_sorted
8,341
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/filter_config_types.py#L100-L155
[ "def", "_adapt_WSDateTime", "(", "dt", ")", ":", "try", ":", "ts", "=", "int", "(", "(", "dt", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", "-", "datetime", "(", "1970", ",", "1", ",", "1", ",", "tzinfo", "=", "pytz", ".", "utc", ")", ")", ".", "total_seconds", "(", ")", ")", "except", "(", "OverflowError", ",", "OSError", ")", ":", "if", "dt", "<", "datetime", ".", "now", "(", ")", ":", "ts", "=", "0", "else", ":", "ts", "=", "2", "**", "63", "-", "1", "return", "ts" ]
Given a set of dipole - dipole configurations sort them according to their current skip .
def _sort_dd_skips ( configs , dd_indices_all ) : config_current_skips = np . abs ( configs [ : , 1 ] - configs [ : , 0 ] ) if np . all ( np . isnan ( config_current_skips ) ) : return { 0 : [ ] } # determine skips available_skips_raw = np . unique ( config_current_skips ) available_skips = available_skips_raw [ ~ np . isnan ( available_skips_raw ) ] . astype ( int ) # now determine the configurations dd_configs_sorted = { } for skip in available_skips : indices = np . where ( config_current_skips == skip ) [ 0 ] dd_configs_sorted [ skip - 1 ] = dd_indices_all [ indices ] return dd_configs_sorted
8,342
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/filter_config_types.py#L158-L189
[ "def", "_set_final_freeness", "(", "self", ",", "flag", ")", ":", "if", "flag", ":", "self", ".", "state", ".", "memory", ".", "store", "(", "self", ".", "heap_base", "+", "self", ".", "heap_size", "-", "self", ".", "_chunk_size_t_size", ",", "~", "CHUNK_P_MASK", ")", "else", ":", "self", ".", "state", ".", "memory", ".", "store", "(", "self", ".", "heap_base", "+", "self", ".", "heap_size", "-", "self", ".", "_chunk_size_t_size", ",", "CHUNK_P_MASK", ")" ]
Main entry function to filtering configuration types
def filter ( configs , settings ) : if isinstance ( configs , pd . DataFrame ) : configs = configs [ [ 'a' , 'b' , 'm' , 'n' ] ] . values # assign short labels to Python functions filter_funcs = { 'dd' : _filter_dipole_dipole , 'schlumberger' : _filter_schlumberger , } # we need a list to fix the call order of filter functions keys = [ 'dd' , 'schlumberger' , ] allowed_keys = settings . get ( 'only_types' , filter_funcs . keys ( ) ) results = { } # we operate iteratively on the configs, set the first round here # rows are iteratively set to nan when filters remove them! configs_filtered = configs . copy ( ) . astype ( float ) for key in keys : if key in allowed_keys : configs_filtered , indices_filtered = filter_funcs [ key ] ( configs_filtered , ) if len ( indices_filtered ) > 0 : results [ key ] = indices_filtered # add all remaining indices to the results dict results [ 'not_sorted' ] = np . where ( ~ np . all ( np . isnan ( configs_filtered ) , axis = 1 ) ) [ 0 ] return results
8,343
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/filter_config_types.py#L192-L241
[ "def", "dicom_diff", "(", "file1", ",", "file2", ")", ":", "datasets", "=", "compressed_dicom", ".", "read_file", "(", "file1", ")", ",", "compressed_dicom", ".", "read_file", "(", "file2", ")", "rep", "=", "[", "]", "for", "dataset", "in", "datasets", ":", "lines", "=", "(", "str", "(", "dataset", ".", "file_meta", ")", "+", "\"\\n\"", "+", "str", "(", "dataset", ")", ")", ".", "split", "(", "'\\n'", ")", "lines", "=", "[", "line", "+", "'\\n'", "for", "line", "in", "lines", "]", "# add the newline to the end", "rep", ".", "append", "(", "lines", ")", "diff", "=", "difflib", ".", "Differ", "(", ")", "for", "line", "in", "diff", ".", "compare", "(", "rep", "[", "0", "]", ",", "rep", "[", "1", "]", ")", ":", "if", "(", "line", "[", "0", "]", "==", "'+'", ")", "or", "(", "line", "[", "0", "]", "==", "'-'", ")", ":", "sys", ".", "stdout", ".", "write", "(", "line", ")" ]
Save a dataset to a CRTomo - compatible . crt file
def save_block_to_crt ( filename , group , norrec = 'all' , store_errors = False ) : if norrec != 'all' : group = group . query ( 'norrec == "{0}"' . format ( norrec ) ) # todo: we need to fix the global naming scheme for columns! with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( len ( group ) ) , 'UTF-8' ) ) AB = group [ 'a' ] * 1e4 + group [ 'b' ] MN = group [ 'm' ] * 1e4 + group [ 'n' ] line = [ AB . values . astype ( int ) , MN . values . astype ( int ) , group [ 'r' ] . values , ] if 'rpha' in group : line . append ( group [ 'rpha' ] . values ) else : line . append ( group [ 'r' ] . values * 0.0 ) fmt = '%i %i %f %f' if store_errors : line += ( group [ 'd|Z|_[Ohm]' ] . values , group [ 'dphi_[mrad]' ] . values , ) fmt += ' %f %f' subdata = np . array ( line ) . T np . savetxt ( fid , subdata , fmt = fmt )
8,344
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/exporters/crtomo.py#L7-L53
[ "def", "wait_until_invisibility_of", "(", "self", ",", "locator", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "element", "=", "WebDriverWait", "(", "self", ".", "driver", ",", "timeout", ")", ".", "until", "(", "EC", ".", "invisibility_of_element_located", "(", "(", "self", ".", "locator_handler", ".", "parse_locator", "(", "locator", ")", ".", "By", ",", "self", ".", "locator_handler", ".", "parse_locator", "(", "locator", ")", ".", "value", ")", ")", ")", "return", "WebElementWrapper", ".", "WebElementWrapper", "(", "self", ",", "locator", ",", "element", ")", "return", "self", ".", "execute_and_handle_webdriver_exceptions", "(", "wait", ",", "timeout", ",", "locator", ",", "'Timeout waiting for element to be invisible'", ")" ]
Return the label of a given SIP parameter
def get_label ( parameter , ptype , flavor = None , mpl = None ) : # determine flavor if flavor is not None : if flavor not in ( 'latex' , 'mathml' ) : raise Exception ( 'flavor not recognized: {}' . format ( flavor ) ) else : if mpl is None : raise Exception ( 'either the flavor or mpl must be provided' ) rendering = mpl . rcParams [ 'text.usetex' ] if rendering : flavor = 'latex' else : flavor = 'mathml' # check if the requested label is present if parameter not in labels : raise Exception ( 'parameter not known' ) if ptype not in labels [ parameter ] : raise Exception ( 'ptype not known' ) if flavor not in labels [ parameter ] [ ptype ] : raise Exception ( 'flavor not known' ) return labels [ parameter ] [ ptype ] [ flavor ]
8,345
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/units.py#L47-L90
[ "def", "share", "(", "self", ",", "group_id", ",", "group_access", ",", "expires_at", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'/projects/%s/share'", "%", "self", ".", "get_id", "(", ")", "data", "=", "{", "'group_id'", ":", "group_id", ",", "'group_access'", ":", "group_access", ",", "'expires_at'", ":", "expires_at", "}", "self", ".", "manager", ".", "gitlab", ".", "http_post", "(", "path", ",", "post_data", "=", "data", ",", "*", "*", "kwargs", ")" ]
Given a 2x2 array of axes add x and y labels
def _add_labels ( self , axes , dtype ) : for ax in axes [ 1 , : ] . flat : ax . set_xlabel ( 'frequency [Hz]' ) if dtype == 'rho' : axes [ 0 , 0 ] . set_ylabel ( r'$|\rho| [\Omega m]$' ) axes [ 0 , 1 ] . set_ylabel ( r'$-\phi [mrad]$' ) axes [ 1 , 0 ] . set_ylabel ( r"$\sigma' [S/m]$" ) axes [ 1 , 1 ] . set_ylabel ( r"$\sigma'' [S/m]$" ) elif dtype == 'r' : axes [ 0 , 0 ] . set_ylabel ( r'$|R| [\Omega]$' ) axes [ 0 , 1 ] . set_ylabel ( r'$-\phi [mrad]$' ) axes [ 1 , 0 ] . set_ylabel ( r"$Y' [S]$" ) axes [ 1 , 1 ] . set_ylabel ( r"$Y'' [S]$" ) else : raise Exception ( 'dtype not known: {}' . format ( dtype ) )
8,346
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/plots.py#L78-L108
[ "def", "shutdown", "(", "self", ")", ":", "vm", "=", "self", ".", "get_vm_failfast", "(", "self", ".", "config", "[", "'name'", "]", ")", "if", "vm", ".", "runtime", ".", "powerState", "==", "vim", ".", "VirtualMachinePowerState", ".", "poweredOff", ":", "print", "(", "\"%s already poweredOff\"", "%", "vm", ".", "name", ")", "else", ":", "if", "self", ".", "guestToolsRunning", "(", "vm", ")", ":", "timeout_minutes", "=", "10", "print", "(", "\"waiting for %s to shutdown \"", "\"(%s minutes before forced powerOff)\"", "%", "(", "vm", ".", "name", ",", "str", "(", "timeout_minutes", ")", ")", ")", "vm", ".", "ShutdownGuest", "(", ")", "if", "self", ".", "WaitForVirtualMachineShutdown", "(", "vm", ",", "timeout_minutes", "*", "60", ")", ":", "print", "(", "\"shutdown complete\"", ")", "print", "(", "\"%s poweredOff\"", "%", "vm", ".", "name", ")", "else", ":", "print", "(", "\"%s has not shutdown after %s minutes:\"", "\"will powerOff\"", "%", "(", "vm", ".", "name", ",", "str", "(", "timeout_minutes", ")", ")", ")", "self", ".", "powerOff", "(", ")", "else", ":", "print", "(", "\"GuestTools not running or not installed: will powerOff\"", ")", "self", ".", "powerOff", "(", ")" ]
add one response object to the list
def add ( self , response , label = None ) : if not isinstance ( response , sip_response . sip_response ) : raise Exception ( 'can only add sip_reponse.sip_response objects' ) self . objects . append ( response ) if label is None : self . labels . append ( 'na' ) else : self . labels . append ( label )
8,347
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/plots.py#L358-L370
[ "def", "__create_checksum", "(", "self", ",", "p", ")", ":", "l", "=", "len", "(", "p", ")", "checksum", "=", "0", "while", "l", ">", "1", ":", "checksum", "+=", "unpack", "(", "'H'", ",", "pack", "(", "'BB'", ",", "p", "[", "0", "]", ",", "p", "[", "1", "]", ")", ")", "[", "0", "]", "p", "=", "p", "[", "2", ":", "]", "if", "checksum", ">", "const", ".", "USHRT_MAX", ":", "checksum", "-=", "const", ".", "USHRT_MAX", "l", "-=", "2", "if", "l", ":", "checksum", "=", "checksum", "+", "p", "[", "-", "1", "]", "while", "checksum", ">", "const", ".", "USHRT_MAX", ":", "checksum", "-=", "const", ".", "USHRT_MAX", "checksum", "=", "~", "checksum", "while", "checksum", "<", "0", ":", "checksum", "+=", "const", ".", "USHRT_MAX", "return", "pack", "(", "'H'", ",", "checksum", ")" ]
Split 1D or 2D into two parts using the last axis
def split_data ( data , squeeze = False ) : vdata = np . atleast_2d ( data ) nr_freqs = int ( vdata . shape [ 1 ] / 2 ) part1 = vdata [ : , 0 : nr_freqs ] part2 = vdata [ : , nr_freqs : ] if ( squeeze ) : part1 = part1 . squeeze ( ) part2 = part2 . squeeze ( ) return part1 , part2
8,348
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/convert.py#L14-L30
[ "def", "main", "(", "args", ")", ":", "print_in_box", "(", "'Validating submission '", "+", "args", ".", "submission_filename", ")", "random", ".", "seed", "(", ")", "temp_dir", "=", "args", ".", "temp_dir", "delete_temp_dir", "=", "False", "if", "not", "temp_dir", ":", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "logging", ".", "info", "(", "'Created temporary directory: %s'", ",", "temp_dir", ")", "delete_temp_dir", "=", "True", "validator", "=", "submission_validator_lib", ".", "SubmissionValidator", "(", "temp_dir", ",", "args", ".", "use_gpu", ")", "if", "validator", ".", "validate_submission", "(", "args", ".", "submission_filename", ",", "args", ".", "submission_type", ")", ":", "print_in_box", "(", "'Submission is VALID!'", ")", "else", ":", "print_in_box", "(", "'Submission is INVALID, see log messages for details'", ")", "if", "delete_temp_dir", ":", "logging", ".", "info", "(", "'Deleting temporary directory: %s'", ",", "temp_dir", ")", "subprocess", ".", "call", "(", "[", "'rm'", ",", "'-rf'", ",", "temp_dir", "]", ")" ]
Convert from the given format to the requested format
def convert ( input_format , output_format , data , one_spectrum = False ) : if input_format == output_format : return data if input_format not in from_converters : raise KeyError ( 'Input format {0} not known!' . format ( input_format ) ) if output_format not in to_converters : raise KeyError ( 'Output format {0} not known!' . format ( output_format ) ) # internally we always work with the second axis of double the frequency # size if len ( data . shape ) == 2 and data . shape [ 0 ] == 2 and one_spectrum : work_data = np . hstack ( ( data [ 0 , : ] , data [ 1 , : ] ) ) one_spec_2d = True else : work_data = data one_spec_2d = False cre , cim = from_converters [ input_format ] ( work_data ) converted_data = to_converters [ output_format ] ( cre , cim ) if one_spec_2d : part1 , part2 = split_data ( converted_data , True ) converted_data = np . vstack ( ( part1 , part2 ) ) # reshape to input size (this should only be necessary for 1D data) if len ( data . shape ) == 1 : converted_data = np . squeeze ( converted_data ) return converted_data
8,349
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/convert.py#L233-L311
[ "def", "grpc_fork_support_disabled", "(", ")", ":", "if", "LooseVersion", "(", "GRPC_VERSION", ")", "<", "'1.18.0'", ":", "key", "=", "'GRPC_ENABLE_FORK_SUPPORT'", "try", ":", "os", ".", "environ", "[", "key", "]", "=", "'0'", "yield", "finally", ":", "del", "os", ".", "environ", "[", "key", "]", "else", ":", "yield" ]
Get a list of person objects for the given search params .
def search ( self , params , standardize = False ) : resp = self . _request ( ENDPOINTS [ 'SEARCH' ] , params ) if not standardize : return resp # Standardization logic for res in resp [ 'result_data' ] : res = self . standardize ( res ) return resp
8,350
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/directory.py#L41-L58
[ "def", "from_http", "(", "cls", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ")", "->", "Optional", "[", "\"RateLimit\"", "]", ":", "try", ":", "limit", "=", "int", "(", "headers", "[", "\"x-ratelimit-limit\"", "]", ")", "remaining", "=", "int", "(", "headers", "[", "\"x-ratelimit-remaining\"", "]", ")", "reset_epoch", "=", "float", "(", "headers", "[", "\"x-ratelimit-reset\"", "]", ")", "except", "KeyError", ":", "return", "None", "else", ":", "return", "cls", "(", "limit", "=", "limit", ",", "remaining", "=", "remaining", ",", "reset_epoch", "=", "reset_epoch", ")" ]
Get a detailed list of person objects for the given search params .
def detail_search ( self , params , standardize = False ) : response = self . _request ( ENDPOINTS [ 'SEARCH' ] , params ) result_data = [ ] for person in response [ 'result_data' ] : try : detail = self . person_details ( person [ 'person_id' ] , standardize = standardize ) except ValueError : pass else : result_data . append ( detail ) response [ 'result_data' ] = result_data return response
8,351
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/directory.py#L60-L81
[ "def", "from_http", "(", "cls", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ")", "->", "Optional", "[", "\"RateLimit\"", "]", ":", "try", ":", "limit", "=", "int", "(", "headers", "[", "\"x-ratelimit-limit\"", "]", ")", "remaining", "=", "int", "(", "headers", "[", "\"x-ratelimit-remaining\"", "]", ")", "reset_epoch", "=", "float", "(", "headers", "[", "\"x-ratelimit-reset\"", "]", ")", "except", "KeyError", ":", "return", "None", "else", ":", "return", "cls", "(", "limit", "=", "limit", ",", "remaining", "=", "remaining", ",", "reset_epoch", "=", "reset_epoch", ")" ]
Get a detailed person object
def person_details ( self , person_id , standardize = False ) : resp = self . _request ( path . join ( ENDPOINTS [ 'DETAILS' ] , person_id ) ) if standardize : resp [ 'result_data' ] = [ self . standardize ( res ) for res in resp [ 'result_data' ] ] return resp
8,352
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/directory.py#L83-L94
[ "def", "update_sandbox_product", "(", "self", ",", "product_id", ",", "surge_multiplier", "=", "None", ",", "drivers_available", "=", "None", ",", ")", ":", "args", "=", "{", "'surge_multiplier'", ":", "surge_multiplier", ",", "'drivers_available'", ":", "drivers_available", ",", "}", "endpoint", "=", "'v1.2/sandbox/products/{}'", ".", "format", "(", "product_id", ")", "return", "self", ".", "_api_call", "(", "'PUT'", ",", "endpoint", ",", "args", "=", "args", ")" ]
Create grouped pseudoplots for one or more time steps
def plot_ps_extra ( dataobj , key , * * kwargs ) : if isinstance ( dataobj , pd . DataFrame ) : df_raw = dataobj else : df_raw = dataobj . data if kwargs . get ( 'subquery' , False ) : df = df_raw . query ( kwargs . get ( 'subquery' ) ) else : df = df_raw def fancyfy ( axes , N ) : for ax in axes [ 0 : - 1 , : ] . flat : ax . set_xlabel ( '' ) for ax in axes [ : , 1 : ] . flat : ax . set_ylabel ( '' ) g = df . groupby ( 'timestep' ) N = len ( g . groups . keys ( ) ) nrx = min ( ( N , 5 ) ) nry = int ( np . ceil ( N / nrx ) ) # the sizes are heuristics [inches] sizex = nrx * 3 sizey = nry * 4 - 1 fig , axes = plt . subplots ( nry , nrx , sharex = True , sharey = True , figsize = ( sizex , sizey ) , ) axes = np . atleast_2d ( axes ) cbs = [ ] for ax , ( name , group ) in zip ( axes . flat , g ) : fig1 , axes1 , cb1 = plot_pseudosection_type2 ( group , key , ax = ax , log10 = False , cbmin = kwargs . get ( 'cbmin' , None ) , cbmax = kwargs . get ( 'cbmax' , None ) , ) cbs . append ( cb1 ) ax . set_title ( 'timestep: {0}' . format ( int ( name ) ) ) ax . xaxis . set_ticks_position ( 'bottom' ) ax . set_aspect ( 'equal' ) for cb in np . array ( cbs ) . reshape ( axes . shape ) [ : , 0 : - 1 ] . flat : cb . ax . set_visible ( False ) fancyfy ( axes , N ) fig . tight_layout ( ) return fig
8,353
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/pseudoplots.py#L314-L385
[ "def", "find_package_indexes_in_dir", "(", "self", ",", "simple_dir", ")", ":", "packages", "=", "sorted", "(", "{", "# Filter out all of the \"non\" normalized names here", "canonicalize_name", "(", "x", ")", "for", "x", "in", "os", ".", "listdir", "(", "simple_dir", ")", "}", ")", "# Package indexes must be in directories, so ignore anything else.", "packages", "=", "[", "x", "for", "x", "in", "packages", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "simple_dir", ",", "x", ")", ")", "]", "return", "packages" ]
Hack to fix twisted not accepting absolute URIs
def twisted_absolute_path ( path , request ) : parsed = urlparse . urlparse ( request . uri ) if parsed . scheme != '' : path_parts = parsed . path . lstrip ( '/' ) . split ( '/' ) request . prepath = path_parts [ 0 : 1 ] request . postpath = path_parts [ 1 : ] path = request . prepath [ 0 ] return path , request
8,354
https://github.com/fuzeman/PyUPnP/blob/6dea64be299952346a14300ab6cc7dac42736433/pyupnp/util.py#L24-L32
[ "def", "recv", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'Receiving'", ")", "try", ":", "message_length", "=", "struct", ".", "unpack", "(", "'>i'", ",", "self", ".", "_socket", ".", "recv", "(", "4", ")", ")", "[", "0", "]", "message_length", "-=", "Connection", ".", "COMM_LENGTH", "LOGGER", ".", "debug", "(", "'Length: %i'", ",", "message_length", ")", "except", "socket", ".", "timeout", ":", "return", "None", "comm_status", "=", "struct", ".", "unpack", "(", "'>i'", ",", "self", ".", "_socket", ".", "recv", "(", "4", ")", ")", "[", "0", "]", "LOGGER", ".", "debug", "(", "'Status: %i'", ",", "comm_status", ")", "bytes_received", "=", "0", "message", "=", "b\"\"", "while", "bytes_received", "<", "message_length", ":", "if", "message_length", "-", "bytes_received", ">=", "1024", ":", "recv_len", "=", "1024", "else", ":", "recv_len", "=", "message_length", "-", "bytes_received", "bytes_received", "+=", "recv_len", "LOGGER", ".", "debug", "(", "'Received %i'", ",", "bytes_received", ")", "message", "+=", "self", ".", "_socket", ".", "recv", "(", "recv_len", ")", "if", "comm_status", "==", "0", ":", "message", "=", "self", ".", "_crypt", ".", "decrypt", "(", "message", ")", "else", ":", "return", "Message", "(", "len", "(", "message", ")", ",", "Connection", ".", "COMM_ERROR", ",", "message", ")", "msg", "=", "Message", "(", "message_length", ",", "comm_status", ",", "message", ")", "return", "msg" ]
a simple wrapper to compute K factors and add rhoa
def _add_rhoa ( df , spacing ) : df [ 'k' ] = redaK . compute_K_analytical ( df , spacing = spacing ) df [ 'rho_a' ] = df [ 'r' ] * df [ 'k' ] if 'Zt' in df . columns : df [ 'rho_a_complex' ] = df [ 'Zt' ] * df [ 'k' ] return df
8,355
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/legacy/eit40.py#L52-L59
[ "def", "get_temp_export_dir", "(", "timestamped_export_dir", ")", ":", "(", "dirname", ",", "basename", ")", "=", "os", ".", "path", ".", "split", "(", "timestamped_export_dir", ")", "temp_export_dir", "=", "os", ".", "path", ".", "join", "(", "tf", ".", "compat", ".", "as_bytes", "(", "dirname", ")", ",", "tf", ".", "compat", ".", "as_bytes", "(", "\"temp-{}\"", ".", "format", "(", "basename", ")", ")", ")", "return", "temp_export_dir" ]
Given a list of geoids reduce it to a simpler set . If there are five or more geoids at one summary level convert them to a single geoid at the higher level .
def simplify ( geoids ) : from collections import defaultdict aggregated = defaultdict ( set ) d = { } for g in geoids : if not bool ( g ) : continue av = g . allval ( ) d [ av ] = None aggregated [ av ] . add ( g ) compiled = set ( ) for k , v in aggregated . items ( ) : if len ( v ) >= 5 : compiled . add ( k ) compiled . add ( k . promote ( ) ) else : compiled |= v return compiled
8,356
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/util.py#L3-L38
[ "def", "start_disk_recording", "(", "self", ",", "filename", ",", "autoname", "=", "False", ")", ":", "self", ".", "pdx", ".", "StartDiskRecording", "(", "filename", ",", "autoname", ")" ]
Iteratively simplify until the set stops getting smaller .
def isimplify ( geoids ) : s0 = list ( geoids ) for i in range ( 10 ) : s1 = simplify ( s0 ) if len ( s1 ) == len ( s0 ) : return s1 s0 = s1
8,357
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/util.py#L40-L51
[ "def", "writearff", "(", "data", ",", "filename", ",", "relation_name", "=", "None", ",", "index", "=", "True", ")", ":", "if", "isinstance", "(", "filename", ",", "str", ")", ":", "fp", "=", "open", "(", "filename", ",", "'w'", ")", "if", "relation_name", "is", "None", ":", "relation_name", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "else", ":", "fp", "=", "filename", "if", "relation_name", "is", "None", ":", "relation_name", "=", "\"pandas\"", "try", ":", "data", "=", "_write_header", "(", "data", ",", "fp", ",", "relation_name", ",", "index", ")", "fp", ".", "write", "(", "\"\\n\"", ")", "_write_data", "(", "data", ",", "fp", ")", "finally", ":", "fp", ".", "close", "(", ")" ]
Handle re - generating the thumbnails . All this involves is reading the original file then saving the same exact thing . Kind of annoying but it s simple .
def regenerate_thumbs ( self ) : Model = self . model instances = Model . objects . all ( ) num_instances = instances . count ( ) # Filenames are keys in here, to help avoid re-genning something that # we have already done. regen_tracker = { } counter = 1 for instance in instances : file = getattr ( instance , self . field ) if not file : print "(%d/%d) ID: %d -- Skipped -- No file" % ( counter , num_instances , instance . id ) counter += 1 continue file_name = os . path . basename ( file . name ) if regen_tracker . has_key ( file_name ) : print "(%d/%d) ID: %d -- Skipped -- Already re-genned %s" % ( counter , num_instances , instance . id , file_name ) counter += 1 continue # Keep them informed on the progress. print "(%d/%d) ID: %d -- %s" % ( counter , num_instances , instance . id , file_name ) try : fdat = file . read ( ) file . close ( ) del file . file except IOError : # Key didn't exist. print "(%d/%d) ID %d -- Error -- File missing on S3" % ( counter , num_instances , instance . id ) counter += 1 continue try : file_contents = ContentFile ( fdat ) except ValueError : # This field has no file associated with it, skip it. print "(%d/%d) ID %d -- Skipped -- No file on field)" % ( counter , num_instances , instance . id ) counter += 1 continue # Saving pumps it back through the thumbnailer, if this is a # ThumbnailField. If not, it's still pretty harmless. try : file . generate_thumbs ( file_name , file_contents ) except IOError , e : print "(%d/%d) ID %d -- Error -- Image may be corrupt)" % ( counter , num_instances , instance . id ) counter += 1 continue regen_tracker [ file_name ] = True counter += 1
8,358
https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/management/commands/athumb_regen_field.py#L43-L119
[ "def", "try_set_count", "(", "self", ",", "count", ")", ":", "check_not_negative", "(", "count", ",", "\"count can't be negative\"", ")", "return", "self", ".", "_encode_invoke", "(", "count_down_latch_try_set_count_codec", ",", "count", "=", "count", ")" ]
Count number of occurrences of vowels in a given string
def count_vowels ( text ) : count = 0 for i in text : if i . lower ( ) in config . AVRO_VOWELS : count += 1 return count
8,359
https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/count.py#L31-L37
[ "def", "compile_results", "(", "self", ")", ":", "self", ".", "_init_dataframes", "(", ")", "self", ".", "total_transactions", "=", "len", "(", "self", ".", "main_results", "[", "'raw'", "]", ")", "self", ".", "_init_dates", "(", ")" ]
Count number of occurrences of consonants in a given string
def count_consonants ( text ) : count = 0 for i in text : if i . lower ( ) in config . AVRO_CONSONANTS : count += 1 return count
8,360
https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/count.py#L39-L45
[ "def", "failed", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "finished", "=", "datetime", ".", "now", "(", ")", "self", ".", "status", "=", "'failed'", "self", ".", "information", ".", "update", "(", "kwargs", ")", "self", ".", "logger", ".", "info", "(", "\"Failed - took %f seconds.\"", ",", "self", ".", "duration", "(", ")", ")", "self", ".", "update_report_collector", "(", "int", "(", "time", ".", "mktime", "(", "self", ".", "finished", ".", "timetuple", "(", ")", ")", ")", ")" ]
Given distances between electrodes compute Wenner pseudo depths for the provided configuration
def _pseudodepths_wenner ( configs , spacing = 1 , grid = None ) : if grid is None : xpositions = ( configs - 1 ) * spacing else : xpositions = grid . get_electrode_positions ( ) [ configs - 1 , 0 ] z = np . abs ( np . max ( xpositions , axis = 1 ) - np . min ( xpositions , axis = 1 ) ) * - 0.11 x = np . mean ( xpositions , axis = 1 ) return x , z
8,361
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/plots2d.py#L13-L31
[ "def", "deauthorize_application", "(", "request", ")", ":", "if", "request", ".", "facebook", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "facebook_id", "=", "request", ".", "facebook", ".", "signed_request", ".", "user", ".", "id", ")", "user", ".", "authorized", "=", "False", "user", ".", "save", "(", ")", "return", "HttpResponse", "(", ")", "else", ":", "return", "HttpResponse", "(", "status", "=", "400", ")" ]
Plot pseudodepths for the measurements . If grid is given then the actual electrode positions are used and the parameter spacing is ignored
def plot_pseudodepths ( configs , nr_electrodes , spacing = 1 , grid = None , ctypes = None , dd_merge = False , * * kwargs ) : # for each configuration type we have different ways of computing # pseudodepths pseudo_d_functions = { 'dd' : _pseudodepths_dd_simple , 'schlumberger' : _pseudodepths_schlumberger , 'wenner' : _pseudodepths_wenner , } titles = { 'dd' : 'dipole-dipole configurations' , 'schlumberger' : 'Schlumberger configurations' , 'wenner' : 'Wenner configurations' , } # sort the configurations into the various types of configurations only_types = ctypes or [ 'dd' , ] results = fT . filter ( configs , settings = { 'only_types' : only_types , } ) # loop through all measurement types figs = [ ] axes = [ ] for key in sorted ( results . keys ( ) ) : print ( 'plotting: ' , key ) if key == 'not_sorted' : continue index_dict = results [ key ] # it is possible that we want to generate multiple plots for one # type of measurement, i.e., to separate skips of dipole-dipole # measurements. Therefore we generate two lists: # 1) list of list of indices to plot # 2) corresponding labels if key == 'dd' and not dd_merge : plot_list = [ ] labels_add = [ ] for skip in sorted ( index_dict . keys ( ) ) : plot_list . append ( index_dict [ skip ] ) labels_add . append ( ' - skip {0}' . format ( skip ) ) else : # merge all indices plot_list = [ np . hstack ( index_dict . values ( ) ) , ] print ( 'schlumberger' , plot_list ) labels_add = [ '' , ] grid = None # generate plots for indices , label_add in zip ( plot_list , labels_add ) : if len ( indices ) == 0 : continue ddc = configs [ indices ] px , pz = pseudo_d_functions [ key ] ( ddc , spacing , grid ) fig , ax = plt . subplots ( figsize = ( 15 / 2.54 , 5 / 2.54 ) ) ax . scatter ( px , pz , color = 'k' , alpha = 0.5 ) # plot electrodes if grid is not None : electrodes = grid . get_electrode_positions ( ) ax . scatter ( electrodes [ : , 0 ] , electrodes [ : , 1 ] , color = 'b' , label = 'electrodes' , ) else : ax . scatter ( np . arange ( 0 , nr_electrodes ) * spacing , np . zeros ( nr_electrodes ) , color = 'b' , label = 'electrodes' , ) ax . set_title ( titles [ key ] + label_add ) ax . set_aspect ( 'equal' ) ax . set_xlabel ( 'x [m]' ) ax . set_ylabel ( 'x [z]' ) fig . tight_layout ( ) figs . append ( fig ) axes . append ( ax ) if len ( figs ) == 1 : return figs [ 0 ] , axes [ 0 ] else : return figs , axes
8,362
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/plots2d.py#L72-L227
[ "def", "logEndTime", "(", ")", ":", "logger", ".", "info", "(", "'\\n'", "+", "'#'", "*", "70", ")", "logger", ".", "info", "(", "'Complete'", ")", "logger", ".", "info", "(", "datetime", ".", "today", "(", ")", ".", "strftime", "(", "\"%A, %d %B %Y %I:%M%p\"", ")", ")", "logger", ".", "info", "(", "'#'", "*", "70", "+", "'\\n'", ")" ]
Plot x y z as expected with correct axis labels .
def matplot ( x , y , z , ax = None , colorbar = True , * * kwargs ) : xmin = x . min ( ) xmax = x . max ( ) dx = np . abs ( x [ 0 , 1 ] - x [ 0 , 0 ] ) ymin = y . min ( ) ymax = y . max ( ) dy = np . abs ( y [ 1 , 0 ] - y [ 0 , 0 ] ) x2 , y2 = np . meshgrid ( np . arange ( xmin , xmax + 2 * dx , dx ) - dx / 2. , np . arange ( ymin , ymax + 2 * dy , dy ) - dy / 2. ) if not ax : fig , ax = plt . subplots ( ) else : fig = ax . figure im = ax . pcolormesh ( x2 , y2 , z , * * kwargs ) ax . axis ( [ x2 . min ( ) , x2 . max ( ) , y2 . min ( ) , y2 . max ( ) ] ) ax . set_xticks ( np . arange ( xmin , xmax + dx , dx ) ) ax . set_yticks ( np . arange ( ymin , ymax + dx , dy ) ) if colorbar : cbar = fig . colorbar ( im , ax = ax ) else : cbar = None return ax , cbar
8,363
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/plots2d.py#L417-L470
[ "def", "once", "(", "self", ",", "event", ",", "callback", ")", ":", "self", ".", "_once_events", ".", "add", "(", "event", ")", "self", ".", "on", "(", "event", ",", "callback", ")" ]
Return a string summary of transaction
def summary ( self ) : return "\n" . join ( [ "Transaction:" , " When: " + self . date . strftime ( "%a %d %b %Y" ) , " Description: " + self . desc . replace ( '\n' , ' ' ) , " For amount: {}" . format ( self . amount ) , " From: {}" . format ( ", " . join ( map ( lambda x : x . account , self . src ) ) if self . src else "UNKNOWN" ) , " To: {}" . format ( ", " . join ( map ( lambda x : x . account , self . dst ) ) if self . dst else "UNKNOWN" ) , "" ] )
8,364
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L88-L104
[ "def", "get_settings", "(", ")", ":", "s", "=", "getattr", "(", "settings", ",", "'CLAMAV_UPLOAD'", ",", "{", "}", ")", "s", "=", "{", "'CONTENT_TYPE_CHECK_ENABLED'", ":", "s", ".", "get", "(", "'CONTENT_TYPE_CHECK_ENABLED'", ",", "False", ")", ",", "# LAST_HANDLER is not a user configurable option; we return", "# it with the settings dict simply because it's convenient.", "'LAST_HANDLER'", ":", "getattr", "(", "settings", ",", "'FILE_UPLOAD_HANDLERS'", ")", "[", "-", "1", "]", "}", "return", "s" ]
Check this transaction for completeness
def check ( self ) : if not self . date : raise XnDataError ( "Missing date" ) if not self . desc : raise XnDataError ( "Missing description" ) if not self . dst : raise XnDataError ( "No destination accounts" ) if not self . src : raise XnDataError ( "No source accounts" ) if not self . amount : raise XnDataError ( "No transaction amount" )
8,365
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L106-L117
[ "def", "get_listing", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'listing'", ")", ":", "allEvents", "=", "self", ".", "get_allEvents", "(", ")", "openEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", "closedEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", "publicEvents", "=", "allEvents", ".", "instance_of", "(", "PublicEvent", ")", "allSeries", "=", "allEvents", ".", "instance_of", "(", "Series", ")", "self", ".", "listing", "=", "{", "'allEvents'", ":", "allEvents", ",", "'openEvents'", ":", "openEvents", ",", "'closedEvents'", ":", "closedEvents", ",", "'publicEvents'", ":", "publicEvents", ",", "'allSeries'", ":", "allSeries", ",", "'regOpenEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateEvents'", ":", "publicEvents", ".", "filter", "(", "publicevent__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'publicevent__category'", ")", ",", "'regOpenSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateSeries'", ":", "allSeries", ".", "filter", "(", "series__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'series__category'", ")", ",", "}", "return", "self", ".", "listing" ]
Check this transaction for correctness
def balance ( self ) : self . check ( ) if not sum ( map ( lambda x : x . amount , self . src ) ) == - self . amount : raise XnBalanceError ( "Sum of source amounts " "not equal to transaction amount" ) if not sum ( map ( lambda x : x . amount , self . dst ) ) == self . amount : raise XnBalanceError ( "Sum of destination amounts " "not equal to transaction amount" ) return True
8,366
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L119-L128
[ "def", "_get_exception_class_from_status_code", "(", "status_code", ")", ":", "if", "status_code", "==", "'100'", ":", "return", "None", "exc_class", "=", "STATUS_CODE_MAPPING", ".", "get", "(", "status_code", ")", "if", "not", "exc_class", ":", "# No status code match, return the \"I don't know wtf this is\"", "# exception class.", "return", "STATUS_CODE_MAPPING", "[", "'UNKNOWN'", "]", "else", ":", "# Match found, yay.", "return", "exc_class" ]
Process this transaction against the given ruleset
def match_rules ( self , rules ) : try : self . check ( ) return None except XnDataError : pass scores = { } for r in rules : outcomes = r . match ( self ) if not outcomes : continue for outcome in outcomes : if isinstance ( outcome , rule . SourceOutcome ) : key = 'src' elif isinstance ( outcome , rule . DestinationOutcome ) : key = 'dst' elif isinstance ( outcome , rule . DescriptionOutcome ) : key = 'desc' elif isinstance ( outcome , rule . DropOutcome ) : key = 'drop' elif isinstance ( outcome , rule . RebateOutcome ) : key = 'rebate' else : raise KeyError if key not in scores : scores [ key ] = score . ScoreSet ( ) # initialise ScoreSet scores [ key ] . append ( ( outcome . value , outcome . score ) ) return scores
8,367
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L130-L166
[ "def", "get_listing", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'listing'", ")", ":", "allEvents", "=", "self", ".", "get_allEvents", "(", ")", "openEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", "closedEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", "publicEvents", "=", "allEvents", ".", "instance_of", "(", "PublicEvent", ")", "allSeries", "=", "allEvents", ".", "instance_of", "(", "Series", ")", "self", ".", "listing", "=", "{", "'allEvents'", ":", "allEvents", ",", "'openEvents'", ":", "openEvents", ",", "'closedEvents'", ":", "closedEvents", ",", "'publicEvents'", ":", "publicEvents", ",", "'allSeries'", ":", "allSeries", ",", "'regOpenEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateEvents'", ":", "publicEvents", ".", "filter", "(", "publicevent__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'publicevent__category'", ")", ",", "'regOpenSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateSeries'", ":", "allSeries", ".", "filter", "(", "series__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'series__category'", ")", ",", "}", "return", "self", ".", "listing" ]
Query for all missing information in the transaction
def complete ( self , uio , dropped = False ) : if self . dropped and not dropped : # do nothing for dropped xn, unless specifically told to return for end in [ 'src' , 'dst' ] : if getattr ( self , end ) : continue # we have this information uio . show ( '\nEnter ' + end + ' for transaction:' ) uio . show ( '' ) uio . show ( self . summary ( ) ) try : endpoints = [ ] remaining = self . amount while remaining : account = uio . text ( ' Enter account' , None ) amount = uio . decimal ( ' Enter amount' , default = remaining , lower = 0 , upper = remaining ) endpoints . append ( Endpoint ( account , amount ) ) remaining = self . amount - sum ( map ( lambda x : x . amount , endpoints ) ) except ui . RejectWarning : # bail out sys . exit ( "bye!" ) # flip amounts if it was a src outcome if end == 'src' : endpoints = map ( lambda x : Endpoint ( x . account , - x . amount ) , endpoints ) # set endpoints setattr ( self , end , endpoints )
8,368
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L312-L351
[ "def", "get_settings", "(", ")", ":", "s", "=", "getattr", "(", "settings", ",", "'CLAMAV_UPLOAD'", ",", "{", "}", ")", "s", "=", "{", "'CONTENT_TYPE_CHECK_ENABLED'", ":", "s", ".", "get", "(", "'CONTENT_TYPE_CHECK_ENABLED'", ",", "False", ")", ",", "# LAST_HANDLER is not a user configurable option; we return", "# it with the settings dict simply because it's convenient.", "'LAST_HANDLER'", ":", "getattr", "(", "settings", ",", "'FILE_UPLOAD_HANDLERS'", ")", "[", "-", "1", "]", "}", "return", "s" ]
Matches rules and applies outcomes
def process ( self , rules , uio , prevxn = None ) : self . apply_outcomes ( self . match_rules ( rules ) , uio , prevxn = prevxn )
8,369
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L353-L355
[ "def", "normalize_filename", "(", "filename", ")", ":", "# if the url pointed to a directory then just replace all the special chars", "filename", "=", "re", ".", "sub", "(", "\"/|\\\\|;|:|\\?|=\"", ",", "\"_\"", ",", "filename", ")", "if", "len", "(", "filename", ")", ">", "150", ":", "prefix", "=", "hashlib", ".", "md5", "(", "filename", ")", ".", "hexdigest", "(", ")", "filename", "=", "prefix", "+", "filename", "[", "-", "140", ":", "]", "return", "filename" ]
Visualize time - lapse evolution of a single quadropole .
def plot_quadpole_evolution ( dataobj , quadpole , cols , threshold = 5 , rolling = False , ax = None ) : if isinstance ( dataobj , pd . DataFrame ) : df = dataobj else : df = dataobj . data subquery = df . query ( 'a == {0} and b == {1} and m == {2} and n == {3}' . format ( * quadpole ) ) # rhoa = subquery['rho_a'].values # rhoa[30] = 300 # subquery['rho_a'] = rhoa if ax is not None : fig = ax . get_figure ( ) else : fig , ax = plt . subplots ( 1 , 1 , figsize = ( 20 / 2.54 , 7 / 2.54 ) ) ax . plot ( subquery [ 'timestep' ] , subquery [ cols ] , '.' , color = 'blue' , label = 'valid data' , ) if rolling : # rolling mean rolling_m = subquery . rolling ( 3 , center = True , min_periods = 1 ) . median ( ) ax . plot ( rolling_m [ 'timestep' ] . values , rolling_m [ 'rho_a' ] . values , '-' , label = 'rolling median' , ) ax . fill_between ( rolling_m [ 'timestep' ] . values , rolling_m [ 'rho_a' ] . values * ( 1 - threshold ) , rolling_m [ 'rho_a' ] . values * ( 1 + threshold ) , alpha = 0.4 , color = 'blue' , label = '{0}\% confidence region' . format ( threshold * 100 ) , ) # find all values that deviate by more than X percent from the # rolling_m bad_values = ( np . abs ( np . abs ( subquery [ 'rho_a' ] . values - rolling_m [ 'rho_a' ] . values ) / rolling_m [ 'rho_a' ] . values ) > threshold ) bad = subquery . loc [ bad_values ] ax . plot ( bad [ 'timestep' ] . values , bad [ 'rho_a' ] . values , '.' , # s=15, color = 'r' , label = 'discarded data' , ) ax . legend ( loc = 'upper center' , fontsize = 6 ) # ax.set_xlim(10, 20) ax . set_ylabel ( r'$\rho_a$ [$\Omega$m]' ) ax . set_xlabel ( 'timestep' ) return fig , ax
8,370
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/time_series.py#L9-L93
[ "def", "_register_unicode", "(", "connection", ")", ":", "psycopg2", ".", "extensions", ".", "register_type", "(", "psycopg2", ".", "extensions", ".", "UNICODE", ",", "connection", ")", "psycopg2", ".", "extensions", ".", "register_type", "(", "psycopg2", ".", "extensions", ".", "UNICODEARRAY", ",", "connection", ")" ]
! ^ ? | ^ ! ?
def visitSenseFlags ( self , ctx : ShExDocParser . SenseFlagsContext ) : if '!' in ctx . getText ( ) : self . expression . negated = True if '^' in ctx . getText ( ) : self . expression . inverse = True
8,371
https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/shex_oneofshape_parser.py#L114-L119
[ "def", "put_object", "(", "self", ",", "url", ",", "container", ",", "container_object", ",", "local_object", ",", "object_headers", ",", "meta", "=", "None", ")", ":", "headers", ",", "container_uri", "=", "self", ".", "_return_base_data", "(", "url", "=", "url", ",", "container", "=", "container", ",", "container_object", "=", "container_object", ",", "container_headers", "=", "object_headers", ",", "object_headers", "=", "meta", ")", "return", "self", ".", "_putter", "(", "uri", "=", "container_uri", ",", "headers", "=", "headers", ",", "local_object", "=", "local_object", ")" ]
Date as three - tuple of numbers
def as_tuple ( self ) : if self . _tuple is None : # extract leading digits from year year = 9999 if self . year : m = self . DIGITS . match ( self . year ) if m : year = int ( m . group ( 0 ) ) month = self . month_num or 99 day = self . day if self . day is not None else 99 # should we include calendar name in tuple too? self . _tuple = year , month , day return self . _tuple
8,372
https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/detail/date.py#L142-L157
[ "def", "get_license_assignment_manager", "(", "service_instance", ")", ":", "log", ".", "debug", "(", "'Retrieving license assignment manager'", ")", "try", ":", "lic_assignment_manager", "=", "service_instance", ".", "content", ".", "licenseManager", ".", "licenseAssignmentManager", "except", "vim", ".", "fault", ".", "NoPermission", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareApiError", "(", "'Not enough permissions. Required privilege: '", "'{0}'", ".", "format", "(", "exc", ".", "privilegeId", ")", ")", "except", "vim", ".", "fault", ".", "VimFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareApiError", "(", "exc", ".", "msg", ")", "except", "vmodl", ".", "RuntimeFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareRuntimeError", "(", "exc", ".", "msg", ")", "if", "not", "lic_assignment_manager", ":", "raise", "salt", ".", "exceptions", ".", "VMwareObjectRetrievalError", "(", "'License assignment manager was not retrieved'", ")", "return", "lic_assignment_manager" ]
Returns Calendar date used for comparison .
def _cmp_date ( self ) : dates = sorted ( val for val in self . kw . values ( ) if isinstance ( val , CalendarDate ) ) if dates : return dates [ 0 ] # return date very far in the future return CalendarDate ( )
8,373
https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/detail/date.py#L237-L249
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
takes care of some edge cases of sentence tokenization for cases when websites don t close sentences properly usually after blockquotes image captions or attributions
def better_sentences ( func ) : @ wraps ( func ) def wrapped ( * args ) : sentences = func ( * args ) new_sentences = [ ] for i , l in enumerate ( sentences ) : if '\n\n' in l : splits = l . split ( '\n\n' ) if len ( splits ) > 1 : for ind , spl in enumerate ( splits ) : if len ( spl ) < 20 : #if DEBUG: print "Discarding: ", spl del splits [ ind ] new_sentences . extend ( splits ) else : new_sentences . append ( l ) return new_sentences return wrapped
8,374
https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/better_sentences.py#L3-L26
[ "def", "get_modifier_mapping", "(", "self", ")", ":", "r", "=", "request", ".", "GetModifierMapping", "(", "display", "=", "self", ".", "display", ")", "return", "r", ".", "keycodes" ]
Compute weC from sensor temperature compensation of weV
def __we_c ( cls , calib , tc , temp , we_v ) : offset_v = calib . pid_elc_mv / 1000.0 response_v = we_v - offset_v # remove electronic zero response_c = tc . correct ( temp , response_v ) # correct the response component if response_c is None : return None we_c = response_c + offset_v # replace electronic zero return we_c
8,375
https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/pid_datum.py#L44-L58
[ "def", "plot", "(", "self", ",", "overlay", "=", "True", ",", "*", "*", "labels", ")", ":", "# pragma: no cover", "pylab", "=", "LazyImport", ".", "pylab", "(", ")", "colours", "=", "list", "(", "'rgbymc'", ")", "colours_len", "=", "len", "(", "colours", ")", "colours_pos", "=", "0", "plots", "=", "len", "(", "self", ".", "groups", ")", "for", "name", ",", "series", "in", "self", ".", "groups", ".", "iteritems", "(", ")", ":", "colour", "=", "colours", "[", "colours_pos", "%", "colours_len", "]", "colours_pos", "+=", "1", "if", "not", "overlay", ":", "pylab", ".", "subplot", "(", "plots", ",", "1", ",", "colours_pos", ")", "kwargs", "=", "{", "}", "if", "name", "in", "labels", ":", "name", "=", "labels", "[", "name", "]", "if", "name", "is", "not", "None", ":", "kwargs", "[", "'label'", "]", "=", "name", "pylab", ".", "plot", "(", "series", ".", "dates", ",", "series", ".", "values", ",", "'%s-'", "%", "colour", ",", "*", "*", "kwargs", ")", "if", "name", "is", "not", "None", ":", "pylab", ".", "legend", "(", ")", "pylab", ".", "show", "(", ")" ]
Compute cnc from weC
def __cnc ( cls , calib , we_c ) : if we_c is None : return None offset_v = calib . pid_elc_mv / 1000.0 response_c = we_c - offset_v # remove electronic zero cnc = response_c / calib . pid_sens_mv # pid_sens_mv set for ppb or ppm - see PID.init() return cnc
8,376
https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/pid_datum.py#L62-L74
[ "def", "redactor", "(", "blacklist", ":", "Dict", "[", "Pattern", ",", "str", "]", ")", "->", "Callable", "[", "[", "str", "]", ",", "str", "]", ":", "def", "processor_wrapper", "(", "msg", ":", "str", ")", "->", "str", ":", "for", "regex", ",", "repl", "in", "blacklist", ".", "items", "(", ")", ":", "if", "repl", "is", "None", ":", "repl", "=", "'<redacted>'", "msg", "=", "regex", ".", "sub", "(", "repl", ",", "msg", ")", "return", "msg", "return", "processor_wrapper" ]
Replace the Field attribute with a named _FieldDescriptor .
def add_to_class ( self , model_class ) : model_class . _meta . add_field ( self ) setattr ( model_class , self . name , _FieldDescriptor ( self ) )
8,377
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/model.py#L126-L133
[ "def", "cancelHistoricalData", "(", "self", ",", "contracts", "=", "None", ")", ":", "if", "contracts", "==", "None", ":", "contracts", "=", "list", "(", "self", ".", "contracts", ".", "values", "(", ")", ")", "elif", "not", "isinstance", "(", "contracts", ",", "list", ")", ":", "contracts", "=", "[", "contracts", "]", "for", "contract", "in", "contracts", ":", "# tickerId = self.tickerId(contract.m_symbol)", "tickerId", "=", "self", ".", "tickerId", "(", "self", ".", "contractString", "(", "contract", ")", ")", "self", ".", "ibConn", ".", "cancelHistoricalData", "(", "tickerId", "=", "tickerId", ")" ]
Add the received field to the model .
def add_field ( self , field ) : self . remove_field ( field . name ) self . _fields [ field . name ] = field if field . default is not None : if six . callable ( field . default ) : self . _default_callables [ field . key ] = field . default else : self . _defaults [ field . key ] = field . default
8,378
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/model.py#L157-L166
[ "def", "init", "(", "uri", "=", "None", ",", "alembic_ini", "=", "None", ",", "engine", "=", "None", ",", "create", "=", "False", ")", ":", "if", "uri", "and", "engine", ":", "raise", "ValueError", "(", "\"uri and engine cannot both be specified\"", ")", "if", "uri", "is", "None", "and", "not", "engine", ":", "uri", "=", "'sqlite:////tmp/datanommer.db'", "log", ".", "warning", "(", "\"No db uri given. Using %r\"", "%", "uri", ")", "if", "uri", "and", "not", "engine", ":", "engine", "=", "create_engine", "(", "uri", ")", "if", "'sqlite'", "in", "engine", ".", "driver", ":", "# Enable nested transaction support under SQLite", "# See https://stackoverflow.com/questions/1654857/nested-transactions-with-sqlalchemy-and-sqlite", "@", "event", ".", "listens_for", "(", "engine", ",", "\"connect\"", ")", "def", "do_connect", "(", "dbapi_connection", ",", "connection_record", ")", ":", "# disable pysqlite's emitting of the BEGIN statement entirely.", "# also stops it from emitting COMMIT before any DDL.", "dbapi_connection", ".", "isolation_level", "=", "None", "@", "event", ".", "listens_for", "(", "engine", ",", "\"begin\"", ")", "def", "do_begin", "(", "conn", ")", ":", "# emit our own BEGIN", "conn", ".", "execute", "(", "\"BEGIN\"", ")", "# We need to hang our own attribute on the sqlalchemy session to stop", "# ourselves from initializing twice. That is only a problem is the code", "# calling us isn't consistent.", "if", "getattr", "(", "session", ",", "'_datanommer_initialized'", ",", "None", ")", ":", "log", ".", "warning", "(", "\"Session already initialized. Bailing\"", ")", "return", "session", ".", "_datanommer_initialized", "=", "True", "session", ".", "configure", "(", "bind", "=", "engine", ")", "DeclarativeBase", ".", "query", "=", "session", ".", "query_property", "(", ")", "# Loads the alembic configuration and generates the version table, with", "# the most recent revision stamped as head", "if", "alembic_ini", "is", "not", "None", ":", "from", "alembic", ".", "config", "import", "Config", "from", "alembic", "import", "command", "alembic_cfg", "=", "Config", "(", "alembic_ini", ")", "command", ".", "stamp", "(", "alembic_cfg", ",", "\"head\"", ")", "if", "create", ":", "DeclarativeBase", ".", "metadata", ".", "create_all", "(", "engine", ")" ]
Remove the field with the received field name from model .
def remove_field ( self , field_name ) : field = self . _fields . pop ( field_name , None ) if field is not None and field . default is not None : if six . callable ( field . default ) : self . _default_callables . pop ( field . key , None ) else : self . _defaults . pop ( field . key , None )
8,379
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/model.py#L168-L175
[ "def", "_setup_pyudev_monitoring", "(", "self", ")", ":", "context", "=", "pyudev", ".", "Context", "(", ")", "monitor", "=", "pyudev", ".", "Monitor", ".", "from_netlink", "(", "context", ")", "self", ".", "udev_observer", "=", "pyudev", ".", "MonitorObserver", "(", "monitor", ",", "self", ".", "_udev_event", ")", "self", ".", "udev_observer", ".", "start", "(", ")", "self", ".", "py3_wrapper", ".", "log", "(", "\"udev monitoring enabled\"", ")" ]
Get a dictionary that contains all the available defaults .
def get_defaults ( self ) : defaults = self . _defaults . copy ( ) for field_key , default in self . _default_callables . items ( ) : defaults [ field_key ] = default ( ) return defaults
8,380
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/model.py#L177-L182
[ "def", "write_bits", "(", "self", ",", "*", "args", ")", ":", "# Would be nice to make this a bit smarter", "if", "len", "(", "args", ")", ">", "8", ":", "raise", "ValueError", "(", "\"Can only write 8 bits at a time\"", ")", "self", ".", "_output_buffer", ".", "append", "(", "chr", "(", "reduce", "(", "lambda", "x", ",", "y", ":", "xor", "(", "x", ",", "args", "[", "y", "]", "<<", "y", ")", ",", "xrange", "(", "len", "(", "args", ")", ")", ",", "0", ")", ")", ")", "return", "self" ]
Run will call Microsoft Translate API and and produce audio
def speak ( self , textstr , lang = 'en-US' , gender = 'female' , format = 'riff-16khz-16bit-mono-pcm' ) : # print("speak(textstr=%s, lang=%s, gender=%s, format=%s)" % (textstr, lang, gender, format)) concatkey = '%s-%s-%s-%s' % ( textstr , lang . lower ( ) , gender . lower ( ) , format ) key = self . tts_engine + '' + str ( hash ( concatkey ) ) self . filename = '%s-%s.mp3' % ( key , lang ) # check if file exists fileloc = self . directory + self . filename if self . cache and os . path . isfile ( self . directory + self . filename ) : return self . filename else : with open ( fileloc , 'wb' ) as f : self . speech . speak_to_file ( f , textstr , lang , gender , format ) return self . filename return False
8,381
https://github.com/newfies-dialer/python-msspeak/blob/106475122be73df152865c4fe6e9388caf974085/msspeak/msspeak.py#L193-L210
[ "def", "lbest_idx", "(", "state", ",", "idx", ")", ":", "swarm", "=", "state", ".", "swarm", "n_s", "=", "state", ".", "params", "[", "'n_s'", "]", "cmp", "=", "comparator", "(", "swarm", "[", "0", "]", ".", "best_fitness", ")", "indices", "=", "__lbest_indices__", "(", "len", "(", "swarm", ")", ",", "n_s", ",", "idx", ")", "best", "=", "None", "for", "i", "in", "indices", ":", "if", "best", "is", "None", "or", "cmp", "(", "swarm", "[", "i", "]", ".", "best_fitness", ",", "swarm", "[", "best", "]", ".", "best_fitness", ")", ":", "best", "=", "i", "return", "best" ]
Call terminal command and return exit_code and stdout
def call ( args ) : b = StringIO ( ) p = subprocess . Popen ( args , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) encoding = getattr ( sys . stdout , 'encoding' , None ) or 'utf-8' # old python has bug in p.stdout, so the following little # hack is required. for stdout in iter ( p . stdout . readline , '' ) : if len ( stdout ) == 0 : break # translate non unicode to unicode stdout = force_unicode ( stdout , encoding ) # StringIO store unicode b . write ( stdout ) # stdout require non unicode sys . stdout . write ( from_unicode ( stdout , encoding ) ) sys . stdout . flush ( ) buf = b . getvalue ( ) p . stdout . close ( ) return p . returncode or 0 , buf
8,382
https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/executor.py#L17-L51
[ "def", "create_dirs", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "_path", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_path", ")", "for", "dir_name", "in", "[", "self", ".", "OBJ_DIR", ",", "self", ".", "TMP_OBJ_DIR", ",", "self", ".", "PKG_DIR", ",", "self", ".", "CACHE_DIR", "]", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "dir_name", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "os", ".", "mkdir", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_version_path", "(", ")", ")", ":", "self", ".", "_write_format_version", "(", ")" ]
Get terminal command string from list of command and arguments
def get_command_str ( args ) : single_quote = "'" double_quote = '"' for i , value in enumerate ( args ) : if " " in value and double_quote not in value : args [ i ] = '"%s"' % value elif " " in value and single_quote not in value : args [ i ] = "'%s'" % value return " " . join ( args )
8,383
https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/executor.py#L53-L74
[ "def", "_adapt_WSDateTime", "(", "dt", ")", ":", "try", ":", "ts", "=", "int", "(", "(", "dt", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", "-", "datetime", "(", "1970", ",", "1", ",", "1", ",", "tzinfo", "=", "pytz", ".", "utc", ")", ")", ".", "total_seconds", "(", ")", ")", "except", "(", "OverflowError", ",", "OSError", ")", ":", "if", "dt", "<", "datetime", ".", "now", "(", ")", ":", "ts", "=", "0", "else", ":", "ts", "=", "2", "**", "63", "-", "1", "return", "ts" ]
Over - ridden method to circumvent the worker timeouts on large uploads .
def receive_data_chunk ( self , raw_data , start ) : self . file . write ( raw_data ) # CHANGED: This un-hangs us long enough to keep things rolling. eventlet . sleep ( 0 )
8,384
https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/upload_handlers/gunicorn_eventlet.py#L15-L21
[ "def", "get_app_metadata", "(", "template_dict", ")", ":", "if", "SERVERLESS_REPO_APPLICATION", "in", "template_dict", ".", "get", "(", "METADATA", ",", "{", "}", ")", ":", "app_metadata_dict", "=", "template_dict", ".", "get", "(", "METADATA", ")", ".", "get", "(", "SERVERLESS_REPO_APPLICATION", ")", "return", "ApplicationMetadata", "(", "app_metadata_dict", ")", "raise", "ApplicationMetadataNotFoundError", "(", "error_message", "=", "'missing {} section in template Metadata'", ".", "format", "(", "SERVERLESS_REPO_APPLICATION", ")", ")" ]
Return all stop times in the date range
def stoptimes ( self , start_date , end_date ) : params = { 'start' : self . format_date ( start_date ) , 'end' : self . format_date ( end_date ) } response = self . _request ( ENDPOINTS [ 'STOPTIMES' ] , params ) return response
8,385
https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/transit.py#L115-L131
[ "def", "namedb_open", "(", "path", ")", ":", "con", "=", "sqlite3", ".", "connect", "(", "path", ",", "isolation_level", "=", "None", ",", "timeout", "=", "2", "**", "30", ")", "db_query_execute", "(", "con", ",", "'pragma mmap_size=536870912'", ",", "(", ")", ")", "con", ".", "row_factory", "=", "namedb_row_factory", "version", "=", "namedb_get_version", "(", "con", ")", "if", "not", "semver_equal", "(", "version", ",", "VERSION", ")", ":", "# wrong version", "raise", "Exception", "(", "'Database has version {}, but this node is version {}. Please update your node database (such as with fast_sync).'", ".", "format", "(", "version", ",", "VERSION", ")", ")", "return", "con" ]
Setup a logger
def setup_logger ( self ) : self . log_list = [ ] handler = ListHandler ( self . log_list ) formatter = logging . Formatter ( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) handler . setFormatter ( formatter ) logger = logging . getLogger ( ) logger . addHandler ( handler ) logger . setLevel ( logging . INFO ) self . handler = handler self . logger = logger
8,386
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/main/logger.py#L30-L46
[ "def", "from_cfunits", "(", "cls", ",", "units", ")", "->", "'Date'", ":", "try", ":", "string", "=", "units", "[", "units", ".", "find", "(", "'since'", ")", "+", "6", ":", "]", "idx", "=", "string", ".", "find", "(", "'.'", ")", "if", "idx", "!=", "-", "1", ":", "jdx", "=", "None", "for", "jdx", ",", "char", "in", "enumerate", "(", "string", "[", "idx", "+", "1", ":", "]", ")", ":", "if", "not", "char", ".", "isnumeric", "(", ")", ":", "break", "if", "char", "!=", "'0'", ":", "raise", "ValueError", "(", "'No other decimal fraction of a second '", "'than \"0\" allowed.'", ")", "else", ":", "if", "jdx", "is", "None", ":", "jdx", "=", "idx", "+", "1", "else", ":", "jdx", "+=", "1", "string", "=", "f'{string[:idx]}{string[idx+jdx+1:]}'", "return", "cls", "(", "string", ")", "except", "BaseException", ":", "objecttools", ".", "augment_excmessage", "(", "f'While trying to parse the date of the NetCDF-CF \"units\" '", "f'string `{units}`'", ")" ]
Convert a match object into a dict .
def match_to_dict ( match ) : balance , indent , account_fragment = match . group ( 1 , 2 , 3 ) return { 'balance' : decimal . Decimal ( balance ) , 'indent' : len ( indent ) , 'account_fragment' : account_fragment , 'parent' : None , 'children' : [ ] , }
8,387
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/balance.py#L24-L41
[ "def", "delete_booking", "(", "self", ",", "sessionid", ",", "booking_id", ")", ":", "url", "=", "\"{}{}{}/\"", ".", "format", "(", "BASE_URL", ",", "\"/delete/\"", ",", "booking_id", ")", "cookies", "=", "dict", "(", "sessionid", "=", "sessionid", ")", "try", ":", "resp", "=", "requests", ".", "get", "(", "url", ",", "cookies", "=", "cookies", ",", "headers", "=", "{", "'Referer'", ":", "'{}{}'", ".", "format", "(", "BASE_URL", ",", "\"/reservations/\"", ")", "}", ")", "except", "resp", ".", "exceptions", ".", "HTTPError", "as", "error", ":", "raise", "APIError", "(", "\"Server Error: {}\"", ".", "format", "(", "error", ")", ")", "if", "resp", ".", "status_code", "==", "404", ":", "raise", "APIError", "(", "\"Booking could not be found on server.\"", ")", "html", "=", "resp", ".", "content", ".", "decode", "(", "\"utf8\"", ")", "if", "\"https://weblogin.pennkey.upenn.edu\"", "in", "html", ":", "raise", "APIError", "(", "\"Wharton Auth Failed. Session ID is not valid.\"", ")", "resp", ".", "raise_for_status", "(", ")", "soup", "=", "BeautifulSoup", "(", "html", ",", "\"html5lib\"", ")", "middleware_token", "=", "soup", ".", "find", "(", "\"input\"", ",", "{", "'name'", ":", "\"csrfmiddlewaretoken\"", "}", ")", ".", "get", "(", "'value'", ")", "csrftoken", "=", "resp", ".", "cookies", "[", "'csrftoken'", "]", "cookies2", "=", "{", "'sessionid'", ":", "sessionid", ",", "'csrftoken'", ":", "csrftoken", "}", "headers", "=", "{", "'Referer'", ":", "url", "}", "payload", "=", "{", "'csrfmiddlewaretoken'", ":", "middleware_token", "}", "try", ":", "resp2", "=", "requests", ".", "post", "(", "url", ",", "cookies", "=", "cookies2", ",", "data", "=", "payload", ",", "headers", "=", "headers", ")", "except", "resp2", ".", "exceptions", ".", "HTTPError", "as", "error", ":", "raise", "APIError", "(", "\"Server Error: {}\"", ".", "format", "(", "error", ")", ")", "return", "{", "\"success\"", ":", "True", "}" ]
Convert ledger balance output into an hierarchical data structure .
def balance ( output ) : lines = map ( pattern . search , output . splitlines ( ) ) stack = [ ] top = [ ] for item in map ( match_to_dict , itertools . takewhile ( lambda x : x , lines ) ) : # pop items off stack while current item has indent <= while stack and item [ 'indent' ] <= stack [ - 1 ] [ 'indent' ] : stack . pop ( ) # check if this is a top-level item if not stack : stack . append ( item ) top . append ( item ) else : item [ 'parent' ] = stack [ - 1 ] stack [ - 1 ] [ 'children' ] . append ( item ) stack . append ( item ) return top
8,388
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/balance.py#L44-L64
[ "def", "get_all_indices", "(", "self", ",", "n_samples", "=", "None", ",", "max_samples", "=", "None", ",", "random_state", "=", "None", ")", ":", "if", "self", ".", "_indices_state", "is", "None", "and", "random_state", "is", "None", ":", "raise", "ValueError", "(", "'The program has not been evaluated for fitness '", "'yet, indices not available.'", ")", "if", "n_samples", "is", "not", "None", "and", "self", ".", "_n_samples", "is", "None", ":", "self", ".", "_n_samples", "=", "n_samples", "if", "max_samples", "is", "not", "None", "and", "self", ".", "_max_samples", "is", "None", ":", "self", ".", "_max_samples", "=", "max_samples", "if", "random_state", "is", "not", "None", "and", "self", ".", "_indices_state", "is", "None", ":", "self", ".", "_indices_state", "=", "random_state", ".", "get_state", "(", ")", "indices_state", "=", "check_random_state", "(", "None", ")", "indices_state", ".", "set_state", "(", "self", ".", "_indices_state", ")", "not_indices", "=", "sample_without_replacement", "(", "self", ".", "_n_samples", ",", "self", ".", "_n_samples", "-", "self", ".", "_max_samples", ",", "random_state", "=", "indices_state", ")", "sample_counts", "=", "np", ".", "bincount", "(", "not_indices", ",", "minlength", "=", "self", ".", "_n_samples", ")", "indices", "=", "np", ".", "where", "(", "sample_counts", "==", "0", ")", "[", "0", "]", "return", "indices", ",", "not_indices" ]
Check if given string is a punctuation
def is_punctuation ( text ) : return not ( text . lower ( ) in config . AVRO_VOWELS or text . lower ( ) in config . AVRO_CONSONANTS )
8,389
https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/validate.py#L43-L46
[ "def", "OnRootView", "(", "self", ",", "event", ")", ":", "self", ".", "adapter", ",", "tree", ",", "rows", "=", "self", ".", "RootNode", "(", ")", "self", ".", "squareMap", ".", "SetModel", "(", "tree", ",", "self", ".", "adapter", ")", "self", ".", "RecordHistory", "(", ")", "self", ".", "ConfigureViewTypeChoices", "(", ")" ]
Check exact occurrence of needle in haystack
def is_exact ( needle , haystack , start , end , matchnot ) : return ( ( start >= 0 and end < len ( haystack ) and haystack [ start : end ] == needle ) ^ matchnot )
8,390
https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/validate.py#L52-L55
[ "def", "sample", "(", "self", ",", "event", "=", "None", ",", "record_keepalive", "=", "False", ")", ":", "url", "=", "'https://stream.twitter.com/1.1/statuses/sample.json'", "params", "=", "{", "\"stall_warning\"", ":", "True", "}", "headers", "=", "{", "'accept-encoding'", ":", "'deflate, gzip'", "}", "errors", "=", "0", "while", "True", ":", "try", ":", "log", ".", "info", "(", "\"connecting to sample stream\"", ")", "resp", "=", "self", ".", "post", "(", "url", ",", "params", ",", "headers", "=", "headers", ",", "stream", "=", "True", ")", "errors", "=", "0", "for", "line", "in", "resp", ".", "iter_lines", "(", "chunk_size", "=", "512", ")", ":", "if", "event", "and", "event", ".", "is_set", "(", ")", ":", "log", ".", "info", "(", "\"stopping sample\"", ")", "# Explicitly close response", "resp", ".", "close", "(", ")", "return", "if", "line", "==", "\"\"", ":", "log", ".", "info", "(", "\"keep-alive\"", ")", "if", "record_keepalive", ":", "yield", "\"keep-alive\"", "continue", "try", ":", "yield", "json", ".", "loads", "(", "line", ".", "decode", "(", ")", ")", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", "\"json parse error: %s - %s\"", ",", "e", ",", "line", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "e", ":", "errors", "+=", "1", "log", ".", "error", "(", "\"caught http error %s on %s try\"", ",", "e", ",", "errors", ")", "if", "self", ".", "http_errors", "and", "errors", "==", "self", ".", "http_errors", ":", "log", ".", "warning", "(", "\"too many errors\"", ")", "raise", "e", "if", "e", ".", "response", ".", "status_code", "==", "420", ":", "if", "interruptible_sleep", "(", "errors", "*", "60", ",", "event", ")", ":", "log", ".", "info", "(", "\"stopping filter\"", ")", "return", "else", ":", "if", "interruptible_sleep", "(", "errors", "*", "5", ",", "event", ")", ":", "log", ".", "info", "(", "\"stopping filter\"", ")", "return", "except", "Exception", "as", "e", ":", "errors", "+=", "1", "log", ".", "error", "(", "\"caught exception %s on %s try\"", ",", "e", ",", "errors", ")", "if", "self", ".", "http_errors", "and", "errors", "==", "self", ".", "http_errors", ":", "log", ".", "warning", "(", "\"too many errors\"", ")", "raise", "e", "if", "interruptible_sleep", "(", "errors", ",", "event", ")", ":", "log", ".", "info", "(", "\"stopping filter\"", ")", "return" ]
Converts case - insensitive characters to lower case
def fix_string_case ( text ) : fixed = [ ] for i in text : if is_case_sensitive ( i ) : fixed . append ( i ) else : fixed . append ( i . lower ( ) ) return '' . join ( fixed )
8,391
https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/validate.py#L57-L71
[ "def", "_expand_node", "(", "node", ")", ":", "ret", "=", "{", "}", "ret", ".", "update", "(", "node", ".", "__dict__", ")", "try", ":", "del", "ret", "[", "'extra'", "]", "[", "'boot_disk'", "]", "except", "Exception", ":", "# pylint: disable=W0703", "pass", "zone", "=", "ret", "[", "'extra'", "]", "[", "'zone'", "]", "ret", "[", "'extra'", "]", "[", "'zone'", "]", "=", "{", "}", "ret", "[", "'extra'", "]", "[", "'zone'", "]", ".", "update", "(", "zone", ".", "__dict__", ")", "# Remove unserializable GCENodeDriver objects", "if", "'driver'", "in", "ret", ":", "del", "ret", "[", "'driver'", "]", "if", "'driver'", "in", "ret", "[", "'extra'", "]", "[", "'zone'", "]", ":", "del", "ret", "[", "'extra'", "]", "[", "'zone'", "]", "[", "'driver'", "]", "return", "ret" ]
convert crmod - style configurations to a Nx4 array
def _crmod_to_abmn ( self , configs ) : A = configs [ : , 0 ] % 1e4 B = np . floor ( configs [ : , 0 ] / 1e4 ) . astype ( int ) M = configs [ : , 1 ] % 1e4 N = np . floor ( configs [ : , 1 ] / 1e4 ) . astype ( int ) ABMN = np . hstack ( ( A [ : , np . newaxis ] , B [ : , np . newaxis ] , M [ : , np . newaxis ] , N [ : , np . newaxis ] ) ) . astype ( int ) return ABMN
8,392
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L54-L93
[ "def", "_create_download_failed_message", "(", "exception", ",", "url", ")", ":", "message", "=", "'Failed to download from:\\n{}\\nwith {}:\\n{}'", ".", "format", "(", "url", ",", "exception", ".", "__class__", ".", "__name__", ",", "exception", ")", "if", "_is_temporal_problem", "(", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "requests", ".", "ConnectionError", ")", ":", "message", "+=", "'\\nPlease check your internet connection and try again.'", "else", ":", "message", "+=", "'\\nThere might be a problem in connection or the server failed to process '", "'your request. Please try again.'", "elif", "isinstance", "(", "exception", ",", "requests", ".", "HTTPError", ")", ":", "try", ":", "server_message", "=", "''", "for", "elem", "in", "decode_data", "(", "exception", ".", "response", ".", "content", ",", "MimeType", ".", "XML", ")", ":", "if", "'ServiceException'", "in", "elem", ".", "tag", "or", "'Message'", "in", "elem", ".", "tag", ":", "server_message", "+=", "elem", ".", "text", ".", "strip", "(", "'\\n\\t '", ")", "except", "ElementTree", ".", "ParseError", ":", "server_message", "=", "exception", ".", "response", ".", "text", "message", "+=", "'\\nServer response: \"{}\"'", ".", "format", "(", "server_message", ")", "return", "message" ]
Load a CRMod configuration file
def load_crmod_config ( self , filename ) : with open ( filename , 'r' ) as fid : nr_of_configs = int ( fid . readline ( ) . strip ( ) ) configs = np . loadtxt ( fid ) print ( 'loaded configs:' , configs . shape ) if nr_of_configs != configs . shape [ 0 ] : raise Exception ( 'indicated number of measurements does not equal ' + 'to actual number of measurements' ) ABMN = self . _crmod_to_abmn ( configs [ : , 0 : 2 ] ) self . configs = ABMN
8,393
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L101-L119
[ "def", "alloc_data", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "return", "self", ".", "_alloc_data", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", ":", "return", "self", ".", "_alloc_data", "(", "value", ".", "encode", "(", "'utf-8'", ")", "+", "b'\\0'", ")", "else", ":", "raise", "TypeError", "(", "'No idea how to encode %s'", "%", "repr", "(", "value", ")", ")" ]
return a Nx2 array with the measurement configurations formatted CRTomo style
def _get_crmod_abmn ( self ) : ABMN = np . vstack ( ( self . configs [ : , 0 ] * 1e4 + self . configs [ : , 1 ] , self . configs [ : , 2 ] * 1e4 + self . configs [ : , 3 ] , ) ) . T . astype ( int ) return ABMN
8,394
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L156-L164
[ "def", "unlock", "(", "name", ",", "zk_hosts", "=", "None", ",", "# in case you need to unlock without having run lock (failed execution for example)", "identifier", "=", "None", ",", "max_concurrency", "=", "1", ",", "ephemeral_lease", "=", "False", ",", "profile", "=", "None", ",", "scheme", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "default_acl", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "conn_kwargs", "=", "{", "'profile'", ":", "profile", ",", "'scheme'", ":", "scheme", ",", "'username'", ":", "username", ",", "'password'", ":", "password", ",", "'default_acl'", ":", "default_acl", "}", "if", "__opts__", "[", "'test'", "]", ":", "ret", "[", "'result'", "]", "=", "None", "ret", "[", "'comment'", "]", "=", "'Released lock if it is here'", "return", "ret", "if", "identifier", "is", "None", ":", "identifier", "=", "__grains__", "[", "'id'", "]", "unlocked", "=", "__salt__", "[", "'zk_concurrency.unlock'", "]", "(", "name", ",", "zk_hosts", "=", "zk_hosts", ",", "identifier", "=", "identifier", ",", "max_concurrency", "=", "max_concurrency", ",", "ephemeral_lease", "=", "ephemeral_lease", ",", "*", "*", "conn_kwargs", ")", "if", "unlocked", ":", "ret", "[", "'result'", "]", "=", "True", "else", ":", "ret", "[", "'comment'", "]", "=", "'Unable to find lease for path {0}'", ".", "format", "(", "name", ")", "return", "ret" ]
Write the measurements to the output file in the volt . dat file format that can be read by CRTomo .
def write_crmod_volt ( self , filename , mid ) : ABMN = self . _get_crmod_abmn ( ) if isinstance ( mid , ( list , tuple ) ) : mag_data = self . measurements [ mid [ 0 ] ] pha_data = self . measurements [ mid [ 1 ] ] else : mag_data = self . measurements [ mid ] pha_data = np . zeros ( mag_data . shape ) all_data = np . hstack ( ( ABMN , mag_data [ : , np . newaxis ] , pha_data [ : , np . newaxis ] ) ) with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( ABMN . shape [ 0 ] ) , 'utf-8' , ) ) np . savetxt ( fid , all_data , fmt = '%i %i %f %f' )
8,395
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L166-L196
[ "def", "levenshtein_distance", "(", "word1", ",", "word2", ")", ":", "if", "len", "(", "word1", ")", "<", "len", "(", "word2", ")", ":", "return", "levenshtein_distance", "(", "word2", ",", "word1", ")", "if", "len", "(", "word2", ")", "==", "0", ":", "return", "len", "(", "word1", ")", "previous_row", "=", "list", "(", "range", "(", "len", "(", "word2", ")", "+", "1", ")", ")", "for", "i", ",", "char1", "in", "enumerate", "(", "word1", ")", ":", "current_row", "=", "[", "i", "+", "1", "]", "for", "j", ",", "char2", "in", "enumerate", "(", "word2", ")", ":", "insertions", "=", "previous_row", "[", "j", "+", "1", "]", "+", "1", "deletions", "=", "current_row", "[", "j", "]", "+", "1", "substitutions", "=", "previous_row", "[", "j", "]", "+", "(", "char1", "!=", "char2", ")", "current_row", ".", "append", "(", "min", "(", "insertions", ",", "deletions", ",", "substitutions", ")", ")", "previous_row", "=", "current_row", "return", "previous_row", "[", "-", "1", "]" ]
Write the configurations to a configuration file in the CRMod format All configurations are merged into one previor to writing to file
def write_crmod_config ( self , filename ) : ABMN = self . _get_crmod_abmn ( ) with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( ABMN . shape [ 0 ] ) , 'utf-8' , ) ) np . savetxt ( fid , ABMN . astype ( int ) , fmt = '%i %i' )
8,396
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L198-L214
[ "def", "stop_data_fetch", "(", "self", ")", ":", "if", "self", ".", "_data_fetcher", ":", "self", ".", "_data_fetcher", ".", "stop", ".", "set", "(", ")", "self", ".", "_data_fetcher", "=", "None" ]
Generate dipole - dipole configurations
def gen_dipole_dipole ( self , skipc , skipv = None , stepc = 1 , stepv = 1 , nr_voltage_dipoles = 10 , before_current = False , start_skip = 0 , N = None ) : if N is None and self . nr_electrodes is None : raise Exception ( 'You must provide the number of electrodes' ) elif N is None : N = self . nr_electrodes # by default, current voltage dipoles have the same size if skipv is None : skipv = skipc configs = [ ] # current dipoles for a in range ( 0 , N - skipv - skipc - 3 , stepc ) : b = a + skipc + 1 nr = 0 # potential dipoles before current injection if before_current : for n in range ( a - start_skip - 1 , - 1 , - stepv ) : nr += 1 if nr > nr_voltage_dipoles : continue m = n - skipv - 1 if m < 0 : continue quadpole = np . array ( ( a , b , m , n ) ) + 1 configs . append ( quadpole ) # potential dipoles after current injection nr = 0 for m in range ( b + start_skip + 1 , N - skipv - 1 , stepv ) : nr += 1 if nr > nr_voltage_dipoles : continue n = m + skipv + 1 quadpole = np . array ( ( a , b , m , n ) ) + 1 configs . append ( quadpole ) configs = np . array ( configs ) # now add to the instance if self . configs is None : self . configs = configs else : self . configs = np . vstack ( ( self . configs , configs ) ) return configs
8,397
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L216-L311
[ "def", "_adapt_WSDateTime", "(", "dt", ")", ":", "try", ":", "ts", "=", "int", "(", "(", "dt", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", "-", "datetime", "(", "1970", ",", "1", ",", "1", ",", "tzinfo", "=", "pytz", ".", "utc", ")", ")", ".", "total_seconds", "(", ")", ")", "except", "(", "OverflowError", ",", "OSError", ")", ":", "if", "dt", "<", "datetime", ".", "now", "(", ")", ":", "ts", "=", "0", "else", ":", "ts", "=", "2", "**", "63", "-", "1", "return", "ts" ]
Generate gradient measurements
def gen_gradient ( self , skip = 0 , step = 1 , vskip = 0 , vstep = 1 ) : N = self . nr_electrodes quadpoles = [ ] for a in range ( 1 , N - skip , step ) : b = a + skip + 1 for m in range ( a + 1 , b - vskip - 1 , vstep ) : n = m + vskip + 1 quadpoles . append ( ( a , b , m , n ) ) configs = np . array ( quadpoles ) if configs . size == 0 : return None self . add_to_configs ( configs ) return configs
8,398
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L313-L341
[ "def", "signalize_extensions", "(", ")", ":", "warnings", ".", "warn", "(", "\"DB-API extension cursor.rownumber used\"", ",", "SalesforceWarning", ")", "warnings", ".", "warn", "(", "\"DB-API extension connection.<exception> used\"", ",", "SalesforceWarning", ")", "# TODO", "warnings", ".", "warn", "(", "\"DB-API extension cursor.connection used\"", ",", "SalesforceWarning", ")", "# not implemented DB-API extension cursor.scroll(, SalesforceWarning)", "warnings", ".", "warn", "(", "\"DB-API extension cursor.messages used\"", ",", "SalesforceWarning", ")", "warnings", ".", "warn", "(", "\"DB-API extension connection.messages used\"", ",", "SalesforceWarning", ")", "warnings", ".", "warn", "(", "\"DB-API extension cursor.next(, SalesforceWarning) used\"", ")", "warnings", ".", "warn", "(", "\"DB-API extension cursor.__iter__(, SalesforceWarning) used\"", ")", "warnings", ".", "warn", "(", "\"DB-API extension cursor.lastrowid used\"", ",", "SalesforceWarning", ")", "warnings", ".", "warn", "(", "\"DB-API extension .errorhandler used\"", ",", "SalesforceWarning", ")" ]
remove duplicate entries from 4 - point configurations . If no configurations are provided then use self . configs . Unique configurations are only returned if configs is not None .
def remove_duplicates ( self , configs = None ) : if configs is None : c = self . configs else : c = configs struct = c . view ( c . dtype . descr * 4 ) configs_unique = np . unique ( struct ) . view ( c . dtype ) . reshape ( - 1 , 4 ) if configs is None : self . configs = configs_unique else : return configs_unique
8,399
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L431-L457
[ "def", "_read_body_by_chunk", "(", "self", ",", "response", ",", "file", ",", "raw", "=", "False", ")", ":", "reader", "=", "ChunkedTransferReader", "(", "self", ".", "_connection", ")", "file_is_async", "=", "hasattr", "(", "file", ",", "'drain'", ")", "while", "True", ":", "chunk_size", ",", "data", "=", "yield", "from", "reader", ".", "read_chunk_header", "(", ")", "self", ".", "_data_event_dispatcher", ".", "notify_read", "(", "data", ")", "if", "raw", ":", "file", ".", "write", "(", "data", ")", "if", "not", "chunk_size", ":", "break", "while", "True", ":", "content", ",", "data", "=", "yield", "from", "reader", ".", "read_chunk_body", "(", ")", "self", ".", "_data_event_dispatcher", ".", "notify_read", "(", "data", ")", "if", "not", "content", ":", "if", "raw", ":", "file", ".", "write", "(", "data", ")", "break", "content", "=", "self", ".", "_decompress_data", "(", "content", ")", "if", "file", ":", "file", ".", "write", "(", "content", ")", "if", "file_is_async", ":", "yield", "from", "file", ".", "drain", "(", ")", "content", "=", "self", ".", "_flush_decompressor", "(", ")", "if", "file", ":", "file", ".", "write", "(", "content", ")", "if", "file_is_async", ":", "yield", "from", "file", ".", "drain", "(", ")", "trailer_data", "=", "yield", "from", "reader", ".", "read_trailer", "(", ")", "self", ".", "_data_event_dispatcher", ".", "notify_read", "(", "trailer_data", ")", "if", "file", "and", "raw", ":", "file", ".", "write", "(", "trailer_data", ")", "if", "file_is_async", ":", "yield", "from", "file", ".", "drain", "(", ")", "response", ".", "fields", ".", "parse", "(", "trailer_data", ")" ]