query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
User of KE - chain .
def user ( self , username = None , pk = None , * * kwargs ) : _users = self . users ( username = username , pk = pk , * * kwargs ) if len ( _users ) == 0 : raise NotFoundError ( "No user criteria matches" ) if len ( _users ) != 1 : raise MultipleFoundError ( "Multiple users fit criteria" ) return _users [ 0 ]
4,300
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L818-L841
[ "def", "_generate_examples_validation", "(", "self", ",", "archive", ",", "labels", ")", ":", "# Get the current random seeds.", "numpy_st0", "=", "np", ".", "random", ".", "get_state", "(", ")", "# Set new random seeds.", "np", ".", "random", ".", "seed", "(", "135", ")", "logging", ".", "warning", "(", "'Overwriting cv2 RNG seed.'", ")", "tfds", ".", "core", ".", "lazy_imports", ".", "cv2", ".", "setRNGSeed", "(", "357", ")", "for", "example", "in", "super", "(", "Imagenet2012Corrupted", ",", "self", ")", ".", "_generate_examples_validation", "(", "archive", ",", "labels", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "tf_img", "=", "tf", ".", "image", ".", "decode_jpeg", "(", "example", "[", "'image'", "]", ".", "read", "(", ")", ",", "channels", "=", "3", ")", "image_np", "=", "tfds", ".", "as_numpy", "(", "tf_img", ")", "example", "[", "'image'", "]", "=", "self", ".", "_get_corrupted_example", "(", "image_np", ")", "yield", "example", "# Reset the seeds back to their original values.", "np", ".", "random", ".", "set_state", "(", "numpy_st0", ")" ]
Team of KE - chain .
def team ( self , name = None , id = None , is_hidden = False , * * kwargs ) : _teams = self . teams ( name = name , id = id , * * kwargs ) if len ( _teams ) == 0 : raise NotFoundError ( "No team criteria matches" ) if len ( _teams ) != 1 : raise MultipleFoundError ( "Multiple teams fit criteria" ) return _teams [ 0 ]
4,301
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L843-L868
[ "def", "_generate_examples_validation", "(", "self", ",", "archive", ",", "labels", ")", ":", "# Get the current random seeds.", "numpy_st0", "=", "np", ".", "random", ".", "get_state", "(", ")", "# Set new random seeds.", "np", ".", "random", ".", "seed", "(", "135", ")", "logging", ".", "warning", "(", "'Overwriting cv2 RNG seed.'", ")", "tfds", ".", "core", ".", "lazy_imports", ".", "cv2", ".", "setRNGSeed", "(", "357", ")", "for", "example", "in", "super", "(", "Imagenet2012Corrupted", ",", "self", ")", ".", "_generate_examples_validation", "(", "archive", ",", "labels", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "tf_img", "=", "tf", ".", "image", ".", "decode_jpeg", "(", "example", "[", "'image'", "]", ".", "read", "(", ")", ",", "channels", "=", "3", ")", "image_np", "=", "tfds", ".", "as_numpy", "(", "tf_img", ")", "example", "[", "'image'", "]", "=", "self", ".", "_get_corrupted_example", "(", "image_np", ")", "yield", "example", "# Reset the seeds back to their original values.", "np", ".", "random", ".", "set_state", "(", "numpy_st0", ")" ]
Teams of KE - chain .
def teams ( self , name = None , id = None , is_hidden = False , * * kwargs ) : request_params = { 'name' : name , 'id' : id , 'is_hidden' : is_hidden } if kwargs : request_params . update ( * * kwargs ) r = self . _request ( 'GET' , self . _build_url ( 'teams' ) , params = request_params ) if r . status_code != requests . codes . ok : # pragma: no cover raise NotFoundError ( "Could not find teams: '{}'" . format ( r . json ( ) ) ) data = r . json ( ) return [ Team ( team , client = self ) for team in data [ 'results' ] ]
4,302
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L870-L901
[ "def", "render_to_response", "(", "self", ",", "context", ",", "*", "*", "response_kwargs", ")", ":", "serializer", "=", "PollPublicSerializer", "(", "self", ".", "object", ")", "response", "=", "HttpResponse", "(", "json", ".", "dumps", "(", "serializer", ".", "data", ")", ",", "content_type", "=", "\"application/json\"", ")", "if", "\"HTTP_ORIGIN\"", "in", "self", ".", "request", ".", "META", ":", "response", "[", "\"Access-Control-Allow-Origin\"", "]", "=", "self", ".", "request", ".", "META", "[", "\"HTTP_ORIGIN\"", "]", "response", "[", "\"Access-Control-Allow-Credentials\"", "]", "=", "'true'", "return", "response" ]
Create a part internal core function .
def _create_part ( self , action , data , * * kwargs ) : # suppress_kevents should be in the data (not the query_params) if 'suppress_kevents' in kwargs : data [ 'suppress_kevents' ] = kwargs . pop ( 'suppress_kevents' ) # prepare url query parameters query_params = kwargs query_params [ 'select_action' ] = action response = self . _request ( 'POST' , self . _build_url ( 'parts' ) , params = query_params , # {"select_action": action}, data = data ) if response . status_code != requests . codes . created : raise APIError ( "Could not create part, {}: {}" . format ( str ( response ) , response . content ) ) return Part ( response . json ( ) [ 'results' ] [ 0 ] , client = self )
4,303
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L1043-L1060
[ "def", "propagate_defaults", "(", "config_doc", ")", ":", "for", "group_name", ",", "group_doc", "in", "config_doc", ".", "items", "(", ")", ":", "if", "isinstance", "(", "group_doc", ",", "dict", ")", ":", "defaults", "=", "group_doc", ".", "get", "(", "'defaults'", ",", "{", "}", ")", "for", "item_name", ",", "item_doc", "in", "group_doc", ".", "items", "(", ")", ":", "if", "item_name", "==", "'defaults'", ":", "continue", "if", "isinstance", "(", "item_doc", ",", "dict", ")", ":", "group_doc", "[", "item_name", "]", "=", "dict_merge_pair", "(", "copy", ".", "deepcopy", "(", "defaults", ")", ",", "item_doc", ")", "return", "config_doc" ]
Create a new part instance from a given model under a given parent .
def create_part ( self , parent , model , name = None , * * kwargs ) : if parent . category != Category . INSTANCE : raise IllegalArgumentError ( "The parent should be an category 'INSTANCE'" ) if model . category != Category . MODEL : raise IllegalArgumentError ( "The models should be of category 'MODEL'" ) if not name : name = model . name data = { "name" : name , "parent" : parent . id , "model" : model . id } return self . _create_part ( action = "new_instance" , data = data , * * kwargs )
4,304
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L1062-L1096
[ "def", "feedkeys", "(", "self", ",", "keys", ",", "options", "=", "''", ",", "escape_csi", "=", "True", ")", ":", "return", "self", ".", "request", "(", "'nvim_feedkeys'", ",", "keys", ",", "options", ",", "escape_csi", ")" ]
Create a new child model under a given parent .
def create_model ( self , parent , name , multiplicity = 'ZERO_MANY' , * * kwargs ) : if parent . category != Category . MODEL : raise IllegalArgumentError ( "The parent should be of category 'MODEL'" ) data = { "name" : name , "parent" : parent . id , "multiplicity" : multiplicity } return self . _create_part ( action = "create_child_model" , data = data , * * kwargs )
4,305
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L1098-L1129
[ "def", "complete", "(", "self", ",", "text", ",", "state", ")", ":", "# dexnet entity tab completion", "results", "=", "[", "w", "for", "w", "in", "self", ".", "words", "if", "w", ".", "startswith", "(", "text", ")", "]", "+", "[", "None", "]", "if", "results", "!=", "[", "None", "]", ":", "return", "results", "[", "state", "]", "buffer", "=", "readline", ".", "get_line_buffer", "(", ")", "line", "=", "readline", ".", "get_line_buffer", "(", ")", ".", "split", "(", ")", "# dexnet entity tab completion", "results", "=", "[", "w", "for", "w", "in", "self", ".", "words", "if", "w", ".", "startswith", "(", "text", ")", "]", "+", "[", "None", "]", "if", "results", "!=", "[", "None", "]", ":", "return", "results", "[", "state", "]", "# account for last argument ending in a space", "if", "RE_SPACE", ".", "match", "(", "buffer", ")", ":", "line", ".", "append", "(", "''", ")", "return", "(", "self", ".", "complete_extra", "(", "line", ")", "+", "[", "None", "]", ")", "[", "state", "]" ]
Create a new Part clone under the Parent .
def _create_clone ( self , parent , part , * * kwargs ) : if part . category == Category . MODEL : select_action = 'clone_model' else : select_action = 'clone_instance' data = { "part" : part . id , "parent" : parent . id , "suppress_kevents" : kwargs . pop ( 'suppress_kevents' , None ) } # prepare url query parameters query_params = kwargs query_params [ 'select_action' ] = select_action response = self . _request ( 'POST' , self . _build_url ( 'parts' ) , params = query_params , data = data ) if response . status_code != requests . codes . created : raise APIError ( "Could not clone part, {}: {}" . format ( str ( response ) , response . content ) ) return Part ( response . json ( ) [ 'results' ] [ 0 ] , client = self )
4,306
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L1131-L1167
[ "def", "get_changed_devices", "(", "self", ",", "timestamp", ")", ":", "if", "timestamp", "is", "None", ":", "payload", "=", "{", "}", "else", ":", "payload", "=", "{", "'timeout'", ":", "SUBSCRIPTION_WAIT", ",", "'minimumdelay'", ":", "SUBSCRIPTION_MIN_WAIT", "}", "payload", ".", "update", "(", "timestamp", ")", "# double the timeout here so requests doesn't timeout before vera", "payload", ".", "update", "(", "{", "'id'", ":", "'lu_sdata'", ",", "}", ")", "logger", ".", "debug", "(", "\"get_changed_devices() requesting payload %s\"", ",", "str", "(", "payload", ")", ")", "r", "=", "self", ".", "data_request", "(", "payload", ",", "TIMEOUT", "*", "2", ")", "r", ".", "raise_for_status", "(", ")", "# If the Vera disconnects before writing a full response (as lu_sdata", "# will do when interrupted by a Luup reload), the requests module will", "# happily return 200 with an empty string. So, test for empty response,", "# so we don't rely on the JSON parser to throw an exception.", "if", "r", ".", "text", "==", "\"\"", ":", "raise", "PyveraError", "(", "\"Empty response from Vera\"", ")", "# Catch a wide swath of what the JSON parser might throw, within", "# reason. Unfortunately, some parsers don't specifically return", "# json.decode.JSONDecodeError, but so far most seem to derive what", "# they do throw from ValueError, so that's helpful.", "try", ":", "result", "=", "r", ".", "json", "(", ")", "except", "ValueError", "as", "ex", ":", "raise", "PyveraError", "(", "\"JSON decode error: \"", "+", "str", "(", "ex", ")", ")", "if", "not", "(", "type", "(", "result", ")", "is", "dict", "and", "'loadtime'", "in", "result", "and", "'dataversion'", "in", "result", ")", ":", "raise", "PyveraError", "(", "\"Unexpected/garbled response from Vera\"", ")", "# At this point, all good. Update timestamp and return change data.", "device_data", "=", "result", ".", "get", "(", "'devices'", ")", "timestamp", "=", "{", "'loadtime'", ":", "result", ".", "get", "(", "'loadtime'", ")", ",", "'dataversion'", ":", "result", ".", "get", "(", "'dataversion'", ")", "}", "return", "[", "device_data", ",", "timestamp", "]" ]
Create a new property model under a given model .
def create_property ( self , model , name , description = None , property_type = PropertyType . CHAR_VALUE , default_value = None , unit = None , options = None ) : if model . category != Category . MODEL : raise IllegalArgumentError ( "The model should be of category MODEL" ) if not property_type . endswith ( '_VALUE' ) : warnings . warn ( "Please use the `PropertyType` enumeration to ensure providing correct " "values to the backend." , UserWarning ) property_type = '{}_VALUE' . format ( property_type . upper ( ) ) if property_type not in PropertyType . values ( ) : raise IllegalArgumentError ( "Please provide a valid propertytype, please use one of `enums.PropertyType`. " "Got: '{}'" . format ( property_type ) ) # because the references value only accepts a single 'model_id' in the default value, we need to convert this # to a single value from the list of values. if property_type in ( PropertyType . REFERENCE_VALUE , PropertyType . REFERENCES_VALUE ) and isinstance ( default_value , ( list , tuple ) ) and default_value : default_value = default_value [ 0 ] data = { "name" : name , "part" : model . id , "description" : description or '' , "property_type" : property_type . upper ( ) , "value" : default_value , "unit" : unit or '' , "options" : options or { } } # # We add options after the fact only if they are available, otherwise the options will be set to null in the # # request and that can't be handled by KE-chain. # if options: # data['options'] = options response = self . _request ( 'POST' , self . _build_url ( 'properties' ) , json = data ) if response . status_code != requests . codes . created : raise APIError ( "Could not create property" ) prop = Property . create ( response . json ( ) [ 'results' ] [ 0 ] , client = self ) model . properties . append ( prop ) return prop
4,307
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L1208-L1277
[ "def", "recv", "(", "self", ")", ":", "responses", "=", "self", ".", "_recv", "(", ")", "if", "not", "responses", "and", "self", ".", "requests_timed_out", "(", ")", ":", "log", ".", "warning", "(", "'%s timed out after %s ms. Closing connection.'", ",", "self", ",", "self", ".", "config", "[", "'request_timeout_ms'", "]", ")", "self", ".", "close", "(", "error", "=", "Errors", ".", "RequestTimedOutError", "(", "'Request timed out after %s ms'", "%", "self", ".", "config", "[", "'request_timeout_ms'", "]", ")", ")", "return", "(", ")", "# augment respones w/ correlation_id, future, and timestamp", "for", "i", ",", "(", "correlation_id", ",", "response", ")", "in", "enumerate", "(", "responses", ")", ":", "try", ":", "with", "self", ".", "_lock", ":", "(", "future", ",", "timestamp", ")", "=", "self", ".", "in_flight_requests", ".", "pop", "(", "correlation_id", ")", "except", "KeyError", ":", "self", ".", "close", "(", "Errors", ".", "KafkaConnectionError", "(", "'Received unrecognized correlation id'", ")", ")", "return", "(", ")", "latency_ms", "=", "(", "time", ".", "time", "(", ")", "-", "timestamp", ")", "*", "1000", "if", "self", ".", "_sensors", ":", "self", ".", "_sensors", ".", "request_time", ".", "record", "(", "latency_ms", ")", "log", ".", "debug", "(", "'%s Response %d (%s ms): %s'", ",", "self", ",", "correlation_id", ",", "latency_ms", ",", "response", ")", "responses", "[", "i", "]", "=", "(", "response", ",", "future", ")", "return", "responses" ]
Create a Service .
def create_service ( self , name , scope , description = None , version = None , service_type = ServiceType . PYTHON_SCRIPT , environment_version = ServiceEnvironmentVersion . PYTHON_3_5 , pkg_path = None ) : if service_type not in ServiceType . values ( ) : raise IllegalArgumentError ( "The type should be of one of {}" . format ( ServiceType . values ( ) ) ) if environment_version not in ServiceEnvironmentVersion . values ( ) : raise IllegalArgumentError ( "The environment version should be of one of {}" . format ( ServiceEnvironmentVersion . values ( ) ) ) data = { "name" : name , "scope" : scope , "description" : description , "script_type" : service_type , "script_version" : version , "env_version" : environment_version , } response = self . _request ( 'POST' , self . _build_url ( 'services' ) , data = data ) if response . status_code != requests . codes . created : # pragma: no cover raise APIError ( "Could not create service ({})" . format ( ( response , response . json ( ) ) ) ) service = Service ( response . json ( ) . get ( 'results' ) [ 0 ] , client = self ) if pkg_path : # upload the package service . upload ( pkg_path ) # refresh service contents in place service . refresh ( ) return service
4,308
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L1279-L1346
[ "def", "mergeDQarray", "(", "maskname", ",", "dqarr", ")", ":", "maskarr", "=", "None", "if", "maskname", "is", "not", "None", ":", "if", "isinstance", "(", "maskname", ",", "str", ")", ":", "# working with file on disk (default case)", "if", "os", ".", "path", ".", "exists", "(", "maskname", ")", ":", "mask", "=", "fileutil", ".", "openImage", "(", "maskname", ",", "memmap", "=", "False", ")", "maskarr", "=", "mask", "[", "0", "]", ".", "data", ".", "astype", "(", "np", ".", "bool", ")", "mask", ".", "close", "(", ")", "else", ":", "if", "isinstance", "(", "maskname", ",", "fits", ".", "HDUList", ")", ":", "# working with a virtual input file", "maskarr", "=", "maskname", "[", "0", "]", ".", "data", ".", "astype", "(", "np", ".", "bool", ")", "else", ":", "maskarr", "=", "maskname", ".", "data", ".", "astype", "(", "np", ".", "bool", ")", "if", "maskarr", "is", "not", "None", ":", "# merge array with dqarr now", "np", ".", "bitwise_and", "(", "dqarr", ",", "maskarr", ",", "dqarr", ")" ]
Delete a scope .
def delete_scope ( self , scope ) : assert isinstance ( scope , Scope ) , 'Scope "{}" is not a scope!' . format ( scope . name ) response = self . _request ( 'DELETE' , self . _build_url ( 'scope' , scope_id = str ( scope . id ) ) ) if response . status_code != requests . codes . no_content : # pragma: no cover raise APIError ( "Could not delete scope, {}: {}" . format ( str ( response ) , response . content ) )
4,309
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L1447-L1466
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Take the sort parameter from the get parameters and split it into the field and the prefix
def set_sort ( self , request ) : # Look for 'sort' in get request. If not available use default. sort_request = request . GET . get ( self . sort_parameter , self . default_sort ) if sort_request . startswith ( '-' ) : sort_order = '-' sort_field = sort_request . split ( '-' ) [ 1 ] else : sort_order = '' sort_field = sort_request # Invalid sort requests fail silently if not sort_field in self . _allowed_sort_fields : sort_order = self . default_sort_order sort_field = self . default_sort_field return ( sort_order , sort_field )
4,310
https://github.com/aptivate/django-sortable-listview/blob/9d5fa5847f0c3e80893780c6540e5098635ace9f/sortable_listview/views.py#L108-L125
[ "def", "native_libraries_verify", "(", ")", ":", "with", "open", "(", "BINARY_EXT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "expected", "=", "template", ".", "format", "(", "revision", "=", "REVISION", ")", "with", "open", "(", "BINARY_EXT_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", "if", "contents", "!=", "expected", ":", "err_msg", "=", "\"\\n\"", "+", "get_diff", "(", "contents", ",", "expected", ",", "\"docs/python/binary-extension.rst.actual\"", ",", "\"docs/python/binary-extension.rst.expected\"", ",", ")", "raise", "ValueError", "(", "err_msg", ")", "else", ":", "print", "(", "\"docs/python/binary-extension.rst contents are as expected.\"", ")" ]
If we re already sorted by the field then the sort query returned reverses the sort order .
def get_next_sort_string ( self , field ) : # self.sort_field is the currect sort field if field == self . sort_field : next_sort = self . toggle_sort_order ( ) + field else : default_order_for_field = self . _allowed_sort_fields [ field ] [ 'default_direction' ] next_sort = default_order_for_field + field return self . get_sort_string ( next_sort )
4,311
https://github.com/aptivate/django-sortable-listview/blob/9d5fa5847f0c3e80893780c6540e5098635ace9f/sortable_listview/views.py#L135-L147
[ "def", "temperature_hub", "(", "self", ",", "weather_df", ")", ":", "if", "self", ".", "power_plant", ".", "hub_height", "in", "weather_df", "[", "'temperature'", "]", ":", "temperature_hub", "=", "weather_df", "[", "'temperature'", "]", "[", "self", ".", "power_plant", ".", "hub_height", "]", "elif", "self", ".", "temperature_model", "==", "'linear_gradient'", ":", "logging", ".", "debug", "(", "'Calculating temperature using temperature '", "'gradient.'", ")", "closest_height", "=", "weather_df", "[", "'temperature'", "]", ".", "columns", "[", "min", "(", "range", "(", "len", "(", "weather_df", "[", "'temperature'", "]", ".", "columns", ")", ")", ",", "key", "=", "lambda", "i", ":", "abs", "(", "weather_df", "[", "'temperature'", "]", ".", "columns", "[", "i", "]", "-", "self", ".", "power_plant", ".", "hub_height", ")", ")", "]", "temperature_hub", "=", "temperature", ".", "linear_gradient", "(", "weather_df", "[", "'temperature'", "]", "[", "closest_height", "]", ",", "closest_height", ",", "self", ".", "power_plant", ".", "hub_height", ")", "elif", "self", ".", "temperature_model", "==", "'interpolation_extrapolation'", ":", "logging", ".", "debug", "(", "'Calculating temperature using linear inter- or '", "'extrapolation.'", ")", "temperature_hub", "=", "tools", ".", "linear_interpolation_extrapolation", "(", "weather_df", "[", "'temperature'", "]", ",", "self", ".", "power_plant", ".", "hub_height", ")", "else", ":", "raise", "ValueError", "(", "\"'{0}' is an invalid value. \"", ".", "format", "(", "self", ".", "temperature_model", ")", "+", "\"`temperature_model` must be \"", "\"'linear_gradient' or 'interpolation_extrapolation'.\"", ")", "return", "temperature_hub" ]
Returns a sort class for the active sort only . That is if field is not sort_field then nothing will be returned becaues the sort is not active .
def get_sort_indicator ( self , field ) : indicator = '' if field == self . sort_field : indicator = 'sort-asc' if self . sort_order == '-' : indicator = 'sort-desc' return indicator
4,312
https://github.com/aptivate/django-sortable-listview/blob/9d5fa5847f0c3e80893780c6540e5098635ace9f/sortable_listview/views.py#L149-L160
[ "def", "upload_cbn_dir", "(", "dir_path", ",", "manager", ")", ":", "t", "=", "time", ".", "time", "(", ")", "for", "jfg_path", "in", "os", ".", "listdir", "(", "dir_path", ")", ":", "if", "not", "jfg_path", ".", "endswith", "(", "'.jgf'", ")", ":", "continue", "path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "jfg_path", ")", "log", ".", "info", "(", "'opening %s'", ",", "path", ")", "with", "open", "(", "path", ")", "as", "f", ":", "cbn_jgif_dict", "=", "json", ".", "load", "(", "f", ")", "graph", "=", "pybel", ".", "from_cbn_jgif", "(", "cbn_jgif_dict", ")", "out_path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "jfg_path", ".", "replace", "(", "'.jgf'", ",", "'.bel'", ")", ")", "with", "open", "(", "out_path", ",", "'w'", ")", "as", "o", ":", "pybel", ".", "to_bel", "(", "graph", ",", "o", ")", "strip_annotations", "(", "graph", ")", "enrich_pubmed_citations", "(", "manager", "=", "manager", ",", "graph", "=", "graph", ")", "pybel", ".", "to_database", "(", "graph", ",", "manager", "=", "manager", ")", "log", ".", "info", "(", "''", ")", "log", ".", "info", "(", "'done in %.2f'", ",", "time", ".", "time", "(", ")", "-", "t", ")" ]
Thanks to del_query_parameters and get_querystring we build the link with preserving interesting get parameters and removing the others
def get_basic_sort_link ( self , request , field ) : query_string = self . get_querystring ( ) sort_string = self . get_next_sort_string ( field ) if sort_string : sort_link = request . path + '?' + sort_string if query_string : sort_link += '&' + query_string else : sort_link = request . path if query_string : sort_link += '?' + query_string return sort_link
4,313
https://github.com/aptivate/django-sortable-listview/blob/9d5fa5847f0c3e80893780c6540e5098635ace9f/sortable_listview/views.py#L180-L195
[ "def", "construct_error_message", "(", "driver_id", ",", "error_type", ",", "message", ",", "timestamp", ")", ":", "builder", "=", "flatbuffers", ".", "Builder", "(", "0", ")", "driver_offset", "=", "builder", ".", "CreateString", "(", "driver_id", ".", "binary", "(", ")", ")", "error_type_offset", "=", "builder", ".", "CreateString", "(", "error_type", ")", "message_offset", "=", "builder", ".", "CreateString", "(", "message", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataStart", "(", "builder", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddDriverId", "(", "builder", ",", "driver_offset", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddType", "(", "builder", ",", "error_type_offset", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddErrorMessage", "(", "builder", ",", "message_offset", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddTimestamp", "(", "builder", ",", "timestamp", ")", "error_data_offset", "=", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataEnd", "(", "builder", ")", "builder", ".", "Finish", "(", "error_data_offset", ")", "return", "bytes", "(", "builder", ".", "Output", "(", ")", ")" ]
Build the absolute path of the to - be - saved thumbnail .
def build_thumb_path ( self , image ) : image_file = image . file image_name_w_ext = split ( image . name ) [ - 1 ] image_name , ext = splitext ( image_name_w_ext ) if not self . in_memory ( image_file ) : # `image_file` is already in disk (not in memory). # `image_name` is the full path, not just the name image_name = image_name . split ( '/' ) [ - 1 ] upload_to = image . field . upload_to if not upload_to . endswith ( '/' ) : upload_to = f'{upload_to}/' path_upload_to = f'{upload_to}{image_name}' return f'{self.storage.location}/{path_upload_to}{THUMB_EXT}{ext}'
4,314
https://github.com/manikos/django-progressiveimagefield/blob/a432c79d23d87ea8944ac252ae7d15df1e4f3072/progressiveimagefield/fields.py#L22-L37
[ "def", "Handle", "(", "self", ",", "args", ",", "token", "=", "None", ")", ":", "# Get all artifacts that aren't Bootstrap and aren't the base class.", "artifacts_list", "=", "sorted", "(", "artifact_registry", ".", "REGISTRY", ".", "GetArtifacts", "(", "reload_datastore_artifacts", "=", "True", ")", ",", "key", "=", "lambda", "art", ":", "art", ".", "name", ")", "total_count", "=", "len", "(", "artifacts_list", ")", "if", "args", ".", "count", ":", "artifacts_list", "=", "artifacts_list", "[", "args", ".", "offset", ":", "args", ".", "offset", "+", "args", ".", "count", "]", "else", ":", "artifacts_list", "=", "artifacts_list", "[", "args", ".", "offset", ":", "]", "descriptors", "=", "self", ".", "BuildArtifactDescriptors", "(", "artifacts_list", ")", "return", "ApiListArtifactsResult", "(", "items", "=", "descriptors", ",", "total_count", "=", "total_count", ")" ]
Override runserver s entry point to bring Gunicorn on .
def run ( self , * * options ) : shutdown_message = options . get ( 'shutdown_message' , '' ) self . stdout . write ( "Performing system checks...\n\n" ) self . check ( display_num_errors = True ) self . check_migrations ( ) now = datetime . datetime . now ( ) . strftime ( r'%B %d, %Y - %X' ) if six . PY2 : now = now . decode ( get_system_encoding ( ) ) self . stdout . write ( now ) addr , port = self . addr , self . port addr = '[{}]' . format ( addr ) if self . _raw_ipv6 else addr runner = GunicornRunner ( addr , port , options ) try : runner . run ( ) except KeyboardInterrupt : runner . shutdown ( ) if shutdown_message : self . stdout . write ( shutdown_message ) sys . exit ( 0 ) except : runner . shutdown ( ) raise
4,315
https://github.com/uranusjr/django-gunicorn/blob/4fb16f48048ff5fff8f889a007f376236646497b/djgunicorn/management/commands/gunserver.py#L34-L63
[ "def", "Add", "(", "self", ",", "other", ")", ":", "if", "len", "(", "self", ".", "data", ")", "!=", "len", "(", "other", ".", "data", ")", ":", "raise", "RuntimeError", "(", "\"Can only add series of identical lengths.\"", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "data", ")", ")", ":", "if", "self", ".", "data", "[", "i", "]", "[", "1", "]", "!=", "other", ".", "data", "[", "i", "]", "[", "1", "]", ":", "raise", "RuntimeError", "(", "\"Timestamp mismatch.\"", ")", "if", "self", ".", "data", "[", "i", "]", "[", "0", "]", "is", "None", "and", "other", ".", "data", "[", "i", "]", "[", "0", "]", "is", "None", ":", "continue", "self", ".", "data", "[", "i", "]", "[", "0", "]", "=", "(", "self", ".", "data", "[", "i", "]", "[", "0", "]", "or", "0", ")", "+", "(", "other", ".", "data", "[", "i", "]", "[", "0", "]", "or", "0", ")" ]
Plot results of the detect_peaks function see its help .
def _plot ( x , mph , mpd , threshold , edge , valley , ax , ind ) : try : import matplotlib . pyplot as plt except ImportError : print ( 'matplotlib is not available.' ) else : if ax is None : _ , ax = plt . subplots ( 1 , 1 , figsize = ( 8 , 4 ) ) ax . plot ( x , 'b' , lw = 1 ) if ind . size : label = 'valley' if valley else 'peak' label = label + 's' if ind . size > 1 else label ax . plot ( ind , x [ ind ] , '+' , mfc = None , mec = 'r' , mew = 2 , ms = 8 , label = '%d %s' % ( ind . size , label ) ) ax . legend ( loc = 'best' , framealpha = .5 , numpoints = 1 ) ax . set_xlim ( - .02 * x . size , x . size * 1.02 - 1 ) ymin , ymax = x [ np . isfinite ( x ) ] . min ( ) , x [ np . isfinite ( x ) ] . max ( ) yrange = ymax - ymin if ymax > ymin else 1 ax . set_ylim ( ymin - 0.1 * yrange , ymax + 0.1 * yrange ) ax . set_xlabel ( 'Data #' , fontsize = 14 ) ax . set_ylabel ( 'Amplitude' , fontsize = 14 ) mode = 'Valley detection' if valley else 'Peak detection' ax . set_title ( "%s (mph=%s, mpd=%d, threshold=%s, edge='%s')" % ( mode , str ( mph ) , mpd , str ( threshold ) , edge ) )
4,316
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/panthomkins/detect_panthomkins_peaks.py#L119-L144
[ "def", "persist", "(", "self", ",", "context", ")", ":", "D", "=", "self", ".", "_Document", "document", "=", "context", ".", "session", "[", "self", ".", "name", "]", "D", ".", "get_collection", "(", ")", ".", "replace_one", "(", "D", ".", "id", "==", "document", ".", "id", ",", "document", ",", "True", ")" ]
List of assignees to the activity .
def assignees ( self ) : if 'assignees' in self . _json_data and self . _json_data . get ( 'assignees_ids' ) == list ( ) : return [ ] elif 'assignees' in self . _json_data and self . _json_data . get ( 'assignees_ids' ) : assignees_ids_str = ',' . join ( [ str ( id ) for id in self . _json_data . get ( 'assignees_ids' ) ] ) return self . _client . users ( id__in = assignees_ids_str , is_hidden = False ) return None
4,317
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/activity2.py#L45-L52
[ "def", "get_token_data", "(", "self", ")", ":", "token_data", "=", "self", ".", "_keystone_auth", ".", "conn", ".", "auth_ref", "token", "=", "token_data", "[", "'auth_token'", "]", "self", ".", "set_token", "(", "token", ")", "if", "self", ".", "cache", ".", "is_redis_ok", "(", ")", ":", "try", ":", "self", ".", "cache", ".", "set_cache_token", "(", "token_data", ")", "except", "CacheException", ":", "self", ".", "logger", ".", "error", "(", "'Token not setted in cache.'", ")", "token_data", "=", "{", "'expires_at'", ":", "token_data", "[", "'expires_at'", "]", ",", "'token'", ":", "token", "}", "return", "token_data" ]
Determine if the Activity is at the root level of a project .
def is_rootlevel ( self ) : # when the activity itself is a root, than return False immediately if self . is_root ( ) : return False parent_name = None parent_dict = self . _json_data . get ( 'parent_id_name' ) if parent_dict and 'name' in parent_dict : parent_name = parent_dict . get ( 'name' ) if not parent_dict : parent_name = self . _client . activity ( id = self . _json_data . get ( 'parent_id' ) ) . name if parent_name in ActivityRootNames . values ( ) : return True return False
4,318
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/activity2.py#L58-L82
[ "def", "authenticate_credentials", "(", "self", ",", "token", ")", ":", "msg", "=", "_", "(", "'Invalid token.'", ")", "token", "=", "token", ".", "decode", "(", "\"utf-8\"", ")", "for", "auth_token", "in", "AuthToken", ".", "objects", ".", "filter", "(", "token_key", "=", "token", "[", ":", "CONSTANTS", ".", "TOKEN_KEY_LENGTH", "]", ")", ":", "if", "self", ".", "_cleanup_token", "(", "auth_token", ")", ":", "continue", "try", ":", "digest", "=", "hash_token", "(", "token", ",", "auth_token", ".", "salt", ")", "except", "(", "TypeError", ",", "binascii", ".", "Error", ")", ":", "raise", "exceptions", ".", "AuthenticationFailed", "(", "msg", ")", "if", "compare_digest", "(", "digest", ",", "auth_token", ".", "digest", ")", ":", "if", "knox_settings", ".", "AUTO_REFRESH", "and", "auth_token", ".", "expiry", ":", "self", ".", "renew_token", "(", "auth_token", ")", "return", "self", ".", "validate_user", "(", "auth_token", ")", "raise", "exceptions", ".", "AuthenticationFailed", "(", "msg", ")" ]
Retrieve the parent in which this activity is defined .
def parent ( self ) : parent_id = self . _json_data . get ( 'parent_id' ) if parent_id is None : raise NotFoundError ( "Cannot find subprocess for this task '{}', " "as this task exist on top level." . format ( self . name ) ) return self . _client . activity ( pk = parent_id , scope = self . scope_id )
4,319
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/activity2.py#L192-L211
[ "def", "_make_request", "(", "self", ",", "type", ",", "path", ",", "args", ",", "noRetry", "=", "False", ")", ":", "response", "=", "getattr", "(", "requests", ",", "type", ")", "(", "path", ",", "headers", "=", "self", ".", "_add_auth_headers", "(", "_JSON_HEADERS", ")", ",", "*", "*", "args", ")", "if", "response", ".", "status_code", "==", "200", "or", "response", ".", "status_code", "==", "201", ":", "return", "response", ".", "json", "(", ")", "elif", "not", "noRetry", "and", "self", ".", "_is_expired_response", "(", "response", ")", "and", "'refresh_token'", "in", "self", ".", "creds", ":", "try", ":", "self", ".", "exchange_refresh_token", "(", ")", "except", "TokenEndpointError", ":", "raise", "_rest_error_from_response", "(", "response", ")", "return", "self", ".", "_make_request", "(", "type", ",", "path", ",", "args", ",", "noRetry", "=", "True", ")", "raise", "_rest_error_from_response", "(", "response", ")" ]
Retrieve the other activities that also belong to the parent .
def siblings ( self , * * kwargs ) : parent_id = self . _json_data . get ( 'parent_id' ) if parent_id is None : raise NotFoundError ( "Cannot find subprocess for this task '{}', " "as this task exist on top level." . format ( self . name ) ) return self . _client . activities ( parent_id = parent_id , scope = self . scope_id , * * kwargs )
4,320
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/activity2.py#L241-L266
[ "def", "_generateForOAuthSecurity", "(", "self", ",", "client_id", ",", "secret_id", ",", "token_url", "=", "None", ")", ":", "grant_type", "=", "\"client_credentials\"", "if", "token_url", "is", "None", ":", "token_url", "=", "\"https://www.arcgis.com/sharing/rest/oauth2/token\"", "params", "=", "{", "\"client_id\"", ":", "client_id", ",", "\"client_secret\"", ":", "secret_id", ",", "\"grant_type\"", ":", "grant_type", ",", "\"f\"", ":", "\"json\"", "}", "token", "=", "self", ".", "_post", "(", "url", "=", "token_url", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "None", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "proxy_url", "=", "self", ".", "_proxy_url", ")", "if", "'access_token'", "in", "token", ":", "self", ".", "_token", "=", "token", "[", "'access_token'", "]", "self", ".", "_expires_in", "=", "token", "[", "'expires_in'", "]", "self", ".", "_token_created_on", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "self", ".", "_token_expires_on", "=", "self", ".", "_token_created_on", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "token", "[", "'expires_in'", "]", ")", ")", "self", ".", "_valid", "=", "True", "self", ".", "_message", "=", "\"Token Generated\"", "else", ":", "self", ".", "_token", "=", "None", "self", ".", "_expires_in", "=", "None", "self", ".", "_token_created_on", "=", "None", "self", ".", "_token_expires_on", "=", "None", "self", ".", "_valid", "=", "False", "self", ".", "_message", "=", "token" ]
Retrieve the PDF of the Activity .
def download_as_pdf ( self , target_dir = None , pdf_filename = None , paper_size = PaperSize . A4 , paper_orientation = PaperOrientation . PORTRAIT , include_appendices = False ) : if not pdf_filename : pdf_filename = self . name + '.pdf' if not pdf_filename . endswith ( '.pdf' ) : pdf_filename += '.pdf' full_path = os . path . join ( target_dir or os . getcwd ( ) , pdf_filename ) request_params = { 'papersize' : paper_size , 'orientation' : paper_orientation , 'appendices' : include_appendices } url = self . _client . _build_url ( 'activity_export' , activity_id = self . id ) response = self . _client . _request ( 'GET' , url , params = request_params ) if response . status_code != requests . codes . ok : # pragma: no cover raise APIError ( "Could not download PDF of activity {}" . format ( self . name ) ) # If appendices are included, the request becomes asynchronous if include_appendices : data = response . json ( ) # Download the pdf async url = urljoin ( self . _client . api_root , data [ 'download_url' ] ) count = 0 while count <= ASYNC_TIMEOUT_LIMIT : response = self . _client . _request ( 'GET' , url = url ) if response . status_code == requests . codes . ok : # pragma: no cover with open ( full_path , 'wb' ) as f : for chunk in response . iter_content ( 1024 ) : f . write ( chunk ) return count += ASYNC_REFRESH_INTERVAL time . sleep ( ASYNC_REFRESH_INTERVAL ) raise APIError ( "Could not download PDF of activity {} within the time-out limit of {} " "seconds" . format ( self . name , ASYNC_TIMEOUT_LIMIT ) ) with open ( full_path , 'wb' ) as f : for chunk in response . iter_content ( 1024 ) : f . write ( chunk )
4,321
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/activity2.py#L437-L509
[ "def", "user_deleted_from_site_event", "(", "event", ")", ":", "userid", "=", "event", ".", "principal", "catalog", "=", "api", ".", "portal", ".", "get_tool", "(", "'portal_catalog'", ")", "query", "=", "{", "'object_provides'", ":", "WORKSPACE_INTERFACE", "}", "query", "[", "'workspace_members'", "]", "=", "userid", "workspaces", "=", "[", "IWorkspace", "(", "b", ".", "_unrestrictedGetObject", "(", ")", ")", "for", "b", "in", "catalog", ".", "unrestrictedSearchResults", "(", "query", ")", "]", "for", "workspace", "in", "workspaces", ":", "workspace", ".", "remove_from_team", "(", "userid", ")" ]
Parse cli args .
def parse ( argv ) : args = docopt ( __doc__ , argv = argv ) try : call ( sys . argv [ 2 ] , args ) except KytosException as exception : print ( "Error parsing args: {}" . format ( exception ) ) exit ( )
4,322
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/users/parser.py#L26-L33
[ "def", "_remove_vm", "(", "name", ",", "datacenter", ",", "service_instance", ",", "placement", "=", "None", ",", "power_off", "=", "None", ")", ":", "results", "=", "{", "}", "if", "placement", ":", "(", "resourcepool_object", ",", "placement_object", ")", "=", "salt", ".", "utils", ".", "vmware", ".", "get_placement", "(", "service_instance", ",", "datacenter", ",", "placement", ")", "else", ":", "placement_object", "=", "salt", ".", "utils", ".", "vmware", ".", "get_datacenter", "(", "service_instance", ",", "datacenter", ")", "if", "power_off", ":", "power_off_vm", "(", "name", ",", "datacenter", ",", "service_instance", ")", "results", "[", "'powered_off'", "]", "=", "True", "vm_ref", "=", "salt", ".", "utils", ".", "vmware", ".", "get_mor_by_property", "(", "service_instance", ",", "vim", ".", "VirtualMachine", ",", "name", ",", "property_name", "=", "'name'", ",", "container_ref", "=", "placement_object", ")", "if", "not", "vm_ref", ":", "raise", "salt", ".", "exceptions", ".", "VMwareObjectRetrievalError", "(", "'The virtual machine object {0} in datacenter '", "'{1} was not found'", ".", "format", "(", "name", ",", "datacenter", ")", ")", "return", "results", ",", "vm_ref" ]
Clean build dist pyc and egg from package and docs .
def run ( self ) : super ( ) . run ( ) call ( 'rm -vrf ./build ./dist ./*.egg-info' , shell = True ) call ( 'find . -name __pycache__ -type d | xargs rm -rf' , shell = True ) call ( 'test -d docs && make -C docs/ clean' , shell = True )
4,323
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/setup.py#L71-L76
[ "def", "_ensure_file_path", "(", "self", ")", ":", "storage_root", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "file_path", ")", "needs_storage_root", "=", "storage_root", "and", "not", "os", ".", "path", ".", "isdir", "(", "storage_root", ")", "if", "needs_storage_root", ":", "# pragma: no cover", "os", ".", "makedirs", "(", "storage_root", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "file_path", ")", ":", "# create the file without group/world permissions", "with", "open", "(", "self", ".", "file_path", ",", "'w'", ")", ":", "pass", "user_read_write", "=", "0o600", "os", ".", "chmod", "(", "self", ".", "file_path", ",", "user_read_write", ")" ]
Run yala .
def run ( self ) : print ( 'Yala is running. It may take several seconds...' ) try : check_call ( 'yala setup.py tests kytos' , shell = True ) print ( 'No linter error found.' ) except CalledProcessError : print ( 'Linter check failed. Fix the error(s) above and try again.' ) sys . exit ( - 1 )
4,324
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/setup.py#L106-L114
[ "def", "_get_device_template", "(", "disk", ",", "disk_info", ",", "template", "=", "None", ")", ":", "def", "_require_disk_opts", "(", "*", "args", ")", ":", "for", "arg", "in", "args", ":", "if", "arg", "not", "in", "disk_info", ":", "raise", "SaltCloudSystemExit", "(", "'The disk {0} requires a {1}\\\n argument'", ".", "format", "(", "disk", ",", "arg", ")", ")", "_require_disk_opts", "(", "'disk_type'", ",", "'size'", ")", "size", "=", "disk_info", "[", "'size'", "]", "disk_type", "=", "disk_info", "[", "'disk_type'", "]", "if", "disk_type", "==", "'clone'", ":", "if", "'image'", "in", "disk_info", ":", "clone_image", "=", "disk_info", "[", "'image'", "]", "else", ":", "clone_image", "=", "get_template_image", "(", "kwargs", "=", "{", "'name'", ":", "template", "}", ")", "clone_image_id", "=", "get_image_id", "(", "kwargs", "=", "{", "'name'", ":", "clone_image", "}", ")", "temp", "=", "'DISK=[IMAGE={0}, IMAGE_ID={1}, CLONE=YES,\\\n SIZE={2}]'", ".", "format", "(", "clone_image", ",", "clone_image_id", ",", "size", ")", "return", "temp", "if", "disk_type", "==", "'volatile'", ":", "_require_disk_opts", "(", "'type'", ")", "v_type", "=", "disk_info", "[", "'type'", "]", "temp", "=", "'DISK=[TYPE={0}, SIZE={1}]'", ".", "format", "(", "v_type", ",", "size", ")", "if", "v_type", "==", "'fs'", ":", "_require_disk_opts", "(", "'format'", ")", "format", "=", "disk_info", "[", "'format'", "]", "temp", "=", "'DISK=[TYPE={0}, SIZE={1}, FORMAT={2}]'", ".", "format", "(", "v_type", ",", "size", ",", "format", ")", "return", "temp" ]
Allow the add - on to be installed .
def allow ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : self . find_primary_button ( ) . click ( )
4,325
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/addons.py#L14-L17
[ "def", "from_memory", "(", "cls", ",", "data", ",", "meta", ")", ":", "obj", "=", "cls", "(", ")", "obj", ".", "data", "=", "data", "obj", ".", "meta", "=", "meta", "return", "obj" ]
Provide access to the add - on name .
def addon_name ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : el = self . find_description ( ) return el . find_element ( By . CSS_SELECTOR , "b" ) . text
4,326
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/addons.py#L24-L33
[ "def", "poll", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "-", "1", "message", "=", "super", "(", "AvroConsumer", ",", "self", ")", ".", "poll", "(", "timeout", ")", "if", "message", "is", "None", ":", "return", "None", "if", "not", "message", ".", "error", "(", ")", ":", "try", ":", "if", "message", ".", "value", "(", ")", "is", "not", "None", ":", "decoded_value", "=", "self", ".", "_serializer", ".", "decode_message", "(", "message", ".", "value", "(", ")", ",", "is_key", "=", "False", ")", "message", ".", "set_value", "(", "decoded_value", ")", "if", "message", ".", "key", "(", ")", "is", "not", "None", ":", "decoded_key", "=", "self", ".", "_serializer", ".", "decode_message", "(", "message", ".", "key", "(", ")", ",", "is_key", "=", "True", ")", "message", ".", "set_key", "(", "decoded_key", ")", "except", "SerializerError", "as", "e", ":", "raise", "SerializerError", "(", "\"Message deserialization failed for message at {} [{}] offset {}: {}\"", ".", "format", "(", "message", ".", "topic", "(", ")", ",", "message", ".", "partition", "(", ")", ",", "message", ".", "offset", "(", ")", ",", "e", ")", ")", "return", "message" ]
Cancel add - on install .
def cancel ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : self . find_secondary_button ( ) . click ( )
4,327
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/addons.py#L35-L38
[ "def", "record", "(", "self", ")", ":", "while", "True", ":", "frames", "=", "[", "]", "self", ".", "stream", ".", "start_stream", "(", ")", "for", "i", "in", "range", "(", "self", ".", "num_frames", ")", ":", "data", "=", "self", ".", "stream", ".", "read", "(", "self", ".", "config", ".", "FRAMES_PER_BUFFER", ")", "frames", ".", "append", "(", "data", ")", "self", ".", "output", ".", "seek", "(", "0", ")", "w", "=", "wave", ".", "open", "(", "self", ".", "output", ",", "'wb'", ")", "w", ".", "setnchannels", "(", "self", ".", "config", ".", "CHANNELS", ")", "w", ".", "setsampwidth", "(", "self", ".", "audio", ".", "get_sample_size", "(", "self", ".", "config", ".", "FORMAT", ")", ")", "w", ".", "setframerate", "(", "self", ".", "config", ".", "RATE", ")", "w", ".", "writeframes", "(", "b''", ".", "join", "(", "frames", ")", ")", "w", ".", "close", "(", ")", "yield" ]
Confirm add - on install .
def install ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : self . find_primary_button ( ) . click ( )
4,328
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/notifications/addons.py#L40-L43
[ "def", "record", "(", "self", ")", ":", "while", "True", ":", "frames", "=", "[", "]", "self", ".", "stream", ".", "start_stream", "(", ")", "for", "i", "in", "range", "(", "self", ".", "num_frames", ")", ":", "data", "=", "self", ".", "stream", ".", "read", "(", "self", ".", "config", ".", "FRAMES_PER_BUFFER", ")", "frames", ".", "append", "(", "data", ")", "self", ".", "output", ".", "seek", "(", "0", ")", "w", "=", "wave", ".", "open", "(", "self", ".", "output", ",", "'wb'", ")", "w", ".", "setnchannels", "(", "self", ".", "config", ".", "CHANNELS", ")", "w", ".", "setsampwidth", "(", "self", ".", "audio", ".", "get_sample_size", "(", "self", ".", "config", ".", "FORMAT", ")", ")", "w", ".", "setframerate", "(", "self", ".", "config", ".", "RATE", ")", "w", ".", "writeframes", "(", "b''", ".", "join", "(", "frames", ")", ")", "w", ".", "close", "(", ")", "yield" ]
Function used for reading . txt files generated by OpenSignals .
def _load_txt ( file , devices , channels , header , * * kwargs ) : # %%%%%%%%%%%%%%%%%%%%%%%%%%% Exclusion of invalid keywords %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% kwargs_txt = _filter_keywords ( numpy . loadtxt , kwargs ) # %%%%%%%%%%%%%%%%%%%%%%%%%% Columns of the selected channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% out_dict = { } for dev_nbr , device in enumerate ( devices ) : out_dict [ device ] = { } columns = [ ] for chn in channels [ dev_nbr ] : columns . append ( header [ device ] [ "column labels" ] [ chn ] ) # header[device]["column labels"] contains the column of .txt file where the data of # channel "chn" is located. out_dict [ device ] [ "CH" + str ( chn ) ] = numpy . loadtxt ( fname = file , usecols = header [ device ] [ "column labels" ] [ chn ] , * * kwargs_txt ) return out_dict
4,329
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/load.py#L487-L533
[ "def", "delete_network_acl", "(", "network_acl_id", "=", "None", ",", "network_acl_name", "=", "None", ",", "disassociate", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "disassociate", ":", "network_acl", "=", "_get_resource", "(", "'network_acl'", ",", "name", "=", "network_acl_name", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "if", "network_acl", "and", "network_acl", ".", "associations", ":", "subnet_id", "=", "network_acl", ".", "associations", "[", "0", "]", ".", "subnet_id", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "conn", ".", "disassociate_network_acl", "(", "subnet_id", ")", "except", "BotoServerError", ":", "pass", "return", "_delete_resource", "(", "resource", "=", "'network_acl'", ",", "name", "=", "network_acl_name", ",", "resource_id", "=", "network_acl_id", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")" ]
Function used for reading . h5 files generated by OpenSignals .
def _load_h5 ( file , devices , channels ) : # %%%%%%%%%%%%%%%%%%%%%%%%%%%% Creation of h5py object %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% h5_object = h5py . File ( file ) # %%%%%%%%%%%%%%%%%%%%%%%%% Data of the selected channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% out_dict = { } for dev_nbr , device in enumerate ( devices ) : out_dict [ device ] = { } for chn in channels [ dev_nbr ] : data_temp = list ( h5_object . get ( device ) . get ( "raw" ) . get ( "channel_" + str ( chn ) ) ) # Conversion of a nested list to a flatten list by list-comprehension # The following line is equivalent to: # for sublist in h5_data: # for item in sublist: # flat_list.append(item) #out_dict[device]["CH" + str(chn)] = [item for sublist in data_temp for item in sublist] out_dict [ device ] [ "CH" + str ( chn ) ] = numpy . concatenate ( data_temp ) return out_dict
4,330
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/load.py#L536-L577
[ "def", "__add_delayed_assert_failure", "(", "self", ")", ":", "current_url", "=", "self", ".", "driver", ".", "current_url", "message", "=", "self", ".", "__get_exception_message", "(", ")", "self", ".", "__delayed_assert_failures", ".", "append", "(", "\"CHECK #%s: (%s)\\n %s\"", "%", "(", "self", ".", "__delayed_assert_count", ",", "current_url", ",", "message", ")", ")" ]
Function used for checking weather the elements in channels input are coincident with the available channels .
def _check_chn_type ( channels , available_channels ) : # ------------------------ Definition of constants and variables ------------------------------- chn_list_standardized = [ ] # %%%%%%%%%%%%%%%%%%%%%%%%%%% Fill of "chn_list_standardized" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% devices = list ( available_channels . keys ( ) ) for dev_nbr , device in enumerate ( devices ) : if channels is not None : sub_unit = channels [ dev_nbr ] for channel in sub_unit : # Each sublist must be composed by integers. if channel in available_channels [ devices [ dev_nbr ] ] : continue else : raise RuntimeError ( "At least one of the specified channels is not available in " "the acquisition file." ) chn_list_standardized . append ( sub_unit ) else : # By omission all the channels were selected. chn_list_standardized . append ( available_channels [ device ] ) return chn_list_standardized
4,331
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/load.py#L642-L683
[ "def", "save", "(", "self", ",", "filename", ")", ":", "self", ".", "doc", ".", "save", "(", "os", ".", "path", ".", "expanduser", "(", "filename", ")", ")" ]
Function used for the determination of the available channels in each device .
def _available_channels ( devices , header ) : # ------------------------ Definition of constants and variables ------------------------------ chn_dict = { } # %%%%%%%%%%%%%%%%%%%%%% Access to the relevant data in the header %%%%%%%%%%%%%%%%%%%%%%%%%%%% for dev in devices : chn_dict [ dev ] = header [ dev ] [ "column labels" ] . keys ( ) return chn_dict
4,332
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/load.py#L686-L714
[ "def", "saveSession", "(", "self", ",", "filepath", ")", ":", "try", ":", "session_module", ".", "Save", "(", "self", ".", "session", ",", "filepath", ")", "except", "RuntimeError", "as", "e", ":", "log", ".", "exception", "(", "e", ")", "os", ".", "remove", "(", "filepath", ")", "log", ".", "warning", "(", "\"Session not saved\"", ")" ]
Function used for checking weather the devices field only contain devices used during the acquisition .
def _check_dev_type ( devices , dev_list ) : if devices is not None : for device in devices : if device in dev_list : # List element is one of the available devices. continue else : raise RuntimeError ( "At least one of the specified devices is not available in the " "acquisition file." ) out = devices else : out = dev_list return out
4,333
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/load.py#L717-L750
[ "def", "_make_association", "(", "self", ",", "subject_id", ",", "object_id", ",", "rel_id", ",", "pubmed_ids", ")", ":", "# TODO pass in the relevant Assoc class rather than relying on G2P", "assoc", "=", "G2PAssoc", "(", "self", ".", "graph", ",", "self", ".", "name", ",", "subject_id", ",", "object_id", ",", "rel_id", ")", "if", "pubmed_ids", "is", "not", "None", "and", "len", "(", "pubmed_ids", ")", ">", "0", ":", "for", "pmid", "in", "pubmed_ids", ":", "ref", "=", "Reference", "(", "self", ".", "graph", ",", "pmid", ",", "self", ".", "globaltt", "[", "'journal article'", "]", ")", "ref", ".", "addRefToGraph", "(", ")", "assoc", ".", "add_source", "(", "pmid", ")", "assoc", ".", "add_evidence", "(", "self", ".", "globaltt", "[", "'traceable author statement'", "]", ")", "assoc", ".", "add_association_to_graph", "(", ")", "return" ]
Function intended for identification of the file type .
def _file_type ( file ) : # %%%%%%%%%%%%%%%%%%%%%%%%%%%%% Verification of file type %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if "." in file : # File with known extension. file_type = file . split ( "." ) [ - 1 ] else : # File without known extension. file_type = magic . from_file ( file , mime = True ) . split ( "/" ) [ - 1 ] return file_type
4,334
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/load.py#L753-L775
[ "def", "make_noise_surface", "(", "dims", "=", "DEFAULT_DIMS", ",", "blur", "=", "10", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "not", "None", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "return", "gaussian_filter", "(", "np", ".", "random", ".", "normal", "(", "size", "=", "dims", ")", ",", "blur", ")" ]
Team to which the scope is assigned .
def team ( self ) : team_dict = self . _json_data . get ( 'team' ) if team_dict and team_dict . get ( 'id' ) : return self . _client . team ( id = team_dict . get ( 'id' ) ) else : return None
4,335
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L56-L62
[ "def", "get_or_generate_vocabulary", "(", "data_dir", ",", "tmp_dir", ",", "data_prefix", ",", "max_page_size_exp", ",", "approx_vocab_size", "=", "32768", ",", "strip", "=", "True", ")", ":", "num_pages_for_vocab_generation", "=", "approx_vocab_size", "//", "3", "vocab_file", "=", "vocab_filename", "(", "approx_vocab_size", ",", "strip", ")", "def", "my_generator", "(", "data_prefix", ")", ":", "\"\"\"Line generator for vocab.\"\"\"", "count", "=", "0", "for", "page", "in", "corpus_page_generator", "(", "all_corpus_files", "(", "data_prefix", ")", "[", ":", ":", "-", "1", "]", ",", "tmp_dir", ",", "max_page_size_exp", ")", ":", "revisions", "=", "page", "[", "\"revisions\"", "]", "if", "revisions", ":", "text", "=", "get_text", "(", "revisions", "[", "-", "1", "]", ",", "strip", "=", "strip", ")", "yield", "text", "count", "+=", "1", "if", "count", "%", "100", "==", "0", ":", "tf", ".", "logging", ".", "info", "(", "\"reading pages for vocab %d\"", "%", "count", ")", "if", "count", ">", "num_pages_for_vocab_generation", ":", "break", "return", "generator_utils", ".", "get_or_generate_vocab_inner", "(", "data_dir", ",", "vocab_file", ",", "approx_vocab_size", ",", "my_generator", "(", "data_prefix", ")", ")" ]
Retrieve parts belonging to this scope .
def parts ( self , * args , * * kwargs ) : return self . _client . parts ( * args , bucket = self . bucket . get ( 'id' ) , * * kwargs )
4,336
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L76-L81
[ "def", "_retrieve_offsets", "(", "self", ",", "timestamps", ",", "timeout_ms", "=", "float", "(", "\"inf\"", ")", ")", ":", "if", "not", "timestamps", ":", "return", "{", "}", "start_time", "=", "time", ".", "time", "(", ")", "remaining_ms", "=", "timeout_ms", "while", "remaining_ms", ">", "0", ":", "future", "=", "self", ".", "_send_offset_requests", "(", "timestamps", ")", "self", ".", "_client", ".", "poll", "(", "future", "=", "future", ",", "timeout_ms", "=", "remaining_ms", ")", "if", "future", ".", "succeeded", "(", ")", ":", "return", "future", ".", "value", "if", "not", "future", ".", "retriable", "(", ")", ":", "raise", "future", ".", "exception", "# pylint: disable-msg=raising-bad-type", "elapsed_ms", "=", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", "*", "1000", "remaining_ms", "=", "timeout_ms", "-", "elapsed_ms", "if", "remaining_ms", "<", "0", ":", "break", "if", "future", ".", "exception", ".", "invalid_metadata", ":", "refresh_future", "=", "self", ".", "_client", ".", "cluster", ".", "request_update", "(", ")", "self", ".", "_client", ".", "poll", "(", "future", "=", "refresh_future", ",", "timeout_ms", "=", "remaining_ms", ")", "else", ":", "time", ".", "sleep", "(", "self", ".", "config", "[", "'retry_backoff_ms'", "]", "/", "1000.0", ")", "elapsed_ms", "=", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", "*", "1000", "remaining_ms", "=", "timeout_ms", "-", "elapsed_ms", "raise", "Errors", ".", "KafkaTimeoutError", "(", "\"Failed to get offsets by timestamps in %s ms\"", "%", "(", "timeout_ms", ",", ")", ")" ]
Retrieve a single part belonging to this scope .
def part ( self , * args , * * kwargs ) : return self . _client . part ( * args , bucket = self . bucket . get ( 'id' ) , * * kwargs )
4,337
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L83-L88
[ "def", "_load_latex2unicode_constants", "(", "kb_file", "=", "None", ")", ":", "if", "kb_file", "is", "None", ":", "kb_file", "=", "get_kb_filename", "(", ")", "try", ":", "data", "=", "open", "(", "kb_file", ")", "except", "IOError", ":", "# File not found or similar", "sys", ".", "stderr", ".", "write", "(", "\"\\nCould not open LaTeX to Unicode KB file. \"", "\"Aborting translation.\\n\"", ")", "return", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "latex_symbols", "=", "[", "]", "translation_table", "=", "{", "}", "for", "line", "in", "data", ":", "# The file has form of latex|--|utf-8. First decode to Unicode.", "line", "=", "line", ".", "decode", "(", "'utf-8'", ")", "mapping", "=", "line", ".", "split", "(", "'|--|'", ")", "translation_table", "[", "mapping", "[", "0", "]", ".", "rstrip", "(", "'\\n'", ")", "]", "=", "mapping", "[", "1", "]", ".", "rstrip", "(", "'\\n'", ")", "latex_symbols", ".", "append", "(", "re", ".", "escape", "(", "mapping", "[", "0", "]", ".", "rstrip", "(", "'\\n'", ")", ")", ")", "data", ".", "close", "(", ")", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "[", "'regexp_obj'", "]", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "latex_symbols", ")", ")", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "[", "'table'", "]", "=", "translation_table" ]
Create a single part model in this scope .
def create_model ( self , parent , name , multiplicity = Multiplicity . ZERO_MANY ) : return self . _client . create_model ( parent , name , multiplicity = multiplicity )
4,338
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L90-L95
[ "def", "_load_latex2unicode_constants", "(", "kb_file", "=", "None", ")", ":", "if", "kb_file", "is", "None", ":", "kb_file", "=", "get_kb_filename", "(", ")", "try", ":", "data", "=", "open", "(", "kb_file", ")", "except", "IOError", ":", "# File not found or similar", "sys", ".", "stderr", ".", "write", "(", "\"\\nCould not open LaTeX to Unicode KB file. \"", "\"Aborting translation.\\n\"", ")", "return", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "latex_symbols", "=", "[", "]", "translation_table", "=", "{", "}", "for", "line", "in", "data", ":", "# The file has form of latex|--|utf-8. First decode to Unicode.", "line", "=", "line", ".", "decode", "(", "'utf-8'", ")", "mapping", "=", "line", ".", "split", "(", "'|--|'", ")", "translation_table", "[", "mapping", "[", "0", "]", ".", "rstrip", "(", "'\\n'", ")", "]", "=", "mapping", "[", "1", "]", ".", "rstrip", "(", "'\\n'", ")", "latex_symbols", ".", "append", "(", "re", ".", "escape", "(", "mapping", "[", "0", "]", ".", "rstrip", "(", "'\\n'", ")", ")", ")", "data", ".", "close", "(", ")", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "[", "'regexp_obj'", "]", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "latex_symbols", ")", ")", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "[", "'table'", "]", "=", "translation_table" ]
Retrieve a single model belonging to this scope .
def model ( self , * args , * * kwargs ) : return self . _client . model ( * args , bucket = self . bucket . get ( 'id' ) , * * kwargs )
4,339
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L97-L102
[ "def", "read", "(", "self", ")", ":", "line", "=", "self", ".", "trace_file", ".", "readline", "(", ")", "if", "line", "==", "''", ":", "if", "self", ".", "loop", ":", "self", ".", "_reopen_file", "(", ")", "else", ":", "self", ".", "trace_file", ".", "close", "(", ")", "self", ".", "trace_file", "=", "None", "raise", "DataSourceError", "(", ")", "message", "=", "JsonFormatter", ".", "deserialize", "(", "line", ")", "timestamp", "=", "message", ".", "get", "(", "'timestamp'", ",", "None", ")", "if", "self", ".", "realtime", "and", "timestamp", "is", "not", "None", ":", "self", ".", "_store_timestamp", "(", "timestamp", ")", "self", ".", "_wait", "(", "self", ".", "starting_time", ",", "self", ".", "first_timestamp", ",", "timestamp", ")", "return", "line", "+", "\"\\x00\"" ]
Retrieve activities belonging to this scope .
def activities ( self , * args , * * kwargs ) : if self . _client . match_app_version ( label = 'wim' , version = '<2.0.0' , default = True ) : return self . _client . activities ( * args , scope = self . id , * * kwargs ) else : return self . _client . activities ( * args , scope_id = self . id , * * kwargs )
4,340
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L104-L112
[ "def", "_retrieve_offsets", "(", "self", ",", "timestamps", ",", "timeout_ms", "=", "float", "(", "\"inf\"", ")", ")", ":", "if", "not", "timestamps", ":", "return", "{", "}", "start_time", "=", "time", ".", "time", "(", ")", "remaining_ms", "=", "timeout_ms", "while", "remaining_ms", ">", "0", ":", "future", "=", "self", ".", "_send_offset_requests", "(", "timestamps", ")", "self", ".", "_client", ".", "poll", "(", "future", "=", "future", ",", "timeout_ms", "=", "remaining_ms", ")", "if", "future", ".", "succeeded", "(", ")", ":", "return", "future", ".", "value", "if", "not", "future", ".", "retriable", "(", ")", ":", "raise", "future", ".", "exception", "# pylint: disable-msg=raising-bad-type", "elapsed_ms", "=", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", "*", "1000", "remaining_ms", "=", "timeout_ms", "-", "elapsed_ms", "if", "remaining_ms", "<", "0", ":", "break", "if", "future", ".", "exception", ".", "invalid_metadata", ":", "refresh_future", "=", "self", ".", "_client", ".", "cluster", ".", "request_update", "(", ")", "self", ".", "_client", ".", "poll", "(", "future", "=", "refresh_future", ",", "timeout_ms", "=", "remaining_ms", ")", "else", ":", "time", ".", "sleep", "(", "self", ".", "config", "[", "'retry_backoff_ms'", "]", "/", "1000.0", ")", "elapsed_ms", "=", "(", "time", ".", "time", "(", ")", "-", "start_time", ")", "*", "1000", "remaining_ms", "=", "timeout_ms", "-", "elapsed_ms", "raise", "Errors", ".", "KafkaTimeoutError", "(", "\"Failed to get offsets by timestamps in %s ms\"", "%", "(", "timeout_ms", ",", ")", ")" ]
Create a new activity belonging to this scope .
def create_activity ( self , * args , * * kwargs ) : if self . _client . match_app_version ( label = 'wim' , version = '<2.0.0' , default = True ) : return self . _client . create_activity ( self . process , * args , * * kwargs ) else : return self . _client . create_activity ( self . workflow_root , * args , * * kwargs )
4,341
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L124-L132
[ "def", "_fetch_secrets", "(", "vault_url", ",", "path", ",", "token", ")", ":", "url", "=", "_url_joiner", "(", "vault_url", ",", "'v1'", ",", "path", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "VaultLoader", ".", "_get_headers", "(", "token", ")", ")", "resp", ".", "raise_for_status", "(", ")", "data", "=", "resp", ".", "json", "(", ")", "if", "data", ".", "get", "(", "'errors'", ")", ":", "raise", "VaultException", "(", "u'Error fetching Vault secrets from path {}: {}'", ".", "format", "(", "path", ",", "data", "[", "'errors'", "]", ")", ")", "return", "data", "[", "'data'", "]" ]
Create a service to current scope .
def create_service ( self , * args , * * kwargs ) : return self . _client . create_service ( * args , scope = self . id , * * kwargs )
4,342
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L143-L150
[ "def", "update", "(", "self", ",", "data", ")", ":", "self", ".", "_md", ".", "update", "(", "data", ")", "bufpos", "=", "self", ".", "_nbytes", "&", "63", "self", ".", "_nbytes", "+=", "len", "(", "data", ")", "if", "self", ".", "_rarbug", "and", "len", "(", "data", ")", ">", "64", ":", "dpos", "=", "self", ".", "block_size", "-", "bufpos", "while", "dpos", "+", "self", ".", "block_size", "<=", "len", "(", "data", ")", ":", "self", ".", "_corrupt", "(", "data", ",", "dpos", ")", "dpos", "+=", "self", ".", "block_size" ]
Retrieve a single service belonging to this scope .
def service ( self , * args , * * kwargs ) : return self . _client . service ( * args , scope = self . id , * * kwargs )
4,343
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L152-L159
[ "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\"", ")" ]
Retrieve a single service execution belonging to this scope .
def service_execution ( self , * args , * * kwargs ) : return self . _client . service_execution ( * args , scope = self . id , * * kwargs )
4,344
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L170-L177
[ "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\"", ")" ]
Retrieve members of the scope .
def members ( self , is_manager = None ) : if not is_manager : return [ member for member in self . _json_data [ 'members' ] if member [ 'is_active' ] ] else : return [ member for member in self . _json_data [ 'members' ] if member . get ( 'is_active' , False ) and member . get ( 'is_manager' , False ) ]
4,345
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L179-L197
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Add a single member to the scope .
def add_member ( self , member ) : select_action = 'add_member' self . _update_scope_project_team ( select_action = select_action , user = member , user_type = 'member' )
4,346
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L199-L211
[ "def", "_load_latex2unicode_constants", "(", "kb_file", "=", "None", ")", ":", "if", "kb_file", "is", "None", ":", "kb_file", "=", "get_kb_filename", "(", ")", "try", ":", "data", "=", "open", "(", "kb_file", ")", "except", "IOError", ":", "# File not found or similar", "sys", ".", "stderr", ".", "write", "(", "\"\\nCould not open LaTeX to Unicode KB file. \"", "\"Aborting translation.\\n\"", ")", "return", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "latex_symbols", "=", "[", "]", "translation_table", "=", "{", "}", "for", "line", "in", "data", ":", "# The file has form of latex|--|utf-8. First decode to Unicode.", "line", "=", "line", ".", "decode", "(", "'utf-8'", ")", "mapping", "=", "line", ".", "split", "(", "'|--|'", ")", "translation_table", "[", "mapping", "[", "0", "]", ".", "rstrip", "(", "'\\n'", ")", "]", "=", "mapping", "[", "1", "]", ".", "rstrip", "(", "'\\n'", ")", "latex_symbols", ".", "append", "(", "re", ".", "escape", "(", "mapping", "[", "0", "]", ".", "rstrip", "(", "'\\n'", ")", ")", ")", "data", ".", "close", "(", ")", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "[", "'regexp_obj'", "]", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "latex_symbols", ")", ")", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "[", "'table'", "]", "=", "translation_table" ]
Remove a single member to the scope .
def remove_member ( self , member ) : select_action = 'remove_member' self . _update_scope_project_team ( select_action = select_action , user = member , user_type = 'member' )
4,347
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L213-L223
[ "def", "_load_latex2unicode_constants", "(", "kb_file", "=", "None", ")", ":", "if", "kb_file", "is", "None", ":", "kb_file", "=", "get_kb_filename", "(", ")", "try", ":", "data", "=", "open", "(", "kb_file", ")", "except", "IOError", ":", "# File not found or similar", "sys", ".", "stderr", ".", "write", "(", "\"\\nCould not open LaTeX to Unicode KB file. \"", "\"Aborting translation.\\n\"", ")", "return", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "latex_symbols", "=", "[", "]", "translation_table", "=", "{", "}", "for", "line", "in", "data", ":", "# The file has form of latex|--|utf-8. First decode to Unicode.", "line", "=", "line", ".", "decode", "(", "'utf-8'", ")", "mapping", "=", "line", ".", "split", "(", "'|--|'", ")", "translation_table", "[", "mapping", "[", "0", "]", ".", "rstrip", "(", "'\\n'", ")", "]", "=", "mapping", "[", "1", "]", ".", "rstrip", "(", "'\\n'", ")", "latex_symbols", ".", "append", "(", "re", ".", "escape", "(", "mapping", "[", "0", "]", ".", "rstrip", "(", "'\\n'", ")", ")", ")", "data", ".", "close", "(", ")", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "[", "'regexp_obj'", "]", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "latex_symbols", ")", ")", "CFG_LATEX_UNICODE_TRANSLATION_CONST", "[", "'table'", "]", "=", "translation_table" ]
Add a single manager to the scope .
def add_manager ( self , manager ) : select_action = 'add_manager' self . _update_scope_project_team ( select_action = select_action , user = manager , user_type = 'manager' )
4,348
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L225-L235
[ "def", "_generate_examples_validation", "(", "self", ",", "archive", ",", "labels", ")", ":", "# Get the current random seeds.", "numpy_st0", "=", "np", ".", "random", ".", "get_state", "(", ")", "# Set new random seeds.", "np", ".", "random", ".", "seed", "(", "135", ")", "logging", ".", "warning", "(", "'Overwriting cv2 RNG seed.'", ")", "tfds", ".", "core", ".", "lazy_imports", ".", "cv2", ".", "setRNGSeed", "(", "357", ")", "for", "example", "in", "super", "(", "Imagenet2012Corrupted", ",", "self", ")", ".", "_generate_examples_validation", "(", "archive", ",", "labels", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "tf_img", "=", "tf", ".", "image", ".", "decode_jpeg", "(", "example", "[", "'image'", "]", ".", "read", "(", ")", ",", "channels", "=", "3", ")", "image_np", "=", "tfds", ".", "as_numpy", "(", "tf_img", ")", "example", "[", "'image'", "]", "=", "self", ".", "_get_corrupted_example", "(", "image_np", ")", "yield", "example", "# Reset the seeds back to their original values.", "np", ".", "random", ".", "set_state", "(", "numpy_st0", ")" ]
Remove a single manager to the scope .
def remove_manager ( self , manager ) : select_action = 'remove_manager' self . _update_scope_project_team ( select_action = select_action , user = manager , user_type = 'manager' )
4,349
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L237-L247
[ "def", "_generate_examples_validation", "(", "self", ",", "archive", ",", "labels", ")", ":", "# Get the current random seeds.", "numpy_st0", "=", "np", ".", "random", ".", "get_state", "(", ")", "# Set new random seeds.", "np", ".", "random", ".", "seed", "(", "135", ")", "logging", ".", "warning", "(", "'Overwriting cv2 RNG seed.'", ")", "tfds", ".", "core", ".", "lazy_imports", ".", "cv2", ".", "setRNGSeed", "(", "357", ")", "for", "example", "in", "super", "(", "Imagenet2012Corrupted", ",", "self", ")", ".", "_generate_examples_validation", "(", "archive", ",", "labels", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "tf_img", "=", "tf", ".", "image", ".", "decode_jpeg", "(", "example", "[", "'image'", "]", ".", "read", "(", ")", ",", "channels", "=", "3", ")", "image_np", "=", "tfds", ".", "as_numpy", "(", "tf_img", ")", "example", "[", "'image'", "]", "=", "self", ".", "_get_corrupted_example", "(", "image_np", ")", "yield", "example", "# Reset the seeds back to their original values.", "np", ".", "random", ".", "set_state", "(", "numpy_st0", ")" ]
Update the Project Team of the Scope . Updates include addition or removing of managers or members .
def _update_scope_project_team ( self , select_action , user , user_type ) : if isinstance ( user , str ) : users = self . _client . _retrieve_users ( ) manager_object = next ( ( item for item in users [ 'results' ] if item [ "username" ] == user ) , None ) if manager_object : url = self . _client . _build_url ( 'scope' , scope_id = self . id ) r = self . _client . _request ( 'PUT' , url , params = { 'select_action' : select_action } , data = { 'user_id' : manager_object [ 'pk' ] } ) if r . status_code != requests . codes . ok : # pragma: no cover raise APIError ( "Could not {} {} in Scope" . format ( select_action . split ( '_' ) [ 0 ] , user_type ) ) else : raise NotFoundError ( "User {} does not exist" . format ( user ) ) else : raise TypeError ( "User {} should be defined as a string" . format ( user ) )
4,350
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L249-L275
[ "def", "waitForOSState", "(", "rh", ",", "userid", ",", "desiredState", ",", "maxQueries", "=", "90", ",", "sleepSecs", "=", "5", ")", ":", "rh", ".", "printSysLog", "(", "\"Enter vmUtils.waitForOSState, userid: \"", "+", "userid", "+", "\" state: \"", "+", "desiredState", "+", "\" maxWait: \"", "+", "str", "(", "maxQueries", ")", "+", "\" sleepSecs: \"", "+", "str", "(", "sleepSecs", ")", ")", "results", "=", "{", "}", "strCmd", "=", "\"echo 'ping'\"", "stateFnd", "=", "False", "for", "i", "in", "range", "(", "1", ",", "maxQueries", "+", "1", ")", ":", "results", "=", "execCmdThruIUCV", "(", "rh", ",", "rh", ".", "userid", ",", "strCmd", ")", "if", "results", "[", "'overallRC'", "]", "==", "0", ":", "if", "desiredState", "==", "'up'", ":", "stateFnd", "=", "True", "break", "else", ":", "if", "desiredState", "==", "'down'", ":", "stateFnd", "=", "True", "break", "if", "i", "<", "maxQueries", ":", "time", ".", "sleep", "(", "sleepSecs", ")", "if", "stateFnd", "is", "True", ":", "results", "=", "{", "'overallRC'", ":", "0", ",", "'rc'", ":", "0", ",", "'rs'", ":", "0", ",", "}", "else", ":", "maxWait", "=", "maxQueries", "*", "sleepSecs", "rh", ".", "printLn", "(", "\"ES\"", ",", "msgs", ".", "msg", "[", "'0413'", "]", "[", "1", "]", "%", "(", "modId", ",", "userid", ",", "desiredState", ",", "maxWait", ")", ")", "results", "=", "msgs", ".", "msg", "[", "'0413'", "]", "[", "0", "]", "rh", ".", "printSysLog", "(", "\"Exit vmUtils.waitForOSState, rc: \"", "+", "str", "(", "results", "[", "'overallRC'", "]", ")", ")", "return", "results" ]
Clone current scope .
def clone ( self , * args , * * kwargs ) : return self . _client . clone_scope ( * args , source_scope = self , * * kwargs )
4,351
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L413-L421
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Friendly name for the stop place or platform
def name ( self ) -> str : if self . is_platform : if self . _data [ "publicCode" ] : return self . _data [ 'name' ] + " Platform " + self . _data [ "publicCode" ] else : return self . _data [ 'name' ] + " Platform " + self . place_id . split ( ':' ) [ - 1 ] else : return self . _data [ 'name' ]
4,352
https://github.com/hfurubotten/enturclient/blob/8230f9e9cf5b3a4911e860bc8cbe621231aa5ae4/enturclient/dto.py#L18-L28
[ "def", "print_class_details", "(", "self", ",", "fname", ",", "classname", ")", ":", "fobj", "=", "open", "(", "fname", ",", "\"w\"", ")", "fobj", ".", "write", "(", "self", ".", "header", "%", "(", "classname", ",", "self", ".", "style", ")", ")", "fobj", ".", "write", "(", "\"<h1>%s</h1>\\n\"", "%", "(", "classname", ")", ")", "sizes", "=", "[", "tobj", ".", "get_max_size", "(", ")", "for", "tobj", "in", "self", ".", "index", "[", "classname", "]", "]", "total", "=", "0", "for", "s", "in", "sizes", ":", "total", "+=", "s", "data", "=", "{", "'cnt'", ":", "len", "(", "self", ".", "index", "[", "classname", "]", ")", ",", "'cls'", ":", "classname", "}", "data", "[", "'avg'", "]", "=", "pp", "(", "total", "/", "len", "(", "sizes", ")", ")", "data", "[", "'max'", "]", "=", "pp", "(", "max", "(", "sizes", ")", ")", "data", "[", "'min'", "]", "=", "pp", "(", "min", "(", "sizes", ")", ")", "fobj", ".", "write", "(", "self", ".", "class_summary", "%", "data", ")", "fobj", ".", "write", "(", "self", ".", "charts", "[", "classname", "]", ")", "fobj", ".", "write", "(", "\"<h2>Coalesced Referents per Snapshot</h2>\\n\"", ")", "for", "snapshot", "in", "self", ".", "snapshots", ":", "if", "classname", "in", "snapshot", ".", "classes", ":", "merged", "=", "snapshot", ".", "classes", "[", "classname", "]", "[", "'merged'", "]", "fobj", ".", "write", "(", "self", ".", "class_snapshot", "%", "{", "'name'", ":", "snapshot", ".", "desc", ",", "'cls'", ":", "classname", ",", "'total'", ":", "pp", "(", "merged", ".", "size", ")", "}", ")", "if", "merged", ".", "refs", ":", "self", ".", "_print_refs", "(", "fobj", ",", "merged", ".", "refs", ",", "merged", ".", "size", ")", "else", ":", "fobj", ".", "write", "(", "'<p>No per-referent sizes recorded.</p>\\n'", ")", "fobj", ".", "write", "(", "\"<h2>Instances</h2>\\n\"", ")", "for", "tobj", "in", "self", ".", "index", "[", "classname", "]", ":", "fobj", ".", "write", "(", "'<table id=\"tl\" width=\"100%\" rules=\"rows\">\\n'", ")", "fobj", ".", "write", "(", "'<tr><td id=\"hl\" width=\"140px\">Instance</td><td id=\"hl\">%s at 0x%08x</td></tr>\\n'", "%", "(", "tobj", ".", "name", ",", "tobj", ".", "id", ")", ")", "if", "tobj", ".", "repr", ":", "fobj", ".", "write", "(", "\"<tr><td>Representation</td><td>%s&nbsp;</td></tr>\\n\"", "%", "tobj", ".", "repr", ")", "fobj", ".", "write", "(", "\"<tr><td>Lifetime</td><td>%s - %s</td></tr>\\n\"", "%", "(", "pp_timestamp", "(", "tobj", ".", "birth", ")", ",", "pp_timestamp", "(", "tobj", ".", "death", ")", ")", ")", "if", "tobj", ".", "trace", ":", "trace", "=", "\"<pre>%s</pre>\"", "%", "(", "_format_trace", "(", "tobj", ".", "trace", ")", ")", "fobj", ".", "write", "(", "\"<tr><td>Instantiation</td><td>%s</td></tr>\\n\"", "%", "trace", ")", "for", "(", "timestamp", ",", "size", ")", "in", "tobj", ".", "snapshots", ":", "fobj", ".", "write", "(", "\"<tr><td>%s</td>\"", "%", "pp_timestamp", "(", "timestamp", ")", ")", "if", "not", "size", ".", "refs", ":", "fobj", ".", "write", "(", "\"<td>%s</td></tr>\\n\"", "%", "pp", "(", "size", ".", "size", ")", ")", "else", ":", "fobj", ".", "write", "(", "\"<td>%s\"", "%", "pp", "(", "size", ".", "size", ")", ")", "self", ".", "_print_refs", "(", "fobj", ",", "size", ".", "refs", ",", "size", ".", "size", ")", "fobj", ".", "write", "(", "\"</td></tr>\\n\"", ")", "fobj", ".", "write", "(", "\"</table>\\n\"", ")", "fobj", ".", "write", "(", "self", ".", "footer", ")", "fobj", ".", "close", "(", ")" ]
Remove an item by value consulting the keyfunc for the key .
def remove ( self , value , _sa_initiator = None ) : key = self . keyfunc ( value ) # Let self[key] raise if key is not in this collection # testlib.pragma exempt:__ne__ if not self . __contains__ ( key ) or value not in self [ key ] : raise sa_exc . InvalidRequestError ( "Can not remove '%s': collection holds '%s' for key '%s'. " "Possible cause: is the MappedCollection key function " "based on mutable properties or properties that only obtain " "values after flush?" % ( value , self [ key ] , key ) ) self . __getitem__ ( key , _sa_initiator ) . remove ( value )
4,353
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/custom_collections.py#L20-L33
[ "def", "get_bert_model", "(", "model_name", "=", "None", ",", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "True", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "use_pooler", "=", "True", ",", "use_decoder", "=", "True", ",", "use_classifier", "=", "True", ",", "output_attention", "=", "False", ",", "output_all_encodings", "=", "False", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'", ")", ",", "*", "*", "kwargs", ")", ":", "predefined_args", "=", "bert_hparams", "[", "model_name", "]", "mutable_args", "=", "[", "'use_residual'", ",", "'dropout'", ",", "'embed_dropout'", ",", "'word_embed'", "]", "mutable_args", "=", "frozenset", "(", "mutable_args", ")", "assert", "all", "(", "(", "k", "not", "in", "kwargs", "or", "k", "in", "mutable_args", ")", "for", "k", "in", "predefined_args", ")", ",", "'Cannot override predefined model settings.'", "predefined_args", ".", "update", "(", "kwargs", ")", "# encoder", "encoder", "=", "BERTEncoder", "(", "attention_cell", "=", "predefined_args", "[", "'attention_cell'", "]", ",", "num_layers", "=", "predefined_args", "[", "'num_layers'", "]", ",", "units", "=", "predefined_args", "[", "'units'", "]", ",", "hidden_size", "=", "predefined_args", "[", "'hidden_size'", "]", ",", "max_length", "=", "predefined_args", "[", "'max_length'", "]", ",", "num_heads", "=", "predefined_args", "[", "'num_heads'", "]", ",", "scaled", "=", "predefined_args", "[", "'scaled'", "]", ",", "dropout", "=", "predefined_args", "[", "'dropout'", "]", ",", "output_attention", "=", "output_attention", ",", "output_all_encodings", "=", "output_all_encodings", ",", "use_residual", "=", "predefined_args", "[", "'use_residual'", "]", ")", "# bert_vocab", "from", ".", ".", "vocab", "import", "BERTVocab", "if", "dataset_name", "in", "[", "'wiki_cn'", ",", "'wiki_multilingual'", "]", ":", "warnings", ".", "warn", "(", "'wiki_cn/wiki_multilingual will be deprecated.'", "' Please use wiki_cn_cased/wiki_multilingual_uncased instead.'", ")", "bert_vocab", "=", "_load_vocab", "(", "dataset_name", ",", "vocab", ",", "root", ",", "cls", "=", "BERTVocab", ")", "# BERT", "net", "=", "BERTModel", "(", "encoder", ",", "len", "(", "bert_vocab", ")", ",", "token_type_vocab_size", "=", "predefined_args", "[", "'token_type_vocab_size'", "]", ",", "units", "=", "predefined_args", "[", "'units'", "]", ",", "embed_size", "=", "predefined_args", "[", "'embed_size'", "]", ",", "embed_dropout", "=", "predefined_args", "[", "'embed_dropout'", "]", ",", "word_embed", "=", "predefined_args", "[", "'word_embed'", "]", ",", "use_pooler", "=", "use_pooler", ",", "use_decoder", "=", "use_decoder", ",", "use_classifier", "=", "use_classifier", ")", "if", "pretrained", ":", "ignore_extra", "=", "not", "(", "use_pooler", "and", "use_decoder", "and", "use_classifier", ")", "_load_pretrained_params", "(", "net", ",", "model_name", ",", "dataset_name", ",", "root", ",", "ctx", ",", "ignore_extra", "=", "ignore_extra", ")", "return", "net", ",", "bert_vocab" ]
Used as a Jinja2 filter this function returns a safe HTML chunk .
def progressive ( image_field , alt_text = '' ) : if not isinstance ( image_field , ImageFieldFile ) : raise ValueError ( '"image_field" argument must be an ImageField.' ) for engine in engines . all ( ) : if isinstance ( engine , BaseEngine ) and hasattr ( engine , 'env' ) : env = engine . env if isinstance ( env , Environment ) : context = render_progressive_field ( image_field , alt_text ) template = env . get_template ( 'progressiveimagefield/render_field.html' ) rendered = template . render ( * * context ) return Markup ( rendered ) return ''
4,354
https://github.com/manikos/django-progressiveimagefield/blob/a432c79d23d87ea8944ac252ae7d15df1e4f3072/progressiveimagefield/jinja/filters.py#L17-L42
[ "def", "stop_experiment", "(", "args", ")", ":", "experiment_id_list", "=", "parse_ids", "(", "args", ")", "if", "experiment_id_list", ":", "experiment_config", "=", "Experiments", "(", ")", "experiment_dict", "=", "experiment_config", ".", "get_all_experiments", "(", ")", "for", "experiment_id", "in", "experiment_id_list", ":", "print_normal", "(", "'Stoping experiment %s'", "%", "experiment_id", ")", "nni_config", "=", "Config", "(", "experiment_dict", "[", "experiment_id", "]", "[", "'fileName'", "]", ")", "rest_port", "=", "nni_config", ".", "get_config", "(", "'restServerPort'", ")", "rest_pid", "=", "nni_config", ".", "get_config", "(", "'restServerPid'", ")", "if", "rest_pid", ":", "kill_command", "(", "rest_pid", ")", "tensorboard_pid_list", "=", "nni_config", ".", "get_config", "(", "'tensorboardPidList'", ")", "if", "tensorboard_pid_list", ":", "for", "tensorboard_pid", "in", "tensorboard_pid_list", ":", "try", ":", "kill_command", "(", "tensorboard_pid", ")", "except", "Exception", "as", "exception", ":", "print_error", "(", "exception", ")", "nni_config", ".", "set_config", "(", "'tensorboardPidList'", ",", "[", "]", ")", "print_normal", "(", "'Stop experiment success!'", ")", "experiment_config", ".", "update_experiment", "(", "experiment_id", ",", "'status'", ",", "'STOPPED'", ")", "time_now", "=", "time", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ",", "time", ".", "localtime", "(", "time", ".", "time", "(", ")", ")", ")", "experiment_config", ".", "update_experiment", "(", "experiment_id", ",", "'endTime'", ",", "str", "(", "time_now", ")", ")" ]
If the task was only saved treat all form fields as not required .
def get_form ( self , form_class = None ) : form = super ( ) . get_form ( form_class ) if self . _save : make_form_or_formset_fields_not_required ( form ) return form
4,355
https://github.com/Thermondo/viewflow-extensions/blob/5d2bbfe28ced7dda3e6832b96ea031c1b871053e/viewflow_extensions/views.py#L40-L45
[ "def", "list_event_sources", "(", "self", ")", ":", "# Server does not do pagination on listings of this resource.", "# Return an iterator anyway for similarity with other API methods", "path", "=", "'/archive/{}/events/sources'", ".", "format", "(", "self", ".", "_instance", ")", "response", "=", "self", ".", "_client", ".", "get_proto", "(", "path", "=", "path", ")", "message", "=", "archive_pb2", ".", "EventSourceInfo", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "sources", "=", "getattr", "(", "message", ",", "'source'", ")", "return", "iter", "(", "sources", ")" ]
Transition to save the task and return to ASSIGNED state .
def save_task ( self ) : task = self . request . activation . task task . status = STATUS . ASSIGNED task . save ( )
4,356
https://github.com/Thermondo/viewflow-extensions/blob/5d2bbfe28ced7dda3e6832b96ea031c1b871053e/viewflow_extensions/views.py#L47-L51
[ "def", "calibrate_data", "(", "params", ",", "raw_data", ",", "calib_data", ")", ":", "start", "=", "calib_data", ".", "before", "(", "datetime", ".", "max", ")", "if", "start", "is", "None", ":", "start", "=", "datetime", ".", "min", "start", "=", "raw_data", ".", "after", "(", "start", "+", "SECOND", ")", "if", "start", "is", "None", ":", "return", "start", "del", "calib_data", "[", "start", ":", "]", "calibrator", "=", "Calib", "(", "params", ",", "raw_data", ")", "def", "calibgen", "(", "inputdata", ")", ":", "\"\"\"Internal generator function\"\"\"", "count", "=", "0", "for", "data", "in", "inputdata", ":", "idx", "=", "data", "[", "'idx'", "]", "count", "+=", "1", "if", "count", "%", "10000", "==", "0", ":", "logger", ".", "info", "(", "\"calib: %s\"", ",", "idx", ".", "isoformat", "(", "' '", ")", ")", "elif", "count", "%", "500", "==", "0", ":", "logger", ".", "debug", "(", "\"calib: %s\"", ",", "idx", ".", "isoformat", "(", "' '", ")", ")", "for", "key", "in", "(", "'rain'", ",", "'abs_pressure'", ",", "'temp_in'", ")", ":", "if", "data", "[", "key", "]", "is", "None", ":", "logger", ".", "error", "(", "'Ignoring invalid data at %s'", ",", "idx", ".", "isoformat", "(", "' '", ")", ")", "break", "else", ":", "yield", "calibrator", ".", "calib", "(", "data", ")", "calib_data", ".", "update", "(", "calibgen", "(", "raw_data", "[", "start", ":", "]", ")", ")", "return", "start" ]
Complete the activation or save only depending on form submit .
def activation_done ( self , * args , * * kwargs ) : if self . _save : self . save_task ( ) else : super ( ) . activation_done ( * args , * * kwargs )
4,357
https://github.com/Thermondo/viewflow-extensions/blob/5d2bbfe28ced7dda3e6832b96ea031c1b871053e/viewflow_extensions/views.py#L53-L58
[ "def", "play", "(", ")", ":", "with", "sqlite3", ".", "connect", "(", "ARGS", ".", "database", ")", "as", "connection", ":", "connection", ".", "text_factory", "=", "str", "cursor", "=", "connection", ".", "cursor", "(", ")", "if", "ARGS", ".", "pattern", ":", "if", "not", "ARGS", ".", "strict", ":", "ARGS", ".", "pattern", "=", "'%{0}%'", ".", "format", "(", "ARGS", ".", "pattern", ")", "cursor", ".", "execute", "(", "'SELECT * FROM Movies WHERE Name LIKE (?)'", ",", "[", "ARGS", ".", "pattern", "]", ")", "try", ":", "path", "=", "sorted", "(", "[", "row", "for", "row", "in", "cursor", "]", ")", "[", "0", "]", "[", "1", "]", "replace_map", "=", "{", "' '", ":", "'\\\\ '", ",", "'\"'", ":", "'\\\\\"'", ",", "\"'\"", ":", "\"\\\\'\"", "}", "for", "key", ",", "val", "in", "replace_map", ".", "iteritems", "(", ")", ":", "path", "=", "path", ".", "replace", "(", "key", ",", "val", ")", "os", ".", "system", "(", "'{0} {1} &'", ".", "format", "(", "ARGS", ".", "player", ",", "path", ")", ")", "except", "IndexError", ":", "exit", "(", "'Error: Movie not found.'", ")" ]
This script extends the native matplolib keyboard bindings . This script allows to use the up down left and right keys to move the visualization window . Zooming can be performed using the + and - keys . Finally the scroll wheel can be used to zoom under cursor .
def niplot ( ) : fig = gcf ( ) cid = fig . canvas . mpl_connect ( 'key_press_event' , # @UnusedVariable on_key_press ) cid = fig . canvas . mpl_connect ( 'key_release_event' , # @UnusedVariable on_key_release ) cid = fig . canvas . mpl_connect ( 'scroll_event' , zoom )
4,358
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/niplot.py#L101-L117
[ "def", "fail_participant", "(", "self", ",", "participant", ")", ":", "participant_nodes", "=", "Node", ".", "query", ".", "filter_by", "(", "participant_id", "=", "participant", ".", "id", ",", "failed", "=", "False", ")", ".", "all", "(", ")", "for", "node", "in", "participant_nodes", ":", "node", ".", "fail", "(", ")" ]
Function invoked for plotting a grid - plot with 3x2 format showing the differences in ECG signals accordingly to the chosen sampling frequency .
def acquire_subsamples_gp1 ( input_data , file_name = None ) : # Generation of the HTML file where the plot will be stored. #file_name = _generate_bokeh_file(file_name) # Number of acquired samples (Original sample_rate = 4000 Hz) fs_orig = 4000 nbr_samples_orig = len ( input_data ) data_interp = { "4000" : { } } data_interp [ "4000" ] [ "data" ] = input_data data_interp [ "4000" ] [ "time" ] = numpy . linspace ( 0 , nbr_samples_orig / fs_orig , nbr_samples_orig ) # Constants time_orig = data_interp [ "4000" ] [ "time" ] data_orig = data_interp [ "4000" ] [ "data" ] # ============ Interpolation of data accordingly to the desired sampling frequency ============ # sample_rate in [3000, 1000, 500, 200, 100] - Some of the available sample frequencies at Plux # acquisition systems # sample_rate in [50, 20] - Non-functional sampling frequencies (Not available at Plux devices # because of their limited application) for sample_rate in [ 3000 , 1000 , 500 , 200 , 100 , 50 , 20 ] : fs_str = str ( sample_rate ) nbr_samples_interp = int ( ( nbr_samples_orig * sample_rate ) / fs_orig ) data_interp [ fs_str ] = { } data_interp [ fs_str ] [ "time" ] = numpy . linspace ( 0 , nbr_samples_orig / fs_orig , nbr_samples_interp ) data_interp [ fs_str ] [ "data" ] = numpy . interp ( data_interp [ fs_str ] [ "time" ] , time_orig , data_orig ) # List that store the figure handler. list_figures = [ ] # Generation of Bokeh Figures. for iter_nbr , sample_rate in enumerate ( [ "4000" , "3000" , "1000" , "500" , "200" , "100" ] ) : # If figure number is a multiple of 3 or if we are generating the first figure... if iter_nbr == 0 or iter_nbr % 2 == 0 : list_figures . append ( [ ] ) # Plotting phase. list_figures [ - 1 ] . append ( figure ( x_axis_label = 'Time (s)' , y_axis_label = 'Raw Data' , title = "Sampling Frequency: " + sample_rate + " Hz" , * * opensignals_kwargs ( "figure" ) ) ) list_figures [ - 1 ] [ - 1 ] . line ( data_interp [ sample_rate ] [ "time" ] [ : int ( sample_rate ) ] , data_interp [ sample_rate ] [ "data" ] [ : int ( sample_rate ) ] , * * opensignals_kwargs ( "line" ) )
4,359
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/__notebook_support__.py#L206-L266
[ "def", "free", "(", "self", ",", "lpAddress", ")", ":", "hProcess", "=", "self", ".", "get_handle", "(", "win32", ".", "PROCESS_VM_OPERATION", ")", "win32", ".", "VirtualFreeEx", "(", "hProcess", ",", "lpAddress", ")" ]
Downloading data from websites such as previously acquired physiological signals is an extremely relevant task taking into consideration that without data processing cannot take place .
def download ( link , out ) : # [Source: https://stackoverflow.com/questions/7243750/download-file-from-web-in-python-3] r = requests . get ( link ) with open ( out , 'wb' ) as outfile : outfile . write ( r . content )
4,360
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/__notebook_support__.py#L1496-L1517
[ "def", "controls", "(", "self", ",", "timeline_slider_args", "=", "{", "}", ",", "toggle_args", "=", "{", "}", ")", ":", "self", ".", "timeline_slider", "(", "*", "*", "timeline_slider_args", ")", "self", ".", "toggle", "(", "*", "*", "toggle_args", ")" ]
Calculate the relative minima of data .
def argrelmin ( data , axis = 0 , order = 1 , mode = 'clip' ) : return argrelextrema ( data , np . less , axis , order , mode )
4,361
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/peaks.py#L75-L110
[ "def", "add_recipient", "(", "self", ",", "key", ",", "header", "=", "None", ")", ":", "if", "self", ".", "plaintext", "is", "None", ":", "raise", "ValueError", "(", "'Missing plaintext'", ")", "if", "not", "isinstance", "(", "self", ".", "plaintext", ",", "bytes", ")", ":", "raise", "ValueError", "(", "\"Plaintext must be 'bytes'\"", ")", "if", "isinstance", "(", "header", ",", "dict", ")", ":", "header", "=", "json_encode", "(", "header", ")", "jh", "=", "self", ".", "_get_jose_header", "(", "header", ")", "alg", ",", "enc", "=", "self", ".", "_get_alg_enc_from_headers", "(", "jh", ")", "rec", "=", "dict", "(", ")", "if", "header", ":", "rec", "[", "'header'", "]", "=", "header", "wrapped", "=", "alg", ".", "wrap", "(", "key", ",", "enc", ".", "wrap_key_size", ",", "self", ".", "cek", ",", "jh", ")", "self", ".", "cek", "=", "wrapped", "[", "'cek'", "]", "if", "'ek'", "in", "wrapped", ":", "rec", "[", "'encrypted_key'", "]", "=", "wrapped", "[", "'ek'", "]", "if", "'header'", "in", "wrapped", ":", "h", "=", "json_decode", "(", "rec", ".", "get", "(", "'header'", ",", "'{}'", ")", ")", "nh", "=", "self", ".", "_merge_headers", "(", "h", ",", "wrapped", "[", "'header'", "]", ")", "rec", "[", "'header'", "]", "=", "json_encode", "(", "nh", ")", "if", "'ciphertext'", "not", "in", "self", ".", "objects", ":", "self", ".", "_encrypt", "(", "alg", ",", "enc", ",", "jh", ")", "if", "'recipients'", "in", "self", ".", "objects", ":", "self", ".", "objects", "[", "'recipients'", "]", ".", "append", "(", "rec", ")", "elif", "'encrypted_key'", "in", "self", ".", "objects", "or", "'header'", "in", "self", ".", "objects", ":", "self", ".", "objects", "[", "'recipients'", "]", "=", "list", "(", ")", "n", "=", "dict", "(", ")", "if", "'encrypted_key'", "in", "self", ".", "objects", ":", "n", "[", "'encrypted_key'", "]", "=", "self", ".", "objects", ".", "pop", "(", "'encrypted_key'", ")", "if", "'header'", "in", "self", ".", "objects", ":", "n", "[", "'header'", "]", "=", "self", ".", "objects", ".", "pop", "(", "'header'", ")", "self", ".", "objects", "[", "'recipients'", "]", ".", "append", "(", "n", ")", "self", ".", "objects", "[", "'recipients'", "]", ".", "append", "(", "rec", ")", "else", ":", "self", ".", "objects", ".", "update", "(", "rec", ")" ]
Calculate the relative maxima of data .
def argrelmax ( data , axis = 0 , order = 1 , mode = 'clip' ) : return argrelextrema ( data , np . greater , axis , order , mode )
4,362
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/peaks.py#L113-L148
[ "def", "create_bundle", "(", "self", ",", "bundleId", ",", "data", "=", "None", ")", ":", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", "url", "=", "self", ".", "__get_base_bundle_url", "(", ")", "+", "\"/\"", "+", "bundleId", "if", "data", "is", "None", ":", "data", "=", "{", "}", "data", "[", "'sourceLanguage'", "]", "=", "'en'", "data", "[", "'targetLanguages'", "]", "=", "[", "]", "data", "[", "'notes'", "]", "=", "[", "]", "data", "[", "'metadata'", "]", "=", "{", "}", "data", "[", "'partner'", "]", "=", "''", "data", "[", "'segmentSeparatorPattern'", "]", "=", "''", "data", "[", "'noTranslationPattern'", "]", "=", "''", "json_data", "=", "json", ".", "dumps", "(", "data", ")", "response", "=", "self", ".", "__perform_rest_call", "(", "requestURL", "=", "url", ",", "restType", "=", "'PUT'", ",", "body", "=", "json_data", ",", "headers", "=", "headers", ")", "return", "response" ]
This function detects all the peaks of a signal and returns those time positions . To reduce the amount of peaks detected a threshold is introduced so only the peaks above that value are considered .
def peaks ( signal , tol = None ) : if ( tol is None ) : tol = min ( signal ) pks = argrelmax ( clip ( signal , tol , signal . max ( ) ) ) return pks [ 0 ]
4,363
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/peaks.py#L197-L229
[ "def", "series_upgrade_complete", "(", "resume_unit_helper", "=", "None", ",", "configs", "=", "None", ")", ":", "clear_unit_paused", "(", ")", "clear_unit_upgrading", "(", ")", "if", "configs", ":", "configs", ".", "write_all", "(", ")", "if", "resume_unit_helper", ":", "resume_unit_helper", "(", "configs", ")" ]
Retrieve and return the KE - chain project to be used throughout an app .
def get_project ( url = None , username = None , password = None , token = None , scope = None , scope_id = None , env_filename = None , status = ScopeStatus . ACTIVE ) : if env . bool ( kecenv . KECHAIN_FORCE_ENV_USE , default = False ) : if not os . getenv ( kecenv . KECHAIN_URL ) : raise ClientError ( "Error: KECHAIN_URL should be provided as environment variable (use of env vars is enforced)" ) if not ( os . getenv ( kecenv . KECHAIN_TOKEN ) or ( os . getenv ( kecenv . KECHAIN_PASSWORD ) and os . getenv ( kecenv . KECHAIN_PASSWORD ) ) ) : raise ClientError ( "Error: KECHAIN_TOKEN or KECHAIN_USERNAME and KECHAIN_PASSWORD should be provided as " "environment variable(s) (use of env vars is enforced)" ) if not ( os . getenv ( kecenv . KECHAIN_SCOPE ) or os . getenv ( kecenv . KECHAIN_SCOPE_ID ) ) : raise ClientError ( "Error: KECHAIN_SCOPE or KECHAIN_SCOPE_ID should be provided as environment variable " "(use of env vars is enforced)" ) if env . bool ( kecenv . KECHAIN_FORCE_ENV_USE , default = False ) or not any ( ( url , username , password , token , scope , scope_id ) ) : client = Client . from_env ( env_filename = env_filename ) scope_id = env ( kecenv . KECHAIN_SCOPE_ID , default = None ) scope = env ( kecenv . KECHAIN_SCOPE , default = None ) status = env ( kecenv . KECHAIN_SCOPE_STATUS , default = None ) elif ( url and ( ( username and password ) or ( token ) ) and ( scope or scope_id ) ) and not env . bool ( kecenv . KECHAIN_FORCE_ENV_USE , default = False ) : client = Client ( url = url ) client . login ( username = username , password = password , token = token ) else : raise ClientError ( "Error: insufficient arguments to connect to KE-chain. " "See documentation of `pykechain.get_project()`" ) if scope_id : return client . scope ( pk = scope_id , status = status ) else : return client . scope ( name = scope , status = status )
4,364
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/helpers.py#L9-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" ]
Rebuild the internal key to index mapping .
def _rebuild_key_ids ( self ) : self . _key_ids = collections . defaultdict ( list ) for i , x in enumerate ( self . _pairs ) : self . _key_ids [ x [ 0 ] ] . append ( i )
4,365
https://github.com/mikeboers/MultiMap/blob/0251e5d5df693cc247b4ac5b95adfdd10e3bec04/multimap.py#L71-L75
[ "def", "install_package_requirements", "(", "self", ",", "psrc", ",", "stream_output", "=", "None", ")", ":", "package", "=", "self", ".", "target", "+", "'/'", "+", "psrc", "assert", "isdir", "(", "package", ")", ",", "package", "reqname", "=", "'/requirements.txt'", "if", "not", "exists", "(", "package", "+", "reqname", ")", ":", "reqname", "=", "'/pip-requirements.txt'", "if", "not", "exists", "(", "package", "+", "reqname", ")", ":", "return", "return", "self", ".", "user_run_script", "(", "script", "=", "scripts", ".", "get_script_path", "(", "'install_reqs.sh'", ")", ",", "args", "=", "[", "'/project/'", "+", "psrc", "+", "reqname", "]", ",", "rw_venv", "=", "True", ",", "rw_project", "=", "True", ",", "stream_output", "=", "stream_output", ")" ]
Iterator across all the non - duplicate keys and their values . Only yields the first key of duplicates .
def iteritems ( self ) : keys_yielded = set ( ) for k , v in self . _pairs : if k not in keys_yielded : keys_yielded . add ( k ) yield k , v
4,366
https://github.com/mikeboers/MultiMap/blob/0251e5d5df693cc247b4ac5b95adfdd10e3bec04/multimap.py#L206-L216
[ "def", "GetClientVersion", "(", "client_id", ",", "token", "=", "None", ")", ":", "if", "data_store", ".", "RelationalDBEnabled", "(", ")", ":", "sinfo", "=", "data_store", ".", "REL_DB", ".", "ReadClientStartupInfo", "(", "client_id", "=", "client_id", ")", "if", "sinfo", "is", "not", "None", ":", "return", "sinfo", ".", "client_info", ".", "client_version", "else", ":", "return", "config", ".", "CONFIG", "[", "\"Source.version_numeric\"", "]", "else", ":", "with", "aff4", ".", "FACTORY", ".", "Open", "(", "client_id", ",", "token", "=", "token", ")", "as", "client", ":", "cinfo", "=", "client", ".", "Get", "(", "client", ".", "Schema", ".", "CLIENT_INFO", ")", "if", "cinfo", "is", "not", "None", ":", "return", "cinfo", ".", "client_version", "else", ":", "return", "config", ".", "CONFIG", "[", "\"Source.version_numeric\"", "]" ]
Update the object .
def _update ( self , resource , update_dict = None , params = None , * * kwargs ) : url = self . _client . _build_url ( resource , * * kwargs ) response = self . _client . _request ( 'PUT' , url , json = update_dict , params = params ) if response . status_code != requests . codes . ok : # pragma: no cover raise APIError ( "Could not update {} ({})" . format ( self . __class__ . __name__ , response . json ( ) . get ( 'results' ) ) ) else : self . refresh ( )
4,367
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/team.py#L26-L34
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Members of the team .
def members ( self , role = None ) : if role and role not in TeamRoles . values ( ) : raise IllegalArgumentError ( "role should be one of `TeamRoles` {}, got '{}'" . format ( TeamRoles . values ( ) , role ) ) member_list = self . _json_data . get ( 'members' ) if role : return [ teammember for teammember in member_list if teammember . get ( 'role' ) == role ] else : return member_list
4,368
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/team.py#L36-L63
[ "def", "get_monitors", "(", "self", ",", "condition", "=", "None", ",", "page_size", "=", "1000", ")", ":", "req_kwargs", "=", "{", "}", "if", "condition", ":", "req_kwargs", "[", "'condition'", "]", "=", "condition", ".", "compile", "(", ")", "for", "monitor_data", "in", "self", ".", "_conn", ".", "iter_json_pages", "(", "\"/ws/Monitor\"", ",", "*", "*", "req_kwargs", ")", ":", "yield", "DeviceCloudMonitor", ".", "from_json", "(", "self", ".", "_conn", ",", "monitor_data", ",", "self", ".", "_tcp_client_manager", ")" ]
Scopes associated to the team .
def scopes ( self , * * kwargs ) : return self . _client . scopes ( team = self . id , * * kwargs )
4,369
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/team.py#L136-L138
[ "def", "read_binary", "(", "self", ",", "ba", ",", "param_groups", "=", "None", ")", ":", "if", "ba", "is", "None", ":", "return", "[", "]", "pgr", "=", "ba", ".", "find", "(", "'m:referenceableParamGroupRef'", ",", "namespaces", "=", "self", ".", "ns", ")", "if", "pgr", "is", "not", "None", "and", "param_groups", "is", "not", "None", ":", "q", "=", "'m:referenceableParamGroup[@id=\"'", "+", "pgr", ".", "get", "(", "'ref'", ")", "+", "'\"]'", "pg", "=", "param_groups", ".", "find", "(", "q", ",", "namespaces", "=", "self", ".", "ns", ")", "else", ":", "pg", "=", "ba", "if", "pg", ".", "find", "(", "'m:cvParam[@accession=\"MS:1000574\"]'", ",", "namespaces", "=", "self", ".", "ns", ")", "is", "not", "None", ":", "compress", "=", "True", "elif", "pg", ".", "find", "(", "'m:cvParam[@accession=\"MS:1000576\"]'", ",", "namespaces", "=", "self", ".", "ns", ")", "is", "not", "None", ":", "compress", "=", "False", "else", ":", "# TODO: no info? should check the other record?", "pass", "if", "pg", ".", "find", "(", "'m:cvParam[@accession=\"MS:1000521\"]'", ",", "namespaces", "=", "self", ".", "ns", ")", "is", "not", "None", ":", "dtype", "=", "'f'", "elif", "pg", ".", "find", "(", "'m:cvParam[@accession=\"MS:1000523\"]'", ",", "namespaces", "=", "self", ".", "ns", ")", "is", "not", "None", ":", "dtype", "=", "'d'", "else", ":", "# TODO: no info? should check the other record?", "pass", "datatext", "=", "ba", ".", "find", "(", "'m:binary'", ",", "namespaces", "=", "self", ".", "ns", ")", ".", "text", "if", "compress", ":", "rawdata", "=", "zlib", ".", "decompress", "(", "base64", ".", "b64decode", "(", "datatext", ")", ")", "else", ":", "rawdata", "=", "base64", ".", "b64decode", "(", "datatext", ")", "return", "np", ".", "fromstring", "(", "rawdata", ",", "dtype", "=", "dtype", ")" ]
Insert a hash based on the content into the path after the first dot .
def insert_hash ( path : Path , content : Union [ str , bytes ] , * , hash_length = 7 , hash_algorithm = hashlib . md5 ) : if isinstance ( content , str ) : content = content . encode ( ) hash_ = hash_algorithm ( content ) . hexdigest ( ) [ : hash_length ] if '.' in path . name : new_name = re . sub ( r'\.' , f'.{hash_}.' , path . name , count = 1 ) else : new_name = f'{path.name}.{hash_}' return path . with_name ( new_name )
4,370
https://github.com/samuelcolvin/grablib/blob/2fca8a3950f29fb2a97a7bd75c0839060a91cedf/grablib/build.py#L20-L33
[ "def", "_perturbation", "(", "self", ")", ":", "if", "self", ".", "P", ">", "1", ":", "scales", "=", "[", "]", "for", "term_i", "in", "range", "(", "self", ".", "n_terms", ")", ":", "_scales", "=", "SP", ".", "randn", "(", "self", ".", "diag", "[", "term_i", "]", ".", "shape", "[", "0", "]", ")", "if", "self", ".", "offset", "[", "term_i", "]", ">", "0", ":", "_scales", "=", "SP", ".", "concatenate", "(", "(", "_scales", ",", "SP", ".", "zeros", "(", "1", ")", ")", ")", "scales", ".", "append", "(", "_scales", ")", "scales", "=", "SP", ".", "concatenate", "(", "scales", ")", "else", ":", "scales", "=", "SP", ".", "randn", "(", "self", ".", "vd", ".", "getNumberScales", "(", ")", ")", "return", "scales" ]
Provide a sorted list of options .
def options ( cls ) : return sorted ( ( value , name ) for ( name , value ) in cls . __dict__ . items ( ) if not name . startswith ( '__' ) )
4,371
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/enums.py#L14-L16
[ "def", "gpu_mem_restore", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "tb_clear_frames", "=", "os", ".", "environ", ".", "get", "(", "'FASTAI_TB_CLEAR_FRAMES'", ",", "None", ")", "if", "not", "IS_IN_IPYTHON", "or", "tb_clear_frames", "==", "\"0\"", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "if", "(", "\"CUDA out of memory\"", "in", "str", "(", "e", ")", "or", "\"device-side assert triggered\"", "in", "str", "(", "e", ")", "or", "tb_clear_frames", "==", "\"1\"", ")", ":", "type", ",", "val", ",", "tb", "=", "get_ref_free_exc_info", "(", ")", "# must!", "gc", ".", "collect", "(", ")", "if", "\"device-side assert triggered\"", "in", "str", "(", "e", ")", ":", "warn", "(", "\"\"\"When 'device-side assert triggered' error happens, it's not possible to recover and you must restart the kernel to continue. Use os.environ['CUDA_LAUNCH_BLOCKING']=\"1\" before restarting to debug\"\"\"", ")", "raise", "type", "(", "val", ")", ".", "with_traceback", "(", "tb", ")", "from", "None", "else", ":", "raise", "# re-raises the exact last exception", "return", "wrapper" ]
Provide access to the Navigation Bar .
def navbar ( self ) : window = BaseWindow ( self . selenium , self . selenium . current_window_handle ) with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : el = self . selenium . find_element ( * self . _nav_bar_locator ) return NavBar ( window , el )
4,372
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/window.py#L30-L40
[ "def", "make_random_models_table", "(", "n_sources", ",", "param_ranges", ",", "random_state", "=", "None", ")", ":", "prng", "=", "check_random_state", "(", "random_state", ")", "sources", "=", "Table", "(", ")", "for", "param_name", ",", "(", "lower", ",", "upper", ")", "in", "param_ranges", ".", "items", "(", ")", ":", "# Generate a column for every item in param_ranges, even if it", "# is not in the model (e.g. flux). However, such columns will", "# be ignored when rendering the image.", "sources", "[", "param_name", "]", "=", "prng", ".", "uniform", "(", "lower", ",", "upper", ",", "n_sources", ")", "return", "sources" ]
Provide access to the currently displayed notification .
def notification ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : try : root = self . selenium . find_element ( * self . _notification_locator ) return BaseNotification . create ( self , root ) except NoSuchElementException : pass try : notifications = self . selenium . find_elements ( * self . _app_menu_notification_locator ) root = next ( n for n in notifications if n . is_displayed ( ) ) return BaseNotification . create ( self , root ) except StopIteration : pass return None
4,373
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/window.py#L43-L64
[ "def", "remove_armor", "(", "armored_data", ")", ":", "stream", "=", "io", ".", "BytesIO", "(", "armored_data", ")", "lines", "=", "stream", ".", "readlines", "(", ")", "[", "3", ":", "-", "1", "]", "data", "=", "base64", ".", "b64decode", "(", "b''", ".", "join", "(", "lines", ")", ")", "payload", ",", "checksum", "=", "data", "[", ":", "-", "3", "]", ",", "data", "[", "-", "3", ":", "]", "assert", "util", ".", "crc24", "(", "payload", ")", "==", "checksum", "return", "payload" ]
Wait for the specified notification to be displayed .
def wait_for_notification ( self , notification_class = BaseNotification ) : if notification_class : if notification_class is BaseNotification : message = "No notification was shown." else : message = "{0} was not shown." . format ( notification_class . __name__ ) self . wait . until ( lambda _ : isinstance ( self . notification , notification_class ) , message = message , ) return self . notification else : self . wait . until ( lambda _ : self . notification is None , message = "Unexpected notification shown." , )
4,374
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/window.py#L66-L93
[ "def", "_get_site_term", "(", "self", ",", "C", ",", "vs30", ")", ":", "dg1", ",", "dg2", "=", "self", ".", "_get_regional_site_term", "(", "C", ")", "return", "(", "C", "[", "\"g1\"", "]", "+", "dg1", ")", "+", "(", "C", "[", "\"g2\"", "]", "+", "dg2", ")", "*", "np", ".", "log", "(", "vs30", ")" ]
Open a new browser window .
def open_window ( self , private = False ) : handles_before = self . selenium . window_handles self . switch_to ( ) with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : # Opens private or non-private window self . selenium . find_element ( * self . _file_menu_button_locator ) . click ( ) if private : self . selenium . find_element ( * self . _file_menu_private_window_locator ) . click ( ) else : self . selenium . find_element ( * self . _file_menu_new_window_button_locator ) . click ( ) return self . wait . until ( expected . new_browser_window_is_opened ( self . selenium , handles_before ) , message = "No new browser window opened" , )
4,375
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/window.py#L115-L144
[ "def", "list_distributions", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "retries", "=", "10", "sleep", "=", "6", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "Items", "=", "[", "]", "while", "retries", ":", "try", ":", "log", ".", "debug", "(", "'Garnering list of CloudFront distributions'", ")", "Marker", "=", "''", "while", "Marker", "is", "not", "None", ":", "ret", "=", "conn", ".", "list_distributions", "(", "Marker", "=", "Marker", ")", "Items", "+=", "ret", ".", "get", "(", "'DistributionList'", ",", "{", "}", ")", ".", "get", "(", "'Items'", ",", "[", "]", ")", "Marker", "=", "ret", ".", "get", "(", "'DistributionList'", ",", "{", "}", ")", ".", "get", "(", "'NextMarker'", ")", "return", "Items", "except", "botocore", ".", "exceptions", ".", "ParamValidationError", "as", "err", ":", "raise", "SaltInvocationError", "(", "str", "(", "err", ")", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "err", ":", "if", "retries", "and", "err", ".", "response", ".", "get", "(", "'Error'", ",", "{", "}", ")", ".", "get", "(", "'Code'", ")", "==", "'Throttling'", ":", "retries", "-=", "1", "log", ".", "debug", "(", "'Throttled by AWS API, retrying in %s seconds...'", ",", "sleep", ")", "time", ".", "sleep", "(", "sleep", ")", "continue", "log", ".", "error", "(", "'Failed to list CloudFront distributions: %s'", ",", "err", ".", "message", ")", "return", "None" ]
An alias for todict
def to_serializable_dict ( self , attrs_to_serialize = None , rels_to_expand = None , rels_to_serialize = None , key_modifications = None ) : return self . todict ( attrs_to_serialize = attrs_to_serialize , rels_to_expand = rels_to_expand , rels_to_serialize = rels_to_serialize , key_modifications = key_modifications )
4,376
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/dictizable_mixin.py#L309-L319
[ "def", "display_available_branches", "(", "self", ")", ":", "if", "not", "self", ".", "repo", ".", "remotes", ":", "remote_branches", "=", "False", "else", ":", "remote_branches", "=", "True", "branches", "=", "self", ".", "get_branches", "(", "local", "=", "True", ",", "remote_branches", "=", "remote_branches", ")", "if", "not", "branches", ":", "click", ".", "echo", "(", "crayons", ".", "red", "(", "'No branches available'", ")", ")", "return", "branch_col", "=", "len", "(", "max", "(", "[", "b", ".", "name", "for", "b", "in", "branches", "]", ",", "key", "=", "len", ")", ")", "+", "1", "for", "branch", "in", "branches", ":", "try", ":", "branch_is_selected", "=", "(", "branch", ".", "name", "==", "self", ".", "get_current_branch_name", "(", ")", ")", "except", "TypeError", ":", "branch_is_selected", "=", "False", "marker", "=", "'*'", "if", "branch_is_selected", "else", "' '", "color", "=", "colored", ".", "green", "if", "branch_is_selected", "else", "colored", ".", "yellow", "pub", "=", "'(published)'", "if", "branch", ".", "is_published", "else", "'(unpublished)'", "click", ".", "echo", "(", "columns", "(", "[", "colored", ".", "red", "(", "marker", ")", ",", "2", "]", ",", "[", "color", "(", "branch", ".", "name", ",", "bold", "=", "True", ")", ",", "branch_col", "]", ",", "[", "black", "(", "pub", ")", ",", "14", "]", ")", ")" ]
Converts and instance to a dictionary with only the specified attributes as keys
def serialize_attrs ( self , * args ) : # return dict([(a, getattr(self, a)) for a in args]) cls = type ( self ) result = { } # result = { # a: getattr(self, a) # for a in args # if hasattr(cls, a) and # a not in cls.attrs_forbidden_for_serialization() # } for a in args : if hasattr ( cls , a ) and a not in cls . attrs_forbidden_for_serialization ( ) : val = getattr ( self , a ) if is_list_like ( val ) : result [ a ] = list ( val ) else : result [ a ] = val return result
4,377
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/dictizable_mixin.py#L532-L563
[ "def", "ConsultarTipoRetencion", "(", "self", ",", "sep", "=", "\"||\"", ")", ":", "ret", "=", "self", ".", "client", ".", "tipoRetencionConsultar", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token", ",", "'sign'", ":", "self", ".", "Sign", ",", "'cuit'", ":", "self", ".", "Cuit", ",", "}", ",", ")", "[", "'tipoRetencionReturn'", "]", "self", ".", "__analizar_errores", "(", "ret", ")", "array", "=", "ret", ".", "get", "(", "'tiposRetencion'", ",", "[", "]", ")", "return", "[", "(", "\"%s %%s %s %%s %s\"", "%", "(", "sep", ",", "sep", ",", "sep", ")", ")", "%", "(", "it", "[", "'codigoDescripcion'", "]", "[", "'codigo'", "]", ",", "it", "[", "'codigoDescripcion'", "]", "[", "'descripcion'", "]", ")", "for", "it", "in", "array", "]" ]
Compute fundamental frequency along the specified axes .
def fundamental_frequency ( s , FS ) : # TODO: review fundamental frequency to guarantee that f0 exists # suggestion peak level should be bigger # TODO: explain code s = s - mean ( s ) f , fs = plotfft ( s , FS , doplot = False ) #fs = smooth(fs, 50.0) fs = fs [ 1 : int ( len ( fs ) / 2 ) ] f = f [ 1 : int ( len ( f ) / 2 ) ] cond = find ( f > 0.5 ) [ 0 ] bp = bigPeaks ( fs [ cond : ] , 0 ) if bp == [ ] : f0 = 0 else : bp = bp + cond f0 = f [ min ( bp ) ] return f0
4,378
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/freq_analysis.py#L11-L49
[ "def", "offer_simple", "(", "pool", ",", "answer", ",", "rationale", ",", "student_id", ",", "options", ")", ":", "existing", "=", "pool", ".", "setdefault", "(", "answer", ",", "{", "}", ")", "if", "len", "(", "existing", ")", ">=", "get_max_size", "(", "pool", ",", "len", "(", "options", ")", ",", "POOL_ITEM_LENGTH_SIMPLE", ")", ":", "student_id_to_remove", "=", "random", ".", "choice", "(", "existing", ".", "keys", "(", ")", ")", "del", "existing", "[", "student_id_to_remove", "]", "existing", "[", "student_id", "]", "=", "{", "}", "pool", "[", "answer", "]", "=", "existing" ]
Compute max frequency along the specified axes .
def max_frequency ( sig , FS ) : f , fs = plotfft ( sig , FS , doplot = False ) t = cumsum ( fs ) ind_mag = find ( t > t [ - 1 ] * 0.95 ) [ 0 ] f_max = f [ ind_mag ] return f_max
4,379
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/freq_analysis.py#L52-L72
[ "def", "sync_local_to_remote", "(", "force", "=", "\"no\"", ")", ":", "_check_requirements", "(", ")", "if", "force", "!=", "\"yes\"", ":", "message", "=", "\"This will replace the remote database '%s' with your \"", "\"local '%s', are you sure [y/n]\"", "%", "(", "env", ".", "psql_db", ",", "env", ".", "local_psql_db", ")", "answer", "=", "prompt", "(", "message", ",", "\"y\"", ")", "if", "answer", "!=", "\"y\"", ":", "logger", ".", "info", "(", "\"Sync stopped\"", ")", "return", "init_tasks", "(", ")", "# Bootstrap fabrik", "# Create database dump", "local_file", "=", "\"sync_%s.sql.tar.gz\"", "%", "int", "(", "time", ".", "time", "(", ")", "*", "1000", ")", "local_path", "=", "\"/tmp/%s\"", "%", "local_file", "with", "context_managers", ".", "shell_env", "(", "PGPASSWORD", "=", "env", ".", "local_psql_password", ")", ":", "elocal", "(", "\"pg_dump -h localhost -Fc -f %s -U %s %s -x -O\"", "%", "(", "local_path", ",", "env", ".", "local_psql_user", ",", "env", ".", "local_psql_db", ")", ")", "remote_path", "=", "\"/tmp/%s\"", "%", "local_file", "# Upload sync file", "put", "(", "remote_path", ",", "local_path", ")", "# Import sync file by performing the following task (drop, create, import)", "with", "context_managers", ".", "shell_env", "(", "PGPASSWORD", "=", "env", ".", "psql_password", ")", ":", "env", ".", "run", "(", "\"pg_restore --clean -h localhost -d %s -U %s '%s'\"", "%", "(", "env", ".", "psql_db", ",", "env", ".", "psql_user", ",", "remote_path", ")", ")", "# Cleanup", "env", ".", "run", "(", "\"rm %s\"", "%", "remote_path", ")", "elocal", "(", "\"rm %s\"", "%", "local_path", ")", "# Trigger hook", "run_hook", "(", "\"postgres.after_sync_local_to_remote\"", ")", "logger", ".", "info", "(", "\"Sync complete\"", ")" ]
Compute median frequency along the specified axes .
def median_frequency ( sig , FS ) : f , fs = plotfft ( sig , FS , doplot = False ) t = cumsum ( fs ) ind_mag = find ( t > t [ - 1 ] * 0.50 ) [ 0 ] f_median = f [ ind_mag ] return f_median
4,380
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/freq_analysis.py#L75-L95
[ "def", "reconnect_redis", "(", "self", ")", ":", "if", "self", ".", "shared_client", "and", "Storage", ".", "storage", ":", "return", "Storage", ".", "storage", "storage", "=", "Redis", "(", "port", "=", "self", ".", "context", ".", "config", ".", "REDIS_RESULT_STORAGE_SERVER_PORT", ",", "host", "=", "self", ".", "context", ".", "config", ".", "REDIS_RESULT_STORAGE_SERVER_HOST", ",", "db", "=", "self", ".", "context", ".", "config", ".", "REDIS_RESULT_STORAGE_SERVER_DB", ",", "password", "=", "self", ".", "context", ".", "config", ".", "REDIS_RESULT_STORAGE_SERVER_PASSWORD", ")", "if", "self", ".", "shared_client", ":", "Storage", ".", "storage", "=", "storage", "return", "storage" ]
Call a subcommand passing the args .
def call ( subcommand , args ) : args [ '<napp>' ] = parse_napps ( args [ '<napp>' ] ) func = getattr ( NAppsAPI , subcommand ) func ( args )
4,381
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/parser.py#L57-L61
[ "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", ")" ]
Convert a napp_id in tuple with username napp name and version .
def parse_napp ( napp_id ) : # `napp_id` regex, composed by two mandatory parts (username, napp_name) # and one optional (version). # username and napp_name need to start with a letter, are composed of # letters, numbers and uderscores and must have at least three characters. # They are separated by a colon. # version is optional and can take any format. Is is separated by a hyphen, # if a version is defined. regex = r'([a-zA-Z][a-zA-Z0-9_]{2,})/([a-zA-Z][a-zA-Z0-9_]{2,}):?(.+)?' compiled_regex = re . compile ( regex ) matched = compiled_regex . fullmatch ( napp_id ) if not matched : msg = '"{}" NApp has not the form username/napp_name[:version].' raise KytosException ( msg . format ( napp_id ) ) return matched . groups ( )
4,382
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/parser.py#L88-L118
[ "def", "get_price", "(", "item", ")", ":", "the_price", "=", "\"No Default Pricing\"", "for", "price", "in", "item", ".", "get", "(", "'prices'", ",", "[", "]", ")", ":", "if", "not", "price", ".", "get", "(", "'locationGroupId'", ")", ":", "the_price", "=", "\"%0.4f\"", "%", "float", "(", "price", "[", "'hourlyRecurringFee'", "]", ")", "return", "the_price" ]
Internal function that is used for generation of the generic notebooks header .
def _generate_notebook_header ( notebook_object , notebook_type , notebook_title = "Notebook Title" , tags = "tags" , difficulty_stars = 1 , notebook_description = "Notebook Description" ) : # ============================= Creation of Header ==================================== header_temp = HEADER_ALL_CATEGORIES . replace ( "header_image_color_i" , "header_image_color_" + str ( NOTEBOOK_KEYS [ notebook_type ] ) ) header_temp = header_temp . replace ( "header_image_i" , "header_image_" + str ( NOTEBOOK_KEYS [ notebook_type ] ) ) header_temp = header_temp . replace ( "Notebook Title" , notebook_title ) notebook_object [ "cells" ] . append ( nb . v4 . new_markdown_cell ( header_temp , * * { "metadata" : { "tags" : [ "intro_info_title" ] } } ) ) # =============== Inclusion of the div with "Difficulty" and "Tags" =================== tags_and_diff = HEADER_TAGS . replace ( '<td class="shield_right" id="tags">tags</td>' , '<td class="shield_right" id="tags">' + "&#9729;" . join ( tags ) + '</td>' ) for star in range ( 1 , 6 ) : if star <= difficulty_stars : tags_and_diff = tags_and_diff . replace ( "fa fa-star " + str ( star ) , "fa fa-star " "checked" ) else : tags_and_diff = tags_and_diff . replace ( "fa fa-star " + str ( star ) , "fa fa-star" ) notebook_object [ "cells" ] . append ( nb . v4 . new_markdown_cell ( tags_and_diff , * * { "metadata" : { "tags" : [ "intro_info_tags" ] } } ) ) # ================= Insertion of the div reserved to the Notebook Description ================== notebook_object [ "cells" ] . append ( nb . v4 . new_markdown_cell ( notebook_description , * * { "metadata" : { "tags" : [ "test" ] } } ) ) notebook_object [ "cells" ] . append ( nb . v4 . new_markdown_cell ( SEPARATOR ) ) # ======================= Insertion of a blank Markdown and Code cell ========================== notebook_object [ "cells" ] . append ( nb . v4 . new_markdown_cell ( MD_EXAMPLES ) ) notebook_object [ "cells" ] . append ( nb . v4 . new_code_cell ( CODE_EXAMPLES ) )
4,383
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/factory.py#L414-L492
[ "def", "wait", "(", "self", ",", "poll_interval", "=", "1", ",", "timeout", "=", "None", ",", "full_data", "=", "False", ")", ":", "end_time", "=", "None", "if", "timeout", ":", "end_time", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "end_time", "is", "None", "or", "time", ".", "time", "(", ")", "<", "end_time", ":", "job_data", "=", "self", ".", "collection", ".", "find_one", "(", "{", "\"_id\"", ":", "ObjectId", "(", "self", ".", "id", ")", ",", "\"status\"", ":", "{", "\"$nin\"", ":", "[", "\"started\"", ",", "\"queued\"", "]", "}", "}", ",", "projection", "=", "(", "{", "\"_id\"", ":", "0", ",", "\"result\"", ":", "1", ",", "\"status\"", ":", "1", "}", "if", "not", "full_data", "else", "None", ")", ")", "if", "job_data", ":", "return", "job_data", "time", ".", "sleep", "(", "poll_interval", ")", "raise", "Exception", "(", "\"Waited for job result for %s seconds, timeout.\"", "%", "timeout", ")" ]
Make the actual request and returns the parsed response .
def _request ( self , method , path , params = None ) : url = self . _base_url + path try : if method == 'GET' : response = requests . get ( url , timeout = TIMEOUT ) elif method == "POST" : response = requests . post ( url , params , timeout = TIMEOUT ) elif method == "PUT" : response = requests . put ( url , params , timeout = TIMEOUT ) elif method == "DELETE" : response = requests . delete ( url , timeout = TIMEOUT ) if response : return response . json ( ) else : return { 'status' : 'error' } except requests . exceptions . HTTPError : return { 'status' : 'error' } except requests . exceptions . Timeout : return { 'status' : 'offline' } except requests . exceptions . RequestException : return { 'status' : 'offline' }
4,384
https://github.com/fancybits/pychannels/blob/080f269b6d17d4622a0787000befe31bebc1a15d/pychannels/__init__.py#L30-L53
[ "def", "validate_instance_dbname", "(", "self", ",", "dbname", ")", ":", "# 1-64 alphanumeric characters, cannot be a reserved MySQL word", "if", "re", ".", "match", "(", "'[\\w-]+$'", ",", "dbname", ")", "is", "not", "None", ":", "if", "len", "(", "dbname", ")", "<=", "41", "and", "len", "(", "dbname", ")", ">=", "1", ":", "if", "dbname", ".", "lower", "(", ")", "not", "in", "MYSQL_RESERVED_WORDS", ":", "return", "True", "return", "'*** Error: Database names must be 1-64 alphanumeric characters,\\\n cannot be a reserved MySQL word.'" ]
Hook into Gunicorn to display message after launching .
def post_worker_init ( worker ) : quit_command = 'CTRL-BREAK' if sys . platform == 'win32' else 'CONTROL-C' sys . stdout . write ( "Django version {djangover}, Gunicorn version {gunicornver}, " "using settings {settings!r}\n" "Starting development server at {urls}\n" "Quit the server with {quit_command}.\n" . format ( djangover = django . get_version ( ) , gunicornver = gunicorn . __version__ , settings = os . environ . get ( 'DJANGO_SETTINGS_MODULE' ) , urls = ', ' . join ( 'http://{0}/' . format ( b ) for b in worker . cfg . bind ) , quit_command = quit_command , ) , )
4,385
https://github.com/uranusjr/django-gunicorn/blob/4fb16f48048ff5fff8f889a007f376236646497b/djgunicorn/config.py#L18-L35
[ "def", "update", "(", "self", ",", "other", ")", ":", "self", ".", "update_ttl", "(", "other", ".", "ttl", ")", "super", "(", "Rdataset", ",", "self", ")", ".", "update", "(", "other", ")" ]
Retrieve the data value of this attachment .
def value ( self ) : if 'value' in self . _json_data and self . _json_data [ 'value' ] : return "[Attachment: {}]" . format ( self . _json_data [ 'value' ] . split ( '/' ) [ - 1 ] ) else : return None
4,386
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property_attachment.py#L32-L51
[ "def", "configure", "(", "self", ",", "*", "*", "configs", ")", ":", "configs", "=", "self", ".", "_deprecate_configs", "(", "*", "*", "configs", ")", "self", ".", "_config", "=", "{", "}", "for", "key", "in", "self", ".", "DEFAULT_CONFIG", ":", "self", ".", "_config", "[", "key", "]", "=", "configs", ".", "pop", "(", "key", ",", "self", ".", "DEFAULT_CONFIG", "[", "key", "]", ")", "if", "configs", ":", "raise", "KafkaConfigurationError", "(", "'Unknown configuration key(s): '", "+", "str", "(", "list", "(", "configs", ".", "keys", "(", ")", ")", ")", ")", "if", "self", ".", "_config", "[", "'auto_commit_enable'", "]", ":", "if", "not", "self", ".", "_config", "[", "'group_id'", "]", ":", "raise", "KafkaConfigurationError", "(", "'KafkaConsumer configured to auto-commit '", "'without required consumer group (group_id)'", ")", "# Check auto-commit configuration", "if", "self", ".", "_config", "[", "'auto_commit_enable'", "]", ":", "logger", ".", "info", "(", "\"Configuring consumer to auto-commit offsets\"", ")", "self", ".", "_reset_auto_commit", "(", ")", "if", "not", "self", ".", "_config", "[", "'bootstrap_servers'", "]", ":", "raise", "KafkaConfigurationError", "(", "'bootstrap_servers required to configure KafkaConsumer'", ")", "self", ".", "_client", "=", "KafkaClient", "(", "self", ".", "_config", "[", "'bootstrap_servers'", "]", ",", "client_id", "=", "self", ".", "_config", "[", "'client_id'", "]", ",", "timeout", "=", "(", "self", ".", "_config", "[", "'socket_timeout_ms'", "]", "/", "1000.0", ")", ")" ]
Filename of the attachment without the full attachment path .
def filename ( self ) : if self . value and 'value' in self . _json_data and self . _json_data [ 'value' ] : return self . _json_data [ 'value' ] . split ( '/' ) [ - 1 ] return None
4,387
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property_attachment.py#L68-L72
[ "def", "client_new", "(", ")", ":", "form", "=", "ClientForm", "(", "request", ".", "form", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "c", "=", "Client", "(", "user_id", "=", "current_user", ".", "get_id", "(", ")", ")", "c", ".", "gen_salt", "(", ")", "form", ".", "populate_obj", "(", "c", ")", "db", ".", "session", ".", "add", "(", "c", ")", "db", ".", "session", ".", "commit", "(", ")", "return", "redirect", "(", "url_for", "(", "'.client_view'", ",", "client_id", "=", "c", ".", "client_id", ")", ")", "return", "render_template", "(", "'invenio_oauth2server/settings/client_new.html'", ",", "form", "=", "form", ",", ")" ]
Upload a file to the attachment property .
def upload ( self , data , * * kwargs ) : try : import matplotlib . figure if isinstance ( data , matplotlib . figure . Figure ) : self . _upload_plot ( data , * * kwargs ) return except ImportError : pass if isinstance ( data , str ) : with open ( data , 'rb' ) as fp : self . _upload ( fp ) else : self . _upload_json ( data , * * kwargs )
4,388
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property_attachment.py#L90-L116
[ "def", "show", "(", "feed", ")", ":", "ecode", "=", "0", "try", ":", "feedmeta", "=", "anchore_feeds", ".", "load_anchore_feedmeta", "(", ")", "if", "feed", "in", "feedmeta", ":", "result", "=", "{", "}", "groups", "=", "feedmeta", "[", "feed", "]", ".", "get", "(", "'groups'", ",", "{", "}", ")", ".", "values", "(", ")", "result", "[", "'name'", "]", "=", "feed", "result", "[", "'access_tier'", "]", "=", "int", "(", "feedmeta", "[", "feed", "]", ".", "get", "(", "'access_tier'", ")", ")", "result", "[", "'description'", "]", "=", "feedmeta", "[", "feed", "]", ".", "get", "(", "'description'", ")", "result", "[", "'groups'", "]", "=", "{", "}", "if", "'subscribed'", "not", "in", "feedmeta", "[", "feed", "]", ":", "result", "[", "'subscribed'", "]", "=", "False", "else", ":", "result", "[", "'subscribed'", "]", "=", "feedmeta", "[", "feed", "]", "[", "'subscribed'", "]", "for", "g", "in", "groups", ":", "result", "[", "'groups'", "]", "[", "g", "[", "'name'", "]", "]", "=", "{", "'access_tier'", ":", "int", "(", "g", ".", "get", "(", "'access_tier'", ")", ")", ",", "'description'", ":", "g", ".", "get", "(", "'description'", ")", ",", "'last_sync'", ":", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "g", ".", "get", "(", "'last_update'", ")", ")", ".", "isoformat", "(", ")", "if", "'last_update'", "in", "g", "else", "'None'", "}", "anchore_print", "(", "result", ",", "do_formatting", "=", "True", ")", "else", ":", "anchore_print_err", "(", "'Unknown feed name. Valid feeds can be seen withe the \"list\" command'", ")", "ecode", "=", "1", "except", "Exception", "as", "err", ":", "anchore_print_err", "(", "'operation failed'", ")", "ecode", "=", "1", "sys", ".", "exit", "(", "ecode", ")" ]
Download the attachment to a file .
def save_as ( self , filename ) : with open ( filename , 'w+b' ) as f : for chunk in self . _download ( ) : f . write ( chunk )
4,389
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property_attachment.py#L118-L128
[ "def", "_run_arguement_object_fits", "(", "self", ")", ":", "# run fits", "# fit catalog object", "Y_dict", "=", "self", ".", "_catalog_object", ".", "get_transformed_Y", "(", ")", "# fit designmatrix object", "X", "=", "self", ".", "_designmatrix_object", ".", "get_matrix", "(", ")", "Xcol_names", "=", "self", ".", "_designmatrix_object", ".", "get_columnnames", "(", ")", "row_names", "=", "self", ".", "_designmatrix_object", ".", "get_rownames", "(", ")", "# make sure waveforms are matched", "# loop through Xrow_names, use as key for Y_dict, populate Y_matrix", "Y", "=", "np", ".", "empty", "(", "(", "len", "(", "row_names", ")", ",", "len", "(", "Y_dict", "[", "Y_dict", ".", "keys", "(", ")", "[", "0", "]", "]", ")", ")", ")", "# check if waveforms are complex valued. if so, instantiate Y as complex type", "if", "sum", "(", "np", ".", "iscomplex", "(", "Y_dict", "[", "Y_dict", ".", "keys", "(", ")", "[", "0", "]", "]", ")", ")", ":", "# then it is complex", "Y", "=", "np", ".", "empty", "(", "(", "len", "(", "row_names", ")", ",", "len", "(", "Y_dict", "[", "Y_dict", ".", "keys", "(", ")", "[", "0", "]", "]", ")", ")", ")", ".", "astype", "(", "np", ".", "complex", ")", "for", "i", "in", "np", ".", "arange", "(", "0", ",", "len", "(", "row_names", ")", ")", ":", "Y", "[", "i", ",", ":", "]", "=", "Y_dict", "[", "row_names", "[", "i", "]", "]", "# fit basis object", "A", "=", "self", ".", "_basis_object", ".", "fit_transform", "(", "Y", ")", "return", "Y", ",", "X", ",", "A", ",", "Xcol_names", ",", "row_names" ]
Load theme when theme parameter is semantic - ui .
def devpiserver_cmdline_run ( xom ) : if xom . config . args . theme == 'semantic-ui' : xom . config . args . theme = resource_filename ( 'devpi_semantic_ui' , '' ) xom . log . info ( "Semantic UI Theme loaded" )
4,390
https://github.com/apihackers/devpi-semantic-ui/blob/32bab6a7c3441c855d7005f088c48e7a1af5a72c/devpi_semantic_ui/__init__.py#L6-L12
[ "def", "continueLine", "(", "self", ")", ":", "if", "not", "(", "self", ".", "isLong", "and", "self", ".", "is_regular", ")", ":", "self", ".", "line_conv", "=", "self", ".", "line_conv", ".", "rstrip", "(", ")", "+", "\" &\\n\"", "else", ":", "temp", "=", "self", ".", "line_conv", "[", ":", "72", "]", ".", "rstrip", "(", ")", "+", "\" &\"", "self", ".", "line_conv", "=", "temp", ".", "ljust", "(", "72", ")", "+", "self", ".", "excess_line" ]
Check if a switch is turned on
def is_on ( self , channel ) : if channel in self . _is_on : return self . _is_on [ channel ] return False
4,391
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/modules/vmb4ry.py#L19-L27
[ "def", "export_as_string", "(", "self", ")", ":", "if", "self", ".", "_exc_info", ":", "import", "traceback", "ret", "=", "\"/*\\nWarning: Table %s.%s is incomplete because of an error processing metadata.\\n\"", "%", "(", "self", ".", "keyspace_name", ",", "self", ".", "name", ")", "for", "line", "in", "traceback", ".", "format_exception", "(", "*", "self", ".", "_exc_info", ")", ":", "ret", "+=", "line", "ret", "+=", "\"\\nApproximate structure, for reference:\\n(this should not be used to reproduce this schema)\\n\\n%s\\n*/\"", "%", "self", ".", "_all_as_cql", "(", ")", "elif", "not", "self", ".", "is_cql_compatible", ":", "# If we can't produce this table with CQL, comment inline", "ret", "=", "\"/*\\nWarning: Table %s.%s omitted because it has constructs not compatible with CQL (was created via legacy API).\\n\"", "%", "(", "self", ".", "keyspace_name", ",", "self", ".", "name", ")", "ret", "+=", "\"\\nApproximate structure, for reference:\\n(this should not be used to reproduce this schema)\\n\\n%s\\n*/\"", "%", "self", ".", "_all_as_cql", "(", ")", "elif", "self", ".", "virtual", ":", "ret", "=", "(", "'/*\\nWarning: Table {ks}.{tab} is a virtual table and cannot be recreated with CQL.\\n'", "'Structure, for reference:\\n'", "'{cql}\\n*/'", ")", ".", "format", "(", "ks", "=", "self", ".", "keyspace_name", ",", "tab", "=", "self", ".", "name", ",", "cql", "=", "self", ".", "_all_as_cql", "(", ")", ")", "else", ":", "ret", "=", "self", ".", "_all_as_cql", "(", ")", "return", "ret" ]
Turn on switch .
def turn_on ( self , channel , callback = None ) : if callback is None : def callb ( ) : """No-op""" pass callback = callb message = velbus . SwitchRelayOnMessage ( self . _address ) message . relay_channels = [ channel ] self . _controller . send ( message , callback )
4,392
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/modules/vmb4ry.py#L29-L42
[ "def", "update", "(", "self", ",", "data", ")", ":", "self", ".", "_md", ".", "update", "(", "data", ")", "bufpos", "=", "self", ".", "_nbytes", "&", "63", "self", ".", "_nbytes", "+=", "len", "(", "data", ")", "if", "self", ".", "_rarbug", "and", "len", "(", "data", ")", ">", "64", ":", "dpos", "=", "self", ".", "block_size", "-", "bufpos", "while", "dpos", "+", "self", ".", "block_size", "<=", "len", "(", "data", ")", ":", "self", ".", "_corrupt", "(", "data", ",", "dpos", ")", "dpos", "+=", "self", ".", "block_size" ]
Turn off switch .
def turn_off ( self , channel , callback = None ) : if callback is None : def callb ( ) : """No-op""" pass callback = callb message = velbus . SwitchRelayOffMessage ( self . _address ) message . relay_channels = [ channel ] self . _controller . send ( message , callback )
4,393
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/modules/vmb4ry.py#L44-L57
[ "def", "update", "(", "self", ",", "data", ")", ":", "self", ".", "_md", ".", "update", "(", "data", ")", "bufpos", "=", "self", ".", "_nbytes", "&", "63", "self", ".", "_nbytes", "+=", "len", "(", "data", ")", "if", "self", ".", "_rarbug", "and", "len", "(", "data", ")", ">", "64", ":", "dpos", "=", "self", ".", "block_size", "-", "bufpos", "while", "dpos", "+", "self", ".", "block_size", "<=", "len", "(", "data", ")", ":", "self", ".", "_corrupt", "(", "data", ",", "dpos", ")", "dpos", "+=", "self", ".", "block_size" ]
With t and rh provided does not access the hardware .
def read_dew_point ( self , t = None , rh = None ) : if t is None : t , rh = self . read_t ( ) , None if rh is None : rh = self . read_rh ( t ) t_range = 'water' if t >= 0 else 'ice' tn , m = self . c . tn [ t_range ] , self . c . m [ t_range ] return ( # ch 4.4 tn * ( math . log ( rh / 100.0 ) + ( m * t ) / ( tn + t ) ) / ( m - math . log ( rh / 100.0 ) - m * t / ( tn + t ) ) )
4,394
https://github.com/kizniche/sht-sensor/blob/e44758327eec781297e68f3f59b6937b7c5758e3/sht_sensor/sensor.py#L319-L327
[ "def", "wrap", "(", "indent_int", ",", "unwrap_str", ")", ":", "with", "io", ".", "StringIO", "(", ")", "as", "str_buf", ":", "is_rest_block", "=", "unwrap_str", ".", "startswith", "(", "(", "\"- \"", ",", "\"* \"", ")", ")", "while", "unwrap_str", ":", "cut_pos", "=", "(", "unwrap_str", "+", "\" \"", ")", ".", "rfind", "(", "\" \"", ",", "0", ",", "WRAP_MARGIN_INT", "-", "indent_int", ")", "if", "cut_pos", "==", "-", "1", ":", "cut_pos", "=", "WRAP_MARGIN_INT", "this_str", ",", "unwrap_str", "=", "unwrap_str", "[", ":", "cut_pos", "]", ",", "unwrap_str", "[", "cut_pos", "+", "1", ":", "]", "str_buf", ".", "write", "(", "\"{}{}\\n\"", ".", "format", "(", "\" \"", "*", "indent_int", ",", "this_str", ")", ")", "if", "is_rest_block", ":", "is_rest_block", "=", "False", "indent_int", "+=", "2", "return", "str_buf", ".", "getvalue", "(", ")" ]
Save the options to KE - chain .
def _put_options ( self , options_list ) : new_options = self . _options . copy ( ) # make a full copy of the dict not to only link it and update dict in place new_options . update ( { "value_choices" : options_list } ) validate ( new_options , options_json_schema ) url = self . _client . _build_url ( 'property' , property_id = self . id ) response = self . _client . _request ( 'PUT' , url , json = { 'options' : new_options } ) if response . status_code != 200 : # pragma: no cover raise APIError ( "Could not update property value. Response: {}" . format ( str ( response ) ) ) else : self . _options = new_options
4,395
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property_selectlist.py#L85-L103
[ "def", "update_reg", "(", "self", ",", "addr", ",", "mask", ",", "new_val", ")", ":", "shift", "=", "_mask_to_shift", "(", "mask", ")", "val", "=", "self", ".", "read_reg", "(", "addr", ")", "val", "&=", "~", "mask", "val", "|=", "(", "new_val", "<<", "shift", ")", "&", "mask", "self", ".", "write_reg", "(", "addr", ",", "val", ")", "return", "val" ]
Take a Form or FormSet and set all fields to not required .
def make_form_or_formset_fields_not_required ( form_or_formset ) : if isinstance ( form_or_formset , BaseFormSet ) : for single_form in form_or_formset : make_form_fields_not_required ( single_form ) else : make_form_fields_not_required ( form_or_formset )
4,396
https://github.com/Thermondo/viewflow-extensions/blob/5d2bbfe28ced7dda3e6832b96ea031c1b871053e/viewflow_extensions/utils.py#L4-L10
[ "def", "_GetImportTimestamps", "(", "self", ",", "pefile_object", ")", ":", "import_timestamps", "=", "[", "]", "if", "not", "hasattr", "(", "pefile_object", ",", "'DIRECTORY_ENTRY_IMPORT'", ")", ":", "return", "import_timestamps", "for", "importdata", "in", "pefile_object", ".", "DIRECTORY_ENTRY_IMPORT", ":", "dll_name", "=", "getattr", "(", "importdata", ",", "'dll'", ",", "''", ")", "try", ":", "dll_name", "=", "dll_name", ".", "decode", "(", "'ascii'", ")", "except", "UnicodeDecodeError", ":", "dll_name", "=", "dll_name", ".", "decode", "(", "'ascii'", ",", "errors", "=", "'replace'", ")", "if", "not", "dll_name", ":", "dll_name", "=", "'<NO DLL NAME>'", "timestamp", "=", "getattr", "(", "importdata", ".", "struct", ",", "'TimeDateStamp'", ",", "0", ")", "if", "timestamp", ":", "import_timestamps", ".", "append", "(", "[", "dll_name", ",", "timestamp", "]", ")", "return", "import_timestamps" ]
ID of the scope this Activity belongs to .
def scope_id ( self ) : if self . scope : scope_id = self . scope and self . scope . get ( 'id' ) else : pseudo_self = self . _client . activity ( pk = self . id , fields = "id,scope" ) if pseudo_self . scope and pseudo_self . scope . get ( 'id' ) : self . scope = pseudo_self . scope scope_id = self . scope . get ( 'id' ) else : raise NotFoundError ( "This activity '{}'({}) does not belong to a scope, something is weird!" . format ( self . name , self . id ) ) return scope_id
4,397
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/activity.py#L26-L48
[ "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\"", ")" ]
Determine if Activity is at the root level of a project .
def is_rootlevel ( self ) : container_id = self . _json_data . get ( 'container' ) if container_id : return container_id == self . _json_data . get ( 'root_container' ) else : return False
4,398
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/activity.py#L54-L65
[ "def", "clientUpdated", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ref", "=", "{", "'exchange'", ":", "'client-updated'", ",", "'name'", ":", "'clientUpdated'", ",", "'routingKey'", ":", "[", "{", "'multipleWords'", ":", "True", ",", "'name'", ":", "'reserved'", ",", "}", ",", "]", ",", "'schema'", ":", "'v1/client-message.json#'", ",", "}", "return", "self", ".", "_makeTopicExchange", "(", "ref", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Determine if the Activity is configured with input and output properties .
def is_configured ( self ) : # check configured based on if we get at least 1 part back associated_models = self . parts ( category = Category . MODEL , limit = 1 ) if associated_models : return True else : return False
4,399
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/activity.py#L85-L99
[ "def", "auto_thaw", "(", "vault_client", ",", "opt", ")", ":", "icefile", "=", "opt", ".", "thaw_from", "if", "not", "os", ".", "path", ".", "exists", "(", "icefile", ")", ":", "raise", "aomi", ".", "exceptions", ".", "IceFile", "(", "\"%s missing\"", "%", "icefile", ")", "thaw", "(", "vault_client", ",", "icefile", ",", "opt", ")", "return", "opt" ]