query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Sets the Key to the given Value
def set ( self , key , value , * , flags = None ) : self . append ( { "Verb" : "set" , "Key" : key , "Value" : encode_value ( value , flags , base64 = True ) . decode ( "utf-8" ) , "Flags" : flags } ) return self
11,000
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L356-L370
[ "def", "upload", "(", "self", ",", "params", "=", "{", "}", ")", ":", "if", "self", ".", "upload_token", "is", "not", "None", ":", "# resume upload", "status", "=", "self", ".", "check", "(", ")", "if", "status", "[", "'status'", "]", "!=", "4", ":", "return", "self", ".", "commit", "(", ")", "else", ":", "self", ".", "new_slice", "(", ")", "while", "self", ".", "slice_task_id", "!=", "0", ":", "self", ".", "upload_slice", "(", ")", "return", "self", ".", "commit", "(", ")", "else", ":", "# new upload", "self", ".", "create", "(", "self", ".", "prepare_video_params", "(", "*", "*", "params", ")", ")", "self", ".", "create_file", "(", ")", "self", ".", "new_slice", "(", ")", "while", "self", ".", "slice_task_id", "!=", "0", ":", "self", ".", "upload_slice", "(", ")", "return", "self", ".", "commit", "(", ")" ]
Sets the Key to the given Value with check - and - set semantics
def cas ( self , key , value , * , flags = None , index ) : self . append ( { "Verb" : "cas" , "Key" : key , "Value" : encode_value ( value , flags , base64 = True ) . decode ( "utf-8" ) , "Flags" : flags , "Index" : extract_attr ( index , keys = [ "ModifyIndex" , "Index" ] ) } ) return self
11,001
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L372-L391
[ "def", "wormhole", "(", "context", ",", "dump_timing", ",", "transit_helper", ",", "relay_url", ",", "appid", ")", ":", "context", ".", "obj", "=", "cfg", "=", "Config", "(", ")", "cfg", ".", "appid", "=", "appid", "cfg", ".", "relay_url", "=", "relay_url", "cfg", ".", "transit_helper", "=", "transit_helper", "cfg", ".", "dump_timing", "=", "dump_timing" ]
Locks the Key with the given Session
def lock ( self , key , value , * , flags = None , session ) : self . append ( { "Verb" : "lock" , "Key" : key , "Value" : encode_value ( value , flags , base64 = True ) . decode ( "utf-8" ) , "Flags" : flags , "Session" : extract_attr ( session , keys = [ "ID" ] ) } ) return self
11,002
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L393-L411
[ "async", "def", "unpin_chat_message", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ")", "->", "base", ".", "Boolean", ":", "payload", "=", "generate_payload", "(", "*", "*", "locals", "(", ")", ")", "result", "=", "await", "self", ".", "request", "(", "api", ".", "Methods", ".", "UNPIN_CHAT_MESSAGE", ",", "payload", ")", "return", "result" ]
Fails the transaction if Key does not have a modify index equal to Index
def check_index ( self , key , * , index ) : self . append ( { "Verb" : "check-index" , "Key" : key , "Index" : extract_attr ( index , keys = [ "ModifyIndex" , "Index" ] ) } ) return self
11,003
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L471-L484
[ "def", "_base_placeholder", "(", "self", ")", ":", "base_ph_type", "=", "{", "PP_PLACEHOLDER", ".", "BODY", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "CHART", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "BITMAP", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "CENTER_TITLE", ":", "PP_PLACEHOLDER", ".", "TITLE", ",", "PP_PLACEHOLDER", ".", "ORG_CHART", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "DATE", ":", "PP_PLACEHOLDER", ".", "DATE", ",", "PP_PLACEHOLDER", ".", "FOOTER", ":", "PP_PLACEHOLDER", ".", "FOOTER", ",", "PP_PLACEHOLDER", ".", "MEDIA_CLIP", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "OBJECT", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "PICTURE", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "SLIDE_NUMBER", ":", "PP_PLACEHOLDER", ".", "SLIDE_NUMBER", ",", "PP_PLACEHOLDER", ".", "SUBTITLE", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "TABLE", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "TITLE", ":", "PP_PLACEHOLDER", ".", "TITLE", ",", "}", "[", "self", ".", "_element", ".", "ph_type", "]", "slide_master", "=", "self", ".", "part", ".", "slide_master", "return", "slide_master", ".", "placeholders", ".", "get", "(", "base_ph_type", ",", "None", ")" ]
Fails the transaction if Key is not currently locked by Session
def check_session ( self , key , * , session = None ) : self . append ( { "Verb" : "check-session" , "Key" : key , "Session" : extract_attr ( session , keys = [ "ID" ] ) } ) return self
11,004
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L486-L498
[ "def", "beta_array", "(", "C", ",", "HIGHSCALE", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "beta_odict", "=", "beta", "(", "C", ",", "HIGHSCALE", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "np", ".", "hstack", "(", "[", "np", ".", "asarray", "(", "b", ")", ".", "ravel", "(", ")", "for", "b", "in", "beta_odict", ".", "values", "(", ")", "]", ")" ]
Execute stored operations
async def execute ( self , dc = None , token = None ) : token_id = extract_attr ( token , keys = [ "ID" ] ) try : response = await self . _api . put ( "/v1/txn" , data = self . operations , params = { "dc" : dc , "token" : token_id } ) except ConflictError as error : errors = { elt [ "OpIndex" ] : elt for elt in error . value [ "Errors" ] } operations = [ op [ "KV" ] for op in self . operations ] meta = error . meta raise TransactionError ( errors , operations , meta ) from error except Exception as error : raise error else : self . operations [ : ] = [ ] results = [ ] for _ in response . body [ "Results" ] : data = _ [ "KV" ] if data [ "Value" ] is not None : data [ "Value" ] = decode_value ( data [ "Value" ] , data [ "Flags" ] ) results . append ( data ) return results
11,005
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L542-L579
[ "def", "process", "(", "self", ",", "blob", "=", "None", ")", ":", "try", ":", "blob", "=", "self", ".", "get_blob", "(", "self", ".", "index", ")", "except", "IndexError", ":", "self", ".", "log", ".", "info", "(", "\"Got an IndexError, trying the next file\"", ")", "if", "(", "self", ".", "basename", "or", "self", ".", "filenames", ")", "and", "self", ".", "file_index", "<", "self", ".", "index_stop", ":", "self", ".", "file_index", "+=", "1", "self", ".", "log", ".", "info", "(", "\"Now at file_index={}\"", ".", "format", "(", "self", ".", "file_index", ")", ")", "self", ".", "_reset", "(", ")", "self", ".", "blob_file", ".", "close", "(", ")", "self", ".", "log", ".", "info", "(", "\"Resetting blob index to 0\"", ")", "self", ".", "index", "=", "0", "file_index", "=", "self", ".", "_get_file_index_str", "(", ")", "if", "self", ".", "filenames", ":", "self", ".", "filename", "=", "self", ".", "filenames", "[", "self", ".", "file_index", "-", "1", "]", "elif", "self", ".", "basename", ":", "self", ".", "filename", "=", "\"{}{}{}.evt\"", ".", "format", "(", "self", ".", "basename", ",", "file_index", ",", "self", ".", "suffix", ")", "self", ".", "log", ".", "info", "(", "\"Next filename: {}\"", ".", "format", "(", "self", ".", "filename", ")", ")", "self", ".", "print", "(", "\"Opening {0}\"", ".", "format", "(", "self", ".", "filename", ")", ")", "self", ".", "open_file", "(", "self", ".", "filename", ")", "self", ".", "prepare_blobs", "(", ")", "try", ":", "blob", "=", "self", ".", "get_blob", "(", "self", ".", "index", ")", "except", "IndexError", ":", "self", ".", "log", ".", "warning", "(", "\"No blob found in file {}\"", ".", "format", "(", "self", ".", "filename", ")", ")", "else", ":", "return", "blob", "self", ".", "log", ".", "info", "(", "\"No files left, terminating the pipeline\"", ")", "raise", "StopIteration", "self", ".", "index", "+=", "1", "return", "blob" ]
Send a script to FORM .
def write ( self , script ) : # type: (str) -> None if self . _closed : raise IOError ( 'tried to write to closed connection' ) script = script . strip ( ) if script : assert self . _parentout is not None self . _parentout . write ( script ) self . _parentout . write ( '\n' )
11,006
https://github.com/tueda/python-form/blob/1e5a8464f7a7a6cbbb32411fc2ea3615fd48334b/form/formlink.py#L310-L324
[ "def", "modify_record", "(", "durable_model", ",", "current_revision", ",", "arn", ",", "event_time", ",", "diff_func", ")", ":", "# We want the newest items first.", "# See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html", "items", "=", "list", "(", "durable_model", ".", "query", "(", "arn", ",", "(", "durable_model", ".", "eventTime", "<=", "event_time", ")", ",", "scan_index_forward", "=", "False", ",", "limit", "=", "1", ",", "consistent_read", "=", "True", ")", ")", "if", "items", ":", "latest_revision", "=", "items", "[", "0", "]", "latest_config", "=", "latest_revision", ".", "_get_json", "(", ")", "[", "1", "]", "[", "'attributes'", "]", "# pylint: disable=W0212", "current_config", "=", "current_revision", ".", "_get_json", "(", ")", "[", "1", "]", "[", "'attributes'", "]", "# pylint: disable=W0212", "# Determine if there is truly a difference, disregarding Ephemeral Paths", "diff", "=", "diff_func", "(", "latest_config", ",", "current_config", ")", "if", "diff", ":", "LOG", ".", "debug", "(", "f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} '", "f'CurrentConfig: {json.dumps(current_config)}'", ")", "current_revision", ".", "save", "(", ")", "else", ":", "current_revision", ".", "save", "(", ")", "LOG", ".", "info", "(", "f'[?] Got modify event but no current revision found. Arn: {arn}'", ")" ]
Flush the channel to FORM .
def flush ( self ) : # type: () -> None if self . _closed : raise IOError ( 'tried to flush closed connection' ) assert self . _parentout is not None self . _parentout . flush ( )
11,007
https://github.com/tueda/python-form/blob/1e5a8464f7a7a6cbbb32411fc2ea3615fd48334b/form/formlink.py#L326-L337
[ "def", "modify_record", "(", "durable_model", ",", "current_revision", ",", "arn", ",", "event_time", ",", "diff_func", ")", ":", "# We want the newest items first.", "# See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html", "items", "=", "list", "(", "durable_model", ".", "query", "(", "arn", ",", "(", "durable_model", ".", "eventTime", "<=", "event_time", ")", ",", "scan_index_forward", "=", "False", ",", "limit", "=", "1", ",", "consistent_read", "=", "True", ")", ")", "if", "items", ":", "latest_revision", "=", "items", "[", "0", "]", "latest_config", "=", "latest_revision", ".", "_get_json", "(", ")", "[", "1", "]", "[", "'attributes'", "]", "# pylint: disable=W0212", "current_config", "=", "current_revision", ".", "_get_json", "(", ")", "[", "1", "]", "[", "'attributes'", "]", "# pylint: disable=W0212", "# Determine if there is truly a difference, disregarding Ephemeral Paths", "diff", "=", "diff_func", "(", "latest_config", ",", "current_config", ")", "if", "diff", ":", "LOG", ".", "debug", "(", "f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} '", "f'CurrentConfig: {json.dumps(current_config)}'", ")", "current_revision", ".", "save", "(", ")", "else", ":", "current_revision", ".", "save", "(", ")", "LOG", ".", "info", "(", "f'[?] Got modify event but no current revision found. Arn: {arn}'", ")" ]
Compiles the delete sql statement
def compile ( self ) : sql = '' sql += 'DELETE FROM ' + self . dialect . quote_table ( self . _table ) if self . _where : sql += ' WHERE ' + self . compile_condition ( self . _where ) if self . _order_by : sql += ' ' + self . compile_order_by ( self . _order_by ) if self . _limit : sql += ' LIMIT ' + self . _limit return sql
11,008
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/query/delete.py#L40-L51
[ "def", "metricCompute", "(", "self", ",", "sensorToBody", ",", "bodyToSpecificObject", ")", ":", "overlaps", "=", "self", ".", "metricConnections", ".", "computeActivity", "(", "{", "\"bodyToSpecificObject\"", ":", "bodyToSpecificObject", ",", "\"sensorToBody\"", ":", "sensorToBody", ",", "}", ")", "self", ".", "activeMetricSegments", "=", "np", ".", "where", "(", "overlaps", ">=", "2", ")", "[", "0", "]", "self", ".", "activeCells", "=", "np", ".", "unique", "(", "self", ".", "metricConnections", ".", "mapSegmentsToCells", "(", "self", ".", "activeMetricSegments", ")", ")" ]
Clear and reset to orignal state
def clear ( self ) : WhereQuery . clear ( self ) self . _table = None self . _parameters = [ ] self . _sql = None
11,009
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/query/delete.py#L53-L58
[ "def", "multi_load_data_custom", "(", "Channel", ",", "TraceTitle", ",", "RunNos", ",", "directoryPath", "=", "'.'", ",", "calcPSD", "=", "True", ",", "NPerSegmentPSD", "=", "1000000", ")", ":", "# files = glob('{}/*'.format(directoryPath))", "# files_CorrectChannel = []", "# for file_ in files:", "# if 'C{}'.format(Channel) in file_:", "# files_CorrectChannel.append(file_)", "# files_CorrectRunNo = []", "# for RunNo in RunNos:", "# files_match = _fnmatch.filter(", "# files_CorrectChannel, '*C{}'.format(Channel)+TraceTitle+str(RunNo).zfill(5)+'.*')", "# for file_ in files_match:", "# files_CorrectRunNo.append(file_)", "matching_files", "=", "search_data_custom", "(", "Channel", ",", "TraceTitle", ",", "RunNos", ",", "directoryPath", ")", "cpu_count", "=", "_cpu_count", "(", ")", "workerPool", "=", "_Pool", "(", "cpu_count", ")", "# for filepath in files_CorrectRepeatNo:", "# print(filepath)", "# data.append(load_data(filepath))", "load_data_partial", "=", "_partial", "(", "load_data", ",", "calcPSD", "=", "calcPSD", ",", "NPerSegmentPSD", "=", "NPerSegmentPSD", ")", "data", "=", "workerPool", ".", "map", "(", "load_data_partial", ",", "matching_files", ")", "workerPool", ".", "close", "(", ")", "workerPool", ".", "terminate", "(", ")", "workerPool", ".", "join", "(", ")", "return", "data" ]
Updates this item to mark the item as loading . This will create a QLabel with the loading ajax spinner to indicate that progress is occurring .
def startLoading ( self ) : if self . _loading : return False tree = self . treeWidget ( ) if not tree : return self . _loading = True self . setText ( 0 , '' ) # create the label for this item lbl = QtGui . QLabel ( self . treeWidget ( ) ) lbl . setMovie ( XLoaderWidget . getMovie ( ) ) lbl . setAlignment ( QtCore . Qt . AlignCenter ) tree . setItemWidget ( self , 0 , lbl ) try : tree . loadStarted . emit ( self ) except AttributeError : pass return True
11,010
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xloaderitem.py#L73-L100
[ "def", "del_restriction", "(", "self", ",", "command", ",", "user", ",", "event_types", ")", ":", "if", "user", ".", "lower", "(", ")", "in", "self", ".", "commands_rights", "[", "command", "]", ":", "for", "event_type", "in", "event_types", ":", "try", ":", "self", ".", "commands_rights", "[", "command", "]", "[", "user", ".", "lower", "(", ")", "]", ".", "remove", "(", "event_type", ")", "except", "ValueError", ":", "pass", "if", "not", "self", ".", "commands_rights", "[", "command", "]", "[", "user", ".", "lower", "(", ")", "]", ":", "self", ".", "commands_rights", "[", "command", "]", ".", "pop", "(", "user", ".", "lower", "(", ")", ")" ]
Emits the current index changed signal provided signals are not blocked .
def emitCurrentChanged ( self ) : if not self . signalsBlocked ( ) : self . currentIndexChanged . emit ( self . currentIndex ( ) ) self . currentUrlChanged . emit ( self . currentUrl ( ) ) self . canGoBackChanged . emit ( self . canGoBack ( ) ) self . canGoForwardChanged . emit ( self . canGoForward ( ) )
11,011
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xhistorystack.py#L94-L103
[ "def", "wormhole", "(", "context", ",", "dump_timing", ",", "transit_helper", ",", "relay_url", ",", "appid", ")", ":", "context", ".", "obj", "=", "cfg", "=", "Config", "(", ")", "cfg", ".", "appid", "=", "appid", "cfg", ".", "relay_url", "=", "relay_url", "cfg", ".", "transit_helper", "=", "transit_helper", "cfg", ".", "dump_timing", "=", "dump_timing" ]
Goes to the home url . If there is no home url specifically set then \ this will go to the first url in the history . Otherwise it will \ look to see if the home url is in the stack and go to that level if \ the home url is not found then it will be pushed to the top of the \ stack using the push method .
def goHome ( self ) : if not self . canGoBack ( ) : return '' if self . homeUrl ( ) : self . push ( self . homeUrl ( ) ) self . _blockStack = True self . _index = 0 self . emitCurrentChanged ( ) self . _blockStack = False return self . currentUrl ( )
11,012
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xhistorystack.py#L141-L159
[ "def", "create_calcs", "(", "self", ")", ":", "specs", "=", "self", ".", "_combine_core_aux_specs", "(", ")", "for", "spec", "in", "specs", ":", "spec", "[", "'dtype_out_time'", "]", "=", "_prune_invalid_time_reductions", "(", "spec", ")", "return", "[", "Calc", "(", "*", "*", "sp", ")", "for", "sp", "in", "specs", "]" ]
OpenVPN user_pass_verify method
def cli ( conf ) : config = init_config ( conf ) nas_id = config . get ( 'DEFAULT' , 'nas_id' ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) secret = config . get ( 'DEFAULT' , 'radius_secret' ) radius_addr = config . get ( 'DEFAULT' , 'radius_addr' ) radius_auth_port = config . getint ( 'DEFAULT' , 'radius_auth_port' ) radius_timeout = config . getint ( 'DEFAULT' , 'radius_timeout' ) client_config_dir = config . get ( 'DEFAULT' , 'client_config_dir' ) username = os . environ . get ( 'username' ) req = { 'User-Name' : username } req [ 'CHAP-Challenge' ] = get_challenge ( ) req [ 'CHAP-Password-Plaintext' ] = os . environ . get ( 'password' ) req [ "NAS-IP-Address" ] = nas_addr req [ "NAS-Port-Id" ] = '0/0/0:0.0' req [ "NAS-Port" ] = 0 req [ "Service-Type" ] = "Login-User" req [ "NAS-Identifier" ] = nas_id req [ "Called-Station-Id" ] = '00:00:00:00:00:00' req [ "Calling-Station-Id" ] = '00:00:00:00:00:00' # req["Framed-IP-Address"] = os.environ.get('ifconfig_pool_remote_ip') # log.msg("radius auth: %s" % repr(req)) def shutdown ( exitcode = 0 ) : reactor . addSystemEventTrigger ( 'after' , 'shutdown' , os . _exit , exitcode ) reactor . stop ( ) def onresp ( r ) : if r . code == packet . AccessAccept : try : ccdattrs = [ ] userip = get_radius_addr_attr ( r , 8 ) if userip : ccdattrs . append ( 'ifconfig-push {0} 255.255.255.0' . format ( userip ) ) with open ( os . path . join ( client_config_dir , username ) , 'wb' ) as ccdfs : ccdfs . write ( '\n' . join ( ccdattrs ) ) except : traceback . print_exc ( ) shutdown ( 0 ) else : shutdown ( 1 ) def onerr ( e ) : log . err ( e ) shutdown ( 1 ) d = client . send_auth ( str ( secret ) , get_dictionary ( ) , radius_addr , authport = radius_auth_port , debug = True , * * req ) d . addCallbacks ( onresp , onerr ) reactor . callLater ( radius_timeout , shutdown , 1 ) reactor . run ( )
11,013
https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/user_pass_verify.py#L24-L78
[ "def", "_add_entry", "(", "self", ",", "formdata", "=", "None", ",", "data", "=", "unset_value", ",", "index", "=", "None", ")", ":", "if", "formdata", ":", "prefix", "=", "'-'", ".", "join", "(", "(", "self", ".", "name", ",", "str", "(", "index", ")", ")", ")", "basekey", "=", "'-'", ".", "join", "(", "(", "prefix", ",", "'{0}'", ")", ")", "idkey", "=", "basekey", ".", "format", "(", "'id'", ")", "if", "prefix", "in", "formdata", ":", "formdata", "[", "idkey", "]", "=", "formdata", ".", "pop", "(", "prefix", ")", "if", "hasattr", "(", "self", ".", "nested_model", ",", "'id'", ")", "and", "idkey", "in", "formdata", ":", "id", "=", "self", ".", "nested_model", ".", "id", ".", "to_python", "(", "formdata", "[", "idkey", "]", ")", "data", "=", "get_by", "(", "self", ".", "initial_data", ",", "'id'", ",", "id", ")", "initial", "=", "flatten_json", "(", "self", ".", "nested_form", ",", "data", ".", "to_mongo", "(", ")", ",", "prefix", ")", "for", "key", ",", "value", "in", "initial", ".", "items", "(", ")", ":", "if", "key", "not", "in", "formdata", ":", "formdata", "[", "key", "]", "=", "value", "else", ":", "data", "=", "None", "return", "super", "(", "NestedModelList", ",", "self", ")", ".", "_add_entry", "(", "formdata", ",", "data", ",", "index", ")" ]
Creates a new session
async def create ( self , session , * , dc = None ) : response = await self . _api . put ( "/v1/session/create" , data = session , params = { "dc" : dc } ) return response . body
11,014
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/session_endpoint.py#L18-L76
[ "def", "do_watch", "(", "self", ",", "*", "args", ")", ":", "tables", "=", "[", "]", "if", "not", "self", ".", "engine", ".", "cached_descriptions", ":", "self", ".", "engine", ".", "describe_all", "(", ")", "all_tables", "=", "list", "(", "self", ".", "engine", ".", "cached_descriptions", ")", "for", "arg", "in", "args", ":", "candidates", "=", "set", "(", "(", "t", "for", "t", "in", "all_tables", "if", "fnmatch", "(", "t", ",", "arg", ")", ")", ")", "for", "t", "in", "sorted", "(", "candidates", ")", ":", "if", "t", "not", "in", "tables", ":", "tables", ".", "append", "(", "t", ")", "mon", "=", "Monitor", "(", "self", ".", "engine", ",", "tables", ")", "mon", ".", "start", "(", ")" ]
Destroys a given session
async def destroy ( self , session , * , dc = None ) : session_id = extract_attr ( session , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/session/destroy" , session_id , params = { "dc" : dc } ) return response . body is True
11,015
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/session_endpoint.py#L78-L91
[ "def", "generate_http_manifest", "(", "self", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "translate_path", "(", "self", ".", "path", ")", ")", "self", ".", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "base_path", ")", "admin_metadata_fpath", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "\".dtool\"", ",", "\"dtool\"", ")", "with", "open", "(", "admin_metadata_fpath", ")", "as", "fh", ":", "admin_metadata", "=", "json", ".", "load", "(", "fh", ")", "http_manifest", "=", "{", "\"admin_metadata\"", ":", "admin_metadata", ",", "\"manifest_url\"", ":", "self", ".", "generate_url", "(", "\".dtool/manifest.json\"", ")", ",", "\"readme_url\"", ":", "self", ".", "generate_url", "(", "\"README.yml\"", ")", ",", "\"overlays\"", ":", "self", ".", "generate_overlay_urls", "(", ")", ",", "\"item_urls\"", ":", "self", ".", "generate_item_urls", "(", ")", "}", "return", "bytes", "(", "json", ".", "dumps", "(", "http_manifest", ")", ",", "\"utf-8\"", ")" ]
Queries a given session
async def info ( self , session , * , dc = None , watch = None , consistency = None ) : session_id = extract_attr ( session , keys = [ "ID" ] ) response = await self . _api . get ( "/v1/session/info" , session_id , watch = watch , consistency = consistency , params = { "dc" : dc } ) try : result = response . body [ 0 ] except IndexError : meta = extract_meta ( response . headers ) raise NotFound ( "No session for %r" % session_id , meta = meta ) return consul ( result , meta = extract_meta ( response . headers ) )
11,016
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/session_endpoint.py#L95-L133
[ "def", "GetAttachmentIdFromMediaId", "(", "media_id", ")", ":", "altchars", "=", "'+-'", "if", "not", "six", ".", "PY2", ":", "altchars", "=", "altchars", ".", "encode", "(", "'utf-8'", ")", "# altchars for '+' and '/'. We keep '+' but replace '/' with '-'", "buffer", "=", "base64", ".", "b64decode", "(", "str", "(", "media_id", ")", ",", "altchars", ")", "resoure_id_length", "=", "20", "attachment_id", "=", "''", "if", "len", "(", "buffer", ")", ">", "resoure_id_length", ":", "# We are cutting off the storage index.", "attachment_id", "=", "base64", ".", "b64encode", "(", "buffer", "[", "0", ":", "resoure_id_length", "]", ",", "altchars", ")", "if", "not", "six", ".", "PY2", ":", "attachment_id", "=", "attachment_id", ".", "decode", "(", "'utf-8'", ")", "else", ":", "attachment_id", "=", "media_id", "return", "attachment_id" ]
Renews a TTL - based session
async def renew ( self , session , * , dc = None ) : session_id = extract_attr ( session , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/session/renew" , session_id , params = { "dc" : dc } ) try : result = response . body [ 0 ] except IndexError : meta = extract_meta ( response . headers ) raise NotFound ( "No session for %r" % session_id , meta = meta ) return consul ( result , meta = extract_meta ( response . headers ) )
11,017
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/session_endpoint.py#L198-L237
[ "def", "characters", "(", "self", ",", "data", ")", ":", "data", "=", "data", ".", "encode", "(", "self", ".", "encoding", ",", "\"ignore\"", ")", "self", ".", "fd", ".", "write", "(", "data", ")" ]
Lazily compile a regex with flags .
def _lazy_re_compile ( regex , flags = 0 ) : def _compile ( ) : # Compile the regex if it was not passed pre-compiled. if isinstance ( regex , str ) : return re . compile ( regex , flags ) else : assert not flags , "flags must be empty if regex is passed pre-compiled" return regex return SimpleLazyObject ( _compile )
11,018
https://github.com/adonisnafeh/urlvalidator/blob/008438365faa00b2c580e3991068ec6b161c3578/urlvalidator/utils.py#L95-L104
[ "def", "conv_lstm_2d", "(", "inputs", ",", "state", ",", "output_channels", ",", "kernel_size", "=", "5", ",", "name", "=", "None", ",", "spatial_dims", "=", "None", ")", ":", "input_shape", "=", "common_layers", ".", "shape_list", "(", "inputs", ")", "batch_size", ",", "input_channels", "=", "input_shape", "[", "0", "]", ",", "input_shape", "[", "-", "1", "]", "if", "spatial_dims", "is", "None", ":", "input_shape", "=", "input_shape", "[", "1", ":", "]", "else", ":", "input_shape", "=", "spatial_dims", "+", "[", "input_channels", "]", "cell", "=", "tf", ".", "contrib", ".", "rnn", ".", "ConvLSTMCell", "(", "2", ",", "input_shape", ",", "output_channels", ",", "[", "kernel_size", ",", "kernel_size", "]", ",", "name", "=", "name", ")", "if", "state", "is", "None", ":", "state", "=", "cell", ".", "zero_state", "(", "batch_size", ",", "tf", ".", "float32", ")", "outputs", ",", "new_state", "=", "cell", "(", "inputs", ",", "state", ")", "return", "outputs", ",", "new_state" ]
Class decorator that allows the decorated class to be serialized by the migrations subsystem .
def deconstructible ( * args , path = None ) : def decorator ( klass ) : def __new__ ( cls , * args , * * kwargs ) : # We capture the arguments to make returning them trivial obj = super ( klass , cls ) . __new__ ( cls ) obj . _constructor_args = ( args , kwargs ) return obj klass . __new__ = staticmethod ( __new__ ) return klass if not args : return decorator return decorator ( * args )
11,019
https://github.com/adonisnafeh/urlvalidator/blob/008438365faa00b2c580e3991068ec6b161c3578/urlvalidator/utils.py#L107-L127
[ "def", "free_extent_count", "(", "self", ")", ":", "self", ".", "open", "(", ")", "count", "=", "lvm_vg_get_free_extent_count", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "count" ]
Clears the text from the search edit .
def clear ( self ) : self . _searchEdit . blockSignals ( True ) self . _searchEdit . setText ( '' ) self . _searchEdit . blockSignals ( False )
11,020
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/menus/xmenu.py#L150-L156
[ "def", "define_Precip", "(", "self", ",", "diameter", ",", "density", ",", "molecweight", ",", "alumMPM", ")", ":", "self", ".", "PrecipDiameter", "=", "diameter", "self", ".", "PrecipDensity", "=", "density", "self", ".", "PrecipMolecWeight", "=", "molecweight", "self", ".", "PrecipAluminumMPM", "=", "alumMPM" ]
Clears out the advanced action map .
def clearAdvancedActions ( self ) : self . _advancedMap . clear ( ) margins = list ( self . getContentsMargins ( ) ) margins [ 2 ] = 0 self . setContentsMargins ( * margins )
11,021
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/menus/xmenu.py#L389-L396
[ "def", "loadInternalSheet", "(", "klass", ",", "p", ",", "*", "*", "kwargs", ")", ":", "vs", "=", "klass", "(", "p", ".", "name", ",", "source", "=", "p", ",", "*", "*", "kwargs", ")", "options", ".", "_set", "(", "'encoding'", ",", "'utf8'", ",", "vs", ")", "if", "p", ".", "exists", "(", ")", ":", "vd", ".", "sheets", ".", "insert", "(", "0", ",", "vs", ")", "vs", ".", "reload", ".", "__wrapped__", "(", "vs", ")", "vd", ".", "sheets", ".", "pop", "(", "0", ")", "return", "vs" ]
Rebuilds the buttons for the advanced actions .
def rebuildButtons ( self ) : for btn in self . findChildren ( XAdvancedButton ) : btn . close ( ) btn . setParent ( None ) btn . deleteLater ( ) for standard , advanced in self . _advancedMap . items ( ) : rect = self . actionGeometry ( standard ) btn = XAdvancedButton ( self ) btn . setFixedWidth ( 22 ) btn . setFixedHeight ( rect . height ( ) ) btn . setDefaultAction ( advanced ) btn . setAutoRaise ( True ) btn . move ( rect . right ( ) + 1 , rect . top ( ) ) btn . show ( ) if btn . icon ( ) . isNull ( ) : btn . setIcon ( QIcon ( resources . find ( 'img/advanced.png' ) ) ) btn . clicked . connect ( self . acceptAdvanced )
11,022
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/menus/xmenu.py#L440-L462
[ "def", "_set_max_value", "(", "self", ",", "max_value", ")", ":", "self", ".", "_external_max_value", "=", "max_value", "# Check that the current value of the parameter is still within the boundaries. If not, issue a warning", "if", "self", ".", "_external_max_value", "is", "not", "None", "and", "self", ".", "value", ">", "self", ".", "_external_max_value", ":", "warnings", ".", "warn", "(", "\"The current value of the parameter %s (%s) \"", "\"was above the new maximum %s.\"", "%", "(", "self", ".", "name", ",", "self", ".", "value", ",", "self", ".", "_external_max_value", ")", ",", "exceptions", ".", "RuntimeWarning", ")", "self", ".", "value", "=", "self", ".", "_external_max_value" ]
Rebuilds the information for this scene .
def rebuild ( self ) : self . _buildData . clear ( ) self . _dateGrid . clear ( ) self . _dateTimeGrid . clear ( ) curr_min = self . _minimumDate curr_max = self . _maximumDate self . _maximumDate = QDate ( ) self . _minimumDate = QDate ( ) self . markForRebuild ( False ) # rebuilds the month view if ( self . currentMode ( ) == XCalendarScene . Mode . Month ) : self . rebuildMonth ( ) elif ( self . currentMode ( ) in ( XCalendarScene . Mode . Week , XCalendarScene . Mode . Day ) ) : self . rebuildDays ( ) # rebuild the items in the scene items = sorted ( self . items ( ) ) for item in items : item . setPos ( 0 , 0 ) item . hide ( ) for item in items : if ( isinstance ( item , XCalendarItem ) ) : item . rebuild ( ) if ( curr_min != self . _minimumDate or curr_max != self . _maximumDate ) : parent = self . parent ( ) if ( parent and not parent . signalsBlocked ( ) ) : parent . dateRangeChanged . emit ( self . _minimumDate , self . _maximumDate )
11,023
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcalendarwidget/xcalendarscene.py#L253-L290
[ "def", "_mmUpdateDutyCycles", "(", "self", ")", ":", "period", "=", "self", ".", "getDutyCyclePeriod", "(", ")", "unionSDRArray", "=", "numpy", ".", "zeros", "(", "self", ".", "getNumColumns", "(", ")", ")", "unionSDRArray", "[", "list", "(", "self", ".", "_mmTraces", "[", "\"unionSDR\"", "]", ".", "data", "[", "-", "1", "]", ")", "]", "=", "1", "self", ".", "_mmData", "[", "\"unionSDRDutyCycle\"", "]", "=", "UnionTemporalPoolerMonitorMixin", ".", "_mmUpdateDutyCyclesHelper", "(", "self", ".", "_mmData", "[", "\"unionSDRDutyCycle\"", "]", ",", "unionSDRArray", ",", "period", ")", "self", ".", "_mmData", "[", "\"persistenceDutyCycle\"", "]", "=", "UnionTemporalPoolerMonitorMixin", ".", "_mmUpdateDutyCyclesHelper", "(", "self", ".", "_mmData", "[", "\"persistenceDutyCycle\"", "]", ",", "self", ".", "_poolingActivation", ",", "period", ")" ]
Sets time in seconds since Epoch
def set ( self , time ) : self . _time = time self . _pb . sec = int ( self . _time ) self . _pb . nsec = int ( ( self . _time - self . _pb . sec ) * 10 ** 9 )
11,024
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/timestamp.py#L56-L67
[ "def", "gen_binder_rst", "(", "fpath", ",", "binder_conf", ",", "gallery_conf", ")", ":", "binder_conf", "=", "check_binder_conf", "(", "binder_conf", ")", "binder_url", "=", "gen_binder_url", "(", "fpath", ",", "binder_conf", ",", "gallery_conf", ")", "rst", "=", "(", "\"\\n\"", "\" .. container:: binder-badge\\n\\n\"", "\" .. image:: https://mybinder.org/badge_logo.svg\\n\"", "\" :target: {}\\n\"", "\" :width: 150 px\\n\"", ")", ".", "format", "(", "binder_url", ")", "return", "rst" ]
Building the sql expression
def compile ( self , db ) : sql = self . expression if self . alias : sql += ( ' AS ' + db . quote_column ( self . alias ) ) return sql
11,025
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/query/expr.py#L26-L34
[ "def", "open", "(", "self", ",", "uri", ",", "*", "*", "kwargs", ")", ":", "handler", "=", "self", ".", "handler", "(", "uri", ".", "scheme", "(", ")", ")", "if", "handler", "is", "None", ":", "raise", "WSchemeCollection", ".", "NoHandlerFound", "(", "uri", ")", "if", "uri", ".", "scheme", "(", ")", "is", "None", ":", "uri", ".", "component", "(", "'scheme'", ",", "handler", ".", "scheme_specification", "(", ")", ".", "scheme_name", "(", ")", ")", "if", "handler", ".", "scheme_specification", "(", ")", ".", "is_compatible", "(", "uri", ")", "is", "False", ":", "raise", "WSchemeCollection", ".", "SchemeIncompatible", "(", "uri", ")", "return", "handler", ".", "create_handler", "(", "uri", ",", "*", "*", "kwargs", ")" ]
Registers a new local check
async def register ( self , check , * , token = None ) : token_id = extract_attr ( token , keys = [ "ID" ] ) params = { "token" : token_id } response = await self . _api . put ( "/v1/agent/check/register" , params = params , data = check ) return response . status == 200
11,026
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/checks_endpoint.py#L34-L123
[ "def", "grep_log", "(", "self", ",", "expr", ",", "filename", "=", "'system.log'", ",", "from_mark", "=", "None", ")", ":", "matchings", "=", "[", "]", "pattern", "=", "re", ".", "compile", "(", "expr", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "get_path", "(", ")", ",", "'logs'", ",", "filename", ")", ")", "as", "f", ":", "if", "from_mark", ":", "f", ".", "seek", "(", "from_mark", ")", "for", "line", "in", "f", ":", "m", "=", "pattern", ".", "search", "(", "line", ")", "if", "m", ":", "matchings", ".", "append", "(", "(", "line", ",", "m", ")", ")", "return", "matchings" ]
Deregisters a local check
async def deregister ( self , check ) : check_id = extract_attr ( check , keys = [ "CheckID" , "ID" ] ) response = await self . _api . get ( "/v1/agent/check/deregister" , check_id ) return response . status == 200
11,027
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/checks_endpoint.py#L125-L137
[ "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" ]
Marks a local check as passing warning or critical
async def mark ( self , check , status , * , note = None ) : check_id = extract_attr ( check , keys = [ "CheckID" , "ID" ] ) data = { "Status" : status , "Output" : note } response = await self . _api . put ( "/v1/agent/check/update" , check_id , data = data ) return response . status == 200
11,028
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/checks_endpoint.py#L172-L182
[ "def", "_SeparateTypes", "(", "self", ",", "metadata_value_pairs", ")", ":", "registry_pairs", "=", "[", "]", "file_pairs", "=", "[", "]", "match_pairs", "=", "[", "]", "for", "metadata", ",", "result", "in", "metadata_value_pairs", ":", "if", "(", "result", ".", "stat_entry", ".", "pathspec", ".", "pathtype", "==", "rdf_paths", ".", "PathSpec", ".", "PathType", ".", "REGISTRY", ")", ":", "registry_pairs", ".", "append", "(", "(", "metadata", ",", "result", ".", "stat_entry", ")", ")", "else", ":", "file_pairs", ".", "append", "(", "(", "metadata", ",", "result", ")", ")", "match_pairs", ".", "extend", "(", "[", "(", "metadata", ",", "match", ")", "for", "match", "in", "result", ".", "matches", "]", ")", "return", "registry_pairs", ",", "file_pairs", ",", "match_pairs" ]
Return user by username if find in database otherwise None
def find_by_username ( self , username ) : data = ( db . select ( self . table ) . select ( 'username' , 'email' , 'real_name' , 'password' , 'bio' , 'status' , 'role' , 'uid' ) . condition ( 'username' , username ) . execute ( ) ) if data : return self . load ( data [ 0 ] , self . model )
11,029
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/samples/orm.py#L56-L63
[ "def", "perturbed_contents", "(", "self", ")", ":", "animal", "=", "json", ".", "loads", "(", "self", ".", "contents", ")", "for", "prop", ",", "prop_range", "in", "self", ".", "properties", ".", "items", "(", ")", ":", "range", "=", "prop_range", "[", "1", "]", "-", "prop_range", "[", "0", "]", "jittered", "=", "animal", "[", "prop", "]", "+", "random", ".", "gauss", "(", "0", ",", "0.1", "*", "range", ")", "animal", "[", "prop", "]", "=", "max", "(", "min", "(", "jittered", ",", "prop_range", "[", "1", "]", ")", ",", "prop_range", "[", "0", "]", ")", "return", "json", ".", "dumps", "(", "animal", ")" ]
Find the users match the condition in kw
def search ( self , * * kw ) : q = db . select ( self . table ) . condition ( 'status' , 'active' ) for k , v in kw : q . condition ( k , v ) data = q . execute ( ) users = [ ] for user in data : users . append ( self . load ( user , self . model ) ) return users
11,030
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/samples/orm.py#L70-L79
[ "def", "getOverlayKey", "(", "self", ",", "ulOverlayHandle", ",", "pchValue", ",", "unBufferSize", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getOverlayKey", "pError", "=", "EVROverlayError", "(", ")", "result", "=", "fn", "(", "ulOverlayHandle", ",", "pchValue", ",", "unBufferSize", ",", "byref", "(", "pError", ")", ")", "return", "result", ",", "pError" ]
Paginate the posts
def paginate ( self , page = 1 , perpage = 10 , category = None ) : q = db . select ( self . table ) . fields ( 'title' , 'slug' , 'description' , 'html' , 'css' , 'js' , 'category' , 'status' , 'comments' , 'author' , 'created' , 'pid' ) if category : q . condition ( 'category' , category ) results = ( q . limit ( perpage ) . offset ( ( page - 1 ) * perpage ) . order_by ( 'created' , 'DESC' ) . execute ( ) ) return [ self . load ( data , self . model ) for data in results ]
11,031
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/samples/orm.py#L124-L132
[ "def", "_clean_args", "(", "sys_argv", ",", "args", ")", ":", "base", "=", "[", "x", "for", "x", "in", "sys_argv", "if", "x", ".", "startswith", "(", "\"-\"", ")", "or", "not", "args", ".", "datadir", "==", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "x", ")", ")", "]", "# Remove installer only options we don't pass on", "base", "=", "[", "x", "for", "x", "in", "base", "if", "x", "not", "in", "set", "(", "[", "\"--minimize-disk\"", "]", ")", "]", "if", "\"--nodata\"", "in", "base", ":", "base", ".", "remove", "(", "\"--nodata\"", ")", "else", ":", "base", ".", "append", "(", "\"--data\"", ")", "return", "base" ]
Clears the current scene of all the items and layers .
def clear ( self ) : self . setCurrentLayer ( None ) self . _layers = [ ] self . _cache . clear ( ) super ( XNodeScene , self ) . clear ( )
11,032
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L535-L544
[ "def", "process_from_web", "(", ")", ":", "logger", ".", "info", "(", "'Downloading table from %s'", "%", "trrust_human_url", ")", "res", "=", "requests", ".", "get", "(", "trrust_human_url", ")", "res", ".", "raise_for_status", "(", ")", "df", "=", "pandas", ".", "read_table", "(", "io", ".", "StringIO", "(", "res", ".", "text", ")", ")", "tp", "=", "TrrustProcessor", "(", "df", ")", "tp", ".", "extract_statements", "(", ")", "return", "tp" ]
Rebuilds the grid lines based on the current settings and \ scene width . This method is triggered automatically and \ shouldn t need to be manually called .
def rebuild ( self ) : rect = self . sceneRect ( ) x = rect . left ( ) y = rect . top ( ) w = rect . width ( ) h = rect . height ( ) # calculate background gridlines cx = x + ( w / 2 ) cy = y + ( h / 2 ) self . _centerLines = [ QLine ( cx , rect . top ( ) , cx , rect . bottom ( ) ) , QLine ( rect . left ( ) , cy , rect . right ( ) , cy ) ] # create the horizontal grid lines delta = self . cellHeight ( ) minor_lines = [ ] major_lines = [ ] count = 1 while delta < ( h / 2 ) : pos_line = QLine ( x , cy + delta , x + w , cy + delta ) neg_line = QLine ( x , cy - delta , x + w , cy - delta ) # every 10th line will be a major line if count == 10 : major_lines . append ( pos_line ) major_lines . append ( neg_line ) count = 1 else : minor_lines . append ( pos_line ) minor_lines . append ( neg_line ) # update the current y location delta += self . cellHeight ( ) count += 1 # create the vertical grid lines delta = self . cellWidth ( ) count = 1 while delta < ( w / 2 ) : pos_line = QLine ( cx + delta , y , cx + delta , y + h ) neg_line = QLine ( cx - delta , y , cx - delta , y + h ) # every 10th line will be a major line if count == 10 : major_lines . append ( pos_line ) major_lines . append ( neg_line ) count = 1 else : minor_lines . append ( pos_line ) minor_lines . append ( neg_line ) # update the current y location delta += self . cellWidth ( ) count += 1 # set the line cache self . _majorLines = major_lines self . _minorLines = minor_lines # unmark the scene as being dirty self . setDirty ( False )
11,033
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L1127-L1193
[ "def", "Marginal", "(", "self", ",", "i", ",", "name", "=", "''", ")", ":", "pmf", "=", "Pmf", "(", "name", "=", "name", ")", "for", "vs", ",", "prob", "in", "self", ".", "Items", "(", ")", ":", "pmf", ".", "Incr", "(", "vs", "[", "i", "]", ",", "prob", ")", "return", "pmf" ]
Selects all the items in the scene .
def selectAll ( self ) : currLayer = self . _currentLayer for item in self . items ( ) : layer = item . layer ( ) if ( layer == currLayer or not layer ) : item . setSelected ( True )
11,034
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L1280-L1288
[ "def", "post", "(", "self", ",", "uri", ",", "body", "=", "None", ",", "logon_required", "=", "True", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_urihandler", ".", "post", "(", "self", ".", "_hmc", ",", "uri", ",", "body", ",", "logon_required", ",", "wait_for_completion", ")", "except", "HTTPError", "as", "exc", ":", "raise", "zhmcclient", ".", "HTTPError", "(", "exc", ".", "response", "(", ")", ")", "except", "ConnectionError", "as", "exc", ":", "raise", "zhmcclient", ".", "ConnectionError", "(", "exc", ".", "message", ",", "None", ")" ]
Inverts the currently selected items in the scene .
def selectInvert ( self ) : currLayer = self . _currentLayer for item in self . items ( ) : layer = item . layer ( ) if ( layer == currLayer or not layer ) : item . setSelected ( not item . isSelected ( ) )
11,035
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L1290-L1298
[ "def", "post", "(", "self", ",", "uri", ",", "body", "=", "None", ",", "logon_required", "=", "True", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_urihandler", ".", "post", "(", "self", ".", "_hmc", ",", "uri", ",", "body", ",", "logon_required", ",", "wait_for_completion", ")", "except", "HTTPError", "as", "exc", ":", "raise", "zhmcclient", ".", "HTTPError", "(", "exc", ".", "response", "(", ")", ")", "except", "ConnectionError", "as", "exc", ":", "raise", "zhmcclient", ".", "ConnectionError", "(", "exc", ".", "message", ",", "None", ")" ]
Deselects all the items in the scene .
def selectNone ( self ) : currLayer = self . _currentLayer for item in self . items ( ) : layer = item . layer ( ) if ( layer == currLayer or not layer ) : item . setSelected ( False )
11,036
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L1300-L1308
[ "def", "post", "(", "self", ",", "uri", ",", "body", "=", "None", ",", "logon_required", "=", "True", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_urihandler", ".", "post", "(", "self", ".", "_hmc", ",", "uri", ",", "body", ",", "logon_required", ",", "wait_for_completion", ")", "except", "HTTPError", "as", "exc", ":", "raise", "zhmcclient", ".", "HTTPError", "(", "exc", ".", "response", "(", ")", ")", "except", "ConnectionError", "as", "exc", ":", "raise", "zhmcclient", ".", "ConnectionError", "(", "exc", ".", "message", ",", "None", ")" ]
Starts the view mode for moving around the scene .
def setViewMode ( self , state = True ) : if self . _viewMode == state : return self . _viewMode = state if state : self . _mainView . setDragMode ( self . _mainView . ScrollHandDrag ) else : self . _mainView . setDragMode ( self . _mainView . RubberBandDrag ) self . emitViewModeChanged ( )
11,037
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L1564-L1577
[ "def", "_init_libcrypto", "(", ")", ":", "libcrypto", "=", "_load_libcrypto", "(", ")", "try", ":", "libcrypto", ".", "OPENSSL_init_crypto", "(", ")", "except", "AttributeError", ":", "# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)", "libcrypto", ".", "OPENSSL_no_config", "(", ")", "libcrypto", ".", "OPENSSL_add_all_algorithms_noconf", "(", ")", "libcrypto", ".", "RSA_new", ".", "argtypes", "=", "(", ")", "libcrypto", ".", "RSA_new", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "RSA_size", ".", "argtype", "=", "(", "c_void_p", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "argtypes", "=", "(", "c_char_p", ",", "c_int", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "restype", "=", "c_void_p", "libcrypto", ".", "BIO_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "restype", "=", "c_void_p", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_private_encrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "libcrypto", ".", "RSA_public_decrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "return", "libcrypto" ]
Updates the visible state of nodes based on whether or not they are isolated .
def updateIsolated ( self , force = False ) : if ( not ( self . isolationMode ( ) or force ) ) : return # make sure all nodes are not being hidden because of isolation if ( not self . isolationMode ( ) ) : for node in self . nodes ( ) : node . setIsolateHidden ( False ) return # make sure all the nodes are visible or hidden based on the selection selected_nodes = self . selectedNodes ( ) isolated_nodes = set ( selected_nodes ) connections = self . connections ( ) for connection in connections : in_node = connection . inputNode ( ) out_node = connection . outputNode ( ) if ( in_node in selected_nodes or out_node in selected_nodes ) : isolated_nodes . add ( in_node ) isolated_nodes . add ( out_node ) for node in self . nodes ( ) : node . setIsolateHidden ( not node in isolated_nodes )
11,038
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L1662-L1689
[ "def", "inject_extra_args", "(", "callback", ",", "request", ",", "kwargs", ")", ":", "# TODO: this is a temporary pach, should be managed via honouring the", "# mimetype in the request header....", "annots", "=", "dict", "(", "callback", ".", "__annotations__", ")", "del", "annots", "[", "'return'", "]", "for", "param_name", ",", "(", "param_type", ",", "_", ")", "in", "annots", ".", "items", "(", ")", ":", "if", "param_type", "==", "Ptypes", ".", "path", ":", "continue", "# Already parsed by werkzeug", "elif", "param_type", "==", "Ptypes", ".", "body", ":", "value", "=", "getattr", "(", "request", ",", "PTYPE_TO_REQUEST_PROPERTY", "[", "param_type", "]", ")", "# TODO: The JSON conversion should be dependant from request", "# header type, really...", "value", "=", "json", ".", "loads", "(", "value", ".", "decode", "(", "'utf-8'", ")", ")", "else", ":", "get", "=", "lambda", "attr", ":", "getattr", "(", "request", ",", "attr", ")", ".", "get", "(", "param_name", ",", "None", ")", "value", "=", "get", "(", "PTYPE_TO_REQUEST_PROPERTY", "[", "param_type", "]", ")", "if", "value", "is", "not", "None", ":", "kwargs", "[", "param_name", "]", "=", "value" ]
Merge constraints .
def merge ( constraints ) : # Dictionary :class:`Operator`: set of :class:`Version`. operators = defaultdict ( set ) for constraint in constraints : operators [ constraint . operator ] . add ( constraint . version ) # Get most recent version required by > constraints. if gt in operators : gt_ver = sorted ( operators [ gt ] ) [ - 1 ] else : gt_ver = None # Get most recent version required by >= constraints. if ge in operators : ge_ver = sorted ( operators [ ge ] ) [ - 1 ] else : ge_ver = None # Get least recent version required by < constraints. if lt in operators : lt_ver = sorted ( operators [ lt ] ) [ 0 ] else : lt_ver = None # Get least recent version required by <= constraints. if le in operators : le_ver = sorted ( operators [ le ] ) [ 0 ] else : le_ver = None # Most restrictive LT/LE constraint. l_constraint = None if le_ver : if lt_ver : le_constraint = Constraint ( le , le_ver ) lt_constraint = Constraint ( lt , lt_ver ) if le_ver < lt_ver : # <= 1, < 2 l_constraint = le_constraint l_less_restrictive_c = lt_constraint else : # <= 2, < 1 # <= 2, < 2 l_constraint = lt_constraint l_less_restrictive_c = le_constraint LOGGER . debug ( 'Removed constraint %s because it is less ' 'restrictive than %s' , l_less_restrictive_c , l_constraint ) else : l_constraint = Constraint ( le , le_ver ) elif lt_ver : l_constraint = Constraint ( lt , lt_ver ) # Most restrictive GT/GE constraint. g_constraint = None if ge_ver : if gt_ver : gt_constraint = Constraint ( gt , gt_ver ) ge_constraint = Constraint ( ge , ge_ver ) if ge_ver <= gt_ver : # >= 1, > 2 # >= 2, > 2 g_constraint = gt_constraint g_less_restrictive_c = ge_constraint else : # >= 2, > 1 g_constraint = ge_constraint g_less_restrictive_c = gt_constraint LOGGER . debug ( 'Removed constraint %s because it is less ' 'restrictive than %s' , g_less_restrictive_c , g_constraint ) else : g_constraint = Constraint ( ge , ge_ver ) elif gt_ver : g_constraint = Constraint ( gt , gt_ver ) # Check if g_constraint and l_constraint are conflicting if g_constraint and l_constraint : if g_constraint . version == l_constraint . version : if g_constraint . operator == ge and l_constraint . operator == le : # Merge >= and <= constraints on same version to a == # constraint operators [ eq ] . add ( g_constraint . version ) LOGGER . debug ( 'Merged constraints: %s and %s into ==%s' , l_constraint , g_constraint , g_constraint . version ) l_constraint , g_constraint = None , None else : raise ExclusiveConstraints ( g_constraint , [ l_constraint ] ) elif g_constraint . version > l_constraint . version : raise ExclusiveConstraints ( g_constraint , [ l_constraint ] ) ne_constraints = [ Constraint ( ne , v ) for v in operators [ ne ] ] eq_constraints = [ Constraint ( eq , v ) for v in operators [ eq ] ] if eq_constraints : eq_constraint = eq_constraints . pop ( ) # An eq constraint conflicts with other constraints if g_constraint or l_constraint or ne_constraints or eq_constraints : conflict_list = [ c for c in ( g_constraint , l_constraint ) if c ] conflict_list . extend ( ne_constraints ) conflict_list . extend ( eq_constraints ) raise ExclusiveConstraints ( eq_constraint , conflict_list ) return [ eq_constraint ] else : constraints = ne_constraints + [ g_constraint , l_constraint ] return [ c for c in constraints if c ]
11,039
https://github.com/pmuller/versions/blob/951bc3fd99b6a675190f11ee0752af1d7ff5b440/versions/constraints.py#L109-L224
[ "def", "on_response", "(", "self", ",", "ch", ",", "method_frame", ",", "props", ",", "body", ")", ":", "LOGGER", ".", "debug", "(", "\"rabbitmq.Requester.on_response\"", ")", "if", "self", ".", "corr_id", "==", "props", ".", "correlation_id", ":", "self", ".", "response", "=", "{", "'props'", ":", "props", ",", "'body'", ":", "body", "}", "else", ":", "LOGGER", ".", "warn", "(", "\"rabbitmq.Requester.on_response - discarded response : \"", "+", "str", "(", "props", ".", "correlation_id", ")", ")", "LOGGER", ".", "debug", "(", "\"natsd.Requester.on_response - discarded response : \"", "+", "str", "(", "{", "'properties'", ":", "props", ",", "'body'", ":", "body", "}", ")", ")" ]
Match version with this collection of constraints .
def match ( self , version ) : return all ( constraint . match ( version ) for constraint in self . constraints )
11,040
https://github.com/pmuller/versions/blob/951bc3fd99b6a675190f11ee0752af1d7ff5b440/versions/constraints.py#L46-L56
[ "def", "ApplyPluginToMultiTypeCollection", "(", "plugin", ",", "output_collection", ",", "source_urn", "=", "None", ")", ":", "for", "chunk", "in", "plugin", ".", "Start", "(", ")", ":", "yield", "chunk", "for", "stored_type_name", "in", "sorted", "(", "output_collection", ".", "ListStoredTypes", "(", ")", ")", ":", "stored_cls", "=", "rdfvalue", ".", "RDFValue", ".", "classes", "[", "stored_type_name", "]", "# pylint: disable=cell-var-from-loop", "def", "GetValues", "(", ")", ":", "for", "timestamp", ",", "value", "in", "output_collection", ".", "ScanByType", "(", "stored_type_name", ")", ":", "_", "=", "timestamp", "if", "source_urn", ":", "value", ".", "source", "=", "source_urn", "yield", "value", "# pylint: enable=cell-var-from-loop", "for", "chunk", "in", "plugin", ".", "ProcessValues", "(", "stored_cls", ",", "GetValues", ")", ":", "yield", "chunk", "for", "chunk", "in", "plugin", ".", "Finish", "(", ")", ":", "yield", "chunk" ]
Select the most suitable Memcached backend based on the config and on what s installed
def set_memcached_backend ( self , config ) : # This is the preferred backend as it is the fastest and most fully # featured, so we use this by default config [ 'BACKEND' ] = 'django_pylibmc.memcached.PyLibMCCache' if is_importable ( config [ 'BACKEND' ] ) : return # Otherwise, binary connections can use this pure Python implementation if config . get ( 'BINARY' ) and is_importable ( 'django_bmemcached' ) : config [ 'BACKEND' ] = 'django_bmemcached.memcached.BMemcached' return # For text-based connections without any authentication we can fall # back to Django's core backends if the supporting libraries are # installed if not any ( [ config . get ( key ) for key in ( 'BINARY' , 'USERNAME' , 'PASSWORD' ) ] ) : if is_importable ( 'pylibmc' ) : config [ 'BACKEND' ] = 'django.core.cache.backends.memcached.PyLibMCCache' elif is_importable ( 'memcached' ) : config [ 'BACKEND' ] = 'django.core.cache.backends.memcached.MemcachedCache'
11,041
https://github.com/evansd/django-envsettings/blob/541932af261d5369f211f836a238dc020ee316e8/envsettings/cache.py#L63-L86
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_proc", "is", "not", "None", ":", "self", ".", "_proc", ".", "stdin", ".", "close", "(", ")", "self", ".", "_proc", ".", "wait", "(", ")" ]
This will either add a new widget or switch the joiner based on the state of the entry
def addEntry ( self ) : joiner = self . joiner ( ) curr_joiner = self . _containerWidget . currentJoiner ( ) # update the joining option if it is modified if joiner != curr_joiner : if not self . _last : self . updateJoin ( ) return self . _containerWidget . setCurrentJoiner ( joiner ) # otherwise, add a new entry self . _containerWidget . addEntry ( entry = self )
11,042
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbqueryentrywidget.py#L68-L85
[ "def", "get_file_ids", "(", "object", ")", ":", "import", "MOPdbaccess", "mysql", "=", "MOPdbaccess", ".", "connect", "(", "'cfeps'", ",", "'cfhls'", ",", "dbSystem", "=", "'MYSQL'", ")", "cfeps", "=", "mysql", ".", "cursor", "(", ")", "sql", "=", "\"SELECT file_id FROM measure WHERE provisional LIKE %s\"", "cfeps", ".", "execute", "(", "sql", ",", "(", "object", ",", ")", ")", "file_ids", "=", "cfeps", ".", "fetchall", "(", ")", "return", "(", "file_ids", ")" ]
Assigns an editor based on the current column for this schema .
def assignPlugin ( self ) : self . uiOperatorDDL . blockSignals ( True ) self . uiOperatorDDL . clear ( ) plugin = self . currentPlugin ( ) if plugin : flags = 0 if not self . queryWidget ( ) . showReferencePlugins ( ) : flags |= plugin . Flags . ReferenceRequired self . uiOperatorDDL . addItems ( plugin . operators ( ignore = flags ) ) self . uiOperatorDDL . blockSignals ( False ) self . assignEditor ( )
11,043
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbqueryentrywidget.py#L88-L104
[ "def", "extend_variables", "(", "raw_variables", ",", "override_variables", ")", ":", "if", "not", "raw_variables", ":", "override_variables_mapping", "=", "ensure_mapping_format", "(", "override_variables", ")", "return", "override_variables_mapping", "elif", "not", "override_variables", ":", "raw_variables_mapping", "=", "ensure_mapping_format", "(", "raw_variables", ")", "return", "raw_variables_mapping", "else", ":", "raw_variables_mapping", "=", "ensure_mapping_format", "(", "raw_variables", ")", "override_variables_mapping", "=", "ensure_mapping_format", "(", "override_variables", ")", "raw_variables_mapping", ".", "update", "(", "override_variables_mapping", ")", "return", "raw_variables_mapping" ]
Assigns the editor for this entry based on the plugin .
def assignEditor ( self ) : plugin = self . currentPlugin ( ) column = self . currentColumn ( ) value = self . currentValue ( ) if not plugin : self . setEditor ( None ) return self . setUpdatesEnabled ( False ) self . blockSignals ( True ) op = self . uiOperatorDDL . currentText ( ) self . setEditor ( plugin . createEditor ( self , column , op , value ) ) self . setUpdatesEnabled ( True ) self . blockSignals ( False )
11,044
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbqueryentrywidget.py#L107-L124
[ "def", "wormhole", "(", "context", ",", "dump_timing", ",", "transit_helper", ",", "relay_url", ",", "appid", ")", ":", "context", ".", "obj", "=", "cfg", "=", "Config", "(", ")", "cfg", ".", "appid", "=", "appid", "cfg", ".", "relay_url", "=", "relay_url", "cfg", ".", "transit_helper", "=", "transit_helper", "cfg", ".", "dump_timing", "=", "dump_timing" ]
Refreshes the buttons for building this sql query .
def refreshButtons ( self ) : last = self . _last first = self . _first joiner = self . _containerWidget . currentJoiner ( ) # the first button set can contain the toggle options if first : self . uiJoinSBTN . setActionTexts ( [ 'AND' , 'OR' ] ) elif joiner == QueryCompound . Op . And : self . uiJoinSBTN . setActionTexts ( [ 'AND' ] ) else : self . uiJoinSBTN . setActionTexts ( [ 'OR' ] ) # the last option should not show an active action if last : self . uiJoinSBTN . setCurrentAction ( None ) # otherwise, highlight the proper action else : act = self . uiJoinSBTN . findAction ( QueryCompound . Op [ joiner ] . upper ( ) ) self . uiJoinSBTN . setCurrentAction ( act ) enable = QueryCompound . typecheck ( self . _query ) or self . isChecked ( ) self . uiEnterBTN . setEnabled ( enable )
11,045
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbqueryentrywidget.py#L223-L250
[ "def", "_set_max_value", "(", "self", ",", "max_value", ")", ":", "self", ".", "_external_max_value", "=", "max_value", "# Check that the current value of the parameter is still within the boundaries. If not, issue a warning", "if", "self", ".", "_external_max_value", "is", "not", "None", "and", "self", ".", "value", ">", "self", ".", "_external_max_value", ":", "warnings", ".", "warn", "(", "\"The current value of the parameter %s (%s) \"", "\"was above the new maximum %s.\"", "%", "(", "self", ".", "name", ",", "self", ".", "value", ",", "self", ".", "_external_max_value", ")", ",", "exceptions", ".", "RuntimeWarning", ")", "self", ".", "value", "=", "self", ".", "_external_max_value" ]
Updates the joining method used by the system .
def updateJoin ( self ) : text = self . uiJoinSBTN . currentAction ( ) . text ( ) if text == 'AND' : joiner = QueryCompound . Op . And else : joiner = QueryCompound . Op . Or self . _containerWidget . setCurrentJoiner ( self . joiner ( ) )
11,046
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbqueryentrywidget.py#L350-L360
[ "def", "parse_torrent_properties", "(", "table_datas", ")", ":", "output", "=", "{", "'category'", ":", "table_datas", "[", "0", "]", ".", "text", ",", "'subcategory'", ":", "None", ",", "'quality'", ":", "None", ",", "'language'", ":", "None", "}", "for", "i", "in", "range", "(", "1", ",", "len", "(", "table_datas", ")", ")", ":", "td", "=", "table_datas", "[", "i", "]", "url", "=", "td", ".", "get", "(", "'href'", ")", "params", "=", "Parser", ".", "get_params", "(", "url", ")", "if", "Parser", ".", "is_subcategory", "(", "params", ")", "and", "not", "output", "[", "'subcategory'", "]", ":", "output", "[", "'subcategory'", "]", "=", "td", ".", "text", "elif", "Parser", ".", "is_quality", "(", "params", ")", "and", "not", "output", "[", "'quality'", "]", ":", "output", "[", "'quality'", "]", "=", "td", ".", "text", "elif", "Parser", ".", "is_language", "(", "params", ")", "and", "not", "output", "[", "'language'", "]", ":", "output", "[", "'language'", "]", "=", "td", ".", "text", "return", "output" ]
Check if a symbol is a Chinese character .
def is_chinese ( name ) : if not name : return False for ch in name : ordch = ord ( ch ) if not ( 0x3400 <= ordch <= 0x9fff ) and not ( 0x20000 <= ordch <= 0x2ceaf ) and not ( 0xf900 <= ordch <= ordch ) and not ( 0x2f800 <= ordch <= 0x2fa1f ) : return False return True
11,047
https://github.com/lingpy/sinopy/blob/59a47fcdfae3e0000ac6d2b3d7919bf875ec2056/src/sinopy/sinopy.py#L10-L26
[ "def", "get_frames_singleimage", "(", "self", ")", ":", "frame", "=", "self", ".", "captures", "[", "0", "]", ".", "read", "(", ")", "[", "1", "]", "height", ",", "width", ",", "colors", "=", "frame", ".", "shape", "left_frame", "=", "frame", "[", ":", ",", ":", "width", "/", "2", ",", ":", "]", "right_frame", "=", "frame", "[", ":", ",", "width", "/", "2", ":", ",", ":", "]", "return", "[", "left_frame", ",", "right_frame", "]" ]
Retrieve Pinyin of a character .
def pinyin ( char , variant = 'mandarin' , sep = ' ' , out = 'tones' ) : if len ( char ) > 1 : return sep . join ( [ pinyin ( c , variant = variant , sep = sep , out = out ) for c in char ] ) if not is_chinese ( char ) : return char if char in _cd . GBK : char = gbk2big5 ( char ) out_char = _cd . UNIHAN . get ( char , { variant : '?({0}' . format ( char ) } ) . get ( variant , '!({0})' . format ( char ) ) if out != 'tones' : out_char = '' . join ( [ tone_converter . get ( x , x ) for x in out_char ] ) return out_char
11,048
https://github.com/lingpy/sinopy/blob/59a47fcdfae3e0000ac6d2b3d7919bf875ec2056/src/sinopy/sinopy.py#L29-L47
[ "def", "detach_session", "(", "self", ")", ":", "if", "self", ".", "_session", "is", "not", "None", ":", "self", ".", "_session", ".", "unsubscribe", "(", "self", ")", "self", ".", "_session", "=", "None" ]
Parse a Baxter string and render it with all its contents namely initial medial final and tone .
def parse_baxter ( reading ) : initial = '' medial = '' final = '' tone = '' # determine environments inienv = True medienv = False finenv = False tonenv = False inichars = "pbmrtdnkgnsyhzl'x" chars = list ( reading ) for char in chars : # switch environments if char in 'jw' and not finenv : inienv , medienv , finenv , tonenv = False , True , False , False elif char not in inichars or finenv : if char in 'XH' : inienv , medienv , finenv , tonenv = False , False , False , True else : inienv , medienv , finenv , tonenv = False , False , True , False # fill in slots if inienv : initial += char if medienv : medial += char if finenv : final += char if tonenv : tone += char # post-parse tone if not tone and final [ - 1 ] in 'ptk' : tone = 'R' elif not tone : tone = 'P' # post-parse medial if 'j' not in medial and 'y' in initial : medial += 'j' # post-parse labial if final [ 0 ] in 'u' and 'w' not in medial : medial = 'w' + medial return initial , medial , final , tone
11,049
https://github.com/lingpy/sinopy/blob/59a47fcdfae3e0000ac6d2b3d7919bf875ec2056/src/sinopy/sinopy.py#L69-L128
[ "def", "sync_results_to_new_location", "(", "self", ",", "worker_ip", ")", ":", "if", "worker_ip", "!=", "self", ".", "_log_syncer", ".", "worker_ip", ":", "self", ".", "_log_syncer", ".", "set_worker_ip", "(", "worker_ip", ")", "self", ".", "_log_syncer", ".", "sync_to_worker_if_possible", "(", ")" ]
Get the TLS basic gloss for a characters .
def chars2gloss ( chars ) : out = [ ] chars = gbk2big5 ( chars ) for char in chars : tmp = [ ] if char in _cd . TLS : for entry in _cd . TLS [ char ] : baxter = _cd . TLS [ char ] [ entry ] [ 'UNIHAN_GLOSS' ] if baxter != '?' : tmp += [ baxter ] out += [ ',' . join ( tmp ) ] return out
11,050
https://github.com/lingpy/sinopy/blob/59a47fcdfae3e0000ac6d2b3d7919bf875ec2056/src/sinopy/sinopy.py#L150-L164
[ "def", "transition_matrix_non_reversible", "(", "C", ")", ":", "if", "not", "scipy", ".", "sparse", ".", "issparse", "(", "C", ")", ":", "C", "=", "scipy", ".", "sparse", ".", "csr_matrix", "(", "C", ")", "rowsum", "=", "C", ".", "tocsr", "(", ")", ".", "sum", "(", "axis", "=", "1", ")", "# catch div by zero", "if", "np", ".", "min", "(", "rowsum", ")", "==", "0.0", ":", "raise", "ValueError", "(", "\"matrix C contains rows with sum zero.\"", ")", "rowsum", "=", "np", ".", "array", "(", "1.", "/", "rowsum", ")", ".", "flatten", "(", ")", "norm", "=", "scipy", ".", "sparse", ".", "diags", "(", "rowsum", ",", "0", ")", "return", "norm", "*", "C" ]
Very simple aber convient - enough conversion from baxter MCH to IPA MCH . this is also more or less already implemented in MiddleChinese
def baxter2ipa ( mch , segmented = False ) : out = mch if out [ - 1 ] in 'ptk' : out += 'R' elif out [ - 1 ] not in 'XHP' : out += 'P' for s , t in _cd . GY [ 'ipa' ] : out = out . replace ( s , t ) if segmented : return parse_chinese_morphemes ( out ) return out
11,051
https://github.com/lingpy/sinopy/blob/59a47fcdfae3e0000ac6d2b3d7919bf875ec2056/src/sinopy/sinopy.py#L329-L345
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "stream", ":", "self", ".", "stream", ".", "close", "(", "self", ".", "scheduler", ")", "self", ".", "stream", "=", "None" ]
Convert from gbk format to big5 representation of chars .
def gbk2big5 ( chars ) : out = '' for char in chars : if char in _cd . GBK : out += _cd . BIG5 [ _cd . GBK . index ( char ) ] else : out += char return out
11,052
https://github.com/lingpy/sinopy/blob/59a47fcdfae3e0000ac6d2b3d7919bf875ec2056/src/sinopy/sinopy.py#L348-L358
[ "def", "_build_trial_meta", "(", "cls", ",", "expr_dir", ")", ":", "meta_file", "=", "os", ".", "path", ".", "join", "(", "expr_dir", ",", "EXPR_META_FILE", ")", "meta", "=", "parse_json", "(", "meta_file", ")", "if", "not", "meta", ":", "job_id", "=", "expr_dir", ".", "split", "(", "\"/\"", ")", "[", "-", "2", "]", "trial_id", "=", "expr_dir", "[", "-", "8", ":", "]", "params", "=", "parse_json", "(", "os", ".", "path", ".", "join", "(", "expr_dir", ",", "EXPR_PARARM_FILE", ")", ")", "meta", "=", "{", "\"trial_id\"", ":", "trial_id", ",", "\"job_id\"", ":", "job_id", ",", "\"status\"", ":", "\"RUNNING\"", ",", "\"type\"", ":", "\"TUNE\"", ",", "\"start_time\"", ":", "os", ".", "path", ".", "getctime", "(", "expr_dir", ")", ",", "\"end_time\"", ":", "None", ",", "\"progress_offset\"", ":", "0", ",", "\"result_offset\"", ":", "0", ",", "\"params\"", ":", "params", "}", "if", "not", "meta", ".", "get", "(", "\"start_time\"", ",", "None", ")", ":", "meta", "[", "\"start_time\"", "]", "=", "os", ".", "path", ".", "getctime", "(", "expr_dir", ")", "if", "isinstance", "(", "meta", "[", "\"start_time\"", "]", ",", "float", ")", ":", "meta", "[", "\"start_time\"", "]", "=", "timestamp2date", "(", "meta", "[", "\"start_time\"", "]", ")", "if", "meta", ".", "get", "(", "\"end_time\"", ",", "None", ")", ":", "meta", "[", "\"end_time\"", "]", "=", "timestamp2date", "(", "meta", "[", "\"end_time\"", "]", ")", "meta", "[", "\"params\"", "]", "=", "parse_json", "(", "os", ".", "path", ".", "join", "(", "expr_dir", ",", "EXPR_PARARM_FILE", ")", ")", "return", "meta" ]
Convert from long chars to short chars .
def big52gbk ( chars ) : out = '' for char in chars : if char in _cd . BIG5 : out += _cd . GBK [ _cd . BIG5 . index ( char ) ] else : out += char return out
11,053
https://github.com/lingpy/sinopy/blob/59a47fcdfae3e0000ac6d2b3d7919bf875ec2056/src/sinopy/sinopy.py#L361-L371
[ "def", "eradicate_pgroup", "(", "self", ",", "pgroup", ",", "*", "*", "kwargs", ")", ":", "eradicate", "=", "{", "\"eradicate\"", ":", "True", "}", "eradicate", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"DELETE\"", ",", "\"pgroup/{0}\"", ".", "format", "(", "pgroup", ")", ",", "eradicate", ")" ]
Add or update a transform .
def add_transform ( self , key , xslt ) : self . _remove_converter ( key ) self . _xsltLibrary [ key ] = xslt self . _add_converter ( key )
11,054
https://github.com/cts2/pyjxslt/blob/66cd9233186cf5000d32e3a5b572e0002a8361c4/pyjxslt-python/src/pyjxslt/XSLTGateway.py#L92-L101
[ "def", "__add_endpoints", "(", "self", ")", ":", "for", "mapping", "in", "endpoint_mappings", ":", "if", "all", "(", "map", "(", "self", ".", "config", ".", "get", ",", "mapping", ".", "keys", ")", ")", ":", "self", ".", "__add_single_endpoint", "(", "mapping", ".", "cls", ",", "mapping", ".", "endpoint", ",", "mapping", ".", "is_protected", ")", "self", ".", "bp", ".", "exception", "(", "exceptions", ".", "SanicJWTException", ")", "(", "self", ".", "responses", ".", "exception_response", ")", "if", "not", "self", ".", "instance_is_blueprint", ":", "url_prefix", "=", "self", ".", "_get_url_prefix", "(", ")", "self", ".", "instance", ".", "blueprint", "(", "self", ".", "bp", ",", "url_prefix", "=", "url_prefix", ")" ]
Refresh all of the converters in the py4j library
def _refresh_converters ( self ) : self . _converters . clear ( ) return reduce ( lambda a , b : a and b , [ self . _add_converter ( k ) for k in list ( self . _xsltLibrary . keys ( ) ) ] , True )
11,055
https://github.com/cts2/pyjxslt/blob/66cd9233186cf5000d32e3a5b572e0002a8361c4/pyjxslt-python/src/pyjxslt/XSLTGateway.py#L110-L115
[ "def", "on_end_validation", "(", "self", ",", "event", ")", ":", "self", ".", "Enable", "(", ")", "self", ".", "Show", "(", ")", "self", ".", "magic_gui_frame", ".", "Destroy", "(", ")" ]
Transform the supplied XML using the transform identified by key
def transform ( self , key , xml , * * kwargs ) : if key in self . _xsltLibrary and self . gateway_connected ( ) and key in self . _converters : return self . _converters [ key ] . transform ( xml , self . _parms ( * * kwargs ) ) return None
11,056
https://github.com/cts2/pyjxslt/blob/66cd9233186cf5000d32e3a5b572e0002a8361c4/pyjxslt-python/src/pyjxslt/XSLTGateway.py#L139-L149
[ "def", "run", "(", "self", ")", ":", "try", ":", "# Go through the list of possible ports, hoping we can find", "# one that is free to use for the WSGI server.", "for", "index", ",", "port", "in", "enumerate", "(", "self", ".", "possible_ports", ")", ":", "try", ":", "self", ".", "httpd", "=", "self", ".", "_create_server", "(", "port", ")", "except", "socket", ".", "error", "as", "e", ":", "if", "(", "index", "+", "1", "<", "len", "(", "self", ".", "possible_ports", ")", "and", "e", ".", "error", "==", "errno", ".", "EADDRINUSE", ")", ":", "# This port is already in use, so we go on and try with", "# the next one in the list.", "continue", "else", ":", "# Either none of the given ports are free or the error", "# is something else than \"Address already in use\". So", "# we let that error bubble up to the main thread.", "raise", "else", ":", "# A free port was found.", "self", ".", "port", "=", "port", "break", "self", ".", "is_ready", ".", "set", "(", ")", "self", ".", "httpd", ".", "serve_forever", "(", ")", "except", "Exception", "as", "e", ":", "self", ".", "error", "=", "e", "self", ".", "is_ready", ".", "set", "(", ")" ]
Provides a listing of all prepared queries
async def items ( self , * , dc = None , watch = None , consistency = None ) : response = await self . _api . get ( "/v1/query" , params = { "dc" : dc } ) return response . body
11,057
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/query_endpoint.py#L15-L54
[ "def", "SQRT", "(", "argument", ")", ":", "if", "isinstance", "(", "argument", ",", "MetaField", ")", ":", "return", "argument", ".", "_unary_expression", "(", "\"SQRT\"", ")", "elif", "isinstance", "(", "argument", ",", "RegField", ")", ":", "return", "argument", ".", "_unary_expression", "(", "\"SQRT\"", ")", "else", ":", "raise", "TypeError", "(", "\"You have to give as input a RegField (dataset.field)\"", "\"or a MetaField (dataset['field']\"", ")" ]
Creates a new prepared query
async def create ( self , query , * , dc = None ) : if "Token" in query : # in case of a full token object... query [ "Token" ] = extract_attr ( query [ "Token" ] , keys = [ "ID" ] ) response = await self . _api . post ( "/v1/query" , params = { "dc" : dc } , data = query ) return response . body
11,058
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/query_endpoint.py#L56-L180
[ "def", "status", "(", "self", ",", "remote", "=", "False", ")", ":", "if", "remote", ":", "components", "=", "urlparse", ".", "urlparse", "(", "self", ".", "endpoint", ")", "try", ":", "result", "=", "self", ".", "session", ".", "get", "(", "components", "[", "0", "]", "+", "\"://\"", "+", "components", "[", "1", "]", "+", "\"/status\"", ",", "timeout", "=", "self", ".", "timeout", ")", "except", "Exception", "as", "e", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "\"Failed to connect to server for status: %s\"", ",", "e", ")", "result", "=", "None", "if", "result", "and", "result", ".", "status_code", "==", "200", ":", "self", ".", "server_status", "=", "result", ".", "json", "(", ")", "self", ".", "server_status", "[", "\"endpoint\"", "]", "=", "self", ".", "endpoint", "elif", "result", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "debug", "(", "\"Server status response not understandable: Status: %d, Body: %s\"", ",", "result", ".", "status_code", ",", "result", ".", "text", ")", "self", ".", "server_status", "=", "{", "\"endpoint\"", ":", "self", ".", "endpoint", ",", "\"status\"", ":", "(", "\"Unexpected HTTP status \"", "+", "str", "(", "result", ".", "status_code", ")", "+", "\" at: \"", "+", "strftime", "(", "\"%d %b %Y %H:%M:%S +0000\"", ",", "gmtime", "(", ")", ")", ")", "}", "else", ":", "self", ".", "server_status", "=", "{", "\"endpoint\"", ":", "self", ".", "endpoint", ",", "\"status\"", ":", "\"Unreachable at: \"", "+", "strftime", "(", "\"%d %b %Y %H:%M:%S +0000\"", ",", "gmtime", "(", ")", ")", "}", "return", "self", ".", "local_status", ",", "self", ".", "server_status" ]
Updates existing prepared query
async def update ( self , query , * , dc = None ) : query_id = extract_attr ( query , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/query" , query_id , params = { "dc" : dc } , data = query ) return response . status == 200
11,059
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/query_endpoint.py#L203-L216
[ "def", "get_doc", "(", "logger", "=", "None", ",", "plugin", "=", "None", ",", "reporthook", "=", "None", ")", ":", "from", "ginga", ".", "GingaPlugin", "import", "GlobalPlugin", ",", "LocalPlugin", "if", "isinstance", "(", "plugin", ",", "GlobalPlugin", ")", ":", "plugin_page", "=", "'plugins_global'", "plugin_name", "=", "str", "(", "plugin", ")", "elif", "isinstance", "(", "plugin", ",", "LocalPlugin", ")", ":", "plugin_page", "=", "'plugins_local'", "plugin_name", "=", "str", "(", "plugin", ")", "else", ":", "plugin_page", "=", "None", "plugin_name", "=", "None", "try", ":", "index_html", "=", "_download_rtd_zip", "(", "reporthook", "=", "reporthook", ")", "# Download failed, use online resource", "except", "Exception", "as", "e", ":", "url", "=", "'https://ginga.readthedocs.io/en/latest/'", "if", "plugin_name", "is", "not", "None", ":", "if", "toolkit", ".", "family", ".", "startswith", "(", "'qt'", ")", ":", "# This displays plugin docstring.", "url", "=", "None", "else", ":", "# This redirects to online doc.", "url", "+=", "'manual/{}/{}.html'", ".", "format", "(", "plugin_page", ",", "plugin_name", ")", "if", "logger", "is", "not", "None", ":", "logger", ".", "error", "(", "str", "(", "e", ")", ")", "# Use local resource", "else", ":", "pfx", "=", "'file:'", "url", "=", "'{}{}'", ".", "format", "(", "pfx", ",", "index_html", ")", "# https://github.com/rtfd/readthedocs.org/issues/2803", "if", "plugin_name", "is", "not", "None", ":", "url", "+=", "'#{}'", ".", "format", "(", "plugin_name", ")", "return", "url" ]
Delete existing prepared query
async def delete ( self , query , * , dc = None ) : query_id = extract_attr ( query , keys = [ "ID" ] ) response = await self . _api . delete ( "/v1/query" , query_id , params = { "dc" : dc } ) return response . status == 200
11,060
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/query_endpoint.py#L218-L231
[ "def", "__get_config_table_options", "(", "conf_file_options", ")", ":", "options", "=", "ordereddict", "(", ")", "if", "not", "conf_file_options", ":", "return", "options", "for", "table_name", "in", "conf_file_options", "[", "'tables'", "]", ":", "options", "[", "table_name", "]", "=", "{", "}", "# Regular table options", "for", "option", "in", "DEFAULT_OPTIONS", "[", "'table'", "]", ".", "keys", "(", ")", ":", "options", "[", "table_name", "]", "[", "option", "]", "=", "DEFAULT_OPTIONS", "[", "'table'", "]", "[", "option", "]", "if", "option", "not", "in", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", ":", "continue", "if", "option", "==", "'sns_message_types'", ":", "try", ":", "raw_list", "=", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "option", "]", "options", "[", "table_name", "]", "[", "option", "]", "=", "[", "i", ".", "strip", "(", ")", "for", "i", "in", "raw_list", ".", "split", "(", "','", ")", "]", "except", ":", "print", "(", "'Error parsing the \"sns-message-types\" '", "'option: {0}'", ".", "format", "(", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "option", "]", ")", ")", "else", ":", "options", "[", "table_name", "]", "[", "option", "]", "=", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "option", "]", "# GSI specific options", "if", "'gsis'", "in", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", ":", "for", "gsi_name", "in", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", ":", "for", "option", "in", "DEFAULT_OPTIONS", "[", "'gsi'", "]", ".", "keys", "(", ")", ":", "opt", "=", "DEFAULT_OPTIONS", "[", "'gsi'", "]", "[", "option", "]", "if", "'gsis'", "not", "in", "options", "[", "table_name", "]", ":", "options", "[", "table_name", "]", "[", "'gsis'", "]", "=", "{", "}", "if", "gsi_name", "not", "in", "options", "[", "table_name", "]", "[", "'gsis'", "]", ":", "options", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "=", "{", "}", "if", "(", "option", "not", "in", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", ")", ":", "options", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", "=", "opt", "continue", "if", "option", "==", "'sns_message_types'", ":", "try", ":", "raw_list", "=", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", "opt", "=", "[", "i", ".", "strip", "(", ")", "for", "i", "in", "raw_list", ".", "split", "(", "','", ")", "]", "except", ":", "print", "(", "'Error parsing the \"sns-message-types\" '", "'option: {0}'", ".", "format", "(", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", ")", ")", "else", ":", "opt", "=", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", "options", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", "=", "opt", "return", "options" ]
Executes a prepared query
async def execute ( self , query , * , dc = None , near = None , limit = None , consistency = None ) : query_id = extract_attr ( query , keys = [ "ID" ] ) response = await self . _api . get ( "/v1/query/%s/execute" % query_id , params = { "dc" : dc , "near" : near , "limit" : limit } , consistency = consistency ) return response . body
11,061
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/query_endpoint.py#L233-L324
[ "def", "_custom_fields", "(", ")", ":", "# Import some commonly needed modules", "import", "os", "from", "pyrocore", ".", "torrent", "import", "engine", ",", "matching", "from", "pyrocore", ".", "util", "import", "fmt", "# PUT CUSTOM FIELD CODE HERE", "# Disk space check (as an example)", "# see https://pyrocore.readthedocs.io/en/latest/custom.html#has-room", "def", "has_room", "(", "obj", ")", ":", "\"Check disk space.\"", "pathname", "=", "obj", ".", "path", "if", "pathname", "and", "not", "os", ".", "path", ".", "exists", "(", "pathname", ")", ":", "pathname", "=", "os", ".", "path", ".", "dirname", "(", "pathname", ")", "if", "pathname", "and", "os", ".", "path", ".", "exists", "(", "pathname", ")", ":", "stats", "=", "os", ".", "statvfs", "(", "pathname", ")", "return", "(", "stats", ".", "f_bavail", "*", "stats", ".", "f_frsize", "-", "int", "(", "diskspace_threshold_mb", ")", "*", "1024", "**", "2", ">", "obj", ".", "size", "*", "(", "1.0", "-", "obj", ".", "done", "/", "100.0", ")", ")", "else", ":", "return", "None", "yield", "engine", ".", "DynamicField", "(", "engine", ".", "untyped", ",", "\"has_room\"", ",", "\"check whether the download will fit on its target device\"", ",", "matcher", "=", "matching", ".", "BoolFilter", ",", "accessor", "=", "has_room", ",", "formatter", "=", "lambda", "val", ":", "\"OK\"", "if", "val", "else", "\"??\"", "if", "val", "is", "None", "else", "\"NO\"", ")", "globals", "(", ")", ".", "setdefault", "(", "\"diskspace_threshold_mb\"", ",", "\"500\"", ")" ]
Loads the records from the query set linked with this item .
def load ( self ) : if self . _loaded : return rset = self . recordSet ( ) QApplication . setOverrideCursor ( Qt . WaitCursor ) self . loadRecords ( rset ) QApplication . restoreOverrideCursor ( )
11,062
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbgroupitem.py#L117-L128
[ "def", "start_server", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Opens a browser-based \"", "\"client that interfaces with the \"", "\"chemical format converter.\"", ")", "parser", ".", "add_argument", "(", "'--debug'", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Prints all \"", "\"transmitted data streams.\"", ")", "parser", ".", "add_argument", "(", "'--port'", ",", "type", "=", "int", ",", "default", "=", "8000", ",", "help", "=", "\"The port \"", "\"on which to serve the website.\"", ")", "parser", ".", "add_argument", "(", "'--timeout'", ",", "type", "=", "int", ",", "default", "=", "5", ",", "help", "=", "\"The maximum \"", "\"time, in seconds, allowed for a process to run \"", "\"before returning an error.\"", ")", "parser", ".", "add_argument", "(", "'--workers'", ",", "type", "=", "int", ",", "default", "=", "2", ",", "help", "=", "\"The number of \"", "\"worker processes to use with the server.\"", ")", "parser", ".", "add_argument", "(", "'--no-browser'", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Disables \"", "\"opening a browser window on startup.\"", ")", "global", "args", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "debug", ":", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "handlers", "=", "[", "(", "r'/'", ",", "IndexHandler", ")", ",", "(", "r'/websocket'", ",", "WebSocket", ")", ",", "(", "r'/static/(.*)'", ",", "tornado", ".", "web", ".", "StaticFileHandler", ",", "{", "'path'", ":", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "}", ")", "]", "application", "=", "tornado", ".", "web", ".", "Application", "(", "handlers", ")", "application", ".", "listen", "(", "args", ".", "port", ")", "if", "not", "args", ".", "no_browser", ":", "webbrowser", ".", "open", "(", "'http://localhost:%d/'", "%", "args", ".", "port", ",", "new", "=", "2", ")", "try", ":", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", ".", "start", "(", ")", "except", "KeyboardInterrupt", ":", "sys", ".", "stderr", ".", "write", "(", "\"Received keyboard interrupt. Stopping server.\\n\"", ")", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", ".", "stop", "(", ")", "sys", ".", "exit", "(", "1", ")" ]
Prepare simple table with spacing based on content
def _tabulate ( rows , headers , spacing = 5 ) : if len ( rows ) == 0 : return "None\n" assert len ( rows [ 0 ] ) == len ( headers ) count = len ( rows [ 0 ] ) widths = [ 0 for _ in range ( count ) ] rows = [ headers ] + rows for row in rows : for index , field in enumerate ( row ) : if len ( str ( field ) ) > widths [ index ] : widths [ index ] = len ( str ( field ) ) output = "" for row in rows : for index , field in enumerate ( row ) : field = str ( field ) output += field + ( widths [ index ] - len ( field ) + spacing ) * " " output += "\n" return output
11,063
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/plugin.py#L786-L806
[ "def", "MakeRequest", "(", "self", ",", "data", ")", ":", "stats_collector_instance", ".", "Get", "(", ")", ".", "IncrementCounter", "(", "\"grr_client_sent_bytes\"", ",", "len", "(", "data", ")", ")", "# Verify the response is as it should be from the control endpoint.", "response", "=", "self", ".", "http_manager", ".", "OpenServerEndpoint", "(", "path", "=", "\"control?api=%s\"", "%", "config", ".", "CONFIG", "[", "\"Network.api\"", "]", ",", "verify_cb", "=", "self", ".", "VerifyServerControlResponse", ",", "data", "=", "data", ",", "headers", "=", "{", "\"Content-Type\"", ":", "\"binary/octet-stream\"", "}", ")", "if", "response", ".", "code", "==", "406", ":", "self", ".", "InitiateEnrolment", "(", ")", "return", "response", "if", "response", ".", "code", "==", "200", ":", "stats_collector_instance", ".", "Get", "(", ")", ".", "IncrementCounter", "(", "\"grr_client_received_bytes\"", ",", "len", "(", "response", ".", "data", ")", ")", "return", "response", "# An unspecified error occured.", "return", "response" ]
Add single command line flag
def add_item ( self , item ) : if not ( isinstance ( item . name , basestring ) and isinstance ( item . description , basestring ) ) : raise TypeError ( "Name and description should be strings, are of type {} and {}" . format ( type ( item . name ) , type ( item . description ) ) ) if not ( isinstance ( item . flag_type , FlagType ) ) : raise TypeError ( "Flag type should be of type FlagType, is of {}" . format ( type ( item . flag_type ) ) ) if item . name not in self . _flags : if item . default is not None : if item . default is not False : item . description = item . description + " (default: %(default)s)" self . _flags [ item . name ] = item else : self . _flags [ item . name ] = item
11,064
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/plugin.py#L107-L133
[ "def", "person_same_name_map", "(", "json_content", ",", "role_from", ")", ":", "matched_editors", "=", "[", "(", "i", ",", "person", ")", "for", "i", ",", "person", "in", "enumerate", "(", "json_content", ")", "if", "person", ".", "get", "(", "'role'", ")", "in", "role_from", "]", "same_name_map", "=", "{", "}", "for", "i", ",", "editor", "in", "matched_editors", ":", "if", "not", "editor", ".", "get", "(", "\"name\"", ")", ":", "continue", "# compare name of each", "name", "=", "editor", ".", "get", "(", "\"name\"", ")", ".", "get", "(", "\"index\"", ")", "if", "name", "not", "in", "same_name_map", ":", "same_name_map", "[", "name", "]", "=", "[", "]", "same_name_map", "[", "name", "]", ".", "append", "(", "i", ")", "return", "same_name_map" ]
Add multiple command line flags
def add_multiple ( self , flags ) : if not isinstance ( flags , list ) : raise TypeError ( "Expected list of flags, got object of type{}" . format ( type ( flags ) ) ) for flag in flags : if isinstance ( flag , Flag ) : self . add_item ( flag ) elif isinstance ( flag , tuple ) : try : item = Flag ( * flag ) self . add_item ( item ) except TypeError as e : raise TypeError ( "Invalid arguments to initialize a flag definition, expect ({0} [, {1}]) but got {3}" . format ( ", " . join ( Flag . REQUIRED_FIELDS ) , ", " . join ( Flag . OPTIONAL_FIELDS ) , flag ) )
11,065
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/plugin.py#L138-L160
[ "def", "handle_not_found", "(", "exception", ",", "*", "*", "extra", ")", ":", "assert", "isinstance", "(", "exception", ",", "NotFound", ")", "page", "=", "Page", ".", "query", ".", "filter", "(", "db", ".", "or_", "(", "Page", ".", "url", "==", "request", ".", "path", ",", "Page", ".", "url", "==", "request", ".", "path", "+", "\"/\"", ")", ")", ".", "first", "(", ")", "if", "page", ":", "_add_url_rule", "(", "page", ".", "url", ")", "return", "render_template", "(", "[", "page", ".", "template_name", ",", "current_app", ".", "config", "[", "'PAGES_DEFAULT_TEMPLATE'", "]", "]", ",", "page", "=", "page", ")", "elif", "'wrapped'", "in", "extra", ":", "return", "extra", "[", "'wrapped'", "]", "(", "exception", ")", "else", ":", "return", "exception" ]
Goes to the next date based on the current mode and date .
def gotoNext ( self ) : scene = self . scene ( ) date = scene . currentDate ( ) # go forward a day if ( scene . currentMode ( ) == scene . Mode . Day ) : scene . setCurrentDate ( date . addDays ( 1 ) ) # go forward a week elif ( scene . currentMode ( ) == scene . Mode . Week ) : scene . setCurrentDate ( date . addDays ( 7 ) ) # go forward a month elif ( scene . currentMode ( ) == scene . Mode . Month ) : scene . setCurrentDate ( date . addMonths ( 1 ) )
11,066
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcalendarwidget/xcalendarwidget.py#L168-L185
[ "def", "reset_rammbock", "(", "self", ")", ":", "for", "client", "in", "self", ".", "_clients", ":", "client", ".", "close", "(", ")", "for", "server", "in", "self", ".", "_servers", ":", "server", ".", "close", "(", ")", "self", ".", "_init_caches", "(", ")" ]
Fits all the nodes in the view .
def zoomExtents ( self ) : rect = self . scene ( ) . visibleItemsBoundingRect ( ) vrect = self . viewportRect ( ) if rect . width ( ) : changed = False scene_rect = self . scene ( ) . sceneRect ( ) if scene_rect . width ( ) < rect . width ( ) : scene_rect . setWidth ( rect . width ( ) + 150 ) scene_rect . setX ( - scene_rect . width ( ) / 2.0 ) changed = True if scene_rect . height ( ) < rect . height ( ) : scene_rect . setHeight ( rect . height ( ) + 150 ) scene_rect . setY ( - scene_rect . height ( ) / 2.0 ) changed = True if changed : self . scene ( ) . setSceneRect ( scene_rect ) self . fitInView ( rect , Qt . KeepAspectRatio ) if not self . signalsBlocked ( ) : self . zoomAmountChanged . emit ( self . zoomAmount ( ) )
11,067
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodewidget.py#L287-L314
[ "def", "handlePortfolio", "(", "self", ",", "msg", ")", ":", "# log handler msg", "self", ".", "log_msg", "(", "\"portfolio\"", ",", "msg", ")", "# contract identifier", "contract_tuple", "=", "self", ".", "contract_to_tuple", "(", "msg", ".", "contract", ")", "contractString", "=", "self", ".", "contractString", "(", "contract_tuple", ")", "# try creating the contract", "self", ".", "registerContract", "(", "msg", ".", "contract", ")", "# new account?", "if", "msg", ".", "accountName", "not", "in", "self", ".", "_portfolios", ".", "keys", "(", ")", ":", "self", ".", "_portfolios", "[", "msg", ".", "accountName", "]", "=", "{", "}", "self", ".", "_portfolios", "[", "msg", ".", "accountName", "]", "[", "contractString", "]", "=", "{", "\"symbol\"", ":", "contractString", ",", "\"position\"", ":", "int", "(", "msg", ".", "position", ")", ",", "\"marketPrice\"", ":", "float", "(", "msg", ".", "marketPrice", ")", ",", "\"marketValue\"", ":", "float", "(", "msg", ".", "marketValue", ")", ",", "\"averageCost\"", ":", "float", "(", "msg", ".", "averageCost", ")", ",", "\"unrealizedPNL\"", ":", "float", "(", "msg", ".", "unrealizedPNL", ")", ",", "\"realizedPNL\"", ":", "float", "(", "msg", ".", "realizedPNL", ")", ",", "\"totalPNL\"", ":", "float", "(", "msg", ".", "realizedPNL", ")", "+", "float", "(", "msg", ".", "unrealizedPNL", ")", ",", "\"account\"", ":", "msg", ".", "accountName", "}", "# fire callback", "self", ".", "ibCallback", "(", "caller", "=", "\"handlePortfolio\"", ",", "msg", "=", "msg", ")" ]
Zip up a directory .
def zipdir ( path , ziph , * * kwargs ) : str_arcroot = "" for k , v in kwargs . items ( ) : if k == 'arcroot' : str_arcroot = v for root , dirs , files in os . walk ( path ) : for file in files : str_arcfile = os . path . join ( root , file ) if len ( str_arcroot ) : str_arcname = str_arcroot . split ( '/' ) [ - 1 ] + str_arcfile . split ( str_arcroot ) [ 1 ] else : str_arcname = str_arcfile try : ziph . write ( str_arcfile , arcname = str_arcname ) except : print ( "Skipping %s" % str_arcfile )
11,068
https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L1350-L1373
[ "def", "update_if_client", "(", "fctn", ")", ":", "@", "functools", ".", "wraps", "(", "fctn", ")", "def", "_update_if_client", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "b", "=", "self", ".", "_bundle", "if", "b", "is", "None", "or", "not", "hasattr", "(", "b", ",", "'is_client'", ")", ":", "return", "fctn", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "b", ".", "is_client", "and", "(", "b", ".", "_last_client_update", "is", "None", "or", "(", "datetime", ".", "now", "(", ")", "-", "b", ".", "_last_client_update", ")", ".", "seconds", ">", "1", ")", ":", "b", ".", "client_update", "(", ")", "return", "fctn", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_update_if_client" ]
Process zip operations .
def zip_process ( * * kwargs ) : str_localPath = "" str_zipFileName = "" str_action = "zip" str_arcroot = "" for k , v in kwargs . items ( ) : if k == 'path' : str_localPath = v if k == 'action' : str_action = v if k == 'payloadFile' : str_zipFileName = v if k == 'arcroot' : str_arcroot = v if str_action == 'zip' : str_mode = 'w' str_zipFileName = '%s.zip' % uuid . uuid4 ( ) else : str_mode = 'r' try : ziphandler = zipfile . ZipFile ( str_zipFileName , str_mode , zipfile . ZIP_DEFLATED ) if str_mode == 'w' : if os . path . isdir ( str_localPath ) : zipdir ( str_localPath , ziphandler , arcroot = str_arcroot ) else : if len ( str_arcroot ) : str_arcname = str_arcroot . split ( '/' ) [ - 1 ] + str_localPath . split ( str_arcroot ) [ 1 ] else : str_arcname = str_localPath try : ziphandler . write ( str_localPath , arcname = str_arcname ) except : ziphandler . close ( ) os . remove ( str_zipFileName ) return { 'msg' : json . dumps ( { "msg" : "No file or directory found for '%s'" % str_localPath } ) , 'status' : False } if str_mode == 'r' : ziphandler . extractall ( str_localPath ) ziphandler . close ( ) str_msg = '%s operation successful' % str_action b_status = True except : str_msg = '%s operation failed' % str_action b_status = False return { 'msg' : str_msg , 'fileProcessed' : str_zipFileName , 'status' : b_status , 'path' : str_localPath , 'zipmode' : str_mode , 'filesize' : "{:,}" . format ( os . stat ( str_zipFileName ) . st_size ) , 'timestamp' : '%s' % datetime . datetime . now ( ) }
11,069
https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L1376-L1435
[ "def", "defBoundary", "(", "self", ")", ":", "self", ".", "BoroCnstNatAll", "=", "np", ".", "zeros", "(", "self", ".", "StateCount", ")", "+", "np", ".", "nan", "# Find the natural borrowing constraint conditional on next period's state", "for", "j", "in", "range", "(", "self", ".", "StateCount", ")", ":", "PermShkMinNext", "=", "np", ".", "min", "(", "self", ".", "IncomeDstn_list", "[", "j", "]", "[", "1", "]", ")", "TranShkMinNext", "=", "np", ".", "min", "(", "self", ".", "IncomeDstn_list", "[", "j", "]", "[", "2", "]", ")", "self", ".", "BoroCnstNatAll", "[", "j", "]", "=", "(", "self", ".", "solution_next", ".", "mNrmMin", "[", "j", "]", "-", "TranShkMinNext", ")", "*", "(", "self", ".", "PermGroFac_list", "[", "j", "]", "*", "PermShkMinNext", ")", "/", "self", ".", "Rfree_list", "[", "j", "]", "self", ".", "BoroCnstNat_list", "=", "np", ".", "zeros", "(", "self", ".", "StateCount", ")", "+", "np", ".", "nan", "self", ".", "mNrmMin_list", "=", "np", ".", "zeros", "(", "self", ".", "StateCount", ")", "+", "np", ".", "nan", "self", ".", "BoroCnstDependency", "=", "np", ".", "zeros", "(", "(", "self", ".", "StateCount", ",", "self", ".", "StateCount", ")", ")", "+", "np", ".", "nan", "# The natural borrowing constraint in each current state is the *highest*", "# among next-state-conditional natural borrowing constraints that could", "# occur from this current state.", "for", "i", "in", "range", "(", "self", ".", "StateCount", ")", ":", "possible_next_states", "=", "self", ".", "MrkvArray", "[", "i", ",", ":", "]", ">", "0", "self", ".", "BoroCnstNat_list", "[", "i", "]", "=", "np", ".", "max", "(", "self", ".", "BoroCnstNatAll", "[", "possible_next_states", "]", ")", "# Explicitly handle the \"None\" case: ", "if", "self", ".", "BoroCnstArt", "is", "None", ":", "self", ".", "mNrmMin_list", "[", "i", "]", "=", "self", ".", "BoroCnstNat_list", "[", "i", "]", "else", ":", "self", ".", "mNrmMin_list", "[", "i", "]", "=", "np", ".", "max", "(", "[", "self", ".", "BoroCnstNat_list", "[", "i", "]", ",", "self", ".", "BoroCnstArt", "]", ")", "self", ".", "BoroCnstDependency", "[", "i", ",", ":", "]", "=", "self", ".", "BoroCnstNat_list", "[", "i", "]", "==", "self", ".", "BoroCnstNatAll" ]
Process base64 file io
def base64_process ( * * kwargs ) : str_fileToSave = "" str_fileToRead = "" str_action = "encode" data = None for k , v in kwargs . items ( ) : if k == 'action' : str_action = v if k == 'payloadBytes' : data = v if k == 'payloadFile' : str_fileToRead = v if k == 'saveToFile' : str_fileToSave = v # if k == 'sourcePath': str_sourcePath = v if str_action == "encode" : # Encode the contents of the file at targetPath as ASCII for transmission if len ( str_fileToRead ) : with open ( str_fileToRead , 'rb' ) as f : data = f . read ( ) f . close ( ) data_b64 = base64 . b64encode ( data ) with open ( str_fileToSave , 'wb' ) as f : f . write ( data_b64 ) f . close ( ) return { 'msg' : 'Encode successful' , 'fileProcessed' : str_fileToSave , 'status' : True # 'encodedBytes': data_b64 } if str_action == "decode" : # if len(data) % 4: # not a multiple of 4, add padding: # data += '=' * (4 - len(data) % 4) # adding 3 padding = will never succumb to the TypeError and will always produce the same result. # https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770 bytes_decoded = base64 . b64decode ( data + "===" ) with open ( str_fileToSave , 'wb' ) as f : f . write ( bytes_decoded ) f . close ( ) return { 'msg' : 'Decode successful' , 'fileProcessed' : str_fileToSave , 'status' : True # 'decodedBytes': bytes_decoded }
11,070
https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L1438-L1488
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Call the remote service and ask for the storage location based on the key .
def storage_resolveBasedOnKey ( self , * args , * * kwargs ) : global Gd_internalvar d_msg = { 'action' : 'internalctl' , 'meta' : { 'var' : 'key2address' , 'compute' : '<key>' } } str_key = "" b_status = False for k , v in kwargs . items ( ) : if k == 'key' : str_key = v d_msg [ 'meta' ] [ 'key' ] = str_key # d_ret = self . pullPath_core ( d_msg = d_msg ) return { 'status' : b_status , 'path' : str_internalLocation }
11,071
https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L190-L221
[ "def", "_write_header", "(", "self", ")", ":", "self", ".", "_ostream", ".", "write", "(", "len", "(", "self", ".", "_header", ")", "*", "\"-\"", "+", "\"\\n\"", ")", "self", ".", "_ostream", ".", "write", "(", "self", ".", "_header", ")", "self", ".", "_ostream", ".", "write", "(", "\"\\n\"", ")", "self", ".", "_ostream", ".", "write", "(", "len", "(", "self", ".", "_header", ")", "*", "\"-\"", "+", "\"\\n\"", ")" ]
Resolve the remote path location by returning either the path or key parameter in the remote JSON record .
def remoteLocation_resolveSimple ( self , d_remote ) : b_status = False str_remotePath = "" if 'path' in d_remote . keys ( ) : str_remotePath = d_remote [ 'path' ] b_status = True if 'key' in d_remote . keys ( ) : str_remotePath = d_remote [ 'key' ] b_status = True return { 'status' : b_status , 'path' : str_remotePath }
11,072
https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L223-L242
[ "def", "graded_submissions", "(", "self", ")", ":", "qs", "=", "self", ".", "_valid_submissions", "(", ")", ".", "filter", "(", "state__in", "=", "[", "Submission", ".", "GRADED", "]", ")", "return", "qs" ]
Resolve the remote path location
def remoteLocation_resolve ( self , d_remote ) : b_status = False str_remotePath = "" if 'path' in d_remote . keys ( ) : str_remotePath = d_remote [ 'path' ] b_status = True if 'key' in d_remote . keys ( ) : d_ret = self . storage_resolveBasedOnKey ( key = d_remote [ 'key' ] ) if d_ret [ 'status' ] : b_status = True str_remotePath = d_ret [ 'path' ] return { 'status' : b_status , 'path' : str_remotePath }
11,073
https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L244-L264
[ "def", "union", "(", "self", ",", "*", "dstreams", ")", ":", "if", "not", "dstreams", ":", "raise", "ValueError", "(", "\"should have at least one DStream to union\"", ")", "if", "len", "(", "dstreams", ")", "==", "1", ":", "return", "dstreams", "[", "0", "]", "if", "len", "(", "set", "(", "s", ".", "_jrdd_deserializer", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same serializer\"", ")", "if", "len", "(", "set", "(", "s", ".", "_slideDuration", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same slide duration\"", ")", "cls", "=", "SparkContext", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "streaming", ".", "api", ".", "java", ".", "JavaDStream", "jdstreams", "=", "SparkContext", ".", "_gateway", ".", "new_array", "(", "cls", ",", "len", "(", "dstreams", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "dstreams", ")", ")", ":", "jdstreams", "[", "i", "]", "=", "dstreams", "[", "i", "]", ".", "_jdstream", "return", "DStream", "(", "self", ".", "_jssc", ".", "union", "(", "jdstreams", ")", ",", "self", ",", "dstreams", "[", "0", "]", ".", "_jrdd_deserializer", ")" ]
Check if a path exists on the local filesystem
def path_localLocationCheck ( self , d_msg , * * kwargs ) : b_pull = False d_meta = d_msg [ 'meta' ] if 'do' in d_meta : if d_meta [ 'do' ] == 'pull' : b_pull = True if 'local' in d_meta : d_local = d_meta [ 'local' ] if 'to' in d_meta : d_local = d_meta [ 'to' ] str_localPathFull = d_local [ 'path' ] str_localPath , str_unpack = os . path . split ( str_localPathFull ) str_msg = '' str_checkedDir = str_localPathFull b_isFile = os . path . isfile ( str_localPathFull ) b_isDir = os . path . isdir ( str_localPathFull ) b_exists = os . path . exists ( str_localPathFull ) if 'pull' in d_msg [ 'action' ] or b_pull : # If we are "pulling" data to local, then we assume the local # directory does not exist. If it does, and if 'createDir' is 'true', # we remove the localPath and re-create it, thus assuring it will # only contain the info pulled from the remote source. # If 'writeInExisting' is 'true', then execution continues, but # may fail if the pulled target exists in the localPath. str_checkedDir = str_localPath b_isFile = os . path . isfile ( str_localPath ) b_isDir = os . path . isdir ( str_localPath ) b_exists = os . path . exists ( str_localPath ) if 'createDir' in d_local . keys ( ) : if d_local [ 'createDir' ] : if os . path . isdir ( str_localPathFull ) : self . dp . qprint ( 'Removing local path %s...' % str_localPathFull ) shutil . rmtree ( str_localPathFull ) str_msg = 'Removed existing local path... ' self . dp . qprint ( 'Creating empty local path %s...' % str_localPathFull ) os . makedirs ( str_localPathFull ) b_exists = True str_msg += 'Created new local path' else : str_msg = 'local path already exists!' if 'writeInExisting' in d_local . keys ( ) : if not d_local [ 'writeInExisting' ] : if b_isDir : b_exists = False else : if b_isDir : b_exists = False d_ret = { 'action' : d_msg [ 'action' ] , 'dir' : str_checkedDir , 'status' : b_exists , 'isfile' : b_isFile , 'isdir' : b_isDir , 'msg' : str_msg } return { 'check' : d_ret , 'status' : d_ret [ 'status' ] , 'timestamp' : '%s' % datetime . datetime . now ( ) }
11,074
https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L810-L879
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# XXX: circular import", "from", "fields", "import", "RatingField", "qs", "=", "self", ".", "distinct", "(", ")", ".", "values_list", "(", "'content_type'", ",", "'object_id'", ")", ".", "order_by", "(", "'content_type'", ")", "to_update", "=", "[", "]", "for", "content_type", ",", "objects", "in", "itertools", ".", "groupby", "(", "qs", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", ":", "model_class", "=", "ContentType", ".", "objects", ".", "get", "(", "pk", "=", "content_type", ")", ".", "model_class", "(", ")", "if", "model_class", ":", "to_update", ".", "extend", "(", "list", "(", "model_class", ".", "objects", ".", "filter", "(", "pk__in", "=", "list", "(", "objects", ")", "[", "0", "]", ")", ")", ")", "retval", "=", "super", "(", "VoteQuerySet", ",", "self", ")", ".", "delete", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# TODO: this could be improved", "for", "obj", "in", "to_update", ":", "for", "field", "in", "getattr", "(", "obj", ",", "'_djangoratings'", ",", "[", "]", ")", ":", "getattr", "(", "obj", ",", "field", ".", "name", ")", ".", "_update", "(", "commit", "=", "False", ")", "obj", ".", "save", "(", ")", "return", "retval" ]
Returns the path of an executable file .
def find_executable ( name ) : if sys . platform . startswith ( 'win' ) or os . name . startswith ( 'os2' ) : name = name + '.exe' executable_path = find_file ( name , deep = True ) return executable_path
11,075
https://github.com/SkullTech/webdriver-start/blob/26285fd84c4deaf8906828e0ec0758a650b7ba49/wdstart/helper.py#L91-L117
[ "def", "update_nexusport_binding", "(", "port_id", ",", "new_vlan_id", ")", ":", "if", "not", "new_vlan_id", ":", "LOG", ".", "warning", "(", "\"update_nexusport_binding called with no vlan\"", ")", "return", "LOG", ".", "debug", "(", "\"update_nexusport_binding called\"", ")", "session", "=", "bc", ".", "get_writer_session", "(", ")", "binding", "=", "_lookup_one_nexus_binding", "(", "session", "=", "session", ",", "port_id", "=", "port_id", ")", "binding", ".", "vlan_id", "=", "new_vlan_id", "session", ".", "merge", "(", "binding", ")", "session", ".", "flush", "(", ")", "return", "binding" ]
Returns the contents of a file or a group of files as a string .
def readCorpus ( location ) : print ( "Reading corpus from file(s)..." ) corpus = '' if '.txt' in location : with open ( location ) as fp : corpus = fp . read ( ) else : dirFiles = listdir ( location ) nFiles = len ( dirFiles ) for f in tqdm ( dirFiles ) : with open ( location + "/" + f ) as fp : corpus += fp . read ( ) return corpus
11,076
https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/corpus.py#L33-L78
[ "def", "power_on", "(", "self", ")", ":", "payload", "=", "amt", ".", "wsman", ".", "power_state_request", "(", "self", ".", "uri", ",", "\"on\"", ")", "return", "self", ".", "post", "(", "payload", ",", "CIM_PowerManagementService", ")" ]
Validates incoming data
def validate ( data ) : text = data . get ( 'text' ) if not isinstance ( text , _string_types ) or len ( text ) == 0 : raise ValueError ( 'text field is required and should not be empty' ) if 'markdown' in data and not type ( data [ 'markdown' ] ) is bool : raise ValueError ( 'markdown field should be bool' ) if 'attachments' in data : if not isinstance ( data [ 'attachments' ] , ( list , tuple ) ) : raise ValueError ( 'attachments field should be list or tuple' ) for attachment in data [ 'attachments' ] : if 'text' not in attachment and 'title' not in attachment : raise ValueError ( 'text or title is required in attachment' ) return True
11,077
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/incoming.py#L13-L40
[ "def", "strip_uri", "(", "repo", ")", ":", "splits", "=", "repo", ".", "split", "(", ")", "for", "idx", "in", "range", "(", "len", "(", "splits", ")", ")", ":", "if", "any", "(", "splits", "[", "idx", "]", ".", "startswith", "(", "x", ")", "for", "x", "in", "(", "'http://'", ",", "'https://'", ",", "'ftp://'", ")", ")", ":", "splits", "[", "idx", "]", "=", "splits", "[", "idx", "]", ".", "rstrip", "(", "'/'", ")", "return", "' '", ".", "join", "(", "splits", ")" ]
Sends an incoming message
def send ( url , data ) : validate ( data ) return requests . post ( url , json = data )
11,078
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/incoming.py#L43-L55
[ "def", "EnumKey", "(", "key", ",", "index", ")", ":", "regenumkeyex", "=", "advapi32", "[", "\"RegEnumKeyExW\"", "]", "regenumkeyex", ".", "restype", "=", "ctypes", ".", "c_long", "regenumkeyex", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "wintypes", ".", "DWORD", ",", "ctypes", ".", "c_wchar_p", ",", "LPDWORD", ",", "LPDWORD", ",", "ctypes", ".", "c_wchar_p", ",", "LPDWORD", ",", "ctypes", ".", "POINTER", "(", "FileTime", ")", "]", "buf", "=", "ctypes", ".", "create_unicode_buffer", "(", "257", ")", "length", "=", "ctypes", ".", "wintypes", ".", "DWORD", "(", "257", ")", "rc", "=", "regenumkeyex", "(", "key", ".", "handle", ",", "index", ",", "ctypes", ".", "cast", "(", "buf", ",", "ctypes", ".", "c_wchar_p", ")", ",", "ctypes", ".", "byref", "(", "length", ")", ",", "LPDWORD", "(", ")", ",", "ctypes", ".", "c_wchar_p", "(", ")", ",", "LPDWORD", "(", ")", ",", "ctypes", ".", "POINTER", "(", "FileTime", ")", "(", ")", ")", "if", "rc", "!=", "0", ":", "raise", "ctypes", ".", "WinError", "(", "2", ")", "return", "ctypes", ".", "wstring_at", "(", "buf", ",", "length", ".", "value", ")", ".", "rstrip", "(", "u\"\\x00\"", ")" ]
Switch or run in this env
def switch_or_run ( cmd , venv_name = None ) : if cmd : return _run ( venv_name , cmd ) inenv = InenvManager ( ) if not os . getenv ( INENV_ENV_VAR ) : activator_warn ( inenv ) return else : venv = inenv . get_prepped_venv ( venv_name ) inenv . clear_extra_source_file ( ) inenv . write_extra_source_file ( "source {}" . format ( venv . activate_shell_file ) ) inenv . write_extra_source_file ( override_envars_and_deactivate ( inenv . get_envvars ( venv_name ) ) ) if autojump_enabled ( ) : directory = inenv . guess_contents_dir ( venv_name ) inenv . write_extra_source_file ( 'cd {}' . format ( directory ) ) click . secho ( "Jumping to {}" . format ( directory ) , fg = 'green' ) sys . exit ( EVAL_EXIT_CODE )
11,079
https://github.com/pnegahdar/inenv/blob/8f484e520892bf9eb59f91b4b5c92df9fbd9a4e6/inenv/cli.py#L91-L108
[ "def", "GetAttachmentIdFromMediaId", "(", "media_id", ")", ":", "altchars", "=", "'+-'", "if", "not", "six", ".", "PY2", ":", "altchars", "=", "altchars", ".", "encode", "(", "'utf-8'", ")", "# altchars for '+' and '/'. We keep '+' but replace '/' with '-'", "buffer", "=", "base64", ".", "b64decode", "(", "str", "(", "media_id", ")", ",", "altchars", ")", "resoure_id_length", "=", "20", "attachment_id", "=", "''", "if", "len", "(", "buffer", ")", ">", "resoure_id_length", ":", "# We are cutting off the storage index.", "attachment_id", "=", "base64", ".", "b64encode", "(", "buffer", "[", "0", ":", "resoure_id_length", "]", ",", "altchars", ")", "if", "not", "six", ".", "PY2", ":", "attachment_id", "=", "attachment_id", ".", "decode", "(", "'utf-8'", ")", "else", ":", "attachment_id", "=", "media_id", "return", "attachment_id" ]
Removes the venv by name
def rm ( venv_name ) : inenv = InenvManager ( ) venv = inenv . get_venv ( venv_name ) click . confirm ( "Delete dir {}" . format ( venv . path ) ) shutil . rmtree ( venv . path )
11,080
https://github.com/pnegahdar/inenv/blob/8f484e520892bf9eb59f91b4b5c92df9fbd9a4e6/inenv/cli.py#L113-L118
[ "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" ]
Print the root directory of a virtualenv
def root ( venv_name ) : inenv = InenvManager ( ) inenv . get_venv ( venv_name ) venv = inenv . registered_venvs [ venv_name ] click . secho ( venv [ 'root' ] )
11,081
https://github.com/pnegahdar/inenv/blob/8f484e520892bf9eb59f91b4b5c92df9fbd9a4e6/inenv/cli.py#L123-L128
[ "def", "deletecols", "(", "X", ",", "cols", ")", ":", "if", "isinstance", "(", "cols", ",", "str", ")", ":", "cols", "=", "cols", ".", "split", "(", "','", ")", "retain", "=", "[", "n", "for", "n", "in", "X", ".", "dtype", ".", "names", "if", "n", "not", "in", "cols", "]", "if", "len", "(", "retain", ")", ">", "0", ":", "return", "X", "[", "retain", "]", "else", ":", "return", "None" ]
Initializez a virtualenv
def init ( venv_name ) : inenv = InenvManager ( ) inenv . get_prepped_venv ( venv_name , skip_cached = False ) if not os . getenv ( INENV_ENV_VAR ) : activator_warn ( inenv ) click . secho ( "Your venv is ready. Enjoy!" , fg = 'green' )
11,082
https://github.com/pnegahdar/inenv/blob/8f484e520892bf9eb59f91b4b5c92df9fbd9a4e6/inenv/cli.py#L133-L139
[ "def", "get_class", "(", "class_key", ")", ":", "if", "class_key", "not", "in", "CLASSES", ":", "for", "basecls", "in", "(", "MediaMetadata", ",", "MediaCollection", ")", ":", "if", "class_key", ".", "startswith", "(", "basecls", ".", "__name__", ")", ":", "# So MediaMetadataTrack turns into MSTrack", "class_name", "=", "'MS'", "+", "class_key", ".", "replace", "(", "basecls", ".", "__name__", ",", "''", ")", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "class_name", "=", "class_name", ".", "encode", "(", "'ascii'", ")", "CLASSES", "[", "class_key", "]", "=", "type", "(", "class_name", ",", "(", "basecls", ",", ")", ",", "{", "}", ")", "_LOG", ".", "info", "(", "'Class %s created'", ",", "CLASSES", "[", "class_key", "]", ")", "return", "CLASSES", "[", "class_key", "]" ]
Initializes a virtualenv
def autojump ( ) : currently_enabled = autojump_enabled ( ) toggle_autojump ( ) if not currently_enabled : click . secho ( "Autojump enabled" , fg = 'green' ) else : click . secho ( "Autojump disabled" , fg = 'red' )
11,083
https://github.com/pnegahdar/inenv/blob/8f484e520892bf9eb59f91b4b5c92df9fbd9a4e6/inenv/cli.py#L143-L150
[ "def", "catalogFactory", "(", "name", ",", "*", "*", "kwargs", ")", ":", "fn", "=", "lambda", "member", ":", "inspect", ".", "isclass", "(", "member", ")", "and", "member", ".", "__module__", "==", "__name__", "catalogs", "=", "odict", "(", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "fn", ")", ")", "if", "name", "not", "in", "list", "(", "catalogs", ".", "keys", "(", ")", ")", ":", "msg", "=", "\"%s not found in catalogs:\\n %s\"", "%", "(", "name", ",", "list", "(", "kernels", ".", "keys", "(", ")", ")", ")", "logger", ".", "error", "(", "msg", ")", "msg", "=", "\"Unrecognized catalog: %s\"", "%", "name", "raise", "Exception", "(", "msg", ")", "return", "catalogs", "[", "name", "]", "(", "*", "*", "kwargs", ")" ]
Clears all the cached information about this ruler .
def clear ( self ) : self . _minimum = None self . _maximum = None self . _step = None self . _notches = None self . _format = None self . _formatter = None self . _padEnd = 0 self . _padStart = 0
11,084
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xchartruler.py#L91-L102
[ "def", "rpc_start", "(", "working_dir", ",", "port", ",", "subdomain_index", "=", "None", ",", "thread", "=", "True", ")", ":", "rpc_srv", "=", "BlockstackdRPCServer", "(", "working_dir", ",", "port", ",", "subdomain_index", "=", "subdomain_index", ")", "log", ".", "debug", "(", "\"Starting RPC on port {}\"", ".", "format", "(", "port", ")", ")", "if", "thread", ":", "rpc_srv", ".", "start", "(", ")", "return", "rpc_srv" ]
Listens for the enter event to check if the query is setup .
def keyPressEvent ( self , event ) : if event . key ( ) in ( Qt . Key_Enter , Qt . Key_Return ) : self . queryEntered . emit ( self . query ( ) ) super ( XOrbQuickFilterWidget , self ) . keyPressEvent ( event )
11,085
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbquickfilterwidget.py#L96-L103
[ "def", "network", "(", "self", ",", "borrow", "=", "False", ")", ":", "if", "self", ".", "_network", "is", "None", "and", "self", ".", "network_json", "is", "not", "None", ":", "self", ".", "load_weights", "(", ")", "if", "borrow", ":", "return", "self", ".", "borrow_cached_network", "(", "self", ".", "network_json", ",", "self", ".", "network_weights", ")", "else", ":", "import", "keras", ".", "models", "self", ".", "_network", "=", "keras", ".", "models", ".", "model_from_json", "(", "self", ".", "network_json", ")", "if", "self", ".", "network_weights", "is", "not", "None", ":", "self", ".", "_network", ".", "set_weights", "(", "self", ".", "network_weights", ")", "self", ".", "network_json", "=", "None", "self", ".", "network_weights", "=", "None", "return", "self", ".", "_network" ]
Rebuilds the data associated with this filter widget .
def rebuild ( self ) : table = self . tableType ( ) form = nativestring ( self . filterFormat ( ) ) if not table and form : if self . layout ( ) . count ( ) == 0 : self . layout ( ) . addWidget ( QLabel ( form , self ) ) else : self . layout ( ) . itemAt ( 0 ) . widget ( ) . setText ( form ) return elif not form : return for child in self . findChildren ( QWidget ) : child . close ( ) child . setParent ( None ) child . deleteLater ( ) self . setUpdatesEnabled ( False ) schema = table . schema ( ) vlayout = self . layout ( ) for i in range ( vlayout . count ( ) ) : vlayout . takeAt ( 0 ) self . _plugins = [ ] for line in form . split ( '\n' ) : row = QHBoxLayout ( ) row . setContentsMargins ( 0 , 0 , 0 , 0 ) row . setSpacing ( 0 ) for label , lookup in FORMAT_SPLITTER . findall ( line ) : # create the label lbl = QLabel ( label , self ) row . addWidget ( lbl ) # create the query plugin opts = lookup . split ( ':' ) if len ( opts ) == 1 : opts . append ( 'is' ) column = schema . column ( opts [ 0 ] ) if not column : continue plugin = self . pluginFactory ( ) . plugin ( column ) if not plugin : continue editor = plugin . createEditor ( self , column , opts [ 1 ] , None ) if editor : editor . setObjectName ( opts [ 0 ] ) row . addWidget ( editor ) self . _plugins . append ( ( opts [ 0 ] , opts [ 1 ] , plugin , editor ) ) row . addStretch ( 1 ) vlayout . addLayout ( row ) self . setUpdatesEnabled ( True ) self . adjustSize ( )
11,086
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbquickfilterwidget.py#L105-L168
[ "def", "verify_ocsp", "(", "cls", ",", "certificate", ",", "issuer", ")", ":", "return", "OCSPVerifier", "(", "certificate", ",", "issuer", ",", "cls", ".", "get_ocsp_url", "(", ")", ",", "cls", ".", "get_ocsp_responder_certificate_path", "(", ")", ")", ".", "verify", "(", ")" ]
Displays the menu for this filter widget .
def showMenu ( self , point ) : menu = QMenu ( self ) acts = { } acts [ 'edit' ] = menu . addAction ( 'Edit quick filter...' ) trigger = menu . exec_ ( self . mapToGlobal ( point ) ) if trigger == acts [ 'edit' ] : text , accepted = XTextEdit . getText ( self . window ( ) , 'Edit Format' , 'Format:' , self . filterFormat ( ) , wrapped = False ) if accepted : self . setFilterFormat ( text )
11,087
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbquickfilterwidget.py#L170-L188
[ "def", "_DeserializeResponse", "(", "self", ",", "payload", ")", ":", "# Strip off the status line.", "status_line", ",", "payload", "=", "payload", ".", "split", "(", "'\\n'", ",", "1", ")", "_", ",", "status", ",", "_", "=", "status_line", ".", "split", "(", "' '", ",", "2", ")", "# Parse the rest of the response.", "parser", "=", "email_parser", ".", "Parser", "(", ")", "msg", "=", "parser", ".", "parsestr", "(", "payload", ")", "# Get the headers.", "info", "=", "dict", "(", "msg", ")", "info", "[", "'status'", "]", "=", "status", "# Create Response from the parsed headers.", "content", "=", "msg", ".", "get_payload", "(", ")", "return", "http_wrapper", ".", "Response", "(", "info", ",", "content", ",", "self", ".", "__batch_url", ")" ]
Set the given file descriptor to non - blocking mode .
def set_nonblock ( fd ) : # type: (int) -> None fcntl . fcntl ( fd , fcntl . F_SETFL , fcntl . fcntl ( fd , fcntl . F_GETFL ) | os . O_NONBLOCK )
11,088
https://github.com/tueda/python-form/blob/1e5a8464f7a7a6cbbb32411fc2ea3615fd48334b/form/ioutil.py#L10-L15
[ "def", "resolve_expression", "(", "self", ",", "query", "=", "None", ",", "allow_joins", "=", "True", ",", "reuse", "=", "None", ",", "summarize", "=", "False", ",", "for_save", "=", "False", ")", ":", "c", "=", "self", ".", "copy", "(", ")", "c", ".", "is_summary", "=", "summarize", "c", ".", "for_save", "=", "for_save", "final_points", "=", "[", "]", "for", "i", ",", "p", "in", "enumerate", "(", "self", ".", "params", ")", ":", "try", ":", "float", "(", "p", ")", "except", ":", "_", ",", "source", ",", "_", ",", "join_list", ",", "last", "=", "query", ".", "setup_joins", "(", "six", ".", "text_type", "(", "p", ")", ".", "split", "(", "'__'", ")", ",", "query", ".", "model", ".", "_meta", ",", "query", ".", "get_initial_alias", "(", ")", ")", "[", ":", "5", "]", "target", ",", "alias", ",", "_", "=", "query", ".", "trim_joins", "(", "source", ",", "join_list", ",", "last", ")", "final_points", ".", "append", "(", "\"%s.%s\"", "%", "(", "alias", ",", "target", "[", "0", "]", ".", "get_attname_column", "(", ")", "[", "1", "]", ")", ")", "else", ":", "final_points", ".", "append", "(", "six", ".", "text_type", "(", "p", ")", ")", "c", ".", "params", "=", "final_points", "return", "c" ]
Read data from the stream .
def read ( self ) : # type: () -> str s = self . _buf + self . _raw . read ( ) self . _buf = '' return s
11,089
https://github.com/tueda/python-form/blob/1e5a8464f7a7a6cbbb32411fc2ea3615fd48334b/form/ioutil.py#L37-L42
[ "def", "actually_mount", "(", "self", ",", "client", ")", ":", "a_obj", "=", "self", ".", "config", ".", "copy", "(", ")", "if", "'description'", "in", "a_obj", ":", "del", "a_obj", "[", "'description'", "]", "try", ":", "m_fun", "=", "getattr", "(", "client", ",", "self", ".", "mount_fun", ")", "if", "self", ".", "description", "and", "a_obj", ":", "m_fun", "(", "self", ".", "backend", ",", "mount_point", "=", "self", ".", "path", ",", "description", "=", "self", ".", "description", ",", "config", "=", "a_obj", ")", "elif", "self", ".", "description", ":", "m_fun", "(", "self", ".", "backend", ",", "mount_point", "=", "self", ".", "path", ",", "description", "=", "self", ".", "description", ")", "elif", "a_obj", ":", "m_fun", "(", "self", ".", "backend", ",", "mount_point", "=", "self", ".", "path", ",", "config", "=", "a_obj", ")", "else", ":", "m_fun", "(", "self", ".", "backend", ",", "mount_point", "=", "self", ".", "path", ")", "except", "hvac", ".", "exceptions", ".", "InvalidRequest", "as", "exception", ":", "match", "=", "re", ".", "match", "(", "'existing mount at (?P<path>.+)'", ",", "str", "(", "exception", ")", ")", "if", "match", ":", "e_msg", "=", "\"%s has a mountpoint conflict with %s\"", "%", "(", "self", ".", "path", ",", "match", ".", "group", "(", "'path'", ")", ")", "raise", "aomi_excep", ".", "VaultConstraint", "(", "e_msg", ")", "else", ":", "raise" ]
Websocket on_open event handler
def on_open ( self , ws ) : def keep_alive ( interval ) : while True : time . sleep ( interval ) self . ping ( ) start_new_thread ( keep_alive , ( self . keep_alive_interval , ) )
11,090
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L50-L57
[ "def", "_generate_question", "(", "self", ")", ":", "x", "=", "random", ".", "randint", "(", "1", ",", "10", ")", "y", "=", "random", ".", "randint", "(", "1", ",", "10", ")", "operator", "=", "random", ".", "choice", "(", "(", "'+'", ",", "'-'", ",", "'*'", ",", ")", ")", "if", "operator", "==", "'+'", ":", "answer", "=", "x", "+", "y", "elif", "operator", "==", "'-'", ":", "# Ensure we'll get a non-negative answer", "if", "x", "<", "y", ":", "x", ",", "y", "=", "y", ",", "x", "answer", "=", "x", "-", "y", "else", ":", "# Multiplication is hard, make it easier", "x", "=", "math", ".", "ceil", "(", "x", "/", "2", ")", "y", "=", "math", ".", "ceil", "(", "y", "/", "2", ")", "answer", "=", "x", "*", "y", "# Use a prettied-up HTML multiplication character", "operator", "=", "'&times;'", "# Format the answer nicely, then mark it as safe so Django won't escape it", "question", "=", "'{} {} {}'", ".", "format", "(", "x", ",", "operator", ",", "y", ")", "return", "mark_safe", "(", "question", ")", ",", "answer" ]
Websocket on_message event handler
def on_message ( self , ws , message ) : try : data = json . loads ( message ) except Exception : self . _set_error ( message , "decode message failed" ) else : self . _inbox . put ( RTMMessage ( data ) )
11,091
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L59-L69
[ "def", "pulsation", "(", "feature", ",", "*", "*", "kwargs", ")", ":", "if", "not", "conf", ".", "devel", ":", "raise", "NotImplementedError", "(", "\"'pulsation' feature not officially supported for this release. Enable developer mode to test.\"", ")", "params", "=", "[", "]", "params", "+=", "[", "FloatParameter", "(", "qualifier", "=", "'radamp'", ",", "value", "=", "kwargs", ".", "get", "(", "'radamp'", ",", "0.1", ")", ",", "default_unit", "=", "u", ".", "dimensionless_unscaled", ",", "description", "=", "'Relative radial amplitude of the pulsations'", ")", "]", "params", "+=", "[", "FloatParameter", "(", "qualifier", "=", "'freq'", ",", "value", "=", "kwargs", ".", "get", "(", "'freq'", ",", "1.0", ")", ",", "default_unit", "=", "u", ".", "d", "**", "-", "1", ",", "description", "=", "'Frequency of the pulsations'", ")", "]", "params", "+=", "[", "IntParameter", "(", "qualifier", "=", "'l'", ",", "value", "=", "kwargs", ".", "get", "(", "'l'", ",", "0", ")", ",", "default_unit", "=", "u", ".", "dimensionless_unscaled", ",", "description", "=", "'Non-radial degree l'", ")", "]", "params", "+=", "[", "IntParameter", "(", "qualifier", "=", "'m'", ",", "value", "=", "kwargs", ".", "get", "(", "'m'", ",", "0", ")", ",", "default_unit", "=", "u", ".", "dimensionless_unscaled", ",", "description", "=", "'Azimuthal order m'", ")", "]", "params", "+=", "[", "BoolParameter", "(", "qualifier", "=", "'teffext'", ",", "value", "=", "kwargs", ".", "get", "(", "'teffext'", ",", "False", ")", ",", "description", "=", "'Switch to denote whether Teffs are provided by the external code'", ")", "]", "constraints", "=", "[", "]", "return", "ParameterSet", "(", "params", ")", ",", "constraints" ]
Sends a RTMMessage Should be called after starting the loop
def send ( self , message ) : if "call_id" not in message : message [ "call_id" ] = self . gen_call_id ( ) self . _ws . send ( message . to_json ( ) )
11,092
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L120-L133
[ "def", "from_pint", "(", "cls", ",", "arr", ",", "unit_registry", "=", "None", ")", ":", "p_units", "=", "[", "]", "for", "base", ",", "exponent", "in", "arr", ".", "_units", ".", "items", "(", ")", ":", "bs", "=", "convert_pint_units", "(", "base", ")", "p_units", ".", "append", "(", "\"%s**(%s)\"", "%", "(", "bs", ",", "Rational", "(", "exponent", ")", ")", ")", "p_units", "=", "\"*\"", ".", "join", "(", "p_units", ")", "if", "isinstance", "(", "arr", ".", "magnitude", ",", "np", ".", "ndarray", ")", ":", "return", "unyt_array", "(", "arr", ".", "magnitude", ",", "p_units", ",", "registry", "=", "unit_registry", ")", "else", ":", "return", "unyt_quantity", "(", "arr", ".", "magnitude", ",", "p_units", ",", "registry", "=", "unit_registry", ")" ]
Removes and returns a RTMMessage from self . _inbox
def get_message ( self , block = False , timeout = None ) : try : message = self . _inbox . get ( block = block , timeout = timeout ) return message except Exception : return None
11,093
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L135-L150
[ "def", "backup_file", "(", "*", ",", "file", ",", "host", ")", ":", "if", "_driver", ":", "log", ".", "msg_debug", "(", "\"[{driver}] Backing up file '{file}'\"", ".", "format", "(", "driver", "=", "_driver", ".", "get_name", "(", ")", ",", "file", "=", "file", ")", ")", "_driver", ".", "backup_file", "(", "file", "=", "file", ",", "host", "=", "host", ")" ]
Removes and returns an error from self . _errors
def get_error ( self , block = False , timeout = None ) : try : error = self . _errors . get ( block = block , timeout = timeout ) return error except Exception : return None
11,094
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L152-L167
[ "def", "cudnnSetPooling2dDescriptor", "(", "poolingDesc", ",", "mode", ",", "windowHeight", ",", "windowWidth", ",", "verticalPadding", ",", "horizontalPadding", ",", "verticalStride", ",", "horizontalStride", ")", ":", "status", "=", "_libcudnn", ".", "cudnnSetPooling2dDescriptor", "(", "poolingDesc", ",", "mode", ",", "windowHeight", ",", "windowWidth", ",", "verticalPadding", ",", "horizontalPadding", ",", "verticalStride", ",", "horizontalStride", ")", "cudnnCheckStatus", "(", "status", ")" ]
Creates a new editor for the system .
def createEditor ( self , parent , column , operator , value ) : editor = super ( EnumPlugin , self ) . createEditor ( parent , column , operator , value ) editor . setEnum ( column . enum ( ) ) if operator in ( 'contains' , 'does not contain' ) : editor . setCheckable ( True ) editor . setCurrentValue ( value ) return editor
11,095
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/plugins.py#L127-L141
[ "def", "multivariate_neg_logposterior", "(", "self", ",", "beta", ")", ":", "post", "=", "self", ".", "neg_loglik", "(", "beta", ")", "for", "k", "in", "range", "(", "0", ",", "self", ".", "z_no", ")", ":", "if", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "covariance_prior", "is", "True", ":", "post", "+=", "-", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "logpdf", "(", "self", ".", "custom_covariance", "(", "beta", ")", ")", "break", "else", ":", "post", "+=", "-", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "logpdf", "(", "beta", "[", "k", "]", ")", "return", "post" ]
Sets up the query for this editor .
def setupQuery ( self , query , op , editor ) : if editor is not None : value = editor . currentRecord ( ) if value is None : return False return super ( ForeignKeyPlugin , self ) . setupQuery ( query , op , editor )
11,096
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/plugins.py#L189-L198
[ "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", "(", ")" ]
Color generator for Bokeh plots
def color_gen ( colormap = 'viridis' , key = None , n = 15 ) : if colormap in dir ( bpal ) : palette = getattr ( bpal , colormap ) if isinstance ( palette , dict ) : if key is None : key = list ( palette . keys ( ) ) [ 0 ] palette = palette [ key ] elif callable ( palette ) : palette = palette ( n ) else : raise TypeError ( "pallette must be a bokeh palette name or a sequence of color hex values." ) elif isinstance ( colormap , ( list , tuple ) ) : palette = colormap else : raise TypeError ( "pallette must be a bokeh palette name or a sequence of color hex values." ) yield from itertools . cycle ( palette )
11,097
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L763-L796
[ "def", "EnumKey", "(", "key", ",", "index", ")", ":", "regenumkeyex", "=", "advapi32", "[", "\"RegEnumKeyExW\"", "]", "regenumkeyex", ".", "restype", "=", "ctypes", ".", "c_long", "regenumkeyex", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "ctypes", ".", "wintypes", ".", "DWORD", ",", "ctypes", ".", "c_wchar_p", ",", "LPDWORD", ",", "LPDWORD", ",", "ctypes", ".", "c_wchar_p", ",", "LPDWORD", ",", "ctypes", ".", "POINTER", "(", "FileTime", ")", "]", "buf", "=", "ctypes", ".", "create_unicode_buffer", "(", "257", ")", "length", "=", "ctypes", ".", "wintypes", ".", "DWORD", "(", "257", ")", "rc", "=", "regenumkeyex", "(", "key", ".", "handle", ",", "index", ",", "ctypes", ".", "cast", "(", "buf", ",", "ctypes", ".", "c_wchar_p", ")", ",", "ctypes", ".", "byref", "(", "length", ")", ",", "LPDWORD", "(", ")", ",", "ctypes", ".", "c_wchar_p", "(", ")", ",", "LPDWORD", "(", ")", ",", "ctypes", ".", "POINTER", "(", "FileTime", ")", "(", ")", ")", "if", "rc", "!=", "0", ":", "raise", "ctypes", ".", "WinError", "(", "2", ")", "return", "ctypes", ".", "wstring_at", "(", "buf", ",", "length", ".", "value", ")", ".", "rstrip", "(", "u\"\\x00\"", ")" ]
Get a list of the available filters
def filters ( filter_directory = None , update = False , fmt = 'table' , * * kwargs ) : if filter_directory is None : filter_directory = resource_filename ( 'svo_filters' , 'data/filters/' ) # Get the pickle path and make sure file exists p_path = os . path . join ( filter_directory , 'filter_list.p' ) updated = False if not os . path . isfile ( p_path ) : os . system ( 'touch {}' . format ( p_path ) ) if update : print ( 'Loading filters into table...' ) # Get all the filters (except the pickle) files = glob ( filter_directory + '*' ) files = [ f for f in files if not f . endswith ( '.p' ) ] bands = [ os . path . basename ( b ) for b in files ] tables = [ ] for band in bands : # Load the filter band = band . replace ( '.txt' , '' ) filt = Filter ( band , * * kwargs ) filt . Band = band # Put metadata into table with correct dtypes info = filt . info ( True ) vals = [ float ( i ) if i . replace ( '.' , '' ) . replace ( '-' , '' ) . replace ( '+' , '' ) . isnumeric ( ) else i for i in info [ 'Values' ] ] dtypes = np . array ( [ type ( i ) for i in vals ] ) table = at . Table ( np . array ( [ vals ] ) , names = info [ 'Attributes' ] , dtype = dtypes ) tables . append ( table ) del filt , info , table # Write to the pickle with open ( p_path , 'wb' ) as file : pickle . dump ( at . vstack ( tables ) , file ) # Load the saved pickle data = { } if os . path . isfile ( p_path ) : with open ( p_path , 'rb' ) as file : data = pickle . load ( file ) # Return the data if data : if fmt == 'dict' : data = { r [ 0 ] : { k : r [ k ] . value if hasattr ( r [ k ] , 'unit' ) else r [ k ] for k in data . keys ( ) [ 1 : ] } for r in data } else : # Add Band as index data . add_index ( 'Band' ) return data # Or try to generate it once else : if not updated : updated = True filters ( update = True ) else : print ( 'No filters found in' , filter_directory )
11,098
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L799-L886
[ "def", "consume_path_sep", "(", "self", ",", "i", ")", ":", "try", ":", "if", "self", ".", "bslash_abort", ":", "count", "=", "-", "1", "c", "=", "'\\\\'", "while", "c", "==", "'\\\\'", ":", "count", "+=", "1", "c", "=", "next", "(", "i", ")", "i", ".", "rewind", "(", "1", ")", "# Rewind one more if we have an odd number (escape): \\\\\\*", "if", "count", ">", "0", "and", "count", "%", "2", ":", "i", ".", "rewind", "(", "1", ")", "else", ":", "c", "=", "'/'", "while", "c", "==", "'/'", ":", "c", "=", "next", "(", "i", ")", "i", ".", "rewind", "(", "1", ")", "except", "StopIteration", ":", "pass" ]
Rebin a spectrum to a new wavelength array while preserving the total flux
def rebin_spec ( spec , wavnew , oversamp = 100 , plot = False ) : wave , flux = spec nlam = len ( wave ) x0 = np . arange ( nlam , dtype = float ) x0int = np . arange ( ( nlam - 1. ) * oversamp + 1. , dtype = float ) / oversamp w0int = np . interp ( x0int , x0 , wave ) spec0int = np . interp ( w0int , wave , flux ) / oversamp # Set up the bin edges for down-binning maxdiffw1 = np . diff ( wavnew ) . max ( ) w1bins = np . concatenate ( ( [ wavnew [ 0 ] - maxdiffw1 ] , .5 * ( wavnew [ 1 : : ] + wavnew [ 0 : - 1 ] ) , [ wavnew [ - 1 ] + maxdiffw1 ] ) ) # Bin down the interpolated spectrum: w1bins = np . sort ( w1bins ) nbins = len ( w1bins ) - 1 specnew = np . zeros ( nbins ) inds2 = [ [ w0int . searchsorted ( w1bins [ ii ] , side = 'left' ) , w0int . searchsorted ( w1bins [ ii + 1 ] , side = 'left' ) ] for ii in range ( nbins ) ] for ii in range ( nbins ) : specnew [ ii ] = np . sum ( spec0int [ inds2 [ ii ] [ 0 ] : inds2 [ ii ] [ 1 ] ] ) return specnew
11,099
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L889-L931
[ "def", "version", "(", "self", ")", ":", "url", "=", "\"http://{master_addr}:{master_port}/dir/status\"", ".", "format", "(", "master_addr", "=", "self", ".", "master_addr", ",", "master_port", "=", "self", ".", "master_port", ")", "data", "=", "self", ".", "conn", ".", "get_data", "(", "url", ")", "response_data", "=", "json", ".", "loads", "(", "data", ")", "return", "response_data", ".", "get", "(", "\"Version\"", ")" ]