query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Acknowledges the status update .
def acknowledge ( self , status ) : logging . info ( 'Acknowledges status update {}' . format ( status ) ) return self . driver . acknowledgeStatusUpdate ( encode ( status ) )
1,500
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L221-L232
[ "def", "generateSequences", "(", "n", "=", "2048", ",", "w", "=", "40", ",", "sequenceLength", "=", "5", ",", "sequenceCount", "=", "2", ",", "sharedRange", "=", "None", ",", "seed", "=", "42", ")", ":", "# Lots of room for noise sdrs", "patternAlphabetSize", "=", "10", "*", "(", "sequenceLength", "*", "sequenceCount", ")", "patternMachine", "=", "PatternMachine", "(", "n", ",", "w", ",", "patternAlphabetSize", ",", "seed", ")", "sequenceMachine", "=", "SequenceMachine", "(", "patternMachine", ",", "seed", ")", "numbers", "=", "sequenceMachine", ".", "generateNumbers", "(", "sequenceCount", ",", "sequenceLength", ",", "sharedRange", "=", "sharedRange", ")", "generatedSequences", "=", "sequenceMachine", ".", "generateFromNumbers", "(", "numbers", ")", "return", "sequenceMachine", ",", "generatedSequences", ",", "numbers" ]
Sends a message from the framework to one of its executors .
def message ( self , executor_id , slave_id , message ) : logging . info ( 'Sends message `{}` to executor `{}` on slave `{}`' . format ( message , executor_id , slave_id ) ) return self . driver . sendFrameworkMessage ( encode ( executor_id ) , encode ( slave_id ) , message )
1,501
https://github.com/daskos/mentor/blob/b5fd64e3a3192f5664fa5c03e8517cacb4e0590f/mentor/proxies/scheduler.py#L234-L244
[ "def", "write_zip_fp", "(", "fp", ",", "data", ",", "properties", ",", "dir_data_list", "=", "None", ")", ":", "assert", "data", "is", "not", "None", "or", "properties", "is", "not", "None", "# dir_data_list has the format: local file record offset, name, data length, crc32", "dir_data_list", "=", "list", "(", ")", "if", "dir_data_list", "is", "None", "else", "dir_data_list", "dt", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "data", "is", "not", "None", ":", "offset_data", "=", "fp", ".", "tell", "(", ")", "def", "write_data", "(", "fp", ")", ":", "numpy_start_pos", "=", "fp", ".", "tell", "(", ")", "numpy", ".", "save", "(", "fp", ",", "data", ")", "numpy_end_pos", "=", "fp", ".", "tell", "(", ")", "fp", ".", "seek", "(", "numpy_start_pos", ")", "data_c", "=", "numpy", ".", "require", "(", "data", ",", "dtype", "=", "data", ".", "dtype", ",", "requirements", "=", "[", "\"C_CONTIGUOUS\"", "]", ")", "header_data", "=", "fp", ".", "read", "(", "(", "numpy_end_pos", "-", "numpy_start_pos", ")", "-", "data_c", ".", "nbytes", ")", "# read the header", "data_crc32", "=", "binascii", ".", "crc32", "(", "data_c", ".", "data", ",", "binascii", ".", "crc32", "(", "header_data", ")", ")", "&", "0xFFFFFFFF", "fp", ".", "seek", "(", "numpy_end_pos", ")", "return", "data_crc32", "data_len", ",", "crc32", "=", "write_local_file", "(", "fp", ",", "b\"data.npy\"", ",", "write_data", ",", "dt", ")", "dir_data_list", ".", "append", "(", "(", "offset_data", ",", "b\"data.npy\"", ",", "data_len", ",", "crc32", ")", ")", "if", "properties", "is", "not", "None", ":", "json_str", "=", "str", "(", ")", "try", ":", "class", "JSONEncoder", "(", "json", ".", "JSONEncoder", ")", ":", "def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "Geometry", ".", "IntPoint", ")", "or", "isinstance", "(", "obj", ",", "Geometry", ".", "IntSize", ")", "or", "isinstance", "(", "obj", ",", "Geometry", ".", "IntRect", ")", "or", "isinstance", "(", "obj", ",", "Geometry", ".", "FloatPoint", ")", "or", "isinstance", "(", "obj", ",", "Geometry", ".", "FloatSize", ")", "or", "isinstance", "(", "obj", ",", "Geometry", ".", "FloatRect", ")", ":", "return", "tuple", "(", "obj", ")", "else", ":", "return", "json", ".", "JSONEncoder", ".", "default", "(", "self", ",", "obj", ")", "json_io", "=", "io", ".", "StringIO", "(", ")", "json", ".", "dump", "(", "properties", ",", "json_io", ",", "cls", "=", "JSONEncoder", ")", "json_str", "=", "json_io", ".", "getvalue", "(", ")", "except", "Exception", "as", "e", ":", "# catch exceptions to avoid corrupt zip files", "import", "traceback", "logging", ".", "error", "(", "\"Exception writing zip file %s\"", "+", "str", "(", "e", ")", ")", "traceback", ".", "print_exc", "(", ")", "traceback", ".", "print_stack", "(", ")", "def", "write_json", "(", "fp", ")", ":", "json_bytes", "=", "bytes", "(", "json_str", ",", "'ISO-8859-1'", ")", "fp", ".", "write", "(", "json_bytes", ")", "return", "binascii", ".", "crc32", "(", "json_bytes", ")", "&", "0xFFFFFFFF", "offset_json", "=", "fp", ".", "tell", "(", ")", "json_len", ",", "json_crc32", "=", "write_local_file", "(", "fp", ",", "b\"metadata.json\"", ",", "write_json", ",", "dt", ")", "dir_data_list", ".", "append", "(", "(", "offset_json", ",", "b\"metadata.json\"", ",", "json_len", ",", "json_crc32", ")", ")", "dir_offset", "=", "fp", ".", "tell", "(", ")", "for", "offset", ",", "name_bytes", ",", "data_len", ",", "crc32", "in", "dir_data_list", ":", "write_directory_data", "(", "fp", ",", "offset", ",", "name_bytes", ",", "data_len", ",", "crc32", ",", "dt", ")", "dir_size", "=", "fp", ".", "tell", "(", ")", "-", "dir_offset", "write_end_of_directory", "(", "fp", ",", "dir_size", ",", "dir_offset", ",", "len", "(", "dir_data_list", ")", ")", "fp", ".", "truncate", "(", ")" ]
Handles GtkBuilder signal connect events
def _connect_func ( builder , obj , signal_name , handler_name , connect_object , flags , cls ) : if connect_object is None : extra = ( ) else : extra = ( connect_object , ) # The handler name refers to an attribute on the template instance, # so ask GtkBuilder for the template instance template_inst = builder . get_object ( cls . __gtype_name__ ) if template_inst is None : # This should never happen errmsg = "Internal error: cannot find template instance! obj: %s; " "signal: %s; handler: %s; connect_obj: %s; class: %s" % ( obj , signal_name , handler_name , connect_object , cls ) warnings . warn ( errmsg , GtkTemplateWarning ) return handler = getattr ( template_inst , handler_name ) if flags == GObject . ConnectFlags . AFTER : obj . connect_after ( signal_name , handler , * extra ) else : obj . connect ( signal_name , handler , * extra ) template_inst . __connected_template_signals__ . add ( handler_name )
1,502
https://github.com/virtuald/pygi-composite-templates/blob/a22be54ea95b8125b36deaa3ce7171e84158d486/gi_composites.py#L36-L63
[ "def", "read_tabular", "(", "filename", ",", "dtype_conversion", "=", "None", ")", ":", "if", "dtype_conversion", "is", "None", ":", "dtype_conversion", "=", "{", "}", "name", ",", "ext", "=", "filename", ".", "split", "(", "\".\"", ",", "1", ")", "ext", "=", "ext", ".", "lower", "(", ")", "# Completely empty columns are interpreted as float by default.", "dtype_conversion", "[", "\"comment\"", "]", "=", "str", "if", "\"csv\"", "in", "ext", ":", "df", "=", "pd", ".", "read_csv", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "elif", "\"tsv\"", "in", "ext", ":", "df", "=", "pd", ".", "read_table", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "elif", "\"xls\"", "in", "ext", "or", "\"xlsx\"", "in", "ext", ":", "df", "=", "pd", ".", "read_excel", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "# TODO: Add a function to parse ODS data into a pandas data frame.", "else", ":", "raise", "ValueError", "(", "\"Unknown file format '{}'.\"", ".", "format", "(", "ext", ")", ")", "return", "df" ]
Registers the template for the widget and hooks init_template
def _register_template ( cls , template_bytes ) : # This implementation won't work if there are nested templates, but # we can't do that anyways due to PyGObject limitations so it's ok if not hasattr ( cls , 'set_template' ) : raise TypeError ( "Requires PyGObject 3.13.2 or greater" ) cls . set_template ( template_bytes ) bound_methods = set ( ) bound_widgets = set ( ) # Walk the class, find marked callbacks and child attributes for name in dir ( cls ) : o = getattr ( cls , name , None ) if inspect . ismethod ( o ) : if hasattr ( o , '_gtk_callback' ) : bound_methods . add ( name ) # Don't need to call this, as connect_func always gets called #cls.bind_template_callback_full(name, o) elif isinstance ( o , _Child ) : cls . bind_template_child_full ( name , True , 0 ) bound_widgets . add ( name ) # Have to setup a special connect function to connect at template init # because the methods are not bound yet cls . set_connect_func ( _connect_func , cls ) cls . __gtemplate_methods__ = bound_methods cls . __gtemplate_widgets__ = bound_widgets base_init_template = cls . init_template cls . init_template = lambda s : _init_template ( s , cls , base_init_template )
1,503
https://github.com/virtuald/pygi-composite-templates/blob/a22be54ea95b8125b36deaa3ce7171e84158d486/gi_composites.py#L66-L101
[ "def", "dump", "(", "self", ")", ":", "data", "=", "dict", "(", "# Sessions", "sessions_active", "=", "self", ".", "sess_active", ",", "# Connections", "connections_active", "=", "self", ".", "conn_active", ",", "connections_ps", "=", "self", ".", "conn_ps", ".", "last_average", ",", "# Packets", "packets_sent_ps", "=", "self", ".", "pack_sent_ps", ".", "last_average", ",", "packets_recv_ps", "=", "self", ".", "pack_recv_ps", ".", "last_average", ")", "for", "k", ",", "v", "in", "self", ".", "sess_transports", ".", "items", "(", ")", ":", "data", "[", "'transp_'", "+", "k", "]", "=", "v", "return", "data" ]
This would be better as an override for Gtk . Widget
def _init_template ( self , cls , base_init_template ) : # TODO: could disallow using a metaclass.. but this is good enough # .. if you disagree, feel free to fix it and issue a PR :) if self . __class__ is not cls : raise TypeError ( "Inheritance from classes with @GtkTemplate decorators " "is not allowed at this time" ) connected_signals = set ( ) self . __connected_template_signals__ = connected_signals base_init_template ( self ) for name in self . __gtemplate_widgets__ : widget = self . get_template_child ( cls , name ) self . __dict__ [ name ] = widget if widget is None : # Bug: if you bind a template child, and one of them was # not present, then the whole template is broken (and # it's not currently possible for us to know which # one is broken either -- but the stderr should show # something useful with a Gtk-CRITICAL message) raise AttributeError ( "A missing child widget was set using " "GtkTemplate.Child and the entire " "template is now broken (widgets: %s)" % ', ' . join ( self . __gtemplate_widgets__ ) ) for name in self . __gtemplate_methods__ . difference ( connected_signals ) : errmsg = ( "Signal '%s' was declared with @GtkTemplate.Callback " + "but was not present in template" ) % name warnings . warn ( errmsg , GtkTemplateWarning )
1,504
https://github.com/virtuald/pygi-composite-templates/blob/a22be54ea95b8125b36deaa3ce7171e84158d486/gi_composites.py#L104-L136
[ "def", "_validate_page", "(", "self", ")", ":", "for", "ocrd_file", "in", "self", ".", "mets", ".", "find_files", "(", "mimetype", "=", "MIMETYPE_PAGE", ",", "local_only", "=", "True", ")", ":", "self", ".", "workspace", ".", "download_file", "(", "ocrd_file", ")", "page_report", "=", "PageValidator", ".", "validate", "(", "ocrd_file", "=", "ocrd_file", ",", "strictness", "=", "self", ".", "page_strictness", ")", "self", ".", "report", ".", "merge_report", "(", "page_report", ")" ]
babel translation token extract function for haml files
def extract_haml ( fileobj , keywords , comment_tags , options ) : import haml from mako import lexer , parsetree from mako . ext . babelplugin import extract_nodes encoding = options . get ( 'input_encoding' , options . get ( 'encoding' , None ) ) template_node = lexer . Lexer ( haml . preprocessor ( fileobj . read ( ) ) , input_encoding = encoding ) . parse ( ) for extracted in extract_nodes ( template_node . get_children ( ) , keywords , comment_tags , options ) : yield extracted
1,505
https://github.com/mikeboers/PyHAML/blob/9ecb7c85349948428474869aad5b8d1c7de8dbed/haml/util.py#L3-L13
[ "def", "checkIsConsistent", "(", "self", ")", ":", "if", "is_an_array", "(", "self", ".", "mask", ")", "and", "self", ".", "mask", ".", "shape", "!=", "self", ".", "data", ".", "shape", ":", "raise", "ConsistencyError", "(", "\"Shape mismatch mask={}, data={}\"", ".", "format", "(", "self", ".", "mask", ".", "shape", "!=", "self", ".", "data", ".", "shape", ")", ")" ]
Given a sequence of AlleleRead objects which are expected to all have the same allele return that allele .
def get_single_allele_from_reads ( allele_reads ) : allele_reads = list ( allele_reads ) if len ( allele_reads ) == 0 : raise ValueError ( "Expected non-empty list of AlleleRead objects" ) seq = allele_reads [ 0 ] . allele if any ( read . allele != seq for read in allele_reads ) : raise ValueError ( "Expected all AlleleRead objects to have same allele '%s', got %s" % ( seq , allele_reads ) ) return seq
1,506
https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/read_helpers.py#L25-L39
[ "def", "_load_managed_entries", "(", "self", ")", ":", "for", "process_name", ",", "process_entry", "in", "context", ".", "process_context", ".", "items", "(", ")", ":", "if", "isinstance", "(", "process_entry", ",", "ManagedProcessEntry", ")", ":", "function", "=", "self", ".", "fire_managed_worker", "else", ":", "self", ".", "logger", ".", "warning", "(", "'Skipping non-managed context entry {0} of type {1}.'", ".", "format", "(", "process_name", ",", "process_entry", ".", "__class__", ".", "__name__", ")", ")", "continue", "try", ":", "self", ".", "_register_process_entry", "(", "process_entry", ",", "function", ")", "except", "Exception", ":", "self", ".", "logger", ".", "error", "(", "'Managed Thread Handler {0} failed to start. Skipping it.'", ".", "format", "(", "process_entry", ".", "key", ")", ",", "exc_info", "=", "True", ")" ]
Return an iterator that yields every node which is a child of this one .
def iter_all_children ( self ) : if self . inline_child : yield self . inline_child for x in self . children : yield x
1,507
https://github.com/mikeboers/PyHAML/blob/9ecb7c85349948428474869aad5b8d1c7de8dbed/haml/nodes.py#L18-L27
[ "def", "_write_cors_configuration", "(", "self", ",", "config", ")", ":", "endpoint", "=", "'/'", ".", "join", "(", "(", "self", ".", "server_url", ",", "'_api'", ",", "'v2'", ",", "'user'", ",", "'config'", ",", "'cors'", ")", ")", "resp", "=", "self", ".", "r_session", ".", "put", "(", "endpoint", ",", "data", "=", "json", ".", "dumps", "(", "config", ",", "cls", "=", "self", ".", "encoder", ")", ",", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", ")", "resp", ".", "raise_for_status", "(", ")", "return", "response_to_json_dict", "(", "resp", ")" ]
Transfer functions may need additional information before the supplied numpy array can be modified in place . For instance transfer functions may have state which needs to be allocated in memory with a certain size . In other cases the transfer function may need to know about the coordinate system associated with the input data .
def initialize ( self , * * kwargs ) : if not set ( kwargs . keys ( ) ) . issuperset ( self . init_keys ) : raise Exception ( "TransferFn needs to be initialized with %s" % ',' . join ( repr ( el ) for el in self . init_keys ) )
1,508
https://github.com/pyviz/imagen/blob/53c5685c880f54b42795964d8db50b02e8590e88/imagen/transferfn/__init__.py#L31-L42
[ "def", "is_expired", "(", "self", ")", ":", "if", "time", ".", "time", "(", ")", "-", "self", ".", "last_ping", ">", "HB_PING_TIME", ":", "self", ".", "ping", "(", ")", "return", "(", "time", ".", "time", "(", ")", "-", "self", ".", "last_pong", ")", ">", "HB_PING_TIME", "+", "HB_PONG_TIME" ]
Temporarily disable plasticity of internal state .
def override_plasticity_state ( self , new_plasticity_state ) : self . _plasticity_setting_stack . append ( self . plastic ) self . plastic = new_plasticity_state
1,509
https://github.com/pyviz/imagen/blob/53c5685c880f54b42795964d8db50b02e8590e88/imagen/transferfn/__init__.py#L70-L85
[ "def", "loadTFRecords", "(", "sc", ",", "input_dir", ",", "binary_features", "=", "[", "]", ")", ":", "import", "tensorflow", "as", "tf", "tfr_rdd", "=", "sc", ".", "newAPIHadoopFile", "(", "input_dir", ",", "\"org.tensorflow.hadoop.io.TFRecordFileInputFormat\"", ",", "keyClass", "=", "\"org.apache.hadoop.io.BytesWritable\"", ",", "valueClass", "=", "\"org.apache.hadoop.io.NullWritable\"", ")", "# infer Spark SQL types from tf.Example", "record", "=", "tfr_rdd", ".", "take", "(", "1", ")", "[", "0", "]", "example", "=", "tf", ".", "train", ".", "Example", "(", ")", "example", ".", "ParseFromString", "(", "bytes", "(", "record", "[", "0", "]", ")", ")", "schema", "=", "infer_schema", "(", "example", ",", "binary_features", ")", "# convert serialized protobuf to tf.Example to Row", "example_rdd", "=", "tfr_rdd", ".", "mapPartitions", "(", "lambda", "x", ":", "fromTFExample", "(", "x", ",", "binary_features", ")", ")", "# create a Spark DataFrame from RDD[Row]", "df", "=", "example_rdd", ".", "toDF", "(", "schema", ")", "# save reference of this dataframe", "loadedDF", "[", "df", "]", "=", "input_dir", "return", "df" ]
Register supported hosts
def register_host ( ) : pyblish . api . register_host ( "hython" ) pyblish . api . register_host ( "hpython" ) pyblish . api . register_host ( "houdini" )
1,510
https://github.com/pyblish/pyblish-houdini/blob/661b08696f04b4c5d8b03aa0c75cba3ca72f1e8d/pyblish_houdini/lib.py#L80-L84
[ "def", "load_plugins", "(", "self", ",", "plugin_class_name", ")", ":", "# imp.findmodule('atomic_reactor') doesn't work", "plugins_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'plugins'", ")", "logger", ".", "debug", "(", "\"loading plugins from dir '%s'\"", ",", "plugins_dir", ")", "files", "=", "[", "os", ".", "path", ".", "join", "(", "plugins_dir", ",", "f", ")", "for", "f", "in", "os", ".", "listdir", "(", "plugins_dir", ")", "if", "f", ".", "endswith", "(", "\".py\"", ")", "]", "if", "self", ".", "plugin_files", ":", "logger", ".", "debug", "(", "\"loading additional plugins from files '%s'\"", ",", "self", ".", "plugin_files", ")", "files", "+=", "self", ".", "plugin_files", "plugin_class", "=", "globals", "(", ")", "[", "plugin_class_name", "]", "plugin_classes", "=", "{", "}", "for", "f", "in", "files", ":", "module_name", "=", "os", ".", "path", ".", "basename", "(", "f", ")", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "# Do not reload plugins", "if", "module_name", "in", "sys", ".", "modules", ":", "f_module", "=", "sys", ".", "modules", "[", "module_name", "]", "else", ":", "try", ":", "logger", ".", "debug", "(", "\"load file '%s'\"", ",", "f", ")", "f_module", "=", "imp", ".", "load_source", "(", "module_name", ",", "f", ")", "except", "(", "IOError", ",", "OSError", ",", "ImportError", ",", "SyntaxError", ")", "as", "ex", ":", "logger", ".", "warning", "(", "\"can't load module '%s': %r\"", ",", "f", ",", "ex", ")", "continue", "for", "name", "in", "dir", "(", "f_module", ")", ":", "binding", "=", "getattr", "(", "f_module", ",", "name", ",", "None", ")", "try", ":", "# if you try to compare binding and PostBuildPlugin, python won't match them", "# if you call this script directly b/c:", "# ! <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class", "# '__main__.PostBuildPlugin'>", "# but", "# <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class", "# 'atomic_reactor.plugin.PostBuildPlugin'>", "is_sub", "=", "issubclass", "(", "binding", ",", "plugin_class", ")", "except", "TypeError", ":", "is_sub", "=", "False", "if", "binding", "and", "is_sub", "and", "plugin_class", ".", "__name__", "!=", "binding", ".", "__name__", ":", "plugin_classes", "[", "binding", ".", "key", "]", "=", "binding", "return", "plugin_classes" ]
Maintain selection during context
def maintained_selection ( ) : previous_selection = hou . selectedNodes ( ) try : yield finally : if previous_selection : for node in previous_selection : node . setSelected ( on = True ) else : for node in previous_selection : node . setSelected ( on = False )
1,511
https://github.com/pyblish/pyblish-houdini/blob/661b08696f04b4c5d8b03aa0c75cba3ca72f1e8d/pyblish_houdini/lib.py#L104-L124
[ "def", "retrieve_trace", "(", "self", ",", "filename", "=", "None", ",", "dir", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "\"applicationTrace\"", ")", "and", "self", ".", "applicationTrace", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"Retrieving PE trace: \"", "+", "self", ".", "applicationTrace", ")", "if", "not", "filename", ":", "filename", "=", "_file_name", "(", "'pe'", ",", "self", ".", "id", ",", "'.trace'", ")", "return", "self", ".", "rest_client", ".", "_retrieve_file", "(", "self", ".", "applicationTrace", ",", "filename", ",", "dir", ",", "'text/plain'", ")", "else", ":", "return", "None" ]
Execute several statements in single DB transaction .
def execute_transaction ( conn , statements : Iterable ) : with conn : with conn . cursor ( ) as cursor : for statement in statements : cursor . execute ( statement ) conn . commit ( )
1,512
https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/sql.py#L10-L17
[ "def", "edit", "(", "self", ",", "data_src", ",", "value", ")", ":", "# check if opening file", "if", "'filename'", "in", "value", ":", "items", "=", "[", "k", "for", "k", ",", "v", "in", "self", ".", "reg", ".", "data_source", ".", "iteritems", "(", ")", "if", "v", "==", "data_src", "]", "self", ".", "reg", ".", "unregister", "(", "items", ")", "# remove items from Registry", "# open file and register new data", "self", ".", "open", "(", "data_src", ",", "value", "[", "'filename'", "]", ",", "value", ".", "get", "(", "'path'", ")", ")", "self", ".", "layer", "[", "data_src", "]", ".", "update", "(", "value", ")" ]
Execute several statements each as a single DB transaction .
def execute_transactions ( conn , statements : Iterable ) : with conn . cursor ( ) as cursor : for statement in statements : try : cursor . execute ( statement ) conn . commit ( ) except psycopg2 . ProgrammingError : conn . rollback ( )
1,513
https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/sql.py#L20-L29
[ "def", "get_summary_page_link", "(", "ifo", ",", "utc_time", ")", ":", "search_form", "=", "search_form_string", "data", "=", "{", "'H1'", ":", "data_h1_string", ",", "'L1'", ":", "data_l1_string", "}", "if", "ifo", "not", "in", "data", ":", "return", "ifo", "else", ":", "# alog format is day-month-year", "alog_utc", "=", "'%02d-%02d-%4d'", "%", "(", "utc_time", "[", "2", "]", ",", "utc_time", "[", "1", "]", ",", "utc_time", "[", "0", "]", ")", "# summary page is exactly the reverse", "ext", "=", "'%4d%02d%02d'", "%", "(", "utc_time", "[", "0", "]", ",", "utc_time", "[", "1", "]", ",", "utc_time", "[", "2", "]", ")", "return_string", "=", "search_form", "%", "(", "ifo", ".", "lower", "(", ")", ",", "ifo", ".", "lower", "(", ")", ",", "alog_utc", ",", "alog_utc", ")", "return", "return_string", "+", "data", "[", "ifo", "]", "%", "ext" ]
Open a connection commit a transaction and close it .
def execute_closing_transaction ( statements : Iterable ) : with closing ( connect ( ) ) as conn : with conn . cursor ( ) as cursor : for statement in statements : cursor . execute ( statement )
1,514
https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/sql.py#L32-L38
[ "def", "Run", "(", "self", ",", "args", ")", ":", "with", "vfs", ".", "VFSOpen", "(", "args", ".", "pathspec", ",", "progress_callback", "=", "self", ".", "Progress", ")", "as", "file_obj", ":", "fingerprinter", "=", "Fingerprinter", "(", "self", ".", "Progress", ",", "file_obj", ")", "response", "=", "rdf_client_action", ".", "FingerprintResponse", "(", ")", "response", ".", "pathspec", "=", "file_obj", ".", "pathspec", "if", "args", ".", "tuples", ":", "tuples", "=", "args", ".", "tuples", "else", ":", "# There are none selected -- we will cover everything", "tuples", "=", "list", "(", ")", "for", "k", "in", "self", ".", "_fingerprint_types", ":", "tuples", ".", "append", "(", "rdf_client_action", ".", "FingerprintTuple", "(", "fp_type", "=", "k", ")", ")", "for", "finger", "in", "tuples", ":", "hashers", "=", "[", "self", ".", "_hash_types", "[", "h", "]", "for", "h", "in", "finger", ".", "hashers", "]", "or", "None", "if", "finger", ".", "fp_type", "in", "self", ".", "_fingerprint_types", ":", "invoke", "=", "self", ".", "_fingerprint_types", "[", "finger", ".", "fp_type", "]", "res", "=", "invoke", "(", "fingerprinter", ",", "hashers", ")", "if", "res", ":", "response", ".", "matching_types", ".", "append", "(", "finger", ".", "fp_type", ")", "else", ":", "raise", "RuntimeError", "(", "\"Encountered unknown fingerprint type. %s\"", "%", "finger", ".", "fp_type", ")", "# Structure of the results is a list of dicts, each containing the", "# name of the hashing method, hashes for enabled hash algorithms,", "# and auxilliary data where present (e.g. signature blobs).", "# Also see Fingerprint:HashIt()", "response", ".", "results", "=", "fingerprinter", ".", "HashIt", "(", ")", "# We now return data in a more structured form.", "for", "result", "in", "response", ".", "results", ":", "if", "result", ".", "GetItem", "(", "\"name\"", ")", "==", "\"generic\"", ":", "for", "hash_type", "in", "[", "\"md5\"", ",", "\"sha1\"", ",", "\"sha256\"", "]", ":", "value", "=", "result", ".", "GetItem", "(", "hash_type", ")", "if", "value", "is", "not", "None", ":", "setattr", "(", "response", ".", "hash", ",", "hash_type", ",", "value", ")", "if", "result", "[", "\"name\"", "]", "==", "\"pecoff\"", ":", "for", "hash_type", "in", "[", "\"md5\"", ",", "\"sha1\"", ",", "\"sha256\"", "]", ":", "value", "=", "result", ".", "GetItem", "(", "hash_type", ")", "if", "value", ":", "setattr", "(", "response", ".", "hash", ",", "\"pecoff_\"", "+", "hash_type", ",", "value", ")", "signed_data", "=", "result", ".", "GetItem", "(", "\"SignedData\"", ",", "[", "]", ")", "for", "data", "in", "signed_data", ":", "response", ".", "hash", ".", "signed_data", ".", "Append", "(", "revision", "=", "data", "[", "0", "]", ",", "cert_type", "=", "data", "[", "1", "]", ",", "certificate", "=", "data", "[", "2", "]", ")", "self", ".", "SendReply", "(", "response", ")" ]
Return a select statement s results as a namedtuple .
def select ( conn , query : str , params = None , name = None , itersize = 5000 ) : with conn . cursor ( name , cursor_factory = NamedTupleCursor ) as cursor : cursor . itersize = itersize cursor . execute ( query , params ) for result in cursor : yield result
1,515
https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/sql.py#L41-L58
[ "def", "atlas_peer_has_zonefile", "(", "peer_hostport", ",", "zonefile_hash", ",", "zonefile_bits", "=", "None", ",", "con", "=", "None", ",", "path", "=", "None", ",", "peer_table", "=", "None", ")", ":", "bits", "=", "None", "if", "zonefile_bits", "is", "None", ":", "bits", "=", "atlasdb_get_zonefile_bits", "(", "zonefile_hash", ",", "con", "=", "con", ",", "path", "=", "path", ")", "if", "len", "(", "bits", ")", "==", "0", ":", "return", "None", "else", ":", "bits", "=", "zonefile_bits", "zonefile_inv", "=", "None", "with", "AtlasPeerTableLocked", "(", "peer_table", ")", "as", "ptbl", ":", "if", "peer_hostport", "not", "in", "ptbl", ".", "keys", "(", ")", ":", "return", "False", "zonefile_inv", "=", "atlas_peer_get_zonefile_inventory", "(", "peer_hostport", ",", "peer_table", "=", "ptbl", ")", "res", "=", "atlas_inventory_test_zonefile_bits", "(", "zonefile_inv", ",", "bits", ")", "return", "res" ]
Return a select statement s results as dictionary .
def select_dict ( conn , query : str , params = None , name = None , itersize = 5000 ) : with conn . cursor ( name , cursor_factory = RealDictCursor ) as cursor : cursor . itersize = itersize cursor . execute ( query , params ) for result in cursor : yield result
1,516
https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/sql.py#L61-L78
[ "def", "_file_watcher", "(", "state", ")", ":", "conf", "=", "state", ".", "app", ".", "config", "file_path", "=", "conf", ".", "get", "(", "'WAFFLE_WATCHER_FILE'", ",", "'/tmp/waffleconf.txt'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "# Create watch file", "open", "(", "file_path", ",", "'a'", ")", ".", "close", "(", ")", "while", "True", ":", "tstamp", "=", "os", ".", "path", ".", "getmtime", "(", "file_path", ")", "# Compare timestamps and update config if needed", "if", "tstamp", ">", "state", ".", "_tstamp", ":", "state", ".", "update_conf", "(", ")", "state", ".", "_tstamp", "=", "tstamp", "# Not too critical", "time", ".", "sleep", "(", "10", ")" ]
Run select query for each parameter set in single transaction .
def select_each ( conn , query : str , parameter_groups , name = None ) : with conn : with conn . cursor ( name = name ) as cursor : for parameters in parameter_groups : cursor . execute ( query , parameters ) yield cursor . fetchone ( )
1,517
https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/sql.py#L81-L88
[ "def", "GetAttachmentIdFromMediaId", "(", "media_id", ")", ":", "altchars", "=", "'+-'", "if", "not", "six", ".", "PY2", ":", "altchars", "=", "altchars", ".", "encode", "(", "'utf-8'", ")", "# altchars for '+' and '/'. We keep '+' but replace '/' with '-'", "buffer", "=", "base64", ".", "b64decode", "(", "str", "(", "media_id", ")", ",", "altchars", ")", "resoure_id_length", "=", "20", "attachment_id", "=", "''", "if", "len", "(", "buffer", ")", ">", "resoure_id_length", ":", "# We are cutting off the storage index.", "attachment_id", "=", "base64", ".", "b64encode", "(", "buffer", "[", "0", ":", "resoure_id_length", "]", ",", "altchars", ")", "if", "not", "six", ".", "PY2", ":", "attachment_id", "=", "attachment_id", ".", "decode", "(", "'utf-8'", ")", "else", ":", "attachment_id", "=", "media_id", "return", "attachment_id" ]
Lightweight query to retrieve column list of select query .
def query_columns ( conn , query , name = None ) : with conn . cursor ( name ) as cursor : cursor . itersize = 1 cursor . execute ( query ) cursor . fetchmany ( 0 ) column_names = [ column . name for column in cursor . description ] return column_names
1,518
https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/sql.py#L91-L105
[ "def", "set_bounds", "(", "self", ",", "lb", ",", "ub", ")", ":", "if", "lb", "is", "not", "None", "and", "ub", "is", "not", "None", "and", "lb", ">", "ub", ":", "raise", "ValueError", "(", "\"The provided lower bound {} is larger than the provided upper bound {}\"", ".", "format", "(", "lb", ",", "ub", ")", ")", "self", ".", "_lb", "=", "lb", "self", ".", "_ub", "=", "ub", "if", "self", ".", "problem", "is", "not", "None", ":", "self", ".", "problem", ".", "_pending_modifications", ".", "var_lb", ".", "append", "(", "(", "self", ",", "lb", ")", ")", "self", ".", "problem", ".", "_pending_modifications", ".", "var_ub", ".", "append", "(", "(", "self", ",", "ub", ")", ")" ]
Extracts the reference sequence around a variant locus on a particular transcript and determines the reading frame at the start of that sequence context .
def from_variant_and_transcript ( cls , variant , transcript , context_size ) : if not transcript . contains_start_codon : logger . info ( "Expected transcript %s for variant %s to have start codon" , transcript . name , variant ) return None if not transcript . contains_stop_codon : logger . info ( "Expected transcript %s for variant %s to have stop codon" , transcript . name , variant ) return None if not transcript . protein_sequence : logger . info ( "Expected transript %s for variant %s to have protein sequence" , transcript . name , variant ) return None sequence_key = ReferenceSequenceKey . from_variant_and_transcript ( variant = variant , transcript = transcript , context_size = context_size ) if sequence_key is None : logger . info ( "No sequence key for variant %s on transcript %s" , variant , transcript . name ) return None return cls . from_variant_and_transcript_and_sequence_key ( variant = variant , transcript = transcript , sequence_key = sequence_key )
1,519
https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/reference_coding_sequence_key.py#L150-L207
[ "def", "pop_messages", "(", "self", ",", "type", "=", "None", ")", ":", "key", "=", "self", ".", "_msg_key", "messages", "=", "[", "]", "if", "type", "is", "None", ":", "messages", "=", "self", ".", "pop", "(", "key", ",", "[", "]", ")", "else", ":", "keep_messages", "=", "[", "]", "for", "msg", "in", "self", ".", "get", "(", "key", ",", "[", "]", ")", ":", "if", "msg", ".", "type", "==", "type", ":", "messages", ".", "append", "(", "msg", ")", "else", ":", "keep_messages", ".", "append", "(", "msg", ")", "if", "not", "keep_messages", "and", "key", "in", "self", ":", "del", "self", "[", "key", "]", "else", ":", "self", "[", "key", "]", "=", "keep_messages", "if", "messages", ":", "self", ".", "save", "(", ")", "return", "messages" ]
Try to convert content of README . md into rst format using pypandoc write it into README and return it .
def create_readme_with_long_description ( ) : this_dir = os . path . abspath ( os . path . dirname ( __file__ ) ) readme_md = os . path . join ( this_dir , 'README.md' ) readme = os . path . join ( this_dir , 'README' ) if os . path . exists ( readme_md ) : # this is the case when running `python setup.py sdist` if os . path . exists ( readme ) : os . remove ( readme ) try : import pypandoc long_description = pypandoc . convert ( readme_md , 'rst' , format = 'md' ) except ( ImportError ) : with open ( readme_md , encoding = 'utf-8' ) as in_ : long_description = in_ . read ( ) with open ( readme , 'w' ) as out : out . write ( long_description ) else : # this is in case of `pip install fabsetup-x.y.z.tar.gz` with open ( readme , encoding = 'utf-8' ) as in_ : long_description = in_ . read ( ) return long_description
1,520
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/setup.py#L13-L44
[ "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" ]
Print download statistics for a package .
def stat ( package , graph ) : client = requests . Session ( ) for name_or_url in package : package = get_package ( name_or_url , client ) if not package : secho ( u'Invalid name or URL: "{name}"' . format ( name = name_or_url ) , fg = 'red' , file = sys . stderr ) continue try : version_downloads = package . version_downloads except NotFoundError : secho ( u'No versions found for "{0}". ' u'Skipping. . .' . format ( package . name ) , fg = 'red' , file = sys . stderr ) continue echo ( u"Fetching statistics for '{url}'. . ." . format ( url = package . package_url ) ) min_ver , min_downloads = package . min_version max_ver , max_downloads = package . max_version if min_ver is None or max_ver is None : raise click . ClickException ( 'Package has no releases' ) avg_downloads = package . average_downloads total = package . downloads echo ( ) header = u'Download statistics for {name}' . format ( name = package . name ) echo_header ( header ) if graph : echo ( ) echo ( 'Downloads by version' ) echo ( package . chart ( ) ) echo ( ) echo ( "Min downloads: {min_downloads:12,} ({min_ver})" . format ( * * locals ( ) ) ) echo ( "Max downloads: {max_downloads:12,} ({max_ver})" . format ( * * locals ( ) ) ) echo ( "Avg downloads: {avg_downloads:12,}" . format ( * * locals ( ) ) ) echo ( "Total downloads: {total:12,}" . format ( * * locals ( ) ) ) echo ( ) echo_download_summary ( package ) echo ( )
1,521
https://github.com/sloria/pypi-cli/blob/beb007bf2bdd285209876ce2758982b5d8b54d5d/pypi_cli.py#L97-L143
[ "async", "def", "create", "(", "self", ",", "config", ":", "dict", "=", "None", ",", "access", ":", "str", "=", "None", ",", "replace", ":", "bool", "=", "False", ")", "->", "Wallet", ":", "LOGGER", ".", "debug", "(", "'WalletManager.create >>> config %s, access %s, replace %s'", ",", "config", ",", "access", ",", "replace", ")", "assert", "{", "'name'", ",", "'id'", "}", "&", "{", "k", "for", "k", "in", "config", "}", "wallet_name", "=", "config", ".", "get", "(", "'name'", ",", "config", ".", "get", "(", "'id'", ")", ")", "if", "replace", ":", "von_wallet", "=", "self", ".", "get", "(", "config", ",", "access", ")", "if", "not", "await", "von_wallet", ".", "remove", "(", ")", ":", "LOGGER", ".", "debug", "(", "'WalletManager.create <!< Failed to remove wallet %s for replacement'", ",", "wallet_name", ")", "raise", "ExtantWallet", "(", "'Failed to remove wallet {} for replacement'", ".", "format", "(", "wallet_name", ")", ")", "indy_config", "=", "self", ".", "_config2indy", "(", "config", ")", "von_config", "=", "self", ".", "_config2von", "(", "config", ",", "access", ")", "rv", "=", "Wallet", "(", "indy_config", ",", "von_config", ")", "await", "rv", ".", "create", "(", ")", "LOGGER", ".", "debug", "(", "'WalletManager.create <<< %s'", ",", "rv", ")", "return", "rv" ]
Browse to a package s PyPI or project homepage .
def browse ( package , homepage ) : p = Package ( package ) try : if homepage : secho ( u'Opening homepage for "{0}"...' . format ( package ) , bold = True ) url = p . home_page else : secho ( u'Opening PyPI page for "{0}"...' . format ( package ) , bold = True ) url = p . package_url except NotFoundError : abort_not_found ( package ) click . launch ( url )
1,522
https://github.com/sloria/pypi-cli/blob/beb007bf2bdd285209876ce2758982b5d8b54d5d/pypi_cli.py#L157-L169
[ "def", "parse", "(", "self", ",", "commands", ")", ":", "# Get rid of dummy objects that represented deleted objects in", "# the last parsing round.", "to_delete", "=", "[", "]", "for", "id_", ",", "val", "in", "self", ".", "_objects", ".", "items", "(", ")", ":", "if", "val", "==", "JUST_DELETED", ":", "to_delete", ".", "append", "(", "id_", ")", "for", "id_", "in", "to_delete", ":", "self", ".", "_objects", ".", "pop", "(", "id_", ")", "for", "command", "in", "commands", ":", "self", ".", "_parse", "(", "command", ")" ]
Search for a pypi package .
def search ( query , n_results , web ) : if web : secho ( u'Opening search page for "{0}"...' . format ( query ) , bold = True ) url = SEARCH_URL . format ( query = urlquote ( query ) ) click . launch ( url ) else : searcher = Searcher ( ) results = searcher . search ( query , n = n_results ) first_line = style ( u'Search results for "{0}"\n' . format ( query ) , bold = True ) echo_via_pager ( first_line + '\n' . join ( [ format_result ( result ) for result in results ] ) )
1,523
https://github.com/sloria/pypi-cli/blob/beb007bf2bdd285209876ce2758982b5d8b54d5d/pypi_cli.py#L192-L216
[ "def", "_load_feed", "(", "path", ":", "str", ",", "view", ":", "View", ",", "config", ":", "nx", ".", "DiGraph", ")", "->", "Feed", ":", "config_", "=", "remove_node_attributes", "(", "config", ",", "[", "\"converters\"", ",", "\"transformations\"", "]", ")", "feed_", "=", "Feed", "(", "path", ",", "view", "=", "{", "}", ",", "config", "=", "config_", ")", "for", "filename", ",", "column_filters", "in", "view", ".", "items", "(", ")", ":", "config_", "=", "reroot_graph", "(", "config_", ",", "filename", ")", "view_", "=", "{", "filename", ":", "column_filters", "}", "feed_", "=", "Feed", "(", "feed_", ",", "view", "=", "view_", ",", "config", "=", "config_", ")", "return", "Feed", "(", "feed_", ",", "config", "=", "config", ")" ]
Get info about a package or packages .
def info ( package , long_description , classifiers , license ) : client = requests . Session ( ) for name_or_url in package : package = get_package ( name_or_url , client ) if not package : secho ( u'Invalid name or URL: "{name}"' . format ( name = name_or_url ) , fg = 'red' , file = sys . stderr ) continue # Name and summary try : info = package . data [ 'info' ] except NotFoundError : secho ( u'No versions found for "{0}". ' u'Skipping. . .' . format ( package . name ) , fg = 'red' , file = sys . stderr ) continue echo_header ( name_or_url ) if package . summary : echo ( package . summary ) # Version info echo ( ) echo ( 'Latest release: {version:12}' . format ( version = info [ 'version' ] ) ) # Long description if long_description : echo ( ) echo ( package . description ) # Download info echo ( ) echo_download_summary ( package ) # Author info echo ( ) author , author_email = package . author , package . author_email if author : echo ( u'Author: {author:12}' . format ( * * locals ( ) ) ) if author_email : echo ( u'Author email: {author_email:12}' . format ( * * locals ( ) ) ) # Maintainer info maintainer , maintainer_email = ( package . maintainer , package . maintainer_email ) if maintainer or maintainer_email : echo ( ) if maintainer : echo ( u'Maintainer: {maintainer:12}' . format ( * * locals ( ) ) ) if maintainer_email : echo ( u'Maintainer email: {maintainer_email:12}' . format ( * * locals ( ) ) ) # URLS echo ( ) echo ( u'PyPI URL: {pypi_url:12}' . format ( pypi_url = package . package_url ) ) if package . home_page : echo ( u'Home Page: {home_page:12}' . format ( home_page = package . home_page ) ) if package . docs_url : echo ( u'Documentation: {docs_url:12}' . format ( docs_url = package . docs_url ) ) # Classifiers if classifiers : echo ( ) echo ( u'Classifiers: ' ) for each in info . get ( 'classifiers' , [ ] ) : echo ( '\t' + each ) if license and package . license : echo ( ) echo ( u'License: ' , nl = False ) # license may be just a name, e.g. 'BSD' or the full license text # If a new line is found in the text, print a new line if package . license . find ( '\n' ) >= 0 or len ( package . license ) > 80 : echo ( ) echo ( package . license ) echo ( )
1,524
https://github.com/sloria/pypi-cli/blob/beb007bf2bdd285209876ce2758982b5d8b54d5d/pypi_cli.py#L227-L306
[ "def", "__get_vibration_code", "(", "self", ",", "left_motor", ",", "right_motor", ",", "duration", ")", ":", "inner_event", "=", "struct", ".", "pack", "(", "'2h6x2h2x2H28x'", ",", "0x50", ",", "-", "1", ",", "duration", ",", "0", ",", "int", "(", "left_motor", "*", "65535", ")", ",", "int", "(", "right_motor", "*", "65535", ")", ")", "buf_conts", "=", "ioctl", "(", "self", ".", "_write_device", ",", "1076905344", ",", "inner_event", ")", "return", "int", "(", "codecs", ".", "encode", "(", "buf_conts", "[", "1", ":", "3", "]", ",", "'hex'", ")", ",", "16", ")" ]
Return a bar graph as a string given a dictionary of data .
def bargraph ( data , max_key_width = 30 ) : lines = [ ] max_length = min ( max ( len ( key ) for key in data . keys ( ) ) , max_key_width ) max_val = max ( data . values ( ) ) max_val_length = max ( len ( _style_value ( val ) ) for val in data . values ( ) ) term_width = get_terminal_size ( ) [ 0 ] max_bar_width = term_width - MARGIN - ( max_length + 3 + max_val_length + 3 ) template = u"{key:{key_width}} [ {value:{val_width}} ] {bar}" for key , value in data . items ( ) : try : bar = int ( math . ceil ( max_bar_width * value / max_val ) ) * TICK except ZeroDivisionError : bar = '' line = template . format ( key = key [ : max_length ] , value = _style_value ( value ) , bar = bar , key_width = max_length , val_width = max_val_length ) lines . append ( line ) return '\n' . join ( lines )
1,525
https://github.com/sloria/pypi-cli/blob/beb007bf2bdd285209876ce2758982b5d8b54d5d/pypi_cli.py#L328-L352
[ "def", "check_for_expire_acknowledge", "(", "self", ")", ":", "if", "(", "self", ".", "acknowledgement", "and", "self", ".", "acknowledgement", ".", "end_time", "!=", "0", "and", "self", ".", "acknowledgement", ".", "end_time", "<", "time", ".", "time", "(", ")", ")", ":", "self", ".", "unacknowledge_problem", "(", ")" ]
Version with the most downloads .
def max_version ( self ) : data = self . version_downloads if not data : return None , 0 return max ( data . items ( ) , key = lambda item : item [ 1 ] )
1,526
https://github.com/sloria/pypi-cli/blob/beb007bf2bdd285209876ce2758982b5d8b54d5d/pypi_cli.py#L440-L448
[ "def", "__dump_validators", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_validators'", ")", ":", "validators_json", "=", "[", "]", "for", "validator", "in", "self", ".", "_validators", ":", "if", "isinstance", "(", "validator", ",", "PropertyValidator", ")", ":", "validators_json", ".", "append", "(", "validator", ".", "as_json", "(", ")", ")", "else", ":", "raise", "APIError", "(", "\"validator is not a PropertyValidator: '{}'\"", ".", "format", "(", "validator", ")", ")", "if", "self", ".", "_options", ".", "get", "(", "'validators'", ",", "list", "(", ")", ")", "==", "validators_json", ":", "# no change", "pass", "else", ":", "new_options", "=", "self", ".", "_options", ".", "copy", "(", ")", "# make a copy", "new_options", ".", "update", "(", "{", "'validators'", ":", "validators_json", "}", ")", "validate", "(", "new_options", ",", "options_json_schema", ")", "self", ".", "_options", "=", "new_options" ]
Version with the fewest downloads .
def min_version ( self ) : data = self . version_downloads if not data : return ( None , 0 ) return min ( data . items ( ) , key = lambda item : item [ 1 ] )
1,527
https://github.com/sloria/pypi-cli/blob/beb007bf2bdd285209876ce2758982b5d8b54d5d/pypi_cli.py#L451-L456
[ "def", "restore_type", "(", "self", ",", "type", ")", ":", "# All dialects", "mapping", "=", "{", "ARRAY", ":", "'array'", ",", "sa", ".", "Boolean", ":", "'boolean'", ",", "sa", ".", "Date", ":", "'date'", ",", "sa", ".", "DateTime", ":", "'datetime'", ",", "sa", ".", "Float", ":", "'number'", ",", "sa", ".", "Integer", ":", "'integer'", ",", "JSONB", ":", "'object'", ",", "JSON", ":", "'object'", ",", "sa", ".", "Numeric", ":", "'number'", ",", "sa", ".", "Text", ":", "'string'", ",", "sa", ".", "Time", ":", "'time'", ",", "sa", ".", "VARCHAR", ":", "'string'", ",", "UUID", ":", "'string'", ",", "}", "# Get field type", "field_type", "=", "None", "for", "key", ",", "value", "in", "mapping", ".", "items", "(", ")", ":", "if", "isinstance", "(", "type", ",", "key", ")", ":", "field_type", "=", "value", "# Not supported", "if", "field_type", "is", "None", ":", "message", "=", "'Type \"%s\" is not supported'", "raise", "tableschema", ".", "exceptions", ".", "StorageError", "(", "message", "%", "type", ")", "return", "field_type" ]
Install the tools ripit and burnit in order to rip and burn audio cds .
def ripping_of_cds ( ) : # install and configure ripit install_package ( 'ripit' ) install_file_legacy ( path = '~/.ripit/config' , username = env . user ) # install burnit run ( 'mkdir -p ~/bin' ) install_file_legacy ( '~/bin/burnit' ) run ( 'chmod 755 ~/bin/burnit' )
1,528
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/__init__.py#L34-L45
[ "def", "sync", "(", "self", ")", ":", "if", "self", ".", "writeback", "and", "self", ".", "cache", ":", "super", "(", "_TimeoutMixin", ",", "self", ")", ".", "__delitem__", "(", "self", ".", "_INDEX", ")", "super", "(", "_TimeoutMixin", ",", "self", ")", ".", "sync", "(", ")", "self", ".", "writeback", "=", "False", "super", "(", "_TimeoutMixin", ",", "self", ")", ".", "__setitem__", "(", "self", ".", "_INDEX", ",", "self", ".", "_index", ")", "self", ".", "writeback", "=", "True", "if", "hasattr", "(", "self", ".", "dict", ",", "'sync'", ")", ":", "self", ".", "dict", ".", "sync", "(", ")" ]
Install and customize the tiling window manager i3 .
def i3 ( ) : install_package ( 'i3' ) install_file_legacy ( path = '~/.i3/config' , username = env . user , repos_dir = 'repos' ) # setup: hide the mouse if not in use # in ~/.i3/config: 'exec /home/<USERNAME>/repos/hhpc/hhpc -i 10 &' install_packages ( [ 'make' , 'pkg-config' , 'gcc' , 'libc6-dev' , 'libx11-dev' ] ) checkup_git_repo_legacy ( url = 'https://github.com/aktau/hhpc.git' ) run ( 'cd ~/repos/hhpc && make' )
1,529
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/__init__.py#L78-L87
[ "def", "send_request_if_needed", "(", "request", ",", "relation", "=", "'ceph'", ")", ":", "if", "is_request_sent", "(", "request", ",", "relation", "=", "relation", ")", ":", "log", "(", "'Request already sent but not complete, not sending new request'", ",", "level", "=", "DEBUG", ")", "else", ":", "for", "rid", "in", "relation_ids", "(", "relation", ")", ":", "log", "(", "'Sending request {}'", ".", "format", "(", "request", ".", "request_id", ")", ",", "level", "=", "DEBUG", ")", "relation_set", "(", "relation_id", "=", "rid", ",", "broker_req", "=", "request", ".", "request", ")" ]
Set solarized colors in urxvt tmux and vim .
def solarized ( ) : install_packages ( [ 'rxvt-unicode' , 'tmux' , 'vim' ] ) install_file_legacy ( '~/.Xresources' ) if env . host_string == 'localhost' : run ( 'xrdb ~/.Xresources' ) # install and call term_colors run ( 'mkdir -p ~/bin' ) install_file_legacy ( '~/bin/term_colors' ) run ( 'chmod 755 ~/bin/term_colors' ) run ( '~/bin/term_colors' )
1,530
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/__init__.py#L92-L117
[ "def", "getTimeOfClassesRemaining", "(", "self", ",", "numClasses", "=", "0", ")", ":", "occurrences", "=", "EventOccurrence", ".", "objects", ".", "filter", "(", "cancelled", "=", "False", ",", "event__in", "=", "[", "x", ".", "event", "for", "x", "in", "self", ".", "temporaryeventregistration_set", ".", "filter", "(", "event__series__isnull", "=", "False", ")", "]", ",", ")", ".", "order_by", "(", "'-endTime'", ")", "if", "occurrences", ".", "count", "(", ")", ">", "numClasses", ":", "return", "occurrences", "[", "numClasses", "]", ".", "endTime", "else", ":", "return", "occurrences", ".", "last", "(", ")", ".", "startTime" ]
Customize vim install package manager pathogen and some vim - packages .
def vim ( ) : install_package ( 'vim' ) print_msg ( '## install ~/.vimrc\n' ) install_file_legacy ( '~/.vimrc' ) print_msg ( '\n## set up pathogen\n' ) run ( 'mkdir -p ~/.vim/autoload ~/.vim/bundle' ) checkup_git_repo_legacy ( url = 'https://github.com/tpope/vim-pathogen.git' ) run ( 'ln -snf ~/repos/vim-pathogen/autoload/pathogen.vim ' '~/.vim/autoload/pathogen.vim' ) print_msg ( '\n## install vim packages\n' ) install_package ( 'ctags' ) # required by package tagbar repos = [ { 'name' : 'vim-colors-solarized' , 'url' : 'git://github.com/altercation/vim-colors-solarized.git' , } , { 'name' : 'nerdtree' , 'url' : 'https://github.com/scrooloose/nerdtree.git' , } , { 'name' : 'vim-nerdtree-tabs' , 'url' : 'https://github.com/jistr/vim-nerdtree-tabs.git' , } , { 'name' : 'tagbar' , 'url' : 'https://github.com/majutsushi/tagbar.git' , } , ] checkup_git_repos_legacy ( repos , base_dir = '~/.vim/bundle' )
1,531
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/__init__.py#L122-L167
[ "def", "read_tabular", "(", "filename", ",", "dtype_conversion", "=", "None", ")", ":", "if", "dtype_conversion", "is", "None", ":", "dtype_conversion", "=", "{", "}", "name", ",", "ext", "=", "filename", ".", "split", "(", "\".\"", ",", "1", ")", "ext", "=", "ext", ".", "lower", "(", ")", "# Completely empty columns are interpreted as float by default.", "dtype_conversion", "[", "\"comment\"", "]", "=", "str", "if", "\"csv\"", "in", "ext", ":", "df", "=", "pd", ".", "read_csv", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "elif", "\"tsv\"", "in", "ext", ":", "df", "=", "pd", ".", "read_table", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "elif", "\"xls\"", "in", "ext", "or", "\"xlsx\"", "in", "ext", ":", "df", "=", "pd", ".", "read_excel", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "# TODO: Add a function to parse ODS data into a pandas data frame.", "else", ":", "raise", "ValueError", "(", "\"Unknown file format '{}'.\"", ".", "format", "(", "ext", ")", ")", "return", "df" ]
Install or update the pyenv python environment .
def pyenv ( ) : install_packages ( [ 'make' , 'build-essential' , 'libssl-dev' , 'zlib1g-dev' , 'libbz2-dev' , 'libreadline-dev' , 'libsqlite3-dev' , 'wget' , 'curl' , 'llvm' , 'libncurses5-dev' , 'libncursesw5-dev' , ] ) if exists ( '~/.pyenv' ) : run ( 'cd ~/.pyenv && git pull' ) run ( '~/.pyenv/bin/pyenv update' ) else : run ( 'curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/' 'master/bin/pyenv-installer | bash' ) # add pyenv to $PATH and set up pyenv init bash_snippet = '~/.bashrc_pyenv' install_file_legacy ( path = bash_snippet ) prefix = flo ( 'if [ -f {bash_snippet} ]; ' ) enabler = flo ( 'if [ -f {bash_snippet} ]; then source {bash_snippet}; fi' ) if env . host == 'localhost' : # FIXME: next function currently only works for localhost uncomment_or_update_or_append_line ( filename = '~/.bashrc' , prefix = prefix , new_line = enabler ) else : print ( cyan ( '\nappend to ~/.bashrc:\n\n ' ) + enabler )
1,532
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/__init__.py#L172-L215
[ "def", "union", "(", "self", ",", "*", "dstreams", ")", ":", "if", "not", "dstreams", ":", "raise", "ValueError", "(", "\"should have at least one DStream to union\"", ")", "if", "len", "(", "dstreams", ")", "==", "1", ":", "return", "dstreams", "[", "0", "]", "if", "len", "(", "set", "(", "s", ".", "_jrdd_deserializer", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same serializer\"", ")", "if", "len", "(", "set", "(", "s", ".", "_slideDuration", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same slide duration\"", ")", "cls", "=", "SparkContext", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "streaming", ".", "api", ".", "java", ".", "JavaDStream", "jdstreams", "=", "SparkContext", ".", "_gateway", ".", "new_array", "(", "cls", ",", "len", "(", "dstreams", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "dstreams", ")", ")", ":", "jdstreams", "[", "i", "]", "=", "dstreams", "[", "i", "]", ".", "_jdstream", "return", "DStream", "(", "self", ".", "_jssc", ".", "union", "(", "jdstreams", ")", ",", "self", ",", "dstreams", "[", "0", "]", ".", "_jrdd_deserializer", ")" ]
Install a VirtualBox host system .
def virtualbox_host ( ) : if query_yes_no ( question = 'Uninstall virtualbox-dkms?' , default = 'yes' ) : run ( 'sudo apt-get remove virtualbox-dkms' ) install_packages ( [ 'virtualbox' , 'virtualbox-qt' , 'virtualbox-dkms' , 'virtualbox-guest-dkms' , 'virtualbox-guest-additions-iso' , ] ) users = [ env . user ] for username in users : run ( flo ( 'sudo adduser {username} vboxusers' ) )
1,533
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/__init__.py#L220-L238
[ "def", "generate_filename", "(", "self", ",", "mark", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "kwargs", ".", "copy", "(", ")", "kwargs", "[", "'opacity'", "]", "=", "int", "(", "kwargs", "[", "'opacity'", "]", "*", "100", ")", "kwargs", "[", "'st_mtime'", "]", "=", "kwargs", "[", "'fstat'", "]", ".", "st_mtime", "kwargs", "[", "'st_size'", "]", "=", "kwargs", "[", "'fstat'", "]", ".", "st_size", "params", "=", "[", "'%(original_basename)s'", ",", "'wm'", ",", "'w%(watermark)i'", ",", "'o%(opacity)i'", ",", "'gs%(greyscale)i'", ",", "'r%(rotation)i'", ",", "'fm%(st_mtime)i'", ",", "'fz%(st_size)i'", ",", "'p%(position)s'", ",", "]", "scale", "=", "kwargs", ".", "get", "(", "'scale'", ",", "None", ")", "if", "scale", "and", "scale", "!=", "mark", ".", "size", ":", "params", ".", "append", "(", "'_s%i'", "%", "(", "float", "(", "kwargs", "[", "'scale'", "]", "[", "0", "]", ")", "/", "mark", ".", "size", "[", "0", "]", "*", "100", ")", ")", "if", "kwargs", ".", "get", "(", "'tile'", ",", "None", ")", ":", "params", ".", "append", "(", "'_tiled'", ")", "# make thumbnail filename", "filename", "=", "'%s%s'", "%", "(", "'_'", ".", "join", "(", "params", ")", ",", "kwargs", "[", "'ext'", "]", ")", "return", "filename", "%", "kwargs" ]
Install or update latest Pencil version 2 a GUI prototyping tool .
def pencil2 ( ) : repo_name = 'pencil2' repo_dir = flo ( '~/repos/{repo_name}' ) print_msg ( '## fetch latest pencil\n' ) checkup_git_repo_legacy ( url = 'https://github.com/prikhi/pencil.git' , name = repo_name ) print_msg ( '\n## build properties\n' ) update_or_append_line ( flo ( '{repo_dir}/build/properties.sh' ) , prefix = 'export MAX_VERSION=' , new_line = "export MAX_VERSION='100.*'" ) run ( flo ( 'cat {repo_dir}/build/properties.sh' ) ) run ( flo ( 'cd {repo_dir}/build && ./build.sh linux' ) , msg = '\n## build pencil\n' ) install_user_command_legacy ( 'pencil2' , pencil2_repodir = repo_dir ) print_msg ( '\nNow You can start pencil version 2 with this command:\n\n' ' pencil2' )
1,534
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/__init__.py#L277-L304
[ "def", "prevmonday", "(", "num", ")", ":", "today", "=", "get_today", "(", ")", "lastmonday", "=", "today", "-", "timedelta", "(", "days", "=", "today", ".", "weekday", "(", ")", ",", "weeks", "=", "num", ")", "return", "lastmonday" ]
Install or update latest Pencil version 3 a GUI prototyping tool .
def pencil3 ( ) : repo_name = 'pencil3' repo_dir = flo ( '~/repos/{repo_name}' ) print_msg ( '## fetch latest pencil\n' ) checkup_git_repo_legacy ( url = 'https://github.com/evolus/pencil.git' , name = repo_name ) run ( flo ( 'cd {repo_dir} && npm install' ) , msg = '\n## install npms\n' ) install_user_command_legacy ( 'pencil3' , pencil3_repodir = repo_dir ) print_msg ( '\nNow You can start pencil version 3 with this command:\n\n' ' pencil3' )
1,535
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/__init__.py#L309-L328
[ "def", "set_response_cookie", "(", "response", ",", "cookie_name", ",", "cookie_value", ")", ":", "now", "=", "timezone", ".", "now", "(", ")", "expire_date", "=", "now", "+", "datetime", ".", "timedelta", "(", "days", "=", "365", ")", "response", ".", "set_cookie", "(", "cookie_name", ",", "cookie_value", ",", "expires", "=", "expire_date", ")" ]
Install and set up powerline - shell prompt .
def powerline_shell ( ) : assert env . host == 'localhost' , 'This task cannot run on a remote host' # set up fonts for powerline checkup_git_repo_legacy ( 'https://github.com/powerline/fonts.git' , name = 'powerline-fonts' ) run ( 'cd ~/repos/powerline-fonts && ./install.sh' ) # run('fc-cache -vf ~/.local/share/fonts') prefix = 'URxvt*font: ' from config import fontlist line = prefix + fontlist update_or_append_line ( filename = '~/.Xresources' , prefix = prefix , new_line = line ) if env . host_string == 'localhost' : run ( 'xrdb ~/.Xresources' ) # set up powerline-shell checkup_git_repo_legacy ( 'https://github.com/banga/powerline-shell.git' ) # checkup_git_repo_legacy('https://github.com/ohnonot/powerline-shell.git') install_file_legacy ( path = '~/repos/powerline-shell/config.py' ) run ( 'cd ~/repos/powerline-shell && ./install.py' ) question = 'Use normal question mark (u003F) for untracked files instead ' 'of fancy "black question mark ornament" (u2753, which may not work)?' if query_yes_no ( question , default = 'yes' ) : filename = '~/repos/powerline-shell/powerline-shell.py' update_or_append_line ( filename , keep_backup = False , prefix = " 'untracked': u'\u2753'," , new_line = " 'untracked': u'\u003F'," ) run ( flo ( 'chmod u+x {filename}' ) ) bash_snippet = '~/.bashrc_powerline_shell' install_file_legacy ( path = bash_snippet ) prefix = flo ( 'if [ -f {bash_snippet} ]; ' ) enabler = flo ( 'if [ -f {bash_snippet} ]; then source {bash_snippet}; fi' ) uncomment_or_update_or_append_line ( filename = '~/.bashrc' , prefix = prefix , new_line = enabler )
1,536
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/__init__.py#L378-L423
[ "def", "_DeleteClientStats", "(", "self", ",", "limit", ",", "retention_time", ",", "cursor", "=", "None", ")", ":", "cursor", ".", "execute", "(", "\"DELETE FROM client_stats WHERE timestamp < FROM_UNIXTIME(%s) LIMIT %s\"", ",", "[", "mysql_utils", ".", "RDFDatetimeToTimestamp", "(", "retention_time", ")", ",", "limit", "]", ")", "return", "cursor", ".", "rowcount" ]
The utililty requires boto3 clients to CloudFormation .
def _init_boto3_clients ( self , profile , region ) : try : session = None if profile and region : session = boto3 . session . Session ( profile_name = profile , region_name = region ) elif profile : session = boto3 . session . Session ( profile_name = profile ) elif region : session = boto3 . session . Session ( region_name = region ) else : session = boto3 . session . Session ( ) self . _cloud_formation = session . client ( 'cloudformation' ) return True except Exception as wtf : logging . error ( wtf , exc_info = True ) return False
1,537
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/drift.py#L54-L79
[ "def", "reset", "(", "self", ",", "period", "=", "None", ")", ":", "if", "period", "is", "not", "None", ":", "self", ".", "period", "=", "period", "self", ".", "reset_event", ".", "set", "(", ")" ]
Determine the drift of the stack .
def determine_drift ( self ) : try : response = self . _cloud_formation . detect_stack_drift ( StackName = self . _stack_name ) drift_request_id = response . get ( 'StackDriftDetectionId' , None ) if drift_request_id : logging . info ( 'drift_request_id: %s - polling' , drift_request_id ) drift_calc_done = False while not drift_calc_done : time . sleep ( self . nap_time ) response = self . _cloud_formation . describe_stack_drift_detection_status ( StackDriftDetectionId = drift_request_id ) current_state = response . get ( 'DetectionStatus' , None ) logging . info ( 'describe_stack_drift_detection_status(): {}' . format ( current_state ) ) drift_calc_done = current_state in CALC_DONE_STATES drift_answer = response . get ( 'StackDriftStatus' , 'UNKNOWN' ) logging . info ( 'drift of {}: {}' . format ( self . _stack_name , drift_answer ) ) if drift_answer == 'DRIFTED' : if self . _verbose : self . _print_drift_report ( ) return False else : return True else : logging . warning ( 'drift_request_id is None' ) return False except Exception as wtf : logging . error ( wtf , exc_info = True ) return False
1,538
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/drift.py#L81-L126
[ "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", ")" ]
Report the drift of the stack .
def _print_drift_report ( self ) : try : response = self . _cloud_formation . describe_stack_resources ( StackName = self . _stack_name ) rows = [ ] for resource in response . get ( 'StackResources' , [ ] ) : row = [ ] row . append ( resource . get ( 'LogicalResourceId' , 'unknown' ) ) row . append ( resource . get ( 'PhysicalResourceId' , 'unknown' ) ) row . append ( resource . get ( 'ResourceStatus' , 'unknown' ) ) row . append ( resource . get ( 'DriftInformation' , { } ) . get ( 'StackResourceDriftStatus' , 'unknown' ) ) rows . append ( row ) print ( 'Drift Report:' ) print ( tabulate ( rows , headers = [ 'Logical ID' , 'Physical ID' , 'Resource Status' , 'Drift Info' ] ) ) except Exception as wtf : logging . error ( wtf , exc_info = True ) return False return True
1,539
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/drift.py#L128-L162
[ "def", "get_topic_keyword_dictionary", "(", ")", ":", "topic_keyword_dictionary", "=", "dict", "(", ")", "file_row_gen", "=", "get_file_row_generator", "(", "get_package_path", "(", ")", "+", "\"/twitter/res/topics/topic_keyword_mapping\"", "+", "\".txt\"", ",", "\",\"", ",", "\"utf-8\"", ")", "for", "file_row", "in", "file_row_gen", ":", "topic_keyword_dictionary", "[", "file_row", "[", "0", "]", "]", "=", "set", "(", "[", "keyword", "for", "keyword", "in", "file_row", "[", "1", ":", "]", "]", ")", "return", "topic_keyword_dictionary" ]
Use this method to set the data for this blob
def set_data ( self , data ) : if data is None : self . data_size = 0 self . data = None return self . data_size = len ( data ) # create a string buffer so that null bytes aren't interpreted # as the end of the string self . data = ctypes . cast ( ctypes . create_string_buffer ( data ) , ctypes . c_void_p )
1,540
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/dpapi.py#L43-L52
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Get the data for this blob
def get_data ( self ) : array = ctypes . POINTER ( ctypes . c_char * len ( self ) ) return ctypes . cast ( self . data , array ) . contents . raw
1,541
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/dpapi.py#L54-L57
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Prints metadata for given location .
def printMetaDataFor ( archive , location ) : desc = archive . getMetadataForLocation ( location ) if desc . isEmpty ( ) : print ( " no metadata for '{0}'" . format ( location ) ) return None print ( " metadata for '{0}':" . format ( location ) ) print ( " Created : {0}" . format ( desc . getCreated ( ) . getDateAsString ( ) ) ) for i in range ( desc . getNumModified ( ) ) : print ( " Modified : {0}" . format ( desc . getModified ( i ) . getDateAsString ( ) ) ) print ( " # Creators: {0}" . format ( desc . getNumCreators ( ) ) ) for i in range ( desc . getNumCreators ( ) ) : creator = desc . getCreator ( i ) print ( " {0} {1}" . format ( creator . getGivenName ( ) , creator . getFamilyName ( ) ) )
1,542
https://github.com/sbmlteam/libCombine/blob/d7c11a90129dedbcc8bdba8d204be03f1dd0c3e4/examples/python/printExample.py#L11-L31
[ "def", "register_dataframe_method", "(", "method", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "class", "AccessorMethod", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "pandas_obj", ")", ":", "self", ".", "_obj", "=", "pandas_obj", "@", "wraps", "(", "method", ")", "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "method", "(", "self", ".", "_obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", "register_dataframe_accessor", "(", "method", ".", "__name__", ")", "(", "AccessorMethod", ")", "return", "method", "return", "inner", "(", ")" ]
Prints content of combine archive
def printArchive ( fileName ) : archive = CombineArchive ( ) if archive . initializeFromArchive ( fileName ) is None : print ( "Invalid Combine Archive" ) return None print ( '*' * 80 ) print ( 'Print archive:' , fileName ) print ( '*' * 80 ) printMetaDataFor ( archive , "." ) print ( "Num Entries: {0}" . format ( archive . getNumEntries ( ) ) ) for i in range ( archive . getNumEntries ( ) ) : entry = archive . getEntry ( i ) print ( " {0}: location: {1} format: {2}" . format ( i , entry . getLocation ( ) , entry . getFormat ( ) ) ) printMetaDataFor ( archive , entry . getLocation ( ) ) for j in range ( entry . getNumCrossRefs ( ) ) : print ( " {0}: crossRef location {1}" . format ( j , entry . getCrossRef ( j ) . getLocation ( ) ) ) # the entry could now be extracted via # archive.extractEntry(entry.getLocation(), <filename or folder>) # or used as string # content = archive.extractEntryToString(entry.getLocation()); archive . cleanUp ( )
1,543
https://github.com/sbmlteam/libCombine/blob/d7c11a90129dedbcc8bdba8d204be03f1dd0c3e4/examples/python/printExample.py#L34-L65
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Like cmd . exe s mklink except it will infer directory status of the target .
def mklink ( ) : from optparse import OptionParser parser = OptionParser ( usage = "usage: %prog [options] link target" ) parser . add_option ( '-d' , '--directory' , help = "Target is a directory (only necessary if not present)" , action = "store_true" ) options , args = parser . parse_args ( ) try : link , target = args except ValueError : parser . error ( "incorrect number of arguments" ) symlink ( target , link , options . directory ) sys . stdout . write ( "Symbolic link created: %(link)s --> %(target)s\n" % vars ( ) )
1,544
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/__init__.py#L28-L45
[ "def", "get_cur_batch", "(", "items", ")", ":", "batches", "=", "[", "]", "for", "data", "in", "items", ":", "batch", "=", "tz", ".", "get_in", "(", "[", "\"metadata\"", ",", "\"batch\"", "]", ",", "data", ",", "[", "]", ")", "batches", ".", "append", "(", "set", "(", "batch", ")", "if", "isinstance", "(", "batch", ",", "(", "list", ",", "tuple", ")", ")", "else", "set", "(", "[", "batch", "]", ")", ")", "combo_batches", "=", "reduce", "(", "lambda", "b1", ",", "b2", ":", "b1", ".", "intersection", "(", "b2", ")", ",", "batches", ")", "if", "len", "(", "combo_batches", ")", "==", "1", ":", "return", "combo_batches", ".", "pop", "(", ")", "elif", "len", "(", "combo_batches", ")", "==", "0", ":", "return", "None", "else", ":", "raise", "ValueError", "(", "\"Found multiple overlapping batches: %s -- %s\"", "%", "(", "combo_batches", ",", "batches", ")", ")" ]
Determine if the given path is a reparse point . Return False if the file does not exist or the file attributes cannot be determined .
def is_reparse_point ( path ) : res = api . GetFileAttributes ( path ) return ( res != api . INVALID_FILE_ATTRIBUTES and bool ( res & api . FILE_ATTRIBUTE_REPARSE_POINT ) )
1,545
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/__init__.py#L78-L88
[ "def", "queries", "(", "self", ",", "request", ")", ":", "queries", "=", "self", ".", "get_queries", "(", "request", ")", "worlds", "=", "[", "]", "with", "self", ".", "mapper", ".", "begin", "(", ")", "as", "session", ":", "for", "_", "in", "range", "(", "queries", ")", ":", "world", "=", "session", ".", "query", "(", "World", ")", ".", "get", "(", "randint", "(", "1", ",", "MAXINT", ")", ")", "worlds", ".", "append", "(", "self", ".", "get_json", "(", "world", ")", ")", "return", "Json", "(", "worlds", ")", ".", "http_response", "(", "request", ")" ]
Assuming path is a reparse point determine if it s a symlink .
def is_symlink ( path ) : path = _patch_path ( path ) try : return _is_symlink ( next ( find_files ( path ) ) ) # comment below workaround for PyCQA/pyflakes#376 except WindowsError as orig_error : # noqa: F841 tmpl = "Error accessing {path}: {orig_error.message}" raise builtins . WindowsError ( tmpl . format ( * * locals ( ) ) )
1,546
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/__init__.py#L113-L123
[ "def", "Field", "(", "self", ",", "field", ",", "Value", "=", "None", ")", ":", "if", "Value", "==", "None", ":", "try", ":", "return", "self", ".", "__Bitmap", "[", "field", "]", "except", "KeyError", ":", "return", "None", "elif", "Value", "==", "1", "or", "Value", "==", "0", ":", "self", ".", "__Bitmap", "[", "field", "]", "=", "Value", "else", ":", "raise", "ValueError" ]
r For a given path determine the ultimate location of that path . Useful for resolving symlink targets . This functions wraps the GetFinalPathNameByHandle from the Windows SDK .
def get_final_path ( path ) : desired_access = api . NULL share_mode = ( api . FILE_SHARE_READ | api . FILE_SHARE_WRITE | api . FILE_SHARE_DELETE ) security_attributes = api . LPSECURITY_ATTRIBUTES ( ) # NULL pointer hFile = api . CreateFile ( path , desired_access , share_mode , security_attributes , api . OPEN_EXISTING , api . FILE_FLAG_BACKUP_SEMANTICS , api . NULL , ) if hFile == api . INVALID_HANDLE_VALUE : raise WindowsError ( ) buf_size = api . GetFinalPathNameByHandle ( hFile , LPWSTR ( ) , 0 , api . VOLUME_NAME_DOS ) handle_nonzero_success ( buf_size ) buf = create_unicode_buffer ( buf_size ) result_length = api . GetFinalPathNameByHandle ( hFile , buf , len ( buf ) , api . VOLUME_NAME_DOS ) assert result_length < len ( buf ) handle_nonzero_success ( result_length ) handle_nonzero_success ( api . CloseHandle ( hFile ) ) return buf [ : result_length ]
1,547
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/__init__.py#L163-L203
[ "def", "_read_prm_file", "(", "prm_filename", ")", ":", "logger", ".", "debug", "(", "\"Reading config-file: %s\"", "%", "prm_filename", ")", "try", ":", "with", "open", "(", "prm_filename", ",", "\"r\"", ")", "as", "config_file", ":", "prm_dict", "=", "yaml", ".", "load", "(", "config_file", ")", "except", "yaml", ".", "YAMLError", ":", "raise", "ConfigFileNotRead", "else", ":", "_update_prms", "(", "prm_dict", ")" ]
r Wrapper around os . path . join that works with Windows drive letters .
def join ( * paths ) : paths_with_drives = map ( os . path . splitdrive , paths ) drives , paths = zip ( * paths_with_drives ) # the drive we care about is the last one in the list drive = next ( filter ( None , reversed ( drives ) ) , '' ) return os . path . join ( drive , os . path . join ( * paths ) )
1,548
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/__init__.py#L292-L303
[ "def", "delete_idx_status", "(", "self", ",", "rdf_class", ")", ":", "sparql_template", "=", "\"\"\"\n DELETE\n {{\n ?s kds:esIndexTime ?esTime .\n ?s kds:esIndexError ?esError .\n }}\n WHERE\n {{\n\n VALUES ?rdftypes {{\\n\\t\\t{} }} .\n ?s a ?rdftypes .\n OPTIONAL {{\n ?s kds:esIndexTime ?esTime\n }}\n OPTIONAL {{\n ?s kds:esIndexError ?esError\n }}\n FILTER(bound(?esTime)||bound(?esError))\n }}\n \"\"\"", "rdf_types", "=", "[", "rdf_class", ".", "uri", "]", "+", "[", "item", ".", "uri", "for", "item", "in", "rdf_class", ".", "subclasses", "]", "sparql", "=", "sparql_template", ".", "format", "(", "\"\\n\\t\\t\"", ".", "join", "(", "rdf_types", ")", ")", "log", ".", "warn", "(", "\"Deleting index status for %s\"", ",", "rdf_class", ".", "uri", ")", "return", "self", ".", "tstore_conn", ".", "update_query", "(", "sparql", ")" ]
r Find a path from start to target where target is relative to start .
def resolve_path ( target , start = os . path . curdir ) : return os . path . normpath ( join ( start , target ) )
1,549
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/__init__.py#L306-L343
[ "def", "is_redundant_multiplicon", "(", "self", ",", "value", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_redundant_multiplicon_cache'", ")", ":", "sql", "=", "'''SELECT id FROM multiplicons WHERE is_redundant=\"-1\"'''", "cur", "=", "self", ".", "_dbconn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "sql", ",", "{", "'id'", ":", "str", "(", "value", ")", "}", ")", "result", "=", "[", "int", "(", "r", "[", "0", "]", ")", "for", "r", "in", "cur", ".", "fetchall", "(", ")", "]", "self", ".", "_redundant_multiplicon_cache", "=", "set", "(", "result", ")", "if", "value", "in", "self", ".", "_redundant_multiplicon_cache", ":", "return", "True", "else", ":", "return", "False" ]
Given a file that is known to be a symlink trace it to its ultimate target .
def trace_symlink_target ( link ) : if not is_symlink ( link ) : raise ValueError ( "link must point to a symlink on the system" ) while is_symlink ( link ) : orig = os . path . dirname ( link ) link = readlink ( link ) link = resolve_path ( link , orig ) return link
1,550
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/__init__.py#L349-L364
[ "def", "group_values", "(", "self", ",", "group_name", ")", ":", "group_index", "=", "self", ".", "groups", ".", "index", "(", "group_name", ")", "values", "=", "[", "]", "for", "key", "in", "self", ".", "data_keys", ":", "if", "key", "[", "group_index", "]", "not", "in", "values", ":", "values", ".", "append", "(", "key", "[", "group_index", "]", ")", "return", "values" ]
jaraco . windows provides the os . symlink and os . readlink functions . Monkey - patch the os module to include them if not present .
def patch_os_module ( ) : if not hasattr ( os , 'symlink' ) : os . symlink = symlink os . path . islink = islink if not hasattr ( os , 'readlink' ) : os . readlink = readlink
1,551
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/__init__.py#L398-L407
[ "def", "delete_repository_config", "(", "namespace", ",", "name", ",", "snapshot_id", ")", ":", "uri", "=", "\"configurations/{0}/{1}/{2}\"", ".", "format", "(", "namespace", ",", "name", ",", "snapshot_id", ")", "return", "__delete", "(", "uri", ")" ]
Composition of decorator functions for inherent self - documentation on task execution .
def task ( func , * args , * * kwargs ) : prefix = '\n# ' tail = '\n' return fabric . api . task ( print_full_name ( color = magenta , prefix = prefix , tail = tail ) ( print_doc1 ( func ) ) , * args , * * kwargs )
1,552
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L191-L204
[ "def", "getSymmetricallyEncryptedVal", "(", "val", ",", "secretKey", ":", "Union", "[", "str", ",", "bytes", "]", "=", "None", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "val", "=", "val", ".", "encode", "(", "\"utf-8\"", ")", "if", "secretKey", ":", "if", "isHex", "(", "secretKey", ")", ":", "secretKey", "=", "bytes", "(", "bytearray", ".", "fromhex", "(", "secretKey", ")", ")", "elif", "not", "isinstance", "(", "secretKey", ",", "bytes", ")", ":", "error", "(", "\"Secret key must be either in hex or bytes\"", ")", "box", "=", "libnacl", ".", "secret", ".", "SecretBox", "(", "secretKey", ")", "else", ":", "box", "=", "libnacl", ".", "secret", ".", "SecretBox", "(", ")", "return", "box", ".", "encrypt", "(", "val", ")", ".", "hex", "(", ")", ",", "box", ".", "sk", ".", "hex", "(", ")" ]
Decorator which prints out the name of the decorated function on execution .
def subtask ( * args , * * kwargs ) : depth = kwargs . get ( 'depth' , 2 ) prefix = kwargs . get ( 'prefix' , '\n' + '#' * depth + ' ' ) tail = kwargs . get ( 'tail' , '\n' ) doc1 = kwargs . get ( 'doc1' , False ) color = kwargs . get ( 'color' , cyan ) def real_decorator ( func ) : if doc1 : return print_full_name ( color = color , prefix = prefix , tail = tail ) ( print_doc1 ( func ) ) return print_full_name ( color = color , prefix = prefix , tail = tail ) ( func ) invoked = bool ( not args or kwargs ) if not invoked : # invoke decorator function which returns the wrapper function return real_decorator ( func = args [ 0 ] ) return real_decorator
1,553
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L213-L233
[ "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" ]
Return True if current user is a sudoer else False .
def _is_sudoer ( what_for = '' ) : if env . get ( 'nosudo' , None ) is None : if what_for : print ( yellow ( what_for ) ) with quiet ( ) : # possible outputs: # en: "Sorry, user winhost-tester may not run sudo on <hostname>" # en: "sudo: a password is required" (=> is sudoer) # de: "sudo: Ein Passwort ist notwendig" (=> is sudoer) output = run ( 'sudo -nv' , capture = True ) env . nosudo = not ( output . startswith ( 'sudo: ' ) or output == '' ) if env . nosudo : print ( 'Cannot execute sudo-commands' ) return not env . nosudo
1,554
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L248-L265
[ "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", "(", ")", ")" ]
Try to install . deb packages given by list .
def install_packages ( packages , what_for = 'for a complete setup to work properly' ) : res = True non_installed_packages = _non_installed ( packages ) packages_str = ' ' . join ( non_installed_packages ) if non_installed_packages : with quiet ( ) : dpkg = _has_dpkg ( ) hint = ' (You may have to install them manually)' do_install = False go_on = True if dpkg : if _is_sudoer ( 'Want to install dpkg packages' ) : do_install = True else : do_install is False # cannot install anything info = yellow ( ' ' . join ( [ 'This deb packages are missing to be installed' , flo ( "{what_for}: " ) , ', ' . join ( non_installed_packages ) , ] ) ) question = ' Continue anyway?' go_on = query_yes_no ( info + hint + question , default = 'no' ) else : # dpkg == False, unable to determine if packages are installed do_install = False # cannot install anything info = yellow ( ' ' . join ( [ flo ( 'Required {what_for}: ' ) , ', ' . join ( non_installed_packages ) , ] ) ) go_on = query_yes_no ( info + hint + ' Continue?' , default = 'yes' ) if not go_on : sys . exit ( 'Abort' ) if do_install : command = flo ( 'sudo apt-get install {packages_str}' ) res = run ( command ) . return_code == 0 return res
1,555
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L273-L315
[ "def", "surviors_are_inconsistent", "(", "survivor_mapping", ":", "Mapping", "[", "BaseEntity", ",", "Set", "[", "BaseEntity", "]", "]", ")", "->", "Set", "[", "BaseEntity", "]", ":", "victim_mapping", "=", "set", "(", ")", "for", "victim", "in", "itt", ".", "chain", ".", "from_iterable", "(", "survivor_mapping", ".", "values", "(", ")", ")", ":", "if", "victim", "in", "survivor_mapping", ":", "victim_mapping", ".", "add", "(", "victim", ")", "return", "victim_mapping" ]
Checkout or update git repos .
def checkup_git_repos_legacy ( repos , base_dir = '~/repos' , verbose = False , prefix = '' , postfix = '' ) : run ( flo ( 'mkdir -p {base_dir}' ) ) for repo in repos : cur_base_dir = repo . get ( 'base_dir' , base_dir ) checkup_git_repo_legacy ( url = repo [ 'url' ] , name = repo . get ( 'name' , None ) , base_dir = cur_base_dir , verbose = verbose , prefix = prefix , postfix = postfix )
1,556
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L324-L336
[ "def", "set_archive_layout", "(", "self", ",", "archive_id", ",", "layout_type", ",", "stylesheet", "=", "None", ")", ":", "payload", "=", "{", "'type'", ":", "layout_type", ",", "}", "if", "layout_type", "==", "'custom'", ":", "if", "stylesheet", "is", "not", "None", ":", "payload", "[", "'stylesheet'", "]", "=", "stylesheet", "endpoint", "=", "self", ".", "endpoints", ".", "set_archive_layout_url", "(", "archive_id", ")", "response", "=", "requests", ".", "put", "(", "endpoint", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ",", "headers", "=", "self", ".", "json_headers", "(", ")", ",", "proxies", "=", "self", ".", "proxies", ",", "timeout", "=", "self", ".", "timeout", ")", "if", "response", ".", "status_code", "==", "200", ":", "pass", "elif", "response", ".", "status_code", "==", "400", ":", "raise", "ArchiveError", "(", "'Invalid request. This response may indicate that data in your request data is invalid JSON. It may also indicate that you passed in invalid layout options.'", ")", "elif", "response", ".", "status_code", "==", "403", ":", "raise", "AuthError", "(", "'Authentication error.'", ")", "else", ":", "raise", "RequestError", "(", "'OpenTok server error.'", ",", "response", ".", "status_code", ")" ]
Checkout or update a git repo .
def checkup_git_repo_legacy ( url , name = None , base_dir = '~/repos' , verbose = False , prefix = '' , postfix = '' ) : if not name : match = re . match ( r'.*/(.+)\.git' , url ) assert match , flo ( "Unable to extract repo name from '{url}'" ) name = match . group ( 1 ) assert name is not None , flo ( 'Cannot extract repo name from repo: {url}' ) assert name != '' , flo ( 'Cannot extract repo name from repo: {url} (empty)' ) if verbose : name_blue = blue ( name ) print_msg ( flo ( '{prefix}Checkout or update {name_blue}{postfix}' ) ) if not exists ( base_dir ) : run ( flo ( 'mkdir -p {base_dir}' ) ) if not exists ( flo ( '{base_dir}/{name}/.git' ) ) : run ( flo ( ' && ' . join ( [ 'cd {base_dir}' , 'git clone {url} {name}' ] ) ) , msg = 'clone repo' ) else : if verbose : print_msg ( 'update: pull from origin' ) run ( flo ( 'cd {base_dir}/{name} && git pull' ) ) return name
1,557
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L339-L362
[ "def", "_get_partition_info", "(", "storage_system", ",", "device_path", ")", ":", "try", ":", "partition_infos", "=", "storage_system", ".", "RetrieveDiskPartitionInfo", "(", "devicePath", "=", "[", "device_path", "]", ")", "except", "vim", ".", "fault", ".", "NoPermission", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareApiError", "(", "'Not enough permissions. Required privilege: '", "'{0}'", ".", "format", "(", "exc", ".", "privilegeId", ")", ")", "except", "vim", ".", "fault", ".", "VimFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareApiError", "(", "exc", ".", "msg", ")", "except", "vmodl", ".", "RuntimeFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareRuntimeError", "(", "exc", ".", "msg", ")", "log", ".", "trace", "(", "'partition_info = %s'", ",", "partition_infos", "[", "0", "]", ")", "return", "partition_infos", "[", "0", "]" ]
Install file with path on the host target .
def install_file_legacy ( path , sudo = False , from_path = None , * * substitutions ) : # source paths 'from_custom' and 'from_common' from_path = from_path or path # remove beginning '/' (if any), eg '/foo/bar' -> 'foo/bar' from_tail = join ( 'files' , from_path . lstrip ( os . sep ) ) if from_path . startswith ( '~/' ) : from_tail = join ( 'files' , 'home' , 'USERNAME' , from_path [ 2 : ] ) # without beginning '~/' from_common = join ( FABFILE_DATA_DIR , from_tail ) from_custom = join ( FABSETUP_CUSTOM_DIR , from_tail ) # target path 'to_' (path or tempfile) for subst in [ 'SITENAME' , 'USER' , 'ADDON' , 'TASK' ] : sitename = substitutions . get ( subst , False ) if sitename : path = path . replace ( subst , sitename ) to_ = path if sudo : to_ = join ( os . sep , 'tmp' , 'fabsetup_' + os . path . basename ( path ) ) path_dir = dirname ( path ) # copy file if isfile ( from_custom ) : run ( flo ( 'mkdir -p {path_dir}' ) ) put ( from_custom , to_ ) elif isfile ( from_custom + '.template' ) : _install_file_from_template_legacy ( from_custom + '.template' , to_ = to_ , * * substitutions ) elif isfile ( from_common ) : run ( flo ( 'mkdir -p {path_dir}' ) ) put ( from_common , to_ ) else : _install_file_from_template_legacy ( from_common + '.template' , to_ = to_ , * * substitutions ) if sudo : run ( flo ( 'sudo mv --force {to_} {path}' ) )
1,558
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L481-L524
[ "def", "put_cors", "(", "Bucket", ",", "CORSRules", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "if", "CORSRules", "is", "not", "None", "and", "isinstance", "(", "CORSRules", ",", "six", ".", "string_types", ")", ":", "CORSRules", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "CORSRules", ")", "conn", ".", "put_bucket_cors", "(", "Bucket", "=", "Bucket", ",", "CORSConfiguration", "=", "{", "'CORSRules'", ":", "CORSRules", "}", ")", "return", "{", "'updated'", ":", "True", ",", "'name'", ":", "Bucket", "}", "except", "ClientError", "as", "e", ":", "return", "{", "'updated'", ":", "False", ",", "'error'", ":", "__utils__", "[", "'boto3.get_error'", "]", "(", "e", ")", "}" ]
Install command executable file into users bin dir .
def install_user_command_legacy ( command , * * substitutions ) : path = flo ( '~/bin/{command}' ) install_file_legacy ( path , * * substitutions ) run ( flo ( 'chmod 755 {path}' ) )
1,559
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L527-L535
[ "def", "getGenericAssociatedDeviceInfo", "(", "self", ",", "index", ",", "wifiInterfaceId", "=", "1", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "Wifi", ".", "getServiceType", "(", "\"getGenericAssociatedDeviceInfo\"", ")", "+", "str", "(", "wifiInterfaceId", ")", "uri", "=", "self", ".", "getControlURL", "(", "namespace", ")", "results", "=", "self", ".", "execute", "(", "uri", ",", "namespace", ",", "\"GetGenericAssociatedDeviceInfo\"", ",", "timeout", "=", "timeout", ",", "NewAssociatedDeviceIndex", "=", "index", ")", "return", "WifiDeviceInfo", "(", "results", ")" ]
Return bash variable declaration as name - value pair .
def _line_2_pair ( line ) : key , val = line . split ( '=' ) return key . lower ( ) , val . strip ( '"' )
1,560
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L735-L743
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "TabView", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "try", ":", "tab_group", "=", "self", ".", "get_tabs", "(", "self", ".", "request", ",", "*", "*", "kwargs", ")", "context", "[", "\"tab_group\"", "]", "=", "tab_group", "# Make sure our data is pre-loaded to capture errors.", "context", "[", "\"tab_group\"", "]", ".", "load_tab_data", "(", ")", "except", "Exception", ":", "exceptions", ".", "handle", "(", "self", ".", "request", ")", "return", "context" ]
Extract supported python minor versions from setup . py and return them as a list of str .
def extract_minors_from_setup_py ( filename_setup_py ) : # eg: minors_str = '2.6\n2.7\n3.3\n3.4\n3.5\n3.6' minors_str = fabric . api . local ( flo ( 'grep --perl-regexp --only-matching ' '"(?<=Programming Language :: Python :: )\\d+\\.\\d+" ' '{filename_setup_py}' ) , capture = True ) # eg: minors = ['2.6', '2.7', '3.3', '3.4', '3.5', '3.6'] minors = minors_str . split ( ) return minors
1,561
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L834-L850
[ "def", "exclude_types", "(", "self", ",", "*", "objs", ")", ":", "for", "o", "in", "objs", ":", "for", "t", "in", "_keytuple", "(", "o", ")", ":", "if", "t", "and", "t", "not", "in", "self", ".", "_excl_d", ":", "self", ".", "_excl_d", "[", "t", "]", "=", "0" ]
Install or update Janus a distribution of addons and mappings for vim .
def vim_janus ( uninstall = None ) : if uninstall is not None : uninstall_janus ( ) else : if not exists ( '~/.vim/janus' ) : print_msg ( 'not installed => install' ) install_janus ( ) else : print_msg ( 'already installed => update' ) update_janus ( ) customize_janus ( ) show_files_used_by_vim_and_janus ( )
1,562
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/vim_janus.py#L18-L38
[ "def", "short_title", "(", "self", ")", ":", "if", "self", ".", "title", "and", "self", ".", "parent", "is", "not", "None", "and", "hasattr", "(", "self", ".", "parent", ",", "'title'", ")", "and", "self", ".", "parent", ".", "title", ":", "if", "self", ".", "title", ".", "startswith", "(", "self", ".", "parent", ".", "title", ")", ":", "short", "=", "self", ".", "title", "[", "len", "(", "self", ".", "parent", ".", "title", ")", ":", "]", ".", "strip", "(", ")", "match", "=", "_punctuation_re", ".", "match", "(", "short", ")", "if", "match", ":", "short", "=", "short", "[", "match", ".", "end", "(", ")", ":", "]", ".", "strip", "(", ")", "if", "short", ":", "return", "short", "return", "self", ".", "title" ]
Scan a network port
def scan ( host , port = 80 , url = None , https = False , timeout = 1 , max_size = 65535 ) : starts = OrderedDict ( ) ends = OrderedDict ( ) port = int ( port ) result = dict ( host = host , port = port , state = 'closed' , durations = OrderedDict ( ) ) if url : timeout = 1 result [ 'code' ] = None starts [ 'all' ] = starts [ 'dns' ] = datetime . datetime . now ( ) # DNS Lookup try : hostip = socket . gethostbyname ( host ) result [ 'ip' ] = hostip ends [ 'dns' ] = datetime . datetime . now ( ) except socket . gaierror : raise ScanFailed ( 'DNS Lookup failed' , result = result ) # TCP Connect starts [ 'connect' ] = datetime . datetime . now ( ) network_socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) network_socket . settimeout ( timeout ) result_connection = network_socket . connect_ex ( ( hostip , port ) ) ends [ 'connect' ] = datetime . datetime . now ( ) # SSL if https : starts [ 'ssl' ] = datetime . datetime . now ( ) try : network_socket = ssl . wrap_socket ( network_socket ) except socket . timeout : raise ScanFailed ( 'SSL socket timeout' , result = result ) ends [ 'ssl' ] = datetime . datetime . now ( ) # Get request if result_connection == 0 and url : starts [ 'request' ] = datetime . datetime . now ( ) network_socket . send ( "GET {0} HTTP/1.0\r\nHost: {1}\r\n\r\n" . format ( url , host ) . encode ( 'ascii' ) ) if max_size : data = network_socket . recv ( max_size ) else : data = network_socket . recv ( ) result [ 'length' ] = len ( data ) data = data . decode ( 'ascii' , errors = 'ignore' ) result [ 'response' ] = ( data ) try : result [ 'code' ] = int ( data . split ( '\n' ) [ 0 ] . split ( ) [ 1 ] ) except IndexError : pass ends [ 'request' ] = datetime . datetime . now ( ) network_socket . close ( ) # Calculate durations ends [ 'all' ] = datetime . datetime . now ( ) for duration in starts . keys ( ) : if duration in ends . keys ( ) : result [ 'durations' ] [ duration ] = ends [ duration ] - starts [ duration ] if result_connection == 0 : result [ 'state' ] = 'open' return result
1,563
https://github.com/yahoo/serviceping/blob/1f9df5ee5b3cba466426b1164262278472ba4977/serviceping/network.py#L25-L124
[ "def", "escape_md_section", "(", "text", ",", "snob", "=", "False", ")", ":", "text", "=", "md_backslash_matcher", ".", "sub", "(", "r\"\\\\\\1\"", ",", "text", ")", "if", "snob", ":", "text", "=", "md_chars_matcher_all", ".", "sub", "(", "r\"\\\\\\1\"", ",", "text", ")", "text", "=", "md_dot_matcher", ".", "sub", "(", "r\"\\1\\\\\\2\"", ",", "text", ")", "text", "=", "md_plus_matcher", ".", "sub", "(", "r\"\\1\\\\\\2\"", ",", "text", ")", "text", "=", "md_dash_matcher", ".", "sub", "(", "r\"\\1\\\\\\2\"", ",", "text", ")", "return", "text" ]
Ping a host
def ping ( host , port = 80 , url = None , https = False , timeout = 1 , max_size = 65535 , sequence = 0 ) : try : result = scan ( host = host , port = port , url = url , https = https , timeout = timeout , max_size = max_size ) except ScanFailed as failure : result = failure . result result [ 'error' ] = True result [ 'error_message' ] = str ( failure ) result_obj = PingResponse ( host = host , port = port , ip = result . get ( 'ip' , None ) , sequence = sequence , durations = result . get ( 'durations' , None ) , code = result . get ( 'code' , None ) , state = result . get ( 'state' , 'unknown' ) , length = result . get ( 'length' , 0 ) , response = result . get ( 'response' , None ) , error = result . get ( 'error' , False ) , error_message = result . get ( 'error_message' , None ) , responding = True if result . get ( 'state' , 'unknown' ) in [ 'open' ] else False , start = datetime . datetime . now ( ) , end = datetime . datetime . now ( ) + result [ 'durations' ] . get ( 'all' , datetime . timedelta ( 0 ) ) if result . get ( 'durations' , None ) else None ) return result_obj
1,564
https://github.com/yahoo/serviceping/blob/1f9df5ee5b3cba466426b1164262278472ba4977/serviceping/network.py#L213-L265
[ "def", "render", "(", "self", ")", ":", "context", "=", "self", ".", "context", "if", "'app'", "not", "in", "context", ":", "context", "[", "'app'", "]", "=", "self", ".", "application", ".", "name", "temp_dir", "=", "self", ".", "temp_dir", "templates_root", "=", "self", ".", "blueprint", ".", "templates_directory", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "templates_root", ")", ":", "for", "directory", "in", "dirs", ":", "directory", "=", "os", ".", "path", ".", "join", "(", "root", ",", "directory", ")", "directory", "=", "render_from_string", "(", "directory", ",", "context", ")", "directory", "=", "directory", ".", "replace", "(", "templates_root", ",", "temp_dir", ",", "1", ")", "os", ".", "mkdir", "(", "directory", ")", "for", "file", "in", "files", ":", "full_file", "=", "os", ".", "path", ".", "join", "(", "root", ",", "file", ")", "stat", "=", "os", ".", "stat", "(", "full_file", ")", "content", "=", "render_from_file", "(", "full_file", ",", "context", ")", "full_file", "=", "strip_extension", "(", "render_from_string", "(", "full_file", ",", "context", ")", ")", "full_file", "=", "full_file", ".", "replace", "(", "templates_root", ",", "temp_dir", ",", "1", ")", "with", "open", "(", "full_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "content", ")", "os", ".", "chmod", "(", "full_file", ",", "stat", ".", "st_mode", ")" ]
Delete the given CloudFormation stack .
def delete ( stack , region , profile ) : ini_data = { } environment = { } environment [ 'stack_name' ] = stack if region : environment [ 'region' ] = region else : environment [ 'region' ] = find_myself ( ) if profile : environment [ 'profile' ] = profile ini_data [ 'environment' ] = environment if start_smash ( ini_data ) : sys . exit ( 0 ) else : sys . exit ( 1 )
1,565
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/command.py#L81-L102
[ "def", "_get_rating", "(", "self", ",", "entry", ")", ":", "r_info", "=", "''", "for", "string", "in", "entry", "[", "2", "]", ".", "strings", ":", "r_info", "+=", "string", "rating", ",", "share", "=", "r_info", ".", "split", "(", "'/'", ")", "return", "(", "rating", ",", "share", ".", "strip", "(", "'*'", ")", ")" ]
List all the CloudFormation stacks in the given region .
def list ( region , profile ) : ini_data = { } environment = { } if region : environment [ 'region' ] = region else : environment [ 'region' ] = find_myself ( ) if profile : environment [ 'profile' ] = profile ini_data [ 'environment' ] = environment if start_list ( ini_data ) : sys . exit ( 0 ) else : sys . exit ( 1 )
1,566
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/command.py#L108-L127
[ "async", "def", "add", "(", "ctx", ",", "left", ":", "int", ",", "right", ":", "int", ")", ":", "await", "ctx", ".", "send", "(", "left", "+", "right", ")" ]
Produce a CloudFormation drift report for the given stack .
def drift ( stack , region , profile ) : logging . debug ( 'finding drift - stack: {}' . format ( stack ) ) logging . debug ( 'region: {}' . format ( region ) ) logging . debug ( 'profile: {}' . format ( profile ) ) tool = DriftTool ( Stack = stack , Region = region , Profile = profile , Verbose = True ) if tool . determine_drift ( ) : sys . exit ( 0 ) else : sys . exit ( 1 )
1,567
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/command.py#L134-L151
[ "def", "bind_to_storage_buffer", "(", "self", ",", "binding", "=", "0", ",", "*", ",", "offset", "=", "0", ",", "size", "=", "-", "1", ")", "->", "None", ":", "self", ".", "mglo", ".", "bind_to_storage_buffer", "(", "binding", ",", "offset", ",", "size", ")" ]
Helper function to facilitate upsert .
def start_upsert ( ini_data ) : stack_driver = CloudStackUtility ( ini_data ) poll_stack = not ini_data . get ( 'no_poll' , False ) if stack_driver . upsert ( ) : logging . info ( 'stack create/update was started successfully.' ) if poll_stack : stack_tool = None try : profile = ini_data . get ( 'environment' , { } ) . get ( 'profile' ) if profile : boto3_session = boto3 . session . Session ( profile_name = profile ) else : boto3_session = boto3 . session . Session ( ) region = ini_data [ 'environment' ] [ 'region' ] stack_name = ini_data [ 'environment' ] [ 'stack_name' ] cf_client = stack_driver . get_cloud_formation_client ( ) if not cf_client : cf_client = boto3_session . client ( 'cloudformation' , region_name = region ) stack_tool = stack_tool = StackTool ( stack_name , region , cf_client ) except Exception as wtf : logging . warning ( 'there was a problems creating stack tool: {}' . format ( wtf ) ) if stack_driver . poll_stack ( ) : try : logging . info ( 'stack create/update was finished successfully.' ) stack_tool . print_stack_info ( ) except Exception as wtf : logging . warning ( 'there was a problems printing stack info: {}' . format ( wtf ) ) sys . exit ( 0 ) else : try : logging . error ( 'stack create/update was did not go well.' ) stack_tool . print_stack_events ( ) except Exception as wtf : logging . warning ( 'there was a problems printing stack events: {}' . format ( wtf ) ) sys . exit ( 1 ) else : logging . error ( 'start of stack create/update did not go well.' ) sys . exit ( 1 )
1,568
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/command.py#L154-L212
[ "def", "close_streaming_interface", "(", "self", ")", ":", "super", "(", "ReferenceDevice", ",", "self", ")", ".", "close_streaming_interface", "(", ")", "self", ".", "rpc", "(", "8", ",", "rpcs", ".", "SG_GRAPH_INPUT", ",", "8", ",", "streams", ".", "COMM_TILE_CLOSED", ")" ]
Read the INI file
def read_config_info ( ini_file ) : try : config = RawConfigParser ( ) config . optionxform = lambda option : option config . read ( ini_file ) the_stuff = { } for section in config . sections ( ) : the_stuff [ section ] = { } for option in config . options ( section ) : the_stuff [ section ] [ option ] = config . get ( section , option ) return the_stuff except Exception as wtf : logging . error ( 'Exception caught in read_config_info(): {}' . format ( wtf ) ) traceback . print_exc ( file = sys . stdout ) return sys . exit ( 1 )
1,569
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/command.py#L257-L284
[ "def", "_unscramble_regressor_columns", "(", "parent_data", ",", "data", ")", ":", "matches", "=", "[", "'_power[0-9]+'", ",", "'_derivative[0-9]+'", "]", "var", "=", "OrderedDict", "(", "(", "c", ",", "deque", "(", ")", ")", "for", "c", "in", "parent_data", ".", "columns", ")", "for", "c", "in", "data", ".", "columns", ":", "col", "=", "c", "for", "m", "in", "matches", ":", "col", "=", "re", ".", "sub", "(", "m", ",", "''", ",", "col", ")", "if", "col", "==", "c", ":", "var", "[", "col", "]", ".", "appendleft", "(", "c", ")", "else", ":", "var", "[", "col", "]", ".", "append", "(", "c", ")", "unscrambled", "=", "reduce", "(", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ")", ",", "var", ".", "values", "(", ")", ")", "return", "data", "[", "[", "*", "unscrambled", "]", "]" ]
List resources from the given stack
def print_stack_info ( self ) : try : rest_api_id = None deployment_found = False response = self . _cf_client . describe_stack_resources ( StackName = self . _stack_name ) print ( '\nThe following resources were created:' ) rows = [ ] for resource in response [ 'StackResources' ] : if resource [ 'ResourceType' ] == 'AWS::ApiGateway::RestApi' : rest_api_id = resource [ 'PhysicalResourceId' ] elif resource [ 'ResourceType' ] == 'AWS::ApiGateway::Deployment' : deployment_found = True row = [ ] row . append ( resource [ 'ResourceType' ] ) row . append ( resource [ 'LogicalResourceId' ] ) row . append ( resource [ 'PhysicalResourceId' ] ) rows . append ( row ) ''' print('\t{}\t{}\t{}'.format( resource['ResourceType'], resource['LogicalResourceId'], resource['PhysicalResourceId'] ) ) ''' print ( tabulate ( rows , headers = [ 'Resource Type' , 'Logical ID' , 'Physical ID' ] ) ) if rest_api_id and deployment_found : url = 'https://{}.execute-api.{}.amazonaws.com/{}' . format ( rest_api_id , self . _region , '<stage>' ) print ( '\nThe deployed service can be found at this URL:' ) print ( '\t{}\n' . format ( url ) ) return response except Exception as wtf : print ( wtf ) return None
1,570
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/stack_tool.py#L39-L92
[ "def", "add_headers", "(", "width", "=", "80", ",", "title", "=", "'Untitled'", ",", "subtitle", "=", "''", ",", "author", "=", "''", ",", "email", "=", "''", ",", "description", "=", "''", ",", "tunings", "=", "[", "]", ")", ":", "result", "=", "[", "''", "]", "title", "=", "str", ".", "upper", "(", "title", ")", "result", "+=", "[", "str", ".", "center", "(", "' '", ".", "join", "(", "title", ")", ",", "width", ")", "]", "if", "subtitle", "!=", "''", ":", "result", "+=", "[", "''", ",", "str", ".", "center", "(", "str", ".", "title", "(", "subtitle", ")", ",", "width", ")", "]", "if", "author", "!=", "''", "or", "email", "!=", "''", ":", "result", "+=", "[", "''", ",", "''", "]", "if", "email", "!=", "''", ":", "result", "+=", "[", "str", ".", "center", "(", "'Written by: %s <%s>'", "%", "(", "author", ",", "email", ")", ",", "width", ")", "]", "else", ":", "result", "+=", "[", "str", ".", "center", "(", "'Written by: %s'", "%", "author", ",", "width", ")", "]", "if", "description", "!=", "''", ":", "result", "+=", "[", "''", ",", "''", "]", "words", "=", "description", ".", "split", "(", ")", "lines", "=", "[", "]", "line", "=", "[", "]", "last", "=", "0", "for", "word", "in", "words", ":", "if", "len", "(", "word", ")", "+", "last", "<", "width", "-", "10", ":", "line", ".", "append", "(", "word", ")", "last", "+=", "len", "(", "word", ")", "+", "1", "else", ":", "lines", ".", "append", "(", "line", ")", "line", "=", "[", "word", "]", "last", "=", "len", "(", "word", ")", "+", "1", "lines", ".", "append", "(", "line", ")", "for", "line", "in", "lines", ":", "result", "+=", "[", "str", ".", "center", "(", "' '", ".", "join", "(", "line", ")", ",", "width", ")", "]", "if", "tunings", "!=", "[", "]", ":", "result", "+=", "[", "''", ",", "''", ",", "str", ".", "center", "(", "'Instruments'", ",", "width", ")", "]", "for", "(", "i", ",", "tuning", ")", "in", "enumerate", "(", "tunings", ")", ":", "result", "+=", "[", "''", ",", "str", ".", "center", "(", "'%d. %s'", "%", "(", "i", "+", "1", ",", "tuning", ".", "instrument", ")", ",", "width", ")", ",", "str", ".", "center", "(", "tuning", ".", "description", ",", "width", ")", "]", "result", "+=", "[", "''", ",", "''", "]", "return", "result" ]
List events from the given stack
def print_stack_events ( self ) : first_token = '7be7981bd6287dd8112305e8f3822a6f' keep_going = True next_token = first_token current_request_token = None rows = [ ] try : while keep_going and next_token : if next_token == first_token : response = self . _cf_client . describe_stack_events ( StackName = self . _stack_name ) else : response = self . _cf_client . describe_stack_events ( StackName = self . _stack_name , NextToken = next_token ) next_token = response . get ( 'NextToken' , None ) for event in response [ 'StackEvents' ] : row = [ ] event_time = event . get ( 'Timestamp' ) request_token = event . get ( 'ClientRequestToken' , 'unknown' ) if current_request_token is None : current_request_token = request_token elif current_request_token != request_token : keep_going = False break row . append ( event_time . strftime ( '%x %X' ) ) row . append ( event . get ( 'LogicalResourceId' ) ) row . append ( event . get ( 'ResourceStatus' ) ) row . append ( event . get ( 'ResourceStatusReason' , '' ) ) rows . append ( row ) if len ( rows ) > 0 : print ( '\nEvents for the current upsert:' ) print ( tabulate ( rows , headers = [ 'Time' , 'Logical ID' , 'Status' , 'Message' ] ) ) return True else : print ( '\nNo stack events found\n' ) except Exception as wtf : print ( wtf ) return False
1,571
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/stack_tool.py#L94-L147
[ "def", "add_headers", "(", "width", "=", "80", ",", "title", "=", "'Untitled'", ",", "subtitle", "=", "''", ",", "author", "=", "''", ",", "email", "=", "''", ",", "description", "=", "''", ",", "tunings", "=", "[", "]", ")", ":", "result", "=", "[", "''", "]", "title", "=", "str", ".", "upper", "(", "title", ")", "result", "+=", "[", "str", ".", "center", "(", "' '", ".", "join", "(", "title", ")", ",", "width", ")", "]", "if", "subtitle", "!=", "''", ":", "result", "+=", "[", "''", ",", "str", ".", "center", "(", "str", ".", "title", "(", "subtitle", ")", ",", "width", ")", "]", "if", "author", "!=", "''", "or", "email", "!=", "''", ":", "result", "+=", "[", "''", ",", "''", "]", "if", "email", "!=", "''", ":", "result", "+=", "[", "str", ".", "center", "(", "'Written by: %s <%s>'", "%", "(", "author", ",", "email", ")", ",", "width", ")", "]", "else", ":", "result", "+=", "[", "str", ".", "center", "(", "'Written by: %s'", "%", "author", ",", "width", ")", "]", "if", "description", "!=", "''", ":", "result", "+=", "[", "''", ",", "''", "]", "words", "=", "description", ".", "split", "(", ")", "lines", "=", "[", "]", "line", "=", "[", "]", "last", "=", "0", "for", "word", "in", "words", ":", "if", "len", "(", "word", ")", "+", "last", "<", "width", "-", "10", ":", "line", ".", "append", "(", "word", ")", "last", "+=", "len", "(", "word", ")", "+", "1", "else", ":", "lines", ".", "append", "(", "line", ")", "line", "=", "[", "word", "]", "last", "=", "len", "(", "word", ")", "+", "1", "lines", ".", "append", "(", "line", ")", "for", "line", "in", "lines", ":", "result", "+=", "[", "str", ".", "center", "(", "' '", ".", "join", "(", "line", ")", ",", "width", ")", "]", "if", "tunings", "!=", "[", "]", ":", "result", "+=", "[", "''", ",", "''", ",", "str", ".", "center", "(", "'Instruments'", ",", "width", ")", "]", "for", "(", "i", ",", "tuning", ")", "in", "enumerate", "(", "tunings", ")", ":", "result", "+=", "[", "''", ",", "str", ".", "center", "(", "'%d. %s'", "%", "(", "i", "+", "1", ",", "tuning", ".", "instrument", ")", ",", "width", ")", ",", "str", ".", "center", "(", "tuning", ".", "description", ",", "width", ")", "]", "result", "+=", "[", "''", ",", "''", "]", "return", "result" ]
Set up or update a trac project .
def trac ( ) : hostname = re . sub ( r'^[^@]+@' , '' , env . host ) # without username if any sitename = query_input ( question = '\nEnter site-name of Your trac web service' , default = flo ( 'trac.{hostname}' ) ) username = env . user site_dir = flo ( '/home/{username}/sites/{sitename}' ) bin_dir = flo ( '{site_dir}/virtualenv/bin' ) # provisioning steps install_or_upgrade_virtualenv_pip_package ( ) create_directory_structure ( site_dir ) update_virtualenv ( site_dir , sitename ) set_up_trac_plugins ( sitename , site_dir , bin_dir ) set_up_gunicorn ( site_dir , sitename ) configure_nginx ( username , sitename , hostname ) if query_yes_no ( '\nRestore trac environment from backup tarball?' , default = 'no' ) : restore_tracenv_from_backup_tarball ( site_dir , bin_dir ) elif not tracenv_exists ( site_dir ) : init_tracenv ( site_dir , bin_dir , username ) upgrade_tracenv ( site_dir , bin_dir ) set_up_upstart_for_gunicorn ( sitename , username , site_dir )
1,572
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/service/trac.py#L28-L120
[ "def", "volumes_delete", "(", "storage_pool", ",", "logger", ")", ":", "try", ":", "for", "vol_name", "in", "storage_pool", ".", "listVolumes", "(", ")", ":", "try", ":", "vol", "=", "storage_pool", ".", "storageVolLookupByName", "(", "vol_name", ")", "vol", ".", "delete", "(", "0", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volume %s.\"", ",", "vol_name", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volumes.\"", ")" ]
Do a query to the System API
async def query ( self , path , method = 'get' , * * params ) : if method in ( 'get' , 'post' , 'patch' , 'delete' , 'put' ) : full_path = self . host + path if method == 'get' : resp = await self . aio_sess . get ( full_path , params = params ) elif method == 'post' : resp = await self . aio_sess . post ( full_path , data = params ) elif method == 'patch' : resp = await self . aio_sess . patch ( full_path , data = params ) elif method == 'delete' : resp = await self . aio_sess . delete ( full_path , params = params , headers = params ) elif method == 'put' : resp = await self . aio_sess . put ( full_path , data = params ) async with resp : # return the content if its a binary one if resp . content_type . startswith ( 'application/pdf' ) or resp . content_type . startswith ( 'application/epub' ) : return await resp . read ( ) return await self . handle_json_response ( resp ) else : raise ValueError ( 'method expected: get, post, patch, delete, put' )
1,573
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L60-L91
[ "def", "upload", "(", "self", ",", "params", "=", "{", "}", ")", ":", "if", "self", ".", "upload_token", "is", "not", "None", ":", "# resume upload", "status", "=", "self", ".", "check", "(", ")", "if", "status", "[", "'status'", "]", "!=", "4", ":", "return", "self", ".", "commit", "(", ")", "else", ":", "self", ".", "new_slice", "(", ")", "while", "self", ".", "slice_task_id", "!=", "0", ":", "self", ".", "upload_slice", "(", ")", "return", "self", ".", "commit", "(", ")", "else", ":", "# new upload", "self", ".", "create", "(", "self", ".", "prepare_video_params", "(", "*", "*", "params", ")", ")", "self", ".", "create_file", "(", ")", "self", ".", "new_slice", "(", ")", "while", "self", ".", "slice_task_id", "!=", "0", ":", "self", ".", "upload_slice", "(", ")", "return", "self", ".", "commit", "(", ")" ]
Set up or update a reveals . js presentation with slides written in markdown .
def revealjs ( basedir = None , title = None , subtitle = None , description = None , github_user = None , github_repo = None ) : basedir = basedir or query_input ( 'Base dir of the presentation?' , default = '~/repos/my_presi' ) revealjs_repo_name = 'reveal.js' revealjs_dir = flo ( '{basedir}/{revealjs_repo_name}' ) _lazy_dict [ 'presi_title' ] = title _lazy_dict [ 'presi_subtitle' ] = subtitle _lazy_dict [ 'presi_description' ] = description _lazy_dict [ 'github_user' ] = github_user _lazy_dict [ 'github_repo' ] = github_repo question = flo ( "Base dir already contains a sub dir '{revealjs_repo_name}'." ' Reset (and re-download) reveal.js codebase?' ) if not exists ( revealjs_dir ) or query_yes_no ( question , default = 'no' ) : run ( flo ( 'mkdir -p {basedir}' ) ) set_up_revealjs_codebase ( basedir , revealjs_repo_name ) install_plugins ( revealjs_dir ) apply_customizations ( repo_dir = revealjs_dir ) if exists ( revealjs_dir ) : install_files_in_basedir ( basedir , repo_dir = revealjs_dir ) init_git_repo ( basedir ) create_github_remote_repo ( basedir ) setup_npm ( revealjs_dir ) else : print ( 'abort' )
1,574
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/revealjs.py#L50-L90
[ "def", "volumes_delete", "(", "storage_pool", ",", "logger", ")", ":", "try", ":", "for", "vol_name", "in", "storage_pool", ".", "listVolumes", "(", ")", ":", "try", ":", "vol", "=", "storage_pool", ".", "storageVolLookupByName", "(", "vol_name", ")", "vol", ".", "delete", "(", "0", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volume %s.\"", ",", "vol_name", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volumes.\"", ")" ]
Comment out some css settings .
def tweak_css ( repo_dir ) : print_msg ( "* don't capitalize titles (no uppercase headings)" ) files = [ 'beige.css' , 'black.css' , 'blood.css' , 'league.css' , 'moon.css' , 'night.css' , 'serif.css' , 'simple.css' , 'sky.css' , 'solarized.css' , 'white.css' , ] line = ' text-transform: uppercase;' for file_ in files : update_or_append_line ( filename = flo ( '{repo_dir}/css/theme/{file_}' ) , prefix = line , new_line = flo ( '/*{line}*/' ) ) print_msg ( '* images without border' ) data = [ { 'file' : 'beige.css' , 'line' : ' border: 4px solid #333;' } , { 'file' : 'black.css' , 'line' : ' border: 4px solid #fff;' } , { 'file' : 'blood.css' , 'line' : ' border: 4px solid #eee;' } , { 'file' : 'league.css' , 'line' : ' border: 4px solid #eee;' } , { 'file' : 'moon.css' , 'line' : ' border: 4px solid #93a1a1;' } , { 'file' : 'night.css' , 'line' : ' border: 4px solid #eee;' } , { 'file' : 'serif.css' , 'line' : ' border: 4px solid #000;' } , { 'file' : 'simple.css' , 'line' : ' border: 4px solid #000;' } , { 'file' : 'sky.css' , 'line' : ' border: 4px solid #333;' } , { 'file' : 'solarized.css' , 'line' : ' border: 4px solid #657b83;' } , { 'file' : 'white.css' , 'line' : ' border: 4px solid #222;' } , ] for item in data : file_ = item [ 'file' ] lines = [ item [ 'line' ] , ] lines . extend ( [ ' box-shadow: 0 0 10px rgba(0, 0, 0, 0.15); }' , ' box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); }' ] ) for line in lines : update_or_append_line ( filename = flo ( '{repo_dir}/css/theme/{file_}' ) , prefix = line , new_line = flo ( '/*{line}*/' ) )
1,575
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/revealjs.py#L184-L218
[ "def", "confirmation", "(", "self", ",", "apdu", ")", ":", "if", "_debug", ":", "ClientSSM", ".", "_debug", "(", "\"confirmation %r\"", ",", "apdu", ")", "if", "self", ".", "state", "==", "SEGMENTED_REQUEST", ":", "self", ".", "segmented_request", "(", "apdu", ")", "elif", "self", ".", "state", "==", "AWAIT_CONFIRMATION", ":", "self", ".", "await_confirmation", "(", "apdu", ")", "elif", "self", ".", "state", "==", "SEGMENTED_CONFIRMATION", ":", "self", ".", "segmented_confirmation", "(", "apdu", ")", "else", ":", "raise", "RuntimeError", "(", "\"invalid state\"", ")" ]
Install DeckTape .
def decktape ( ) : run ( 'mkdir -p ~/bin/decktape' ) if not exists ( '~/bin/decktape/decktape-1.0.0' ) : print_msg ( '\n## download decktape 1.0.0\n' ) run ( 'cd ~/bin/decktape && ' 'curl -L https://github.com/astefanutti/decktape/archive/' 'v1.0.0.tar.gz | tar -xz --exclude phantomjs' ) run ( 'cd ~/bin/decktape/decktape-1.0.0 && ' 'curl -L https://github.com/astefanutti/decktape/releases/' 'download/v1.0.0/phantomjs-linux-x86-64 -o phantomjs' ) run ( 'cd ~/bin/decktape/decktape-1.0.0 && ' 'chmod +x phantomjs' ) run ( 'ln -snf ~/bin/decktape/decktape-1.0.0 ~/bin/decktape/active' , msg = '\n## link installed decktape version as active' ) print_msg ( '\nCreate PDF from reveal.js presentation:\n\n ' '# serve presentation:\n ' 'cd ~/repos/my_presi/reveal.js/ && npm start\n\n ' '# create pdf in another shell:\n ' 'cd ~/bin/decktape/active && \\\n ' './phantomjs decktape.js --size 1280x800 localhost:8000 ' '~/repos/my_presi/my_presi.pdf' )
1,576
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/revealjs.py#L366-L395
[ "def", "put_lifecycle_configuration", "(", "Bucket", ",", "Rules", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "if", "Rules", "is", "not", "None", "and", "isinstance", "(", "Rules", ",", "six", ".", "string_types", ")", ":", "Rules", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "Rules", ")", "conn", ".", "put_bucket_lifecycle_configuration", "(", "Bucket", "=", "Bucket", ",", "LifecycleConfiguration", "=", "{", "'Rules'", ":", "Rules", "}", ")", "return", "{", "'updated'", ":", "True", ",", "'name'", ":", "Bucket", "}", "except", "ClientError", "as", "e", ":", "return", "{", "'updated'", ":", "False", ",", "'error'", ":", "__utils__", "[", "'boto3.get_error'", "]", "(", "e", ")", "}" ]
Create or update the template presentation demo using task revealjs .
def revealjs_template ( ) : from config import basedir , github_user , github_repo run ( flo ( 'rm -f {basedir}/index.html' ) ) run ( flo ( 'rm -f {basedir}/slides.md' ) ) run ( flo ( 'rm -f {basedir}/README.md' ) ) run ( flo ( 'rm -rf {basedir}/img/' ) ) title = 'reveal.js template' subtitle = '[reveal.js][3] presentation written ' 'in [markdown][4] set up with [fabric][5] & [fabsetup][6]' description = '''\ This presentation shows how to create a reveal.js presentation which will be set up with the fabric task `setup.revealjs` of fabsetup. Also, you can use this presentation source as a reveal.js template: * Checkout this repo * Then set the title in the `index.html` and edit the `slides.md`.''' execute ( revealjs , basedir , title , subtitle , description , github_user , github_repo ) # (README.md was removed, but not the github remote repo) print_msg ( '\n## Re-add github repo infos into README.md' ) basename = os . path . basename ( basedir ) _insert_repo_infos_into_readme ( basedir , github_user = _lazy ( 'github_user' ) , github_repo = _lazy ( 'github_repo' , default = basename ) ) print_msg ( '\n## Assure symbolic link not tracked by git exists\n' ) run ( flo ( 'ln -snf ../reveal.js {basedir}/reveal.js/reveal.js' ) )
1,577
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/revealjs.py#L401-L434
[ "def", "makeFontBoundingBox", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"glyphBoundingBoxes\"", ")", ":", "self", ".", "glyphBoundingBoxes", "=", "self", ".", "makeGlyphsBoundingBoxes", "(", ")", "fontBox", "=", "None", "for", "glyphName", ",", "glyphBox", "in", "self", ".", "glyphBoundingBoxes", ".", "items", "(", ")", ":", "if", "glyphBox", "is", "None", ":", "continue", "if", "fontBox", "is", "None", ":", "fontBox", "=", "glyphBox", "else", ":", "fontBox", "=", "unionRect", "(", "fontBox", ",", "glyphBox", ")", "if", "fontBox", "is", "None", ":", "# unlikely", "fontBox", "=", "BoundingBox", "(", "0", ",", "0", ",", "0", ",", "0", ")", "return", "fontBox" ]
Superposition of analytical solutions without a gridded domain
def spatialDomainNoGrid ( self ) : self . w = np . zeros ( self . xw . shape ) if self . Debug : print ( "w = " ) print ( self . w . shape ) for i in range ( len ( self . q ) ) : # More efficient if we have created some 0-load points # (e.g., for where we want output) if self . q [ i ] != 0 : dist = np . abs ( self . xw - self . x [ i ] ) self . w -= self . q [ i ] * self . coeff * np . exp ( - dist / self . alpha ) * ( np . cos ( dist / self . alpha ) + np . sin ( dist / self . alpha ) )
1,578
https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/f1d.py#L143-L159
[ "def", "to_protobuf", "(", "self", ")", ":", "key", "=", "_entity_pb2", ".", "Key", "(", ")", "key", ".", "partition_id", ".", "project_id", "=", "self", ".", "project", "if", "self", ".", "namespace", ":", "key", ".", "partition_id", ".", "namespace_id", "=", "self", ".", "namespace", "for", "item", "in", "self", ".", "path", ":", "element", "=", "key", ".", "path", ".", "add", "(", ")", "if", "\"kind\"", "in", "item", ":", "element", ".", "kind", "=", "item", "[", "\"kind\"", "]", "if", "\"id\"", "in", "item", ":", "element", ".", "id", "=", "item", "[", "\"id\"", "]", "if", "\"name\"", "in", "item", ":", "element", ".", "name", "=", "item", "[", "\"name\"", "]", "return", "key" ]
Builds the diagonals for the coefficient array
def build_diagonals ( self ) : ########################################################## # INCORPORATE BOUNDARY CONDITIONS INTO COEFFICIENT ARRAY # ########################################################## # Roll to keep the proper coefficients at the proper places in the # arrays: Python will naturally just do vertical shifts instead of # diagonal shifts, so this takes into account the horizontal compoent # to ensure that boundary values are at the right place. self . l2 = np . roll ( self . l2 , - 2 ) self . l1 = np . roll ( self . l1 , - 1 ) self . r1 = np . roll ( self . r1 , 1 ) self . r2 = np . roll ( self . r2 , 2 ) # Then assemble these rows: this is where the periodic boundary condition # can matter. if self . coeff_matrix is not None : pass elif self . BC_E == 'Periodic' and self . BC_W == 'Periodic' : # In this case, the boundary-condition-related stacking has already # happened inside b.c.-handling function. This is because periodic # boundary conditions require extra diagonals to exist on the edges of # the solution array pass else : self . diags = np . vstack ( ( self . l2 , self . l1 , self . c0 , self . r1 , self . r2 ) ) self . offsets = np . array ( [ - 2 , - 1 , 0 , 1 , 2 ] ) # Everybody now (including periodic b.c. cases) self . coeff_matrix = spdiags ( self . diags , self . offsets , self . nx , self . nx , format = 'csr' )
1,579
https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/f1d.py#L344-L377
[ "def", "update_custom_field_options", "(", "self", ",", "custom_field_key", ",", "new_options", ",", "keep_existing_options", ")", ":", "custom_field_key", "=", "quote", "(", "custom_field_key", ",", "''", ")", "body", "=", "{", "\"Options\"", ":", "new_options", ",", "\"KeepExistingOptions\"", ":", "keep_existing_options", "}", "response", "=", "self", ".", "_put", "(", "self", ".", "uri_for", "(", "\"customfields/%s/options\"", "%", "custom_field_key", ")", ",", "json", ".", "dumps", "(", "body", ")", ")" ]
Creates Combine Archive containing the given file .
def createArchiveExample ( fileName ) : print ( '*' * 80 ) print ( 'Create archive' ) print ( '*' * 80 ) archive = CombineArchive ( ) archive . addFile ( fileName , # filename "./models/model.xml" , # target file name KnownFormats . lookupFormat ( "sbml" ) , # look up identifier for SBML models True # mark file as master ) # add metadata to the archive itself description = OmexDescription ( ) description . setAbout ( "." ) description . setDescription ( "Simple test archive including one SBML model" ) description . setCreated ( OmexDescription . getCurrentDateAndTime ( ) ) creator = VCard ( ) creator . setFamilyName ( "Bergmann" ) creator . setGivenName ( "Frank" ) creator . setEmail ( "fbergman@caltech.edu" ) creator . setOrganization ( "Caltech" ) description . addCreator ( creator ) archive . addMetadata ( "." , description ) # add metadata to the added file location = "./models/model.xml" description = OmexDescription ( ) description . setAbout ( location ) description . setDescription ( "SBML model" ) description . setCreated ( OmexDescription . getCurrentDateAndTime ( ) ) archive . addMetadata ( location , description ) # write the archive out_file = "out.omex" archive . writeToFile ( out_file ) print ( 'Archive created:' , out_file )
1,580
https://github.com/sbmlteam/libCombine/blob/d7c11a90129dedbcc8bdba8d204be03f1dd0c3e4/examples/python/createArchiveExample.py#L11-L57
[ "def", "audit_customer_subscription", "(", "customer", ",", "unknown", "=", "True", ")", ":", "if", "(", "hasattr", "(", "customer", ",", "'suspended'", ")", "and", "customer", ".", "suspended", ")", ":", "result", "=", "AUDIT_RESULTS", "[", "'suspended'", "]", "else", ":", "if", "hasattr", "(", "customer", ",", "'subscription'", ")", ":", "try", ":", "result", "=", "AUDIT_RESULTS", "[", "customer", ".", "subscription", ".", "status", "]", "except", "KeyError", ",", "err", ":", "# TODO should this be a more specific exception class?", "raise", "Exception", "(", "\"Unable to locate a result set for \\\nsubscription status %s in ZEBRA_AUDIT_RESULTS\"", ")", "%", "str", "(", "err", ")", "else", ":", "result", "=", "AUDIT_RESULTS", "[", "'no_subscription'", "]", "return", "result" ]
Calculate the standard deviation of a list of values
def calc_deviation ( values , average ) : size = len ( values ) if size < 2 : return 0 calc_sum = 0.0 for number in range ( 0 , size ) : calc_sum += math . sqrt ( ( values [ number ] - average ) ** 2 ) return math . sqrt ( ( 1.0 / ( size - 1 ) ) * ( calc_sum / size ) )
1,581
https://github.com/yahoo/serviceping/blob/1f9df5ee5b3cba466426b1164262278472ba4977/serviceping/serviceping.py#L106-L120
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Append a value to the stats list
def append ( self , value ) : self . count += 1 if self . count == 1 : self . old_m = self . new_m = value self . old_s = 0 else : self . new_m = self . old_m + ( value - self . old_m ) / self . count self . new_s = self . old_s + ( value - self . old_m ) * ( value - self . new_m ) self . old_m = self . new_m self . old_s = self . new_s
1,582
https://github.com/yahoo/serviceping/blob/1f9df5ee5b3cba466426b1164262278472ba4977/serviceping/serviceping.py#L35-L54
[ "def", "guess_extension", "(", "amimetype", ",", "normalize", "=", "False", ")", ":", "ext", "=", "_mimes", ".", "guess_extension", "(", "amimetype", ")", "if", "ext", "and", "normalize", ":", "# Normalize some common magic mis-interpreation", "ext", "=", "{", "'.asc'", ":", "'.txt'", ",", "'.obj'", ":", "'.bin'", "}", ".", "get", "(", "ext", ",", "ext", ")", "from", "invenio", ".", "legacy", ".", "bibdocfile", ".", "api_normalizer", "import", "normalize_format", "return", "normalize_format", "(", "ext", ")", "return", "ext" ]
Chain results from a list of functions . Inverted reduce .
def pipeline ( steps , initial = None ) : def apply ( result , step ) : return step ( result ) return reduce ( apply , steps , initial )
1,583
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/docs/github_docs.py#L186-L197
[ "def", "map_template", "(", "category", ",", "template_list", ")", ":", "if", "isinstance", "(", "template_list", ",", "str", ")", ":", "template_list", "=", "[", "template_list", "]", "for", "template", "in", "template_list", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "category", ")", "while", "path", "is", "not", "None", ":", "for", "extension", "in", "[", "''", ",", "'.html'", ",", "'.htm'", ",", "'.xml'", ",", "'.json'", "]", ":", "candidate", "=", "os", ".", "path", ".", "join", "(", "path", ",", "template", "+", "extension", ")", "file_path", "=", "os", ".", "path", ".", "join", "(", "config", ".", "template_folder", ",", "candidate", ")", "if", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "return", "Template", "(", "template", ",", "candidate", ",", "file_path", ")", "parent", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "parent", "!=", "path", ":", "path", "=", "parent", "else", ":", "path", "=", "None" ]
Add a value to a delimited variable but only when the value isn t already present .
def add ( class_ , name , value , sep = ';' ) : values = class_ . get_values_list ( name , sep ) if value in values : return new_value = sep . join ( values + [ value ] ) winreg . SetValueEx ( class_ . key , name , 0 , winreg . REG_EXPAND_SZ , new_value ) class_ . notify ( )
1,584
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/environ.py#L84-L95
[ "def", "read_jp2_image", "(", "filename", ")", ":", "# Other option:", "# return glymur.Jp2k(filename)[:]", "image", "=", "read_image", "(", "filename", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "file", ":", "bit_depth", "=", "get_jp2_bit_depth", "(", "file", ")", "return", "fix_jp2_image", "(", "image", ",", "bit_depth", ")" ]
Windows Platform SDK GetTimeZoneInformation
def current ( class_ ) : tzi = class_ ( ) kernel32 = ctypes . windll . kernel32 getter = kernel32 . GetTimeZoneInformation getter = getattr ( kernel32 , 'GetDynamicTimeZoneInformation' , getter ) code = getter ( ctypes . byref ( tzi ) ) return code , tzi
1,585
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/timezone.py#L168-L175
[ "def", "remove_entry", "(", "self", ",", "*", "*", "field_value", ")", ":", "field", ",", "value", "=", "next", "(", "iter", "(", "field_value", ".", "items", "(", ")", ")", ")", "self", ".", "data", "[", "'entries'", "]", "[", ":", "]", "=", "[", "entry", "for", "entry", "in", "self", ".", "data", ".", "get", "(", "'entries'", ")", "if", "entry", ".", "get", "(", "'{}_entry'", ".", "format", "(", "self", ".", "typeof", ")", ")", ".", "get", "(", "field", ")", "!=", "str", "(", "value", ")", "]" ]
Return a map that for a given year will return the correct Info
def dynamic_info ( self ) : if self . key_name : dyn_key = self . get_key ( ) . subkey ( 'Dynamic DST' ) del dyn_key [ 'FirstEntry' ] del dyn_key [ 'LastEntry' ] years = map ( int , dyn_key . keys ( ) ) values = map ( Info , dyn_key . values ( ) ) # create a range mapping that searches by descending year and matches # if the target year is greater or equal. return RangeMap ( zip ( years , values ) , RangeMap . descending , operator . ge ) else : return AnyDict ( self )
1,586
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/timezone.py#L198-L210
[ "def", "assert_interrupt_signal", "(", "library", ",", "session", ",", "mode", ",", "status_id", ")", ":", "return", "library", ".", "viAssertIntrSignal", "(", "session", ",", "mode", ",", "status_id", ")" ]
Takes a SYSTEMTIME object such as retrieved from a TIME_ZONE_INFORMATION structure or call to GetTimeZoneInformation and interprets it based on the given year to identify the actual day .
def _locate_day ( year , cutoff ) : # MS stores Sunday as 0, Python datetime stores Monday as zero target_weekday = ( cutoff . day_of_week + 6 ) % 7 # For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day # is the week of the month week_of_month = cutoff . day # so the following is the first day of that week day = ( week_of_month - 1 ) * 7 + 1 result = datetime . datetime ( year , cutoff . month , day , cutoff . hour , cutoff . minute , cutoff . second , cutoff . millisecond ) # now the result is the correct week, but not necessarily # the correct day of the week days_to_go = ( target_weekday - result . weekday ( ) ) % 7 result += datetime . timedelta ( days_to_go ) # if we selected a day in the month following the target month, # move back a week or two. # This is necessary because Microsoft defines the fifth week in a month # to be the last week in a month and adding the time delta might have # pushed the result into the next month. while result . month == cutoff . month + 1 : result -= datetime . timedelta ( weeks = 1 ) return result
1,587
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/timezone.py#L213-L254
[ "def", "_max_weight_state", "(", "states", ":", "Iterable", "[", "TensorProductState", "]", ")", "->", "Union", "[", "None", ",", "TensorProductState", "]", ":", "mapping", "=", "dict", "(", ")", "# type: Dict[int, _OneQState]", "for", "state", "in", "states", ":", "for", "oneq_state", "in", "state", ".", "states", ":", "if", "oneq_state", ".", "qubit", "in", "mapping", ":", "if", "mapping", "[", "oneq_state", ".", "qubit", "]", "!=", "oneq_state", ":", "return", "None", "else", ":", "mapping", "[", "oneq_state", ".", "qubit", "]", "=", "oneq_state", "return", "TensorProductState", "(", "list", "(", "mapping", ".", "values", "(", ")", ")", ")" ]
Return a url matcher suited for urlpatterns .
def redirect ( pattern , to , permanent = True , locale_prefix = True , anchor = None , name = None , query = None , vary = None , cache_timeout = 12 , decorators = None , re_flags = None , to_args = None , to_kwargs = None , prepend_locale = True , merge_query = False ) : if permanent : redirect_class = HttpResponsePermanentRedirect else : redirect_class = HttpResponseRedirect if locale_prefix : pattern = pattern . lstrip ( '^/' ) pattern = LOCALE_RE + pattern if re_flags : pattern = '(?{})' . format ( re_flags ) + pattern view_decorators = [ ] if cache_timeout is not None : view_decorators . append ( cache_control_expires ( cache_timeout ) ) if vary : if isinstance ( vary , basestring ) : vary = [ vary ] view_decorators . append ( vary_on_headers ( * vary ) ) if decorators : if callable ( decorators ) : view_decorators . append ( decorators ) else : view_decorators . extend ( decorators ) def _view ( request , * args , * * kwargs ) : # don't want to have 'None' in substitutions kwargs = { k : v or '' for k , v in kwargs . items ( ) } args = [ x or '' for x in args ] # If it's a callable, call it and get the url out. if callable ( to ) : to_value = to ( request , * args , * * kwargs ) else : to_value = to if to_value . startswith ( '/' ) or HTTP_RE . match ( to_value ) : redirect_url = to_value else : try : redirect_url = reverse ( to_value , args = to_args , kwargs = to_kwargs ) except NoReverseMatch : # Assume it's a URL redirect_url = to_value if prepend_locale and redirect_url . startswith ( '/' ) and kwargs . get ( 'locale' ) : redirect_url = '/{locale}' + redirect_url . lstrip ( '/' ) # use info from url captures. if args or kwargs : redirect_url = strip_tags ( force_text ( redirect_url ) . format ( * args , * * kwargs ) ) if query : if merge_query : req_query = parse_qs ( request . META . get ( 'QUERY_STRING' ) ) req_query . update ( query ) querystring = urlencode ( req_query , doseq = True ) else : querystring = urlencode ( query , doseq = True ) elif query is None : querystring = request . META . get ( 'QUERY_STRING' ) else : querystring = '' if querystring : redirect_url = '?' . join ( [ redirect_url , querystring ] ) if anchor : redirect_url = '#' . join ( [ redirect_url , anchor ] ) if PROTOCOL_RELATIVE_RE . match ( redirect_url ) : redirect_url = '/' + redirect_url . lstrip ( '/' ) return redirect_class ( redirect_url ) # Apply decorators try : # Decorators should be applied in reverse order so that input # can be sent in the order your would write nested decorators # e.g. dec1(dec2(_view)) -> [dec1, dec2] for decorator in reversed ( view_decorators ) : _view = decorator ( _view ) except TypeError : log . exception ( 'decorators not iterable or does not contain ' 'callable items' ) return url ( pattern , _view , name = name )
1,588
https://github.com/pmac/django-redirect-urls/blob/21495194b0b2a2bdd1013e13ec0d54d34dd7f750/redirect_urls/utils.py#L128-L257
[ "def", "inspect_workers", "(", "self", ")", ":", "workers", "=", "tuple", "(", "self", ".", "workers", ".", "values", "(", ")", ")", "expired", "=", "tuple", "(", "w", "for", "w", "in", "workers", "if", "not", "w", ".", "is_alive", "(", ")", ")", "for", "worker", "in", "expired", ":", "self", ".", "workers", ".", "pop", "(", "worker", ".", "pid", ")", "return", "(", "(", "w", ".", "pid", ",", "w", ".", "exitcode", ")", "for", "w", "in", "expired", "if", "w", ".", "exitcode", "!=", "0", ")" ]
Retrieve the size of the buffer needed by calling the method with a null pointer and length of zero . This should trigger an insufficient buffer error and return the size needed for the buffer .
def __get_table_size ( self ) : length = ctypes . wintypes . DWORD ( ) res = self . method ( None , length , False ) if res != errors . ERROR_INSUFFICIENT_BUFFER : raise RuntimeError ( "Error getting table length (%d)" % res ) return length . value
1,589
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/inet.py#L49-L60
[ "def", "dict_from_hdf5", "(", "dict_like", ",", "h5group", ")", ":", "# Read attributes", "for", "name", ",", "value", "in", "h5group", ".", "attrs", ".", "items", "(", ")", ":", "dict_like", "[", "name", "]", "=", "value" ]
Get the table
def get_table ( self ) : buffer_length = self . __get_table_size ( ) returned_buffer_length = ctypes . wintypes . DWORD ( buffer_length ) buffer = ctypes . create_string_buffer ( buffer_length ) pointer_type = ctypes . POINTER ( self . structure ) table_p = ctypes . cast ( buffer , pointer_type ) res = self . method ( table_p , returned_buffer_length , False ) if res != errors . NO_ERROR : raise RuntimeError ( "Error retrieving table (%d)" % res ) return table_p . contents
1,590
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/inet.py#L62-L74
[ "def", "get_placement_solver", "(", "service_instance", ")", ":", "stub", "=", "salt", ".", "utils", ".", "vmware", ".", "get_new_service_instance_stub", "(", "service_instance", ",", "ns", "=", "'pbm/2.0'", ",", "path", "=", "'/pbm/sdk'", ")", "pbm_si", "=", "pbm", ".", "ServiceInstance", "(", "'ServiceInstance'", ",", "stub", ")", "try", ":", "profile_manager", "=", "pbm_si", ".", "RetrieveContent", "(", ")", ".", "placementSolver", "except", "vim", ".", "fault", ".", "NoPermission", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "VMwareApiError", "(", "'Not enough permissions. Required privilege: '", "'{0}'", ".", "format", "(", "exc", ".", "privilegeId", ")", ")", "except", "vim", ".", "fault", ".", "VimFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "VMwareApiError", "(", "exc", ".", "msg", ")", "except", "vmodl", ".", "RuntimeFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "VMwareRuntimeError", "(", "exc", ".", "msg", ")", "return", "profile_manager" ]
Using the table structure return the array of entries based on the table size .
def entries ( self ) : table = self . get_table ( ) entries_array = self . row_structure * table . num_entries pointer_type = ctypes . POINTER ( entries_array ) return ctypes . cast ( table . entries , pointer_type ) . contents
1,591
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/inet.py#L77-L85
[ "def", "acquire_writer", "(", "self", ")", ":", "with", "self", ".", "mutex", ":", "while", "self", ".", "rwlock", "!=", "0", ":", "self", ".", "_writer_wait", "(", ")", "self", ".", "rwlock", "=", "-", "1" ]
Set up owncloud .
def owncloud ( ) : hostname = re . sub ( r'^[^@]+@' , '' , env . host ) # without username if any sitename = query_input ( question = '\nEnter site-name of Your Owncloud web service' , default = flo ( 'owncloud.{hostname}' ) , color = cyan ) username = env . user fabfile_data_dir = FABFILE_DATA_DIR print ( magenta ( ' install owncloud' ) ) repository = '' . join ( [ 'http://download.opensuse.org/repositories/' , 'isv:/ownCloud:/community/Debian_7.0/' , ] ) with hide ( 'output' ) : sudo ( flo ( 'wget -O - {repository}Release.key | apt-key add -' ) ) filename = '/etc/apt/sources.list.d/owncloud.list' sudo ( flo ( "echo 'deb {repository} /' > {filename}" ) ) sudo ( 'apt-get update' ) install_packages ( [ 'owncloud' , 'php5-fpm' , 'php-apc' , 'memcached' , 'php5-memcache' , ] ) # This server uses nginx. owncloud pulls apache2 => Disable apache2 print ( magenta ( ' disable apache' ) ) with hide ( 'output' ) : sudo ( 'service apache2 stop' ) sudo ( 'update-rc.d apache2 disable' ) print ( magenta ( ' nginx setup for owncloud' ) ) filename = 'owncloud_site_config.template' path = flo ( '{fabfile_data_dir}/files/etc/nginx/sites-available/{filename}' ) from_str = filled_out_template ( path , username = username , sitename = sitename , hostname = hostname ) with tempfile . NamedTemporaryFile ( prefix = filename ) as tmp_file : with open ( tmp_file . name , 'w' ) as fp : fp . write ( from_str ) put ( tmp_file . name , flo ( '/tmp/{filename}' ) ) to = flo ( '/etc/nginx/sites-available/{sitename}' ) sudo ( flo ( 'mv /tmp/{filename} {to}' ) ) sudo ( flo ( 'chown root.root {to}' ) ) sudo ( flo ( 'chmod 644 {to}' ) ) sudo ( flo ( ' ' . join ( [ 'ln -snf ../sites-available/{sitename}' , '/etc/nginx/sites-enabled/{sitename}' , ] ) ) ) # php5 fpm fast-cgi config template = 'www.conf' to = flo ( '/etc/php5/fpm/pool.d/{template}' ) from_ = flo ( '{fabfile_data_dir}/files{to}' ) put ( from_ , '/tmp/' ) sudo ( flo ( 'mv /tmp/{template} {to}' ) ) sudo ( flo ( 'chown root.root {to}' ) ) sudo ( flo ( 'chmod 644 {to}' ) ) template = 'php.ini' to = flo ( '/etc/php5/fpm/{template}' ) from_ = flo ( '{fabfile_data_dir}/files{to}' ) put ( from_ , '/tmp/' ) sudo ( flo ( 'mv /tmp/{template} {to}' ) ) sudo ( flo ( 'chown root.root {to}' ) ) sudo ( flo ( 'chmod 644 {to}' ) ) sudo ( 'service php5-fpm restart' ) sudo ( 'service nginx reload' )
1,592
https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/service/__init__.py#L23-L98
[ "def", "_get_dL2L", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "0.18", ":", "dL2L", "=", "-", "0.06", "elif", "0.18", "<=", "imt_per", "<", "0.35", ":", "dL2L", "=", "self", ".", "_interp_function", "(", "0.12", ",", "-", "0.06", ",", "0.35", ",", "0.18", ",", "imt_per", ")", "elif", "0.35", "<=", "imt_per", "<=", "10", ":", "dL2L", "=", "self", ".", "_interp_function", "(", "0.65", ",", "0.12", ",", "10", ",", "0.35", ",", "imt_per", ")", "else", ":", "dL2L", "=", "0", "return", "dL2L" ]
Add orphan to metadata for partials
def doctree_read_handler ( app , doctree ) : # noinspection PyProtectedMember docname = sys . _getframe ( 2 ) . f_locals [ 'docname' ] if docname . startswith ( '_partial' ) : app . env . metadata [ docname ] [ 'orphan' ] = True
1,593
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/docs/source/conf.py#L26-L36
[ "def", "get_user_last_submissions", "(", "self", ",", "limit", "=", "5", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "{", "}", "request", ".", "update", "(", "{", "\"username\"", ":", "self", ".", "_user_manager", ".", "session_username", "(", ")", "}", ")", "# Before, submissions were first sorted by submission date, then grouped", "# and then resorted by submission date before limiting. Actually, grouping", "# and pushing, keeping the max date, followed by result filtering is much more", "# efficient", "data", "=", "self", ".", "_database", ".", "submissions", ".", "aggregate", "(", "[", "{", "\"$match\"", ":", "request", "}", ",", "{", "\"$group\"", ":", "{", "\"_id\"", ":", "{", "\"courseid\"", ":", "\"$courseid\"", ",", "\"taskid\"", ":", "\"$taskid\"", "}", ",", "\"submitted_on\"", ":", "{", "\"$max\"", ":", "\"$submitted_on\"", "}", ",", "\"submissions\"", ":", "{", "\"$push\"", ":", "{", "\"_id\"", ":", "\"$_id\"", ",", "\"result\"", ":", "\"$result\"", ",", "\"status\"", ":", "\"$status\"", ",", "\"courseid\"", ":", "\"$courseid\"", ",", "\"taskid\"", ":", "\"$taskid\"", ",", "\"submitted_on\"", ":", "\"$submitted_on\"", "}", "}", ",", "}", "}", ",", "{", "\"$project\"", ":", "{", "\"submitted_on\"", ":", "1", ",", "\"submissions\"", ":", "{", "# This could be replaced by $filter if mongo v3.2 is set as dependency", "\"$setDifference\"", ":", "[", "{", "\"$map\"", ":", "{", "\"input\"", ":", "\"$submissions\"", ",", "\"as\"", ":", "\"submission\"", ",", "\"in\"", ":", "{", "\"$cond\"", ":", "[", "{", "\"$eq\"", ":", "[", "\"$submitted_on\"", ",", "\"$$submission.submitted_on\"", "]", "}", ",", "\"$$submission\"", ",", "False", "]", "}", "}", "}", ",", "[", "False", "]", "]", "}", "}", "}", ",", "{", "\"$sort\"", ":", "{", "\"submitted_on\"", ":", "pymongo", ".", "DESCENDING", "}", "}", ",", "{", "\"$limit\"", ":", "limit", "}", "]", ")", "return", "[", "item", "[", "\"submissions\"", "]", "[", "0", "]", "for", "item", "in", "data", "]" ]
Skip un parseable functions .
def autodoc_skip_member_handler ( app , what , name , obj , skip , options ) : if 'YAMLTokens' in name : return True return False
1,594
https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/docs/source/conf.py#L39-L54
[ "def", "bind_port", "(", "self", ",", "context", ")", ":", "vnic_type", "=", "context", ".", "current", ".", "get", "(", "bc", ".", "portbindings", ".", "VNIC_TYPE", ",", "bc", ".", "portbindings", ".", "VNIC_NORMAL", ")", "LOG", ".", "debug", "(", "'Attempting to bind port %(port)s with vnic_type '", "'%(vnic_type)s on network %(network)s '", ",", "{", "'port'", ":", "context", ".", "current", "[", "'id'", "]", ",", "'vnic_type'", ":", "vnic_type", ",", "'network'", ":", "context", ".", "network", ".", "current", "[", "'id'", "]", "}", ")", "profile", "=", "context", ".", "current", ".", "get", "(", "bc", ".", "portbindings", ".", "PROFILE", ",", "{", "}", ")", "if", "not", "self", ".", "driver", ".", "check_vnic_type_and_vendor_info", "(", "vnic_type", ",", "profile", ")", ":", "return", "for", "segment", "in", "context", ".", "network", ".", "network_segments", ":", "if", "self", ".", "check_segment", "(", "segment", ")", ":", "vlan_id", "=", "segment", "[", "api", ".", "SEGMENTATION_ID", "]", "if", "not", "vlan_id", ":", "LOG", ".", "warning", "(", "'Cannot bind port: vlan_id is None.'", ")", "return", "LOG", ".", "debug", "(", "\"Port binding to Vlan_id: %s\"", ",", "str", "(", "vlan_id", ")", ")", "# Check if this is a Cisco VM-FEX port or Intel SR_IOV port", "if", "self", ".", "driver", ".", "is_vmfex_port", "(", "profile", ")", ":", "profile_name", "=", "self", ".", "make_profile_name", "(", "vlan_id", ")", "self", ".", "vif_details", "[", "const", ".", "VIF_DETAILS_PROFILEID", "]", "=", "profile_name", "else", ":", "self", ".", "vif_details", "[", "bc", ".", "portbindings", ".", "VIF_DETAILS_VLAN", "]", "=", "str", "(", "vlan_id", ")", "context", ".", "set_binding", "(", "segment", "[", "api", ".", "ID", "]", ",", "self", ".", "vif_type", ",", "self", ".", "vif_details", ",", "bc", ".", "constants", ".", "PORT_STATUS_ACTIVE", ")", "return", "LOG", ".", "error", "(", "'UCS Mech Driver: Failed binding port ID %(id)s '", "'on any segment of network %(network)s'", ",", "{", "'id'", ":", "context", ".", "current", "[", "'id'", "]", ",", "'network'", ":", "context", ".", "network", ".", "current", "[", "'id'", "]", "}", ")" ]
Plot if you want to - for troubleshooting - 1 figure
def surfplot ( self , z , titletext ) : if self . latlon : plt . imshow ( z , extent = ( 0 , self . dx * z . shape [ 0 ] , self . dy * z . shape [ 1 ] , 0 ) ) #,interpolation='nearest' plt . xlabel ( 'longitude [deg E]' , fontsize = 12 , fontweight = 'bold' ) plt . ylabel ( 'latitude [deg N]' , fontsize = 12 , fontweight = 'bold' ) else : plt . imshow ( z , extent = ( 0 , self . dx / 1000. * z . shape [ 0 ] , self . dy / 1000. * z . shape [ 1 ] , 0 ) ) #,interpolation='nearest' plt . xlabel ( 'x [km]' , fontsize = 12 , fontweight = 'bold' ) plt . ylabel ( 'y [km]' , fontsize = 12 , fontweight = 'bold' ) plt . colorbar ( ) plt . title ( titletext , fontsize = 16 )
1,595
https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/base.py#L376-L390
[ "def", "pull", "(", "self", ",", "dict_name", ")", ":", "dict_name", "=", "self", ".", "_namespace", "(", "dict_name", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "res", "=", "conn", ".", "hgetall", "(", "dict_name", ")", "split_res", "=", "dict", "(", "[", "(", "self", ".", "_decode", "(", "key", ")", ",", "self", ".", "_decode", "(", "value", ")", ")", "for", "key", ",", "value", "in", "res", ".", "iteritems", "(", ")", "]", ")", "return", "split_res" ]
Plot multiple subplot figure for 2D array
def twoSurfplots ( self ) : # Could more elegantly just call surfplot twice # And also could include xyzinterp as an option inside surfplot. # Noted here in case anyone wants to take that on in the future... plt . subplot ( 211 ) plt . title ( 'Load thickness, mantle equivalent [m]' , fontsize = 16 ) if self . latlon : plt . imshow ( self . qs / ( self . rho_m * self . g ) , extent = ( 0 , self . dx * self . qs . shape [ 0 ] , self . dy * self . qs . shape [ 1 ] , 0 ) ) plt . xlabel ( 'longitude [deg E]' , fontsize = 12 , fontweight = 'bold' ) plt . ylabel ( 'latitude [deg N]' , fontsize = 12 , fontweight = 'bold' ) else : plt . imshow ( self . qs / ( self . rho_m * self . g ) , extent = ( 0 , self . dx / 1000. * self . qs . shape [ 0 ] , self . dy / 1000. * self . qs . shape [ 1 ] , 0 ) ) plt . xlabel ( 'x [km]' , fontsize = 12 , fontweight = 'bold' ) plt . ylabel ( 'y [km]' , fontsize = 12 , fontweight = 'bold' ) plt . colorbar ( ) plt . subplot ( 212 ) plt . title ( 'Deflection [m]' ) if self . latlon : plt . imshow ( self . w , extent = ( 0 , self . dx * self . w . shape [ 0 ] , self . dy * self . w . shape [ 1 ] , 0 ) ) plt . xlabel ( 'longitude [deg E]' , fontsize = 12 , fontweight = 'bold' ) plt . ylabel ( 'latitude [deg N]' , fontsize = 12 , fontweight = 'bold' ) else : plt . imshow ( self . w , extent = ( 0 , self . dx / 1000. * self . w . shape [ 0 ] , self . dy / 1000. * self . w . shape [ 1 ] , 0 ) ) plt . xlabel ( 'x [km]' , fontsize = 12 , fontweight = 'bold' ) plt . ylabel ( 'y [km]' , fontsize = 12 , fontweight = 'bold' ) plt . colorbar ( )
1,596
https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/base.py#L392-L422
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Outputs a grid of deflections if an output directory is defined in the configuration file If the filename given in the configuration file ends in . npy then a binary numpy grid will be exported . Otherwise an ASCII grid will be exported .
def outputDeflections ( self ) : try : # If wOutFile exists, has already been set by a setter self . wOutFile if self . Verbose : print ( "Output filename provided." ) # Otherwise, it needs to be set by an configuration file except : try : self . wOutFile = self . configGet ( "string" , "output" , "DeflectionOut" , optional = True ) except : # if there is no parsable output string, do not generate output; # this allows the user to leave the line blank and produce no output if self . Debug : print ( "No output filename provided:" ) print ( " not writing any deflection output to file" ) if self . wOutFile : if self . wOutFile [ - 4 : ] == '.npy' : from numpy import save save ( self . wOutFile , self . w ) else : from numpy import savetxt # Shouldn't need more than mm precision, at very most savetxt ( self . wOutFile , self . w , fmt = '%.3f' ) if self . Verbose : print ( "Saving deflections --> " + self . wOutFile )
1,597
https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/base.py#L762-L796
[ "def", "push_peer", "(", "self", ",", "peer", ")", ":", "self", ".", "order", "+=", "1", "peer", ".", "order", "=", "self", ".", "order", "+", "random", ".", "randint", "(", "0", ",", "self", ".", "size", "(", ")", ")", "heap", ".", "push", "(", "self", ",", "peer", ")" ]
Checks that Te and q0 array sizes are compatible For finite difference solution .
def TeArraySizeCheck ( self ) : # Only if they are both defined and are arrays # Both being arrays is a possible bug in this check routine that I have # intentionally introduced if type ( self . Te ) == np . ndarray and type ( self . qs ) == np . ndarray : # Doesn't touch non-arrays or 1D arrays if type ( self . Te ) is np . ndarray : if ( np . array ( self . Te . shape ) != np . array ( self . qs . shape ) ) . any ( ) : sys . exit ( "q0 and Te arrays have incompatible shapes. Exiting." ) else : if self . Debug : print ( "Te and qs array sizes pass consistency check" )
1,598
https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/base.py#L907-L921
[ "def", "_post_tags", "(", "self", ",", "fileobj", ")", ":", "page", "=", "OggPage", ".", "find_last", "(", "fileobj", ",", "self", ".", "serial", ",", "finishing", "=", "True", ")", "if", "page", "is", "None", ":", "raise", "OggVorbisHeaderError", "self", ".", "length", "=", "page", ".", "position", "/", "float", "(", "self", ".", "sample_rate", ")" ]
Set - up for the finite difference solution method
def FD ( self ) : if self . Verbose : print ( "Finite Difference Solution Technique" ) # Used to check for coeff_matrix here, but now doing so in self.bc_check() # called by f1d and f2d at the start # # Define a stress-based qs = q0 # But only if the latter has not already been defined # (e.g., by the getters and setters) try : self . qs except : self . qs = self . q0 . copy ( ) # Remove self.q0 to avoid issues with multiply-defined inputs # q0 is the parsable input to either a qs grid or contains (x,(y),q) del self . q0 # Give it x and y dimensions for help with plotting tools # (not implemented internally, but a help with external methods) self . x = np . arange ( self . dx / 2. , self . dx * self . qs . shape [ 0 ] , self . dx ) if self . dimension == 2 : self . y = np . arange ( self . dy / 2. , self . dy * self . qs . shape [ 1 ] , self . dy ) # Is there a solver defined try : self . Solver # See if it exists already except : # Well, will fail if it doesn't see this, maybe not the most reasonable # error message. if self . filename : self . Solver = self . configGet ( "string" , "numerical" , "Solver" ) else : sys . exit ( "No solver defined!" ) # Check consistency of size if coeff array was loaded if self . filename : # In the case that it is iterative, find the convergence criterion self . iterative_ConvergenceTolerance = self . configGet ( "float" , "numerical" , "ConvergenceTolerance" ) # Try to import Te grid or scalar for the finite difference solution try : self . Te = self . configGet ( "float" , "input" , "ElasticThickness" , optional = False ) if self . Te is None : Tepath = self . configGet ( "string" , "input" , "ElasticThickness" , optional = False ) self . Te = Tepath else : Tepath = None except : Tepath = self . configGet ( "string" , "input" , "ElasticThickness" , optional = False ) self . Te = Tepath if self . Te is None : if self . coeff_matrix is not None : pass else : # Have to bring this out here in case it was discovered in the # try statement that there is no value given sys . exit ( "No input elastic thickness or coefficient matrix supplied." ) # or if getter/setter if type ( self . Te ) == str : # Try to import Te grid or scalar for the finite difference solution Tepath = self . Te else : Tepath = None # in case no self.filename present (like for GRASS GIS) # If there is a Tepath, import Te # Assume that even if a coeff_matrix is defined # That the user wants Te if they gave the path if Tepath : self . Te = self . loadFile ( self . Te , close_on_fail = False ) if self . Te is None : print ( "Requested Te file is provided but cannot be located." ) print ( "No scalar elastic thickness is provided in configuration file" ) print ( "(Typo in path to input Te grid?)" ) if self . coeff_matrix is not None : print ( "But a coefficient matrix has been found." ) print ( "Calculations will be carried forward using it." ) else : print ( "Exiting." ) sys . exit ( ) # Check that Te is the proper size if it was loaded # Will be array if it was loaded if self . Te . any ( ) : self . TeArraySizeCheck ( )
1,599
https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/base.py#L927-L1008
[ "def", "asset_path", "(", "cls", ",", "organization", ",", "asset", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"organizations/{organization}/assets/{asset}\"", ",", "organization", "=", "organization", ",", "asset", "=", "asset", ",", ")" ]