repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
biocore/burrito-fillings
bfillings/mothur.py
Mothur._derive_species_abundance_path
def _derive_species_abundance_path(self): """Guess species abundance file path produced by Mothur""" base, ext = path.splitext(self._input_filename) return '%s.unique.%s.sabund' % (base, self.__get_method_abbrev())
python
def _derive_species_abundance_path(self): """Guess species abundance file path produced by Mothur""" base, ext = path.splitext(self._input_filename) return '%s.unique.%s.sabund' % (base, self.__get_method_abbrev())
[ "def", "_derive_species_abundance_path", "(", "self", ")", ":", "base", ",", "ext", "=", "path", ".", "splitext", "(", "self", ".", "_input_filename", ")", "return", "'%s.unique.%s.sabund'", "%", "(", "base", ",", "self", ".", "__get_method_abbrev", "(", ")", ...
Guess species abundance file path produced by Mothur
[ "Guess", "species", "abundance", "file", "path", "produced", "by", "Mothur" ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L318-L321
biocore/burrito-fillings
bfillings/mothur.py
Mothur.getTmpFilename
def getTmpFilename(self, tmp_dir=None, prefix='tmp', suffix='.txt'): """Returns a temporary filename Similar interface to tempfile.mktmp() """ # Override to change default constructor to str(). FilePath # objects muck up the Mothur script. return super(Mothur, self).getTmpFilename( tmp_dir=tmp_dir, prefix=prefix, suffix=suffix, result_constructor=str)
python
def getTmpFilename(self, tmp_dir=None, prefix='tmp', suffix='.txt'): """Returns a temporary filename Similar interface to tempfile.mktmp() """ # Override to change default constructor to str(). FilePath # objects muck up the Mothur script. return super(Mothur, self).getTmpFilename( tmp_dir=tmp_dir, prefix=prefix, suffix=suffix, result_constructor=str)
[ "def", "getTmpFilename", "(", "self", ",", "tmp_dir", "=", "None", ",", "prefix", "=", "'tmp'", ",", "suffix", "=", "'.txt'", ")", ":", "# Override to change default constructor to str(). FilePath", "# objects muck up the Mothur script.", "return", "super", "(", "Mothur...
Returns a temporary filename Similar interface to tempfile.mktmp()
[ "Returns", "a", "temporary", "filename" ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L323-L332
biocore/burrito-fillings
bfillings/mothur.py
Mothur._input_as_multiline_string
def _input_as_multiline_string(self, data): """Write multiline string to temp file, return filename data: a multiline string to be written to a file. """ self._input_filename = self.getTmpFilename( self.WorkingDir, suffix='.fasta') with open(self._input_filename, 'w') as f: f.write(data) return self._input_filename
python
def _input_as_multiline_string(self, data): """Write multiline string to temp file, return filename data: a multiline string to be written to a file. """ self._input_filename = self.getTmpFilename( self.WorkingDir, suffix='.fasta') with open(self._input_filename, 'w') as f: f.write(data) return self._input_filename
[ "def", "_input_as_multiline_string", "(", "self", ",", "data", ")", ":", "self", ".", "_input_filename", "=", "self", ".", "getTmpFilename", "(", "self", ".", "WorkingDir", ",", "suffix", "=", "'.fasta'", ")", "with", "open", "(", "self", ".", "_input_filena...
Write multiline string to temp file, return filename data: a multiline string to be written to a file.
[ "Write", "multiline", "string", "to", "temp", "file", "return", "filename" ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L337-L346
biocore/burrito-fillings
bfillings/mothur.py
Mothur._input_as_lines
def _input_as_lines(self, data): """Write sequence of lines to temp file, return filename data: a sequence to be written to a file, each element of the sequence will compose a line in the file * Note: '\n' will be stripped off the end of each sequence element before writing to a file in order to avoid multiple new lines accidentally be written to a file """ self._input_filename = self.getTmpFilename( self.WorkingDir, suffix='.fasta') with open(self._input_filename, 'w') as f: # Use lazy iteration instead of list comprehension to # prevent reading entire file into memory for line in data: f.write(str(line).strip('\n')) f.write('\n') return self._input_filename
python
def _input_as_lines(self, data): """Write sequence of lines to temp file, return filename data: a sequence to be written to a file, each element of the sequence will compose a line in the file * Note: '\n' will be stripped off the end of each sequence element before writing to a file in order to avoid multiple new lines accidentally be written to a file """ self._input_filename = self.getTmpFilename( self.WorkingDir, suffix='.fasta') with open(self._input_filename, 'w') as f: # Use lazy iteration instead of list comprehension to # prevent reading entire file into memory for line in data: f.write(str(line).strip('\n')) f.write('\n') return self._input_filename
[ "def", "_input_as_lines", "(", "self", ",", "data", ")", ":", "self", ".", "_input_filename", "=", "self", ".", "getTmpFilename", "(", "self", ".", "WorkingDir", ",", "suffix", "=", "'.fasta'", ")", "with", "open", "(", "self", ".", "_input_filename", ",",...
Write sequence of lines to temp file, return filename data: a sequence to be written to a file, each element of the sequence will compose a line in the file * Note: '\n' will be stripped off the end of each sequence element before writing to a file in order to avoid multiple new lines accidentally be written to a file
[ "Write", "sequence", "of", "lines", "to", "temp", "file", "return", "filename" ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L348-L366
biocore/burrito-fillings
bfillings/mothur.py
Mothur._input_as_path
def _input_as_path(self, data): """Copys the provided file to WorkingDir and returns the new filename data: path or filename """ self._input_filename = self.getTmpFilename( self.WorkingDir, suffix='.fasta') copyfile(data, self._input_filename) return self._input_filename
python
def _input_as_path(self, data): """Copys the provided file to WorkingDir and returns the new filename data: path or filename """ self._input_filename = self.getTmpFilename( self.WorkingDir, suffix='.fasta') copyfile(data, self._input_filename) return self._input_filename
[ "def", "_input_as_path", "(", "self", ",", "data", ")", ":", "self", ".", "_input_filename", "=", "self", ".", "getTmpFilename", "(", "self", ".", "WorkingDir", ",", "suffix", "=", "'.fasta'", ")", "copyfile", "(", "data", ",", "self", ".", "_input_filenam...
Copys the provided file to WorkingDir and returns the new filename data: path or filename
[ "Copys", "the", "provided", "file", "to", "WorkingDir", "and", "returns", "the", "new", "filename" ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L368-L376
biocore/burrito-fillings
bfillings/mothur.py
Mothur._set_WorkingDir
def _set_WorkingDir(self, path): """Sets the working directory """ self._curr_working_dir = path try: mkdir(self.WorkingDir) except OSError: # Directory already exists pass
python
def _set_WorkingDir(self, path): """Sets the working directory """ self._curr_working_dir = path try: mkdir(self.WorkingDir) except OSError: # Directory already exists pass
[ "def", "_set_WorkingDir", "(", "self", ",", "path", ")", ":", "self", ".", "_curr_working_dir", "=", "path", "try", ":", "mkdir", "(", "self", ".", "WorkingDir", ")", "except", "OSError", ":", "# Directory already exists", "pass" ]
Sets the working directory
[ "Sets", "the", "working", "directory" ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L391-L399
biocore/burrito-fillings
bfillings/mothur.py
MothurClassifySeqs._format_function_arguments
def _format_function_arguments(self, opts): """Format a series of function arguments in a Mothur script.""" params = [self.Parameters[x] for x in opts] return ', '.join(filter(None, map(str, params)))
python
def _format_function_arguments(self, opts): """Format a series of function arguments in a Mothur script.""" params = [self.Parameters[x] for x in opts] return ', '.join(filter(None, map(str, params)))
[ "def", "_format_function_arguments", "(", "self", ",", "opts", ")", ":", "params", "=", "[", "self", ".", "Parameters", "[", "x", "]", "for", "x", "in", "opts", "]", "return", "', '", ".", "join", "(", "filter", "(", "None", ",", "map", "(", "str", ...
Format a series of function arguments in a Mothur script.
[ "Format", "a", "series", "of", "function", "arguments", "in", "a", "Mothur", "script", "." ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L451-L454
biocore/burrito-fillings
bfillings/mothur.py
MothurClassifySeqs._compile_mothur_script
def _compile_mothur_script(self): """Returns a Mothur batch script as a string""" fasta = self._input_filename required_params = ["reference", "taxonomy"] for p in required_params: if self.Parameters[p].Value is None: raise ValueError("Must provide value for parameter %s" % p) optional_params = ["ksize", "cutoff", "iters"] args = self._format_function_arguments( required_params + optional_params) script = '#classify.seqs(fasta=%s, %s)' % (fasta, args) return script
python
def _compile_mothur_script(self): """Returns a Mothur batch script as a string""" fasta = self._input_filename required_params = ["reference", "taxonomy"] for p in required_params: if self.Parameters[p].Value is None: raise ValueError("Must provide value for parameter %s" % p) optional_params = ["ksize", "cutoff", "iters"] args = self._format_function_arguments( required_params + optional_params) script = '#classify.seqs(fasta=%s, %s)' % (fasta, args) return script
[ "def", "_compile_mothur_script", "(", "self", ")", ":", "fasta", "=", "self", ".", "_input_filename", "required_params", "=", "[", "\"reference\"", ",", "\"taxonomy\"", "]", "for", "p", "in", "required_params", ":", "if", "self", ".", "Parameters", "[", "p", ...
Returns a Mothur batch script as a string
[ "Returns", "a", "Mothur", "batch", "script", "as", "a", "string" ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L456-L468
scott-maddox/openbandparams
src/openbandparams/alloy.py
Alloy._add_parameter
def _add_parameter(self, parameter): ''' Force adds a `Parameter` object to the instance. ''' if isinstance(parameter, MethodParameter): # create a bound instance of the MethodParameter parameter = parameter.bind(alloy=self) self._parameters[parameter.name] = parameter for alias in parameter.aliases: self._aliases[alias] = parameter
python
def _add_parameter(self, parameter): ''' Force adds a `Parameter` object to the instance. ''' if isinstance(parameter, MethodParameter): # create a bound instance of the MethodParameter parameter = parameter.bind(alloy=self) self._parameters[parameter.name] = parameter for alias in parameter.aliases: self._aliases[alias] = parameter
[ "def", "_add_parameter", "(", "self", ",", "parameter", ")", ":", "if", "isinstance", "(", "parameter", ",", "MethodParameter", ")", ":", "# create a bound instance of the MethodParameter", "parameter", "=", "parameter", ".", "bind", "(", "alloy", "=", "self", ")"...
Force adds a `Parameter` object to the instance.
[ "Force", "adds", "a", "Parameter", "object", "to", "the", "instance", "." ]
train
https://github.com/scott-maddox/openbandparams/blob/bc24e59187326bcb8948117434536082c9055777/src/openbandparams/alloy.py#L82-L91
scott-maddox/openbandparams
src/openbandparams/alloy.py
Alloy.add_parameter
def add_parameter(self, parameter, overload=False): ''' Adds a `Parameter` object to the instance. If a `Parameter` with the same name or alias has already been added and `overload` is False (the default), a `ValueError` is thrown. If a class member or method with the same name or alias is already defined, a `ValueError` is thrown, regardless of the value of overload. ''' if not isinstance(parameter, Parameter): raise TypeError('`parameter` must be an instance of `Parameter`') if hasattr(self, parameter.name): item = getattr(self, parameter.name) if not isinstance(item, Parameter): raise ValueError('"{}" is already a class member or method.' ''.format(parameter.name)) elif not overload: raise ValueError('Parameter "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) if parameter.name in self._parameters and not overload: raise ValueError('Parameter "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) for alias in parameter.aliases: if alias in self._aliases and not overload: raise ValueError('Alias "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) self._add_parameter(parameter)
python
def add_parameter(self, parameter, overload=False): ''' Adds a `Parameter` object to the instance. If a `Parameter` with the same name or alias has already been added and `overload` is False (the default), a `ValueError` is thrown. If a class member or method with the same name or alias is already defined, a `ValueError` is thrown, regardless of the value of overload. ''' if not isinstance(parameter, Parameter): raise TypeError('`parameter` must be an instance of `Parameter`') if hasattr(self, parameter.name): item = getattr(self, parameter.name) if not isinstance(item, Parameter): raise ValueError('"{}" is already a class member or method.' ''.format(parameter.name)) elif not overload: raise ValueError('Parameter "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) if parameter.name in self._parameters and not overload: raise ValueError('Parameter "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) for alias in parameter.aliases: if alias in self._aliases and not overload: raise ValueError('Alias "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) self._add_parameter(parameter)
[ "def", "add_parameter", "(", "self", ",", "parameter", ",", "overload", "=", "False", ")", ":", "if", "not", "isinstance", "(", "parameter", ",", "Parameter", ")", ":", "raise", "TypeError", "(", "'`parameter` must be an instance of `Parameter`'", ")", "if", "ha...
Adds a `Parameter` object to the instance. If a `Parameter` with the same name or alias has already been added and `overload` is False (the default), a `ValueError` is thrown. If a class member or method with the same name or alias is already defined, a `ValueError` is thrown, regardless of the value of overload.
[ "Adds", "a", "Parameter", "object", "to", "the", "instance", ".", "If", "a", "Parameter", "with", "the", "same", "name", "or", "alias", "has", "already", "been", "added", "and", "overload", "is", "False", "(", "the", "default", ")", "a", "ValueError", "i...
train
https://github.com/scott-maddox/openbandparams/blob/bc24e59187326bcb8948117434536082c9055777/src/openbandparams/alloy.py#L93-L124
scott-maddox/openbandparams
src/openbandparams/alloy.py
Alloy.get_parameter
def get_parameter(self, name, default=None): ''' Returns the named parameter if present, or the value of `default`, otherwise. ''' if hasattr(self, name): item = getattr(self, name) if isinstance(item, Parameter): return item return default
python
def get_parameter(self, name, default=None): ''' Returns the named parameter if present, or the value of `default`, otherwise. ''' if hasattr(self, name): item = getattr(self, name) if isinstance(item, Parameter): return item return default
[ "def", "get_parameter", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "name", ")", ":", "item", "=", "getattr", "(", "self", ",", "name", ")", "if", "isinstance", "(", "item", ",", "Parameter", ...
Returns the named parameter if present, or the value of `default`, otherwise.
[ "Returns", "the", "named", "parameter", "if", "present", "or", "the", "value", "of", "default", "otherwise", "." ]
train
https://github.com/scott-maddox/openbandparams/blob/bc24e59187326bcb8948117434536082c9055777/src/openbandparams/alloy.py#L138-L147
scott-maddox/openbandparams
src/openbandparams/alloy.py
Alloy.get_unique_parameters
def get_unique_parameters(self): ''' Returns a list of the unique parameters (no duplicates). ''' # start with parameters in the `_parameters` dictionary parameters = self._parameters.values() # add parameters defined with the class for name in dir(self): item = getattr(self, name) if isinstance(item, Parameter): if item.name not in self._parameters: parameters.append(item) return parameters
python
def get_unique_parameters(self): ''' Returns a list of the unique parameters (no duplicates). ''' # start with parameters in the `_parameters` dictionary parameters = self._parameters.values() # add parameters defined with the class for name in dir(self): item = getattr(self, name) if isinstance(item, Parameter): if item.name not in self._parameters: parameters.append(item) return parameters
[ "def", "get_unique_parameters", "(", "self", ")", ":", "# start with parameters in the `_parameters` dictionary", "parameters", "=", "self", ".", "_parameters", ".", "values", "(", ")", "# add parameters defined with the class", "for", "name", "in", "dir", "(", "self", ...
Returns a list of the unique parameters (no duplicates).
[ "Returns", "a", "list", "of", "the", "unique", "parameters", "(", "no", "duplicates", ")", "." ]
train
https://github.com/scott-maddox/openbandparams/blob/bc24e59187326bcb8948117434536082c9055777/src/openbandparams/alloy.py#L149-L161
9b/frisbee
frisbee/modules/base.py
Base.set_log_level
def set_log_level(self, level: str) -> None: """Override the default log level of the class.""" if level == 'info': to_set = logging.INFO if level == 'debug': to_set = logging.DEBUG if level == 'error': to_set = logging.ERROR self.log.setLevel(to_set)
python
def set_log_level(self, level: str) -> None: """Override the default log level of the class.""" if level == 'info': to_set = logging.INFO if level == 'debug': to_set = logging.DEBUG if level == 'error': to_set = logging.ERROR self.log.setLevel(to_set)
[ "def", "set_log_level", "(", "self", ",", "level", ":", "str", ")", "->", "None", ":", "if", "level", "==", "'info'", ":", "to_set", "=", "logging", ".", "INFO", "if", "level", "==", "'debug'", ":", "to_set", "=", "logging", ".", "DEBUG", "if", "leve...
Override the default log level of the class.
[ "Override", "the", "default", "log", "level", "of", "the", "class", "." ]
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/modules/base.py#L25-L33
9b/frisbee
frisbee/modules/base.py
Base._request_bulk
def _request_bulk(self, urls: List[str]) -> List: """Batch the requests going out.""" if not urls: raise Exception("No results were found") session: FuturesSession = FuturesSession(max_workers=len(urls)) self.log.info("Bulk requesting: %d" % len(urls)) futures = [session.get(u, headers=gen_headers(), timeout=3) for u in urls] done, incomplete = wait(futures) results: List = list() for response in done: try: results.append(response.result()) except Exception as err: self.log.warn("Failed result: %s" % err) return results
python
def _request_bulk(self, urls: List[str]) -> List: """Batch the requests going out.""" if not urls: raise Exception("No results were found") session: FuturesSession = FuturesSession(max_workers=len(urls)) self.log.info("Bulk requesting: %d" % len(urls)) futures = [session.get(u, headers=gen_headers(), timeout=3) for u in urls] done, incomplete = wait(futures) results: List = list() for response in done: try: results.append(response.result()) except Exception as err: self.log.warn("Failed result: %s" % err) return results
[ "def", "_request_bulk", "(", "self", ",", "urls", ":", "List", "[", "str", "]", ")", "->", "List", ":", "if", "not", "urls", ":", "raise", "Exception", "(", "\"No results were found\"", ")", "session", ":", "FuturesSession", "=", "FuturesSession", "(", "ma...
Batch the requests going out.
[ "Batch", "the", "requests", "going", "out", "." ]
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/modules/base.py#L35-L49
scott-maddox/openbandparams
src/openbandparams/parameter.py
MethodParameter.bind
def bind(self, alloy): ''' Shallow copies this MethodParameter, and binds it to an alloy. This is required before calling. ''' param = MethodParameter(self.name, self.method, self.dependencies, self.units, self.aliases, self._references) param.alloy = alloy return param
python
def bind(self, alloy): ''' Shallow copies this MethodParameter, and binds it to an alloy. This is required before calling. ''' param = MethodParameter(self.name, self.method, self.dependencies, self.units, self.aliases, self._references) param.alloy = alloy return param
[ "def", "bind", "(", "self", ",", "alloy", ")", ":", "param", "=", "MethodParameter", "(", "self", ".", "name", ",", "self", ".", "method", ",", "self", ".", "dependencies", ",", "self", ".", "units", ",", "self", ".", "aliases", ",", "self", ".", "...
Shallow copies this MethodParameter, and binds it to an alloy. This is required before calling.
[ "Shallow", "copies", "this", "MethodParameter", "and", "binds", "it", "to", "an", "alloy", ".", "This", "is", "required", "before", "calling", "." ]
train
https://github.com/scott-maddox/openbandparams/blob/bc24e59187326bcb8948117434536082c9055777/src/openbandparams/parameter.py#L134-L142
biocore/burrito-fillings
bfillings/mafft.py
align_unaligned_seqs
def align_unaligned_seqs(seqs,moltype=DNA,params=None,accurate=False): """Aligns unaligned sequences seqs: either list of sequence objects or list of strings add_seq_names: boolean. if True, sequence names are inserted in the list of sequences. if False, it assumes seqs is a list of lines of some proper format that the program can handle """ #create SequenceCollection object from seqs seq_collection = SequenceCollection(seqs,MolType=moltype) #Create mapping between abbreviated IDs and full IDs int_map, int_keys = seq_collection.getIntMap() #Create SequenceCollection from int_map. int_map = SequenceCollection(int_map,MolType=moltype) #Create Mafft app. app = Mafft(InputHandler='_input_as_multiline_string',params=params) #Turn on correct moltype moltype_string = moltype.label.upper() app.Parameters[MOLTYPE_MAP[moltype_string]].on() #Do not report progress app.Parameters['--quiet'].on() #More accurate alignment, sacrificing performance. if accurate: app.Parameters['--globalpair'].on() app.Parameters['--maxiterate'].Value=1000 #Get results using int_map as input to app res = app(int_map.toFasta()) #Get alignment as dict out of results alignment = dict(parse_fasta(res['StdOut'])) #Make new dict mapping original IDs new_alignment = {} for k,v in alignment.items(): new_alignment[int_keys[k]]=v #Create an Alignment object from alignment dict new_alignment = Alignment(new_alignment,MolType=moltype) #Clean up res.cleanUp() del(seq_collection,int_map,int_keys,app,res,alignment) return new_alignment
python
def align_unaligned_seqs(seqs,moltype=DNA,params=None,accurate=False): """Aligns unaligned sequences seqs: either list of sequence objects or list of strings add_seq_names: boolean. if True, sequence names are inserted in the list of sequences. if False, it assumes seqs is a list of lines of some proper format that the program can handle """ #create SequenceCollection object from seqs seq_collection = SequenceCollection(seqs,MolType=moltype) #Create mapping between abbreviated IDs and full IDs int_map, int_keys = seq_collection.getIntMap() #Create SequenceCollection from int_map. int_map = SequenceCollection(int_map,MolType=moltype) #Create Mafft app. app = Mafft(InputHandler='_input_as_multiline_string',params=params) #Turn on correct moltype moltype_string = moltype.label.upper() app.Parameters[MOLTYPE_MAP[moltype_string]].on() #Do not report progress app.Parameters['--quiet'].on() #More accurate alignment, sacrificing performance. if accurate: app.Parameters['--globalpair'].on() app.Parameters['--maxiterate'].Value=1000 #Get results using int_map as input to app res = app(int_map.toFasta()) #Get alignment as dict out of results alignment = dict(parse_fasta(res['StdOut'])) #Make new dict mapping original IDs new_alignment = {} for k,v in alignment.items(): new_alignment[int_keys[k]]=v #Create an Alignment object from alignment dict new_alignment = Alignment(new_alignment,MolType=moltype) #Clean up res.cleanUp() del(seq_collection,int_map,int_keys,app,res,alignment) return new_alignment
[ "def", "align_unaligned_seqs", "(", "seqs", ",", "moltype", "=", "DNA", ",", "params", "=", "None", ",", "accurate", "=", "False", ")", ":", "#create SequenceCollection object from seqs", "seq_collection", "=", "SequenceCollection", "(", "seqs", ",", "MolType", "=...
Aligns unaligned sequences seqs: either list of sequence objects or list of strings add_seq_names: boolean. if True, sequence names are inserted in the list of sequences. if False, it assumes seqs is a list of lines of some proper format that the program can handle
[ "Aligns", "unaligned", "sequences" ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mafft.py#L252-L295
biocore/burrito-fillings
bfillings/mafft.py
add_seqs_to_alignment
def add_seqs_to_alignment(seqs, aln, moltype, params=None, accurate=False): """Returns an Alignment object from seqs and existing Alignment. seqs: a cogent.core.sequence.Sequence object, or data that can be used to build one. aln: an cogent.core.alignment.Alignment object, or data that can be used to build one params: dict of parameters to pass in to the Mafft app controller. """ #create SequenceCollection object from seqs seq_collection = SequenceCollection(seqs,MolType=moltype) #Create mapping between abbreviated IDs and full IDs seq_int_map, seq_int_keys = seq_collection.getIntMap() #Create SequenceCollection from int_map. seq_int_map = SequenceCollection(seq_int_map,MolType=moltype) #create Alignment object from aln aln = Alignment(aln,MolType=moltype) #Create mapping between abbreviated IDs and full IDs aln_int_map, aln_int_keys = aln.getIntMap(prefix='seqn_') #Create SequenceCollection from int_map. aln_int_map = Alignment(aln_int_map,MolType=moltype) #Update seq_int_keys with aln_int_keys seq_int_keys.update(aln_int_keys) #Create Mafft app. app = Mafft(InputHandler='_input_as_multiline_string',\ params=params, SuppressStderr=True) #Turn on correct moltype moltype_string = moltype.label.upper() app.Parameters[MOLTYPE_MAP[moltype_string]].on() #Do not report progress app.Parameters['--quiet'].on() #Add aln_int_map as seed alignment app.Parameters['--seed'].on(\ app._tempfile_as_multiline_string(aln_int_map.toFasta())) #More accurate alignment, sacrificing performance. if accurate: app.Parameters['--globalpair'].on() app.Parameters['--maxiterate'].Value=1000 #Get results using int_map as input to app res = app(seq_int_map.toFasta()) #Get alignment as dict out of results alignment = dict(parse_fasta(res['StdOut'])) #Make new dict mapping original IDs new_alignment = {} for k,v in alignment.items(): key = k.replace('_seed_','') new_alignment[seq_int_keys[key]]=v #Create an Alignment object from alignment dict new_alignment = Alignment(new_alignment,MolType=moltype) #Clean up res.cleanUp() remove(app.Parameters['--seed'].Value) del(seq_collection,seq_int_map,seq_int_keys,\ aln,aln_int_map,aln_int_keys,app,res,alignment) return new_alignment
python
def add_seqs_to_alignment(seqs, aln, moltype, params=None, accurate=False): """Returns an Alignment object from seqs and existing Alignment. seqs: a cogent.core.sequence.Sequence object, or data that can be used to build one. aln: an cogent.core.alignment.Alignment object, or data that can be used to build one params: dict of parameters to pass in to the Mafft app controller. """ #create SequenceCollection object from seqs seq_collection = SequenceCollection(seqs,MolType=moltype) #Create mapping between abbreviated IDs and full IDs seq_int_map, seq_int_keys = seq_collection.getIntMap() #Create SequenceCollection from int_map. seq_int_map = SequenceCollection(seq_int_map,MolType=moltype) #create Alignment object from aln aln = Alignment(aln,MolType=moltype) #Create mapping between abbreviated IDs and full IDs aln_int_map, aln_int_keys = aln.getIntMap(prefix='seqn_') #Create SequenceCollection from int_map. aln_int_map = Alignment(aln_int_map,MolType=moltype) #Update seq_int_keys with aln_int_keys seq_int_keys.update(aln_int_keys) #Create Mafft app. app = Mafft(InputHandler='_input_as_multiline_string',\ params=params, SuppressStderr=True) #Turn on correct moltype moltype_string = moltype.label.upper() app.Parameters[MOLTYPE_MAP[moltype_string]].on() #Do not report progress app.Parameters['--quiet'].on() #Add aln_int_map as seed alignment app.Parameters['--seed'].on(\ app._tempfile_as_multiline_string(aln_int_map.toFasta())) #More accurate alignment, sacrificing performance. if accurate: app.Parameters['--globalpair'].on() app.Parameters['--maxiterate'].Value=1000 #Get results using int_map as input to app res = app(seq_int_map.toFasta()) #Get alignment as dict out of results alignment = dict(parse_fasta(res['StdOut'])) #Make new dict mapping original IDs new_alignment = {} for k,v in alignment.items(): key = k.replace('_seed_','') new_alignment[seq_int_keys[key]]=v #Create an Alignment object from alignment dict new_alignment = Alignment(new_alignment,MolType=moltype) #Clean up res.cleanUp() remove(app.Parameters['--seed'].Value) del(seq_collection,seq_int_map,seq_int_keys,\ aln,aln_int_map,aln_int_keys,app,res,alignment) return new_alignment
[ "def", "add_seqs_to_alignment", "(", "seqs", ",", "aln", ",", "moltype", ",", "params", "=", "None", ",", "accurate", "=", "False", ")", ":", "#create SequenceCollection object from seqs", "seq_collection", "=", "SequenceCollection", "(", "seqs", ",", "MolType", "...
Returns an Alignment object from seqs and existing Alignment. seqs: a cogent.core.sequence.Sequence object, or data that can be used to build one. aln: an cogent.core.alignment.Alignment object, or data that can be used to build one params: dict of parameters to pass in to the Mafft app controller.
[ "Returns", "an", "Alignment", "object", "from", "seqs", "and", "existing", "Alignment", "." ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mafft.py#L342-L409
biocore/burrito-fillings
bfillings/mafft.py
align_two_alignments
def align_two_alignments(aln1, aln2, moltype, params=None): """Returns an Alignment object from two existing Alignments. aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be used to build them. - Mafft profile alignment only works with aligned sequences. Alignment object used to handle unaligned sequences. params: dict of parameters to pass in to the Mafft app controller. """ #create SequenceCollection object from seqs aln1 = Alignment(aln1,MolType=moltype) #Create mapping between abbreviated IDs and full IDs aln1_int_map, aln1_int_keys = aln1.getIntMap() #Create SequenceCollection from int_map. aln1_int_map = Alignment(aln1_int_map,MolType=moltype) #create Alignment object from aln aln2 = Alignment(aln2,MolType=moltype) #Create mapping between abbreviated IDs and full IDs aln2_int_map, aln2_int_keys = aln2.getIntMap(prefix='seqn_') #Create SequenceCollection from int_map. aln2_int_map = Alignment(aln2_int_map,MolType=moltype) #Update aln1_int_keys with aln2_int_keys aln1_int_keys.update(aln2_int_keys) #Create Mafft app. app = Mafft(InputHandler='_input_as_paths',\ params=params, SuppressStderr=False) app._command = 'mafft-profile' aln1_path = app._tempfile_as_multiline_string(aln1_int_map.toFasta()) aln2_path = app._tempfile_as_multiline_string(aln2_int_map.toFasta()) filepaths = [aln1_path,aln2_path] #Get results using int_map as input to app res = app(filepaths) #Get alignment as dict out of results alignment = dict(parse_fasta(res['StdOut'])) #Make new dict mapping original IDs new_alignment = {} for k,v in alignment.items(): key = k.replace('_seed_','') new_alignment[aln1_int_keys[key]]=v #Create an Alignment object from alignment dict new_alignment = Alignment(new_alignment,MolType=moltype) #Clean up res.cleanUp() remove(aln1_path) remove(aln2_path) remove('pre') remove('trace') del(aln1,aln1_int_map,aln1_int_keys,\ aln2,aln2_int_map,aln2_int_keys,app,res,alignment) return new_alignment
python
def align_two_alignments(aln1, aln2, moltype, params=None): """Returns an Alignment object from two existing Alignments. aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be used to build them. - Mafft profile alignment only works with aligned sequences. Alignment object used to handle unaligned sequences. params: dict of parameters to pass in to the Mafft app controller. """ #create SequenceCollection object from seqs aln1 = Alignment(aln1,MolType=moltype) #Create mapping between abbreviated IDs and full IDs aln1_int_map, aln1_int_keys = aln1.getIntMap() #Create SequenceCollection from int_map. aln1_int_map = Alignment(aln1_int_map,MolType=moltype) #create Alignment object from aln aln2 = Alignment(aln2,MolType=moltype) #Create mapping between abbreviated IDs and full IDs aln2_int_map, aln2_int_keys = aln2.getIntMap(prefix='seqn_') #Create SequenceCollection from int_map. aln2_int_map = Alignment(aln2_int_map,MolType=moltype) #Update aln1_int_keys with aln2_int_keys aln1_int_keys.update(aln2_int_keys) #Create Mafft app. app = Mafft(InputHandler='_input_as_paths',\ params=params, SuppressStderr=False) app._command = 'mafft-profile' aln1_path = app._tempfile_as_multiline_string(aln1_int_map.toFasta()) aln2_path = app._tempfile_as_multiline_string(aln2_int_map.toFasta()) filepaths = [aln1_path,aln2_path] #Get results using int_map as input to app res = app(filepaths) #Get alignment as dict out of results alignment = dict(parse_fasta(res['StdOut'])) #Make new dict mapping original IDs new_alignment = {} for k,v in alignment.items(): key = k.replace('_seed_','') new_alignment[aln1_int_keys[key]]=v #Create an Alignment object from alignment dict new_alignment = Alignment(new_alignment,MolType=moltype) #Clean up res.cleanUp() remove(aln1_path) remove(aln2_path) remove('pre') remove('trace') del(aln1,aln1_int_map,aln1_int_keys,\ aln2,aln2_int_map,aln2_int_keys,app,res,alignment) return new_alignment
[ "def", "align_two_alignments", "(", "aln1", ",", "aln2", ",", "moltype", ",", "params", "=", "None", ")", ":", "#create SequenceCollection object from seqs", "aln1", "=", "Alignment", "(", "aln1", ",", "MolType", "=", "moltype", ")", "#Create mapping between abbrevi...
Returns an Alignment object from two existing Alignments. aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be used to build them. - Mafft profile alignment only works with aligned sequences. Alignment object used to handle unaligned sequences. params: dict of parameters to pass in to the Mafft app controller.
[ "Returns", "an", "Alignment", "object", "from", "two", "existing", "Alignments", "." ]
train
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mafft.py#L411-L470
ebu/PlugIt
plugit_proxy/plugIt.py
PlugIt.doQuery
def doQuery(self, url, method='GET', getParmeters=None, postParameters=None, files=None, extraHeaders={}, session={}): """Send a request to the server and return the result""" # Build headers headers = {} if not postParameters: postParameters = {} for key, value in extraHeaders.iteritems(): # Fixes #197 for values with utf-8 chars to be passed into plugit if isinstance(value, basestring): headers['X-Plugit-' + key] = value.encode('utf-8') else: headers['X-Plugit-' + key] = value for key, value in session.iteritems(): headers['X-Plugitsession-' + key] = value if 'Cookie' not in headers: headers['Cookie'] = '' headers['Cookie'] += key + '=' + str(value) + '; ' if method == 'POST': if not files: r = requests.post(self.baseURI + '/' + url, params=getParmeters, data=postParameters, stream=True, headers=headers) else: # Special way, for big files # Requests is not usable: https://github.com/shazow/urllib3/issues/51 from poster.encode import multipart_encode, MultipartParam from poster.streaminghttp import register_openers import urllib2 import urllib # Register the streaming http handlers with urllib2 register_openers() # headers contains the necessary Content-Type and Content-Length # datagen is a generator object that yields the encoded parameters data = [] for x in postParameters: if isinstance(postParameters[x], list): for elem in postParameters[x]: data.append((x, elem)) else: data.append((x, postParameters[x])) for f in files: data.append((f, MultipartParam(f, fileobj=open(files[f].temporary_file_path(), 'rb'), filename=files[f].name))) datagen, headers_multi = multipart_encode(data) headers.update(headers_multi) if getParmeters: get_uri = '?' + urllib.urlencode(getParmeters) else: get_uri = '' # Create the Request object request = urllib2.Request(self.baseURI + '/' + url + get_uri, datagen, headers) re = urllib2.urlopen(request) from requests import Response r = Response() r.status_code = re.getcode() r.headers = dict(re.info()) r.encoding = "application/json" r.raw = re.read() r._content = r.raw return r else: # Call the function based on the method. r = requests.request(method.upper(), self.baseURI + '/' + url, params=getParmeters, stream=True, headers=headers, allow_redirects=True) return r
python
def doQuery(self, url, method='GET', getParmeters=None, postParameters=None, files=None, extraHeaders={}, session={}): """Send a request to the server and return the result""" # Build headers headers = {} if not postParameters: postParameters = {} for key, value in extraHeaders.iteritems(): # Fixes #197 for values with utf-8 chars to be passed into plugit if isinstance(value, basestring): headers['X-Plugit-' + key] = value.encode('utf-8') else: headers['X-Plugit-' + key] = value for key, value in session.iteritems(): headers['X-Plugitsession-' + key] = value if 'Cookie' not in headers: headers['Cookie'] = '' headers['Cookie'] += key + '=' + str(value) + '; ' if method == 'POST': if not files: r = requests.post(self.baseURI + '/' + url, params=getParmeters, data=postParameters, stream=True, headers=headers) else: # Special way, for big files # Requests is not usable: https://github.com/shazow/urllib3/issues/51 from poster.encode import multipart_encode, MultipartParam from poster.streaminghttp import register_openers import urllib2 import urllib # Register the streaming http handlers with urllib2 register_openers() # headers contains the necessary Content-Type and Content-Length # datagen is a generator object that yields the encoded parameters data = [] for x in postParameters: if isinstance(postParameters[x], list): for elem in postParameters[x]: data.append((x, elem)) else: data.append((x, postParameters[x])) for f in files: data.append((f, MultipartParam(f, fileobj=open(files[f].temporary_file_path(), 'rb'), filename=files[f].name))) datagen, headers_multi = multipart_encode(data) headers.update(headers_multi) if getParmeters: get_uri = '?' + urllib.urlencode(getParmeters) else: get_uri = '' # Create the Request object request = urllib2.Request(self.baseURI + '/' + url + get_uri, datagen, headers) re = urllib2.urlopen(request) from requests import Response r = Response() r.status_code = re.getcode() r.headers = dict(re.info()) r.encoding = "application/json" r.raw = re.read() r._content = r.raw return r else: # Call the function based on the method. r = requests.request(method.upper(), self.baseURI + '/' + url, params=getParmeters, stream=True, headers=headers, allow_redirects=True) return r
[ "def", "doQuery", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "getParmeters", "=", "None", ",", "postParameters", "=", "None", ",", "files", "=", "None", ",", "extraHeaders", "=", "{", "}", ",", "session", "=", "{", "}", ")", ":", "#...
Send a request to the server and return the result
[ "Send", "a", "request", "to", "the", "server", "and", "return", "the", "result" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/plugIt.py#L32-L111
ebu/PlugIt
plugit_proxy/plugIt.py
PlugIt.ping
def ping(self): """Return true if the server successfully pinged""" randomToken = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(32)) r = self.doQuery('ping?data=' + randomToken) if r.status_code == 200: # Query ok ? if r.json()['data'] == randomToken: # Token equal ? return True return False
python
def ping(self): """Return true if the server successfully pinged""" randomToken = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(32)) r = self.doQuery('ping?data=' + randomToken) if r.status_code == 200: # Query ok ? if r.json()['data'] == randomToken: # Token equal ? return True return False
[ "def", "ping", "(", "self", ")", ":", "randomToken", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "ascii_lowercase", "+", "string", ".", "digits", ")", "for", "x", "in", "range", "(", ...
Return true if the server successfully pinged
[ "Return", "true", "if", "the", "server", "successfully", "pinged" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/plugIt.py#L113-L123
ebu/PlugIt
plugit_proxy/plugIt.py
PlugIt.checkVersion
def checkVersion(self): """Check if the server use the same version of our protocol""" r = self.doQuery('version') if r.status_code == 200: # Query ok ? data = r.json() if data['result'] == 'Ok' and data['version'] == self.PI_API_VERSION and data['protocol'] == self.PI_API_NAME: return True return False
python
def checkVersion(self): """Check if the server use the same version of our protocol""" r = self.doQuery('version') if r.status_code == 200: # Query ok ? data = r.json() if data['result'] == 'Ok' and data['version'] == self.PI_API_VERSION and data['protocol'] == self.PI_API_NAME: return True return False
[ "def", "checkVersion", "(", "self", ")", ":", "r", "=", "self", ".", "doQuery", "(", "'version'", ")", "if", "r", ".", "status_code", "==", "200", ":", "# Query ok ?", "data", "=", "r", ".", "json", "(", ")", "if", "data", "[", "'result'", "]", "==...
Check if the server use the same version of our protocol
[ "Check", "if", "the", "server", "use", "the", "same", "version", "of", "our", "protocol" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/plugIt.py#L125-L135
ebu/PlugIt
plugit_proxy/plugIt.py
PlugIt.newMail
def newMail(self, data, message): """Send a mail to a plugit server""" r = self.doQuery('mail', method='POST', postParameters={'response_id': str(data), 'message': str(message)}) if r.status_code == 200: # Query ok ? data = r.json() return data['result'] == 'Ok' return False
python
def newMail(self, data, message): """Send a mail to a plugit server""" r = self.doQuery('mail', method='POST', postParameters={'response_id': str(data), 'message': str(message)}) if r.status_code == 200: # Query ok ? data = r.json() return data['result'] == 'Ok' return False
[ "def", "newMail", "(", "self", ",", "data", ",", "message", ")", ":", "r", "=", "self", ".", "doQuery", "(", "'mail'", ",", "method", "=", "'POST'", ",", "postParameters", "=", "{", "'response_id'", ":", "str", "(", "data", ")", ",", "'message'", ":"...
Send a mail to a plugit server
[ "Send", "a", "mail", "to", "a", "plugit", "server" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/plugIt.py#L137-L146
ebu/PlugIt
plugit_proxy/plugIt.py
PlugIt.getMedia
def getMedia(self, uri): """Return a tuple with a media and his content-type. Don't cache anything !""" r = self.doQuery('media/' + uri) if r.status_code == 200: content_type = 'application/octet-stream' if 'content-type' in r.headers: content_type = r.headers['content-type'] cache_control = None if 'cache-control' in r.headers: cache_control = r.headers['cache-control'] return (r.content, content_type, cache_control) else: return (None, None, None)
python
def getMedia(self, uri): """Return a tuple with a media and his content-type. Don't cache anything !""" r = self.doQuery('media/' + uri) if r.status_code == 200: content_type = 'application/octet-stream' if 'content-type' in r.headers: content_type = r.headers['content-type'] cache_control = None if 'cache-control' in r.headers: cache_control = r.headers['cache-control'] return (r.content, content_type, cache_control) else: return (None, None, None)
[ "def", "getMedia", "(", "self", ",", "uri", ")", ":", "r", "=", "self", ".", "doQuery", "(", "'media/'", "+", "uri", ")", "if", "r", ".", "status_code", "==", "200", ":", "content_type", "=", "'application/octet-stream'", "if", "'content-type'", "in", "r...
Return a tuple with a media and his content-type. Don't cache anything !
[ "Return", "a", "tuple", "with", "a", "media", "and", "his", "content", "-", "type", ".", "Don", "t", "cache", "anything", "!" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/plugIt.py#L148-L166
ebu/PlugIt
plugit_proxy/plugIt.py
PlugIt.getMeta
def getMeta(self, uri): """Return meta information about an action. Cache the result as specified by the server""" action = urlparse(uri).path mediaKey = self.cacheKey + '_meta_' + action mediaKey = mediaKey.replace(' ', '__') meta = cache.get(mediaKey, None) # Nothing found -> Retrieve it from the server and cache it if not meta: r = self.doQuery('meta/' + uri) if r.status_code == 200: # Get the content if there is not problem. If there is, template will stay to None meta = r.json() if 'expire' not in r.headers: expire = 5 * 60 # 5 minutes of cache if the server didn't specified anything else: expire = int((parser.parse(r.headers['expire']) - datetime.datetime.now(tzutc())).total_seconds()) # Use the server value for cache if expire > 0: # Do the server want us to cache ? cache.set(mediaKey, meta, expire) return meta
python
def getMeta(self, uri): """Return meta information about an action. Cache the result as specified by the server""" action = urlparse(uri).path mediaKey = self.cacheKey + '_meta_' + action mediaKey = mediaKey.replace(' ', '__') meta = cache.get(mediaKey, None) # Nothing found -> Retrieve it from the server and cache it if not meta: r = self.doQuery('meta/' + uri) if r.status_code == 200: # Get the content if there is not problem. If there is, template will stay to None meta = r.json() if 'expire' not in r.headers: expire = 5 * 60 # 5 minutes of cache if the server didn't specified anything else: expire = int((parser.parse(r.headers['expire']) - datetime.datetime.now(tzutc())).total_seconds()) # Use the server value for cache if expire > 0: # Do the server want us to cache ? cache.set(mediaKey, meta, expire) return meta
[ "def", "getMeta", "(", "self", ",", "uri", ")", ":", "action", "=", "urlparse", "(", "uri", ")", ".", "path", "mediaKey", "=", "self", ".", "cacheKey", "+", "'_meta_'", "+", "action", "mediaKey", "=", "mediaKey", ".", "replace", "(", "' '", ",", "'__...
Return meta information about an action. Cache the result as specified by the server
[ "Return", "meta", "information", "about", "an", "action", ".", "Cache", "the", "result", "as", "specified", "by", "the", "server" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/plugIt.py#L168-L194
ebu/PlugIt
plugit_proxy/plugIt.py
PlugIt.getTemplate
def getTemplate(self, uri, meta=None): """Return the template for an action. Cache the result. Can use an optional meta parameter with meta information""" if not meta: metaKey = self.cacheKey + '_templatesmeta_cache_' + uri meta = cache.get(metaKey, None) if not meta: meta = self.getMeta(uri) cache.set(metaKey, meta, 15) if not meta: # No meta, can return a template return None # Let's find the template in the cache action = urlparse(uri).path templateKey = self.cacheKey + '_templates_' + action + '_' + meta['template_tag'] template = cache.get(templateKey, None) # Nothing found -> Retrieve it from the server and cache it if not template: r = self.doQuery('template/' + uri) if r.status_code == 200: # Get the content if there is not problem. If there is, template will stay to None template = r.content cache.set(templateKey, template, None) # None = Cache forever return template
python
def getTemplate(self, uri, meta=None): """Return the template for an action. Cache the result. Can use an optional meta parameter with meta information""" if not meta: metaKey = self.cacheKey + '_templatesmeta_cache_' + uri meta = cache.get(metaKey, None) if not meta: meta = self.getMeta(uri) cache.set(metaKey, meta, 15) if not meta: # No meta, can return a template return None # Let's find the template in the cache action = urlparse(uri).path templateKey = self.cacheKey + '_templates_' + action + '_' + meta['template_tag'] template = cache.get(templateKey, None) # Nothing found -> Retrieve it from the server and cache it if not template: r = self.doQuery('template/' + uri) if r.status_code == 200: # Get the content if there is not problem. If there is, template will stay to None template = r.content cache.set(templateKey, template, None) # None = Cache forever return template
[ "def", "getTemplate", "(", "self", ",", "uri", ",", "meta", "=", "None", ")", ":", "if", "not", "meta", ":", "metaKey", "=", "self", ".", "cacheKey", "+", "'_templatesmeta_cache_'", "+", "uri", "meta", "=", "cache", ".", "get", "(", "metaKey", ",", "...
Return the template for an action. Cache the result. Can use an optional meta parameter with meta information
[ "Return", "the", "template", "for", "an", "action", ".", "Cache", "the", "result", ".", "Can", "use", "an", "optional", "meta", "parameter", "with", "meta", "information" ]
train
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/plugIt.py#L196-L228
gwastro/pycbc-glue
pycbc_glue/offsetvector.py
component_offsetvectors
def component_offsetvectors(offsetvectors, n): """ Given an iterable of offset vectors, return the shortest list of the unique n-instrument offset vectors from which all the vectors in the input iterable can be constructed. This can be used to determine the minimal set of n-instrument coincs required to construct all of the coincs for all of the requested instrument and offset combinations in a set of offset vectors. It is assumed that the coincs for the vector {"H1": 0, "H2": 10, "L1": 20} can be constructed from the coincs for the vectors {"H1": 0, "H2": 10} and {"H2": 0, "L1": 10}, that is only the relative offsets are significant in determining if two events are coincident, not the absolute offsets. This assumption is not true for the standard inspiral pipeline, where the absolute offsets are significant due to the periodic wrapping of triggers around rings. """ # # collect unique instrument set / deltas combinations # delta_sets = {} for vect in offsetvectors: for instruments in iterutils.choices(sorted(vect), n): # NOTE: the arithmetic used to construct the # offsets *must* match the arithmetic used by # offsetvector.deltas so that the results of the # two can be compared to each other without worry # of floating-point round off confusing things. delta_sets.setdefault(instruments, set()).add(tuple(vect[instrument] - vect[instruments[0]] for instrument in instruments)) # # translate into a list of normalized n-instrument offset vectors # return [offsetvector(zip(instruments, deltas)) for instruments, delta_set in delta_sets.items() for deltas in delta_set]
python
def component_offsetvectors(offsetvectors, n): """ Given an iterable of offset vectors, return the shortest list of the unique n-instrument offset vectors from which all the vectors in the input iterable can be constructed. This can be used to determine the minimal set of n-instrument coincs required to construct all of the coincs for all of the requested instrument and offset combinations in a set of offset vectors. It is assumed that the coincs for the vector {"H1": 0, "H2": 10, "L1": 20} can be constructed from the coincs for the vectors {"H1": 0, "H2": 10} and {"H2": 0, "L1": 10}, that is only the relative offsets are significant in determining if two events are coincident, not the absolute offsets. This assumption is not true for the standard inspiral pipeline, where the absolute offsets are significant due to the periodic wrapping of triggers around rings. """ # # collect unique instrument set / deltas combinations # delta_sets = {} for vect in offsetvectors: for instruments in iterutils.choices(sorted(vect), n): # NOTE: the arithmetic used to construct the # offsets *must* match the arithmetic used by # offsetvector.deltas so that the results of the # two can be compared to each other without worry # of floating-point round off confusing things. delta_sets.setdefault(instruments, set()).add(tuple(vect[instrument] - vect[instruments[0]] for instrument in instruments)) # # translate into a list of normalized n-instrument offset vectors # return [offsetvector(zip(instruments, deltas)) for instruments, delta_set in delta_sets.items() for deltas in delta_set]
[ "def", "component_offsetvectors", "(", "offsetvectors", ",", "n", ")", ":", "#", "# collect unique instrument set / deltas combinations", "#", "delta_sets", "=", "{", "}", "for", "vect", "in", "offsetvectors", ":", "for", "instruments", "in", "iterutils", ".", "choi...
Given an iterable of offset vectors, return the shortest list of the unique n-instrument offset vectors from which all the vectors in the input iterable can be constructed. This can be used to determine the minimal set of n-instrument coincs required to construct all of the coincs for all of the requested instrument and offset combinations in a set of offset vectors. It is assumed that the coincs for the vector {"H1": 0, "H2": 10, "L1": 20} can be constructed from the coincs for the vectors {"H1": 0, "H2": 10} and {"H2": 0, "L1": 10}, that is only the relative offsets are significant in determining if two events are coincident, not the absolute offsets. This assumption is not true for the standard inspiral pipeline, where the absolute offsets are significant due to the periodic wrapping of triggers around rings.
[ "Given", "an", "iterable", "of", "offset", "vectors", "return", "the", "shortest", "list", "of", "the", "unique", "n", "-", "instrument", "offset", "vectors", "from", "which", "all", "the", "vectors", "in", "the", "input", "iterable", "can", "be", "construct...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/offsetvector.py#L268-L303
gwastro/pycbc-glue
pycbc_glue/offsetvector.py
offsetvector.deltas
def deltas(self): """ Dictionary of relative offsets. The keys in the result are pairs of keys from the offset vector, (a, b), and the values are the relative offsets, (offset[b] - offset[a]). Raises ValueError if the offsetvector is empty (WARNING: this behaviour might change in the future). Example: >>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20}) >>> x.deltas {('H1', 'L1'): 10, ('H1', 'V1'): 20, ('H1', 'H1'): 0} >>> y = offsetvector({'H1': 100, 'L1': 110, 'V1': 120}) >>> y.deltas == x.deltas True Note that the result always includes a "dummy" entry, giving the relative offset of self.refkey with respect to itself, which is always 0. See also .fromdeltas(). BUGS: I think the keys in each tuple should be reversed. I can't remember why I put them in the way they are. Expect them to change in the future. """ # FIXME: instead of raising ValueError when the # offsetvector is empty this should return an empty # dictionary. the inverse, .fromdeltas() accepts # empty dictionaries # NOTE: the arithmetic used to construct the offsets # *must* match the arithmetic used by # time_slide_component_vectors() so that the results of the # two functions can be compared to each other without worry # of floating-point round off confusing things. refkey = self.refkey refoffset = self[refkey] return dict(((refkey, key), self[key] - refoffset) for key in self)
python
def deltas(self): """ Dictionary of relative offsets. The keys in the result are pairs of keys from the offset vector, (a, b), and the values are the relative offsets, (offset[b] - offset[a]). Raises ValueError if the offsetvector is empty (WARNING: this behaviour might change in the future). Example: >>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20}) >>> x.deltas {('H1', 'L1'): 10, ('H1', 'V1'): 20, ('H1', 'H1'): 0} >>> y = offsetvector({'H1': 100, 'L1': 110, 'V1': 120}) >>> y.deltas == x.deltas True Note that the result always includes a "dummy" entry, giving the relative offset of self.refkey with respect to itself, which is always 0. See also .fromdeltas(). BUGS: I think the keys in each tuple should be reversed. I can't remember why I put them in the way they are. Expect them to change in the future. """ # FIXME: instead of raising ValueError when the # offsetvector is empty this should return an empty # dictionary. the inverse, .fromdeltas() accepts # empty dictionaries # NOTE: the arithmetic used to construct the offsets # *must* match the arithmetic used by # time_slide_component_vectors() so that the results of the # two functions can be compared to each other without worry # of floating-point round off confusing things. refkey = self.refkey refoffset = self[refkey] return dict(((refkey, key), self[key] - refoffset) for key in self)
[ "def", "deltas", "(", "self", ")", ":", "# FIXME: instead of raising ValueError when the", "# offsetvector is empty this should return an empty", "# dictionary. the inverse, .fromdeltas() accepts", "# empty dictionaries", "# NOTE: the arithmetic used to construct the offsets", "# *must* mat...
Dictionary of relative offsets. The keys in the result are pairs of keys from the offset vector, (a, b), and the values are the relative offsets, (offset[b] - offset[a]). Raises ValueError if the offsetvector is empty (WARNING: this behaviour might change in the future). Example: >>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20}) >>> x.deltas {('H1', 'L1'): 10, ('H1', 'V1'): 20, ('H1', 'H1'): 0} >>> y = offsetvector({'H1': 100, 'L1': 110, 'V1': 120}) >>> y.deltas == x.deltas True Note that the result always includes a "dummy" entry, giving the relative offset of self.refkey with respect to itself, which is always 0. See also .fromdeltas(). BUGS: I think the keys in each tuple should be reversed. I can't remember why I put them in the way they are. Expect them to change in the future.
[ "Dictionary", "of", "relative", "offsets", ".", "The", "keys", "in", "the", "result", "are", "pairs", "of", "keys", "from", "the", "offset", "vector", "(", "a", "b", ")", "and", "the", "values", "are", "the", "relative", "offsets", "(", "offset", "[", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/offsetvector.py#L83-L121
gwastro/pycbc-glue
pycbc_glue/offsetvector.py
offsetvector.contains
def contains(self, other): """ Returns True if offset vector @other can be found in @self, False otherwise. An offset vector is "found in" another offset vector if the latter contains all of the former's instruments and the relative offsets among those instruments are equal (the absolute offsets need not be). Example: >>> a = offsetvector({"H1": 10, "L1": 20, "V1": 30}) >>> b = offsetvector({"H1": 20, "V1": 40}) >>> a.contains(b) True Note the distinction between this and the "in" operator: >>> "H1" in a True """ return offsetvector((key, offset) for key, offset in self.items() if key in other).deltas == other.deltas
python
def contains(self, other): """ Returns True if offset vector @other can be found in @self, False otherwise. An offset vector is "found in" another offset vector if the latter contains all of the former's instruments and the relative offsets among those instruments are equal (the absolute offsets need not be). Example: >>> a = offsetvector({"H1": 10, "L1": 20, "V1": 30}) >>> b = offsetvector({"H1": 20, "V1": 40}) >>> a.contains(b) True Note the distinction between this and the "in" operator: >>> "H1" in a True """ return offsetvector((key, offset) for key, offset in self.items() if key in other).deltas == other.deltas
[ "def", "contains", "(", "self", ",", "other", ")", ":", "return", "offsetvector", "(", "(", "key", ",", "offset", ")", "for", "key", ",", "offset", "in", "self", ".", "items", "(", ")", "if", "key", "in", "other", ")", ".", "deltas", "==", "other",...
Returns True if offset vector @other can be found in @self, False otherwise. An offset vector is "found in" another offset vector if the latter contains all of the former's instruments and the relative offsets among those instruments are equal (the absolute offsets need not be). Example: >>> a = offsetvector({"H1": 10, "L1": 20, "V1": 30}) >>> b = offsetvector({"H1": 20, "V1": 40}) >>> a.contains(b) True Note the distinction between this and the "in" operator: >>> "H1" in a True
[ "Returns", "True", "if", "offset", "vector", "@other", "can", "be", "found", "in", "@self", "False", "otherwise", ".", "An", "offset", "vector", "is", "found", "in", "another", "offset", "vector", "if", "the", "latter", "contains", "all", "of", "the", "for...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/offsetvector.py#L182-L202
gwastro/pycbc-glue
pycbc_glue/offsetvector.py
offsetvector.normalize
def normalize(self, **kwargs): """ Adjust the offsetvector so that a particular instrument has the desired offset. All other instruments have their offsets adjusted so that the relative offsets are preserved. The instrument to noramlize, and the offset one wishes it to have, are provided as a key-word argument. The return value is the time slide dictionary, which is modified in place. If more than one key-word argument is provided the keys are sorted and considered in order until a key is found that is in the offset vector. The offset vector is normalized to that value. This function is a no-op if no key-word argument is found that applies. Example: >>> a = offsetvector({"H1": -10, "H2": -10, "L1": -10}) >>> a.normalize(L1 = 0) offsetvector({'H2': 0, 'H1': 0, 'L1': 0}) >>> a = offsetvector({"H1": -10, "H2": -10}) >>> a.normalize(L1 = 0, H2 = 5) offsetvector({'H2': 5, 'H1': 5}) """ # FIXME: should it be performed in place? if it should # be, the should there be no return value? for key, offset in sorted(kwargs.items()): if key in self: delta = offset - self[key] for key in self.keys(): self[key] += delta break return self
python
def normalize(self, **kwargs): """ Adjust the offsetvector so that a particular instrument has the desired offset. All other instruments have their offsets adjusted so that the relative offsets are preserved. The instrument to noramlize, and the offset one wishes it to have, are provided as a key-word argument. The return value is the time slide dictionary, which is modified in place. If more than one key-word argument is provided the keys are sorted and considered in order until a key is found that is in the offset vector. The offset vector is normalized to that value. This function is a no-op if no key-word argument is found that applies. Example: >>> a = offsetvector({"H1": -10, "H2": -10, "L1": -10}) >>> a.normalize(L1 = 0) offsetvector({'H2': 0, 'H1': 0, 'L1': 0}) >>> a = offsetvector({"H1": -10, "H2": -10}) >>> a.normalize(L1 = 0, H2 = 5) offsetvector({'H2': 5, 'H1': 5}) """ # FIXME: should it be performed in place? if it should # be, the should there be no return value? for key, offset in sorted(kwargs.items()): if key in self: delta = offset - self[key] for key in self.keys(): self[key] += delta break return self
[ "def", "normalize", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# FIXME: should it be performed in place? if it should", "# be, the should there be no return value?", "for", "key", ",", "offset", "in", "sorted", "(", "kwargs", ".", "items", "(", ")", ")", ":"...
Adjust the offsetvector so that a particular instrument has the desired offset. All other instruments have their offsets adjusted so that the relative offsets are preserved. The instrument to noramlize, and the offset one wishes it to have, are provided as a key-word argument. The return value is the time slide dictionary, which is modified in place. If more than one key-word argument is provided the keys are sorted and considered in order until a key is found that is in the offset vector. The offset vector is normalized to that value. This function is a no-op if no key-word argument is found that applies. Example: >>> a = offsetvector({"H1": -10, "H2": -10, "L1": -10}) >>> a.normalize(L1 = 0) offsetvector({'H2': 0, 'H1': 0, 'L1': 0}) >>> a = offsetvector({"H1": -10, "H2": -10}) >>> a.normalize(L1 = 0, H2 = 5) offsetvector({'H2': 5, 'H1': 5})
[ "Adjust", "the", "offsetvector", "so", "that", "a", "particular", "instrument", "has", "the", "desired", "offset", ".", "All", "other", "instruments", "have", "their", "offsets", "adjusted", "so", "that", "the", "relative", "offsets", "are", "preserved", ".", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/offsetvector.py#L204-L237
gwastro/pycbc-glue
pycbc_glue/offsetvector.py
offsetvector.fromdeltas
def fromdeltas(cls, deltas): """ Construct an offsetvector from a dictionary of offset deltas as returned by the .deltas attribute. Example: >>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20}) >>> y = offsetvector.fromdeltas(x.deltas) >>> y offsetvector({'V1': 20, 'H1': 0, 'L1': 10}) >>> y == x True See also .deltas, .fromkeys() """ return cls((key, value) for (refkey, key), value in deltas.items())
python
def fromdeltas(cls, deltas): """ Construct an offsetvector from a dictionary of offset deltas as returned by the .deltas attribute. Example: >>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20}) >>> y = offsetvector.fromdeltas(x.deltas) >>> y offsetvector({'V1': 20, 'H1': 0, 'L1': 10}) >>> y == x True See also .deltas, .fromkeys() """ return cls((key, value) for (refkey, key), value in deltas.items())
[ "def", "fromdeltas", "(", "cls", ",", "deltas", ")", ":", "return", "cls", "(", "(", "key", ",", "value", ")", "for", "(", "refkey", ",", "key", ")", ",", "value", "in", "deltas", ".", "items", "(", ")", ")" ]
Construct an offsetvector from a dictionary of offset deltas as returned by the .deltas attribute. Example: >>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20}) >>> y = offsetvector.fromdeltas(x.deltas) >>> y offsetvector({'V1': 20, 'H1': 0, 'L1': 10}) >>> y == x True See also .deltas, .fromkeys()
[ "Construct", "an", "offsetvector", "from", "a", "dictionary", "of", "offset", "deltas", "as", "returned", "by", "the", ".", "deltas", "attribute", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/offsetvector.py#L240-L256
RadhikaG/markdown-magic
magic/gifAPI.py
processGif
def processGif(searchStr): ''' This function returns the url of the gif searched for with the given search parameters using the Giphy API. Thanks! Fails gracefully when it can't find a gif by returning an appropriate image url with the failure message on it. ''' # Sanitizing searchStr # TODO: Find a better way to do this searchStr.replace('| ', ' ') searchStr.replace('|', ' ') searchStr.replace(', ', ' ') searchStr.replace(',', ' ') searchStr.rstrip() searchStr = searchStr.strip('./?\'!,') searchStr = searchStr.replace(' ', '+') if searchStr is None or searchStr == '': print("No search parameters specified!") return no_search_params api_url = 'http://api.giphy.com/v1/gifs/search' api_key = 'dc6zaTOxFJmzC' payload = { 'q': searchStr, 'limit': 1, 'api_key': api_key, } r = requests.get(api_url, params=payload) parsed_json = json.loads(r.text) # print(parsed_json) if len(parsed_json['data']) == 0: print("Couldn't find suitable match for gif! :(") return -1 else: # Success! imgURL = parsed_json['data'][0]['images']['fixed_height']['url'] # print(imgURL) return imgURL
python
def processGif(searchStr): ''' This function returns the url of the gif searched for with the given search parameters using the Giphy API. Thanks! Fails gracefully when it can't find a gif by returning an appropriate image url with the failure message on it. ''' # Sanitizing searchStr # TODO: Find a better way to do this searchStr.replace('| ', ' ') searchStr.replace('|', ' ') searchStr.replace(', ', ' ') searchStr.replace(',', ' ') searchStr.rstrip() searchStr = searchStr.strip('./?\'!,') searchStr = searchStr.replace(' ', '+') if searchStr is None or searchStr == '': print("No search parameters specified!") return no_search_params api_url = 'http://api.giphy.com/v1/gifs/search' api_key = 'dc6zaTOxFJmzC' payload = { 'q': searchStr, 'limit': 1, 'api_key': api_key, } r = requests.get(api_url, params=payload) parsed_json = json.loads(r.text) # print(parsed_json) if len(parsed_json['data']) == 0: print("Couldn't find suitable match for gif! :(") return -1 else: # Success! imgURL = parsed_json['data'][0]['images']['fixed_height']['url'] # print(imgURL) return imgURL
[ "def", "processGif", "(", "searchStr", ")", ":", "# Sanitizing searchStr", "# TODO: Find a better way to do this", "searchStr", ".", "replace", "(", "'| '", ",", "' '", ")", "searchStr", ".", "replace", "(", "'|'", ",", "' '", ")", "searchStr", ".", "replace", "...
This function returns the url of the gif searched for with the given search parameters using the Giphy API. Thanks! Fails gracefully when it can't find a gif by returning an appropriate image url with the failure message on it.
[ "This", "function", "returns", "the", "url", "of", "the", "gif", "searched", "for", "with", "the", "given", "search", "parameters", "using", "the", "Giphy", "API", ".", "Thanks!" ]
train
https://github.com/RadhikaG/markdown-magic/blob/af99549b033269d861ea13f0541cb4f894057c47/magic/gifAPI.py#L5-L49
PixxxeL/python-html-purifier
purifier/purifier.py
HTMLPurifier.feed
def feed(self, data): """ Main method for purifying HTML (overrided) """ self.reset_purified() HTMLParser.feed(self, data) return self.html()
python
def feed(self, data): """ Main method for purifying HTML (overrided) """ self.reset_purified() HTMLParser.feed(self, data) return self.html()
[ "def", "feed", "(", "self", ",", "data", ")", ":", "self", ".", "reset_purified", "(", ")", "HTMLParser", ".", "feed", "(", "self", ",", "data", ")", "return", "self", ".", "html", "(", ")" ]
Main method for purifying HTML (overrided)
[ "Main", "method", "for", "purifying", "HTML", "(", "overrided", ")" ]
train
https://github.com/PixxxeL/python-html-purifier/blob/00f38b6e7f66be02aa21100949f9ffa5be661e8d/purifier/purifier.py#L31-L37
PixxxeL/python-html-purifier
purifier/purifier.py
HTMLPurifier.handle_starttag
def handle_starttag(self, tag, attrs): """ Handler of starting tag processing (overrided, private) """ self.log.debug( u'Encountered a start tag: {0} {1}'.format(tag, attrs) ) if tag in self.sanitizelist: self.level += 1 return if self.isNotPurify or tag in self.whitelist_keys: attrs = self.__attrs_str(tag, attrs) attrs = ' ' + attrs if attrs else '' tmpl = u'<%s%s />' if tag in self.unclosedTags and self.isStrictHtml else u'<%s%s>' self.data.append( tmpl % (tag, attrs,) )
python
def handle_starttag(self, tag, attrs): """ Handler of starting tag processing (overrided, private) """ self.log.debug( u'Encountered a start tag: {0} {1}'.format(tag, attrs) ) if tag in self.sanitizelist: self.level += 1 return if self.isNotPurify or tag in self.whitelist_keys: attrs = self.__attrs_str(tag, attrs) attrs = ' ' + attrs if attrs else '' tmpl = u'<%s%s />' if tag in self.unclosedTags and self.isStrictHtml else u'<%s%s>' self.data.append( tmpl % (tag, attrs,) )
[ "def", "handle_starttag", "(", "self", ",", "tag", ",", "attrs", ")", ":", "self", ".", "log", ".", "debug", "(", "u'Encountered a start tag: {0} {1}'", ".", "format", "(", "tag", ",", "attrs", ")", ")", "if", "tag", "in", "self", ".", "sanitizelist", ":...
Handler of starting tag processing (overrided, private)
[ "Handler", "of", "starting", "tag", "processing", "(", "overrided", "private", ")" ]
train
https://github.com/PixxxeL/python-html-purifier/blob/00f38b6e7f66be02aa21100949f9ffa5be661e8d/purifier/purifier.py#L51-L63
PixxxeL/python-html-purifier
purifier/purifier.py
HTMLPurifier.handle_endtag
def handle_endtag(self, tag): """ Handler of ending tag processing (overrided, private) """ self.log.debug( u'Encountered an end tag : {0}'.format(tag) ) if tag in self.sanitizelist: self.level -= 1 return if tag in self.unclosedTags: return if self.isNotPurify or tag in self.whitelist_keys: self.data.append(u'</%s>' % tag)
python
def handle_endtag(self, tag): """ Handler of ending tag processing (overrided, private) """ self.log.debug( u'Encountered an end tag : {0}'.format(tag) ) if tag in self.sanitizelist: self.level -= 1 return if tag in self.unclosedTags: return if self.isNotPurify or tag in self.whitelist_keys: self.data.append(u'</%s>' % tag)
[ "def", "handle_endtag", "(", "self", ",", "tag", ")", ":", "self", ".", "log", ".", "debug", "(", "u'Encountered an end tag : {0}'", ".", "format", "(", "tag", ")", ")", "if", "tag", "in", "self", ".", "sanitizelist", ":", "self", ".", "level", "-=", "...
Handler of ending tag processing (overrided, private)
[ "Handler", "of", "ending", "tag", "processing", "(", "overrided", "private", ")" ]
train
https://github.com/PixxxeL/python-html-purifier/blob/00f38b6e7f66be02aa21100949f9ffa5be661e8d/purifier/purifier.py#L65-L76
PixxxeL/python-html-purifier
purifier/purifier.py
HTMLPurifier.handle_data
def handle_data(self, data): """ Handler of processing data inside tag (overrided, private) """ self.log.debug( u'Encountered some data : {0}'.format(data) ) if not self.level: self.data.append(data)
python
def handle_data(self, data): """ Handler of processing data inside tag (overrided, private) """ self.log.debug( u'Encountered some data : {0}'.format(data) ) if not self.level: self.data.append(data)
[ "def", "handle_data", "(", "self", ",", "data", ")", ":", "self", ".", "log", ".", "debug", "(", "u'Encountered some data : {0}'", ".", "format", "(", "data", ")", ")", "if", "not", "self", ".", "level", ":", "self", ".", "data", ".", "append", "(", ...
Handler of processing data inside tag (overrided, private)
[ "Handler", "of", "processing", "data", "inside", "tag", "(", "overrided", "private", ")" ]
train
https://github.com/PixxxeL/python-html-purifier/blob/00f38b6e7f66be02aa21100949f9ffa5be661e8d/purifier/purifier.py#L78-L84
PixxxeL/python-html-purifier
purifier/purifier.py
HTMLPurifier.handle_entityref
def handle_entityref(self, name): """ Handler of processing entity (overrided, private) """ self.log.debug( u'Encountered entity : {0}'.format(name) ) if not self.removeEntity: self.data.append('&%s;' % name)
python
def handle_entityref(self, name): """ Handler of processing entity (overrided, private) """ self.log.debug( u'Encountered entity : {0}'.format(name) ) if not self.removeEntity: self.data.append('&%s;' % name)
[ "def", "handle_entityref", "(", "self", ",", "name", ")", ":", "self", ".", "log", ".", "debug", "(", "u'Encountered entity : {0}'", ".", "format", "(", "name", ")", ")", "if", "not", "self", ".", "removeEntity", ":", "self", ".", "data", ".", "append",...
Handler of processing entity (overrided, private)
[ "Handler", "of", "processing", "entity", "(", "overrided", "private", ")" ]
train
https://github.com/PixxxeL/python-html-purifier/blob/00f38b6e7f66be02aa21100949f9ffa5be661e8d/purifier/purifier.py#L86-L92
PixxxeL/python-html-purifier
purifier/purifier.py
HTMLPurifier.__set_whitelist
def __set_whitelist(self, whitelist=None): """ Update default white list by customer white list """ # add tag's names as key and list of enabled attributes as value for defaults self.whitelist = {} # tags that removed with contents self.sanitizelist = ['script', 'style'] if isinstance(whitelist, dict) and '*' in whitelist.keys(): self.isNotPurify = True self.whitelist_keys = [] return else: self.isNotPurify = False self.whitelist.update(whitelist or {}) self.whitelist_keys = self.whitelist.keys()
python
def __set_whitelist(self, whitelist=None): """ Update default white list by customer white list """ # add tag's names as key and list of enabled attributes as value for defaults self.whitelist = {} # tags that removed with contents self.sanitizelist = ['script', 'style'] if isinstance(whitelist, dict) and '*' in whitelist.keys(): self.isNotPurify = True self.whitelist_keys = [] return else: self.isNotPurify = False self.whitelist.update(whitelist or {}) self.whitelist_keys = self.whitelist.keys()
[ "def", "__set_whitelist", "(", "self", ",", "whitelist", "=", "None", ")", ":", "# add tag's names as key and list of enabled attributes as value for defaults", "self", ".", "whitelist", "=", "{", "}", "# tags that removed with contents", "self", ".", "sanitizelist", "=", ...
Update default white list by customer white list
[ "Update", "default", "white", "list", "by", "customer", "white", "list" ]
train
https://github.com/PixxxeL/python-html-purifier/blob/00f38b6e7f66be02aa21100949f9ffa5be661e8d/purifier/purifier.py#L105-L120
PixxxeL/python-html-purifier
purifier/purifier.py
HTMLPurifier.__attrs_str
def __attrs_str(self, tag, attrs): """ Build string of attributes list for tag """ enabled = self.whitelist.get(tag, ['*']) all_attrs = '*' in enabled items = [] for attr in attrs: key = attr[0] value = attr[1] or '' if all_attrs or key in enabled: items.append( u'%s="%s"' % (key, value,) ) return u' '.join(items)
python
def __attrs_str(self, tag, attrs): """ Build string of attributes list for tag """ enabled = self.whitelist.get(tag, ['*']) all_attrs = '*' in enabled items = [] for attr in attrs: key = attr[0] value = attr[1] or '' if all_attrs or key in enabled: items.append( u'%s="%s"' % (key, value,) ) return u' '.join(items)
[ "def", "__attrs_str", "(", "self", ",", "tag", ",", "attrs", ")", ":", "enabled", "=", "self", ".", "whitelist", ".", "get", "(", "tag", ",", "[", "'*'", "]", ")", "all_attrs", "=", "'*'", "in", "enabled", "items", "=", "[", "]", "for", "attr", "...
Build string of attributes list for tag
[ "Build", "string", "of", "attributes", "list", "for", "tag" ]
train
https://github.com/PixxxeL/python-html-purifier/blob/00f38b6e7f66be02aa21100949f9ffa5be661e8d/purifier/purifier.py#L122-L134
idlesign/srptools
srptools/utils.py
hex_from
def hex_from(val): """Returns hex string representation for a given value. :param bytes|str|unicode|int|long val: :rtype: bytes|str """ if isinstance(val, integer_types): hex_str = '%x' % val if len(hex_str) % 2: hex_str = '0' + hex_str return hex_str return hexlify(val)
python
def hex_from(val): """Returns hex string representation for a given value. :param bytes|str|unicode|int|long val: :rtype: bytes|str """ if isinstance(val, integer_types): hex_str = '%x' % val if len(hex_str) % 2: hex_str = '0' + hex_str return hex_str return hexlify(val)
[ "def", "hex_from", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "integer_types", ")", ":", "hex_str", "=", "'%x'", "%", "val", "if", "len", "(", "hex_str", ")", "%", "2", ":", "hex_str", "=", "'0'", "+", "hex_str", "return", "hex_str", ...
Returns hex string representation for a given value. :param bytes|str|unicode|int|long val: :rtype: bytes|str
[ "Returns", "hex", "string", "representation", "for", "a", "given", "value", "." ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/utils.py#L22-L34
idlesign/srptools
srptools/utils.py
b64_from
def b64_from(val): """Returns base64 encoded bytes for a given int/long/bytes value. :param int|long|bytes val: :rtype: bytes|str """ if isinstance(val, integer_types): val = int_to_bytes(val) return b64encode(val).decode('ascii')
python
def b64_from(val): """Returns base64 encoded bytes for a given int/long/bytes value. :param int|long|bytes val: :rtype: bytes|str """ if isinstance(val, integer_types): val = int_to_bytes(val) return b64encode(val).decode('ascii')
[ "def", "b64_from", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "integer_types", ")", ":", "val", "=", "int_to_bytes", "(", "val", ")", "return", "b64encode", "(", "val", ")", ".", "decode", "(", "'ascii'", ")" ]
Returns base64 encoded bytes for a given int/long/bytes value. :param int|long|bytes val: :rtype: bytes|str
[ "Returns", "base64", "encoded", "bytes", "for", "a", "given", "int", "/", "long", "/", "bytes", "value", "." ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/utils.py#L56-L64
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/print_tables.py
set_output_format
def set_output_format( output_format ): """ Sets output format; returns standard bits of table. These are: ttx: how to start a title for a set of tables xtt: how to end a title for a set of tables tx: how to start a table xt: how to close a table capx: how to start a caption for the table xcap: how to close a caption for the table rx: how to start a row and the first cell in the row xr: how to close a row and the last cell in the row rspx: how to start a cell with a row span argument xrsp: how to close the row span argument cx: how to open a cell xc: how to close a cell """ if output_format == 'wiki': ttx = '== ' xtt = ' ==' tx = '' xt = '' capx = "'''" xcap = "'''" rx = '|' xr = '|' rspx = '|<|' xrsp = '>' cx = '|' xc = '|' hlx = '[' hxl = ' ' xhl = ']' elif output_format == "html": ttx = '<b>' xtt = '</b><hr>' tx = '<table border = "1">' xt = '</table><br><br>' capx = '<caption>' xcap = '</caption>' rx = '<tr>' xr = '</tr>' rspx = '<td rowspan=' xrsp = '>' cx = '<td>' xc = '</td>' hlx = '<a href="' hxl = '">' xhl = "</a>" else: raise ValueError("unrecognized output_format %s" % output_format) return ttx, xtt, tx, xt, capx, xcap, rx, xr, cx, xc, rspx, xrsp, hlx, hxl, xhl
python
def set_output_format( output_format ): """ Sets output format; returns standard bits of table. These are: ttx: how to start a title for a set of tables xtt: how to end a title for a set of tables tx: how to start a table xt: how to close a table capx: how to start a caption for the table xcap: how to close a caption for the table rx: how to start a row and the first cell in the row xr: how to close a row and the last cell in the row rspx: how to start a cell with a row span argument xrsp: how to close the row span argument cx: how to open a cell xc: how to close a cell """ if output_format == 'wiki': ttx = '== ' xtt = ' ==' tx = '' xt = '' capx = "'''" xcap = "'''" rx = '|' xr = '|' rspx = '|<|' xrsp = '>' cx = '|' xc = '|' hlx = '[' hxl = ' ' xhl = ']' elif output_format == "html": ttx = '<b>' xtt = '</b><hr>' tx = '<table border = "1">' xt = '</table><br><br>' capx = '<caption>' xcap = '</caption>' rx = '<tr>' xr = '</tr>' rspx = '<td rowspan=' xrsp = '>' cx = '<td>' xc = '</td>' hlx = '<a href="' hxl = '">' xhl = "</a>" else: raise ValueError("unrecognized output_format %s" % output_format) return ttx, xtt, tx, xt, capx, xcap, rx, xr, cx, xc, rspx, xrsp, hlx, hxl, xhl
[ "def", "set_output_format", "(", "output_format", ")", ":", "if", "output_format", "==", "'wiki'", ":", "ttx", "=", "'== '", "xtt", "=", "' =='", "tx", "=", "''", "xt", "=", "''", "capx", "=", "\"'''\"", "xcap", "=", "\"'''\"", "rx", "=", "'|'", "xr", ...
Sets output format; returns standard bits of table. These are: ttx: how to start a title for a set of tables xtt: how to end a title for a set of tables tx: how to start a table xt: how to close a table capx: how to start a caption for the table xcap: how to close a caption for the table rx: how to start a row and the first cell in the row xr: how to close a row and the last cell in the row rspx: how to start a cell with a row span argument xrsp: how to close the row span argument cx: how to open a cell xc: how to close a cell
[ "Sets", "output", "format", ";", "returns", "standard", "bits", "of", "table", ".", "These", "are", ":", "ttx", ":", "how", "to", "start", "a", "title", "for", "a", "set", "of", "tables", "xtt", ":", "how", "to", "end", "a", "title", "for", "a", "s...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/print_tables.py#L35-L88
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/print_tables.py
smart_round
def smart_round( val, decimal_places = 2 ): """ For floats >= 10.**-(decimal_places - 1), rounds off to the valber of decimal places specified. For floats < 10.**-(decimal_places - 1), puts in exponential form then rounds off to the decimal places specified. @val: value to round; if val is not a float, just returns val @decimal_places: number of decimal places to round to """ if isinstance(val, float) and val != 0.0: if val >= 10.**-(decimal_places - 1): conv_str = ''.join([ '%.', str(decimal_places), 'f' ]) else: conv_str = ''.join([ '%.', str(decimal_places), 'e' ]) val = float( conv_str % val ) return val
python
def smart_round( val, decimal_places = 2 ): """ For floats >= 10.**-(decimal_places - 1), rounds off to the valber of decimal places specified. For floats < 10.**-(decimal_places - 1), puts in exponential form then rounds off to the decimal places specified. @val: value to round; if val is not a float, just returns val @decimal_places: number of decimal places to round to """ if isinstance(val, float) and val != 0.0: if val >= 10.**-(decimal_places - 1): conv_str = ''.join([ '%.', str(decimal_places), 'f' ]) else: conv_str = ''.join([ '%.', str(decimal_places), 'e' ]) val = float( conv_str % val ) return val
[ "def", "smart_round", "(", "val", ",", "decimal_places", "=", "2", ")", ":", "if", "isinstance", "(", "val", ",", "float", ")", "and", "val", "!=", "0.0", ":", "if", "val", ">=", "10.", "**", "-", "(", "decimal_places", "-", "1", ")", ":", "conv_st...
For floats >= 10.**-(decimal_places - 1), rounds off to the valber of decimal places specified. For floats < 10.**-(decimal_places - 1), puts in exponential form then rounds off to the decimal places specified. @val: value to round; if val is not a float, just returns val @decimal_places: number of decimal places to round to
[ "For", "floats", ">", "=", "10", ".", "**", "-", "(", "decimal_places", "-", "1", ")", "rounds", "off", "to", "the", "valber", "of", "decimal", "places", "specified", ".", "For", "floats", "<", "10", ".", "**", "-", "(", "decimal_places", "-", "1", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/print_tables.py#L91-L106
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/print_tables.py
format_hyperlink
def format_hyperlink( val, hlx, hxl, xhl ): """ Formats an html hyperlink into other forms. @hlx, hxl, xhl: values returned by set_output_format """ if '<a href="' in str(val) and hlx != '<a href="': val = val.replace('<a href="', hlx).replace('">', hxl, 1).replace('</a>', xhl) return val
python
def format_hyperlink( val, hlx, hxl, xhl ): """ Formats an html hyperlink into other forms. @hlx, hxl, xhl: values returned by set_output_format """ if '<a href="' in str(val) and hlx != '<a href="': val = val.replace('<a href="', hlx).replace('">', hxl, 1).replace('</a>', xhl) return val
[ "def", "format_hyperlink", "(", "val", ",", "hlx", ",", "hxl", ",", "xhl", ")", ":", "if", "'<a href=\"'", "in", "str", "(", "val", ")", "and", "hlx", "!=", "'<a href=\"'", ":", "val", "=", "val", ".", "replace", "(", "'<a href=\"'", ",", "hlx", ")",...
Formats an html hyperlink into other forms. @hlx, hxl, xhl: values returned by set_output_format
[ "Formats", "an", "html", "hyperlink", "into", "other", "forms", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/print_tables.py#L108-L117
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/print_tables.py
format_cell
def format_cell(val, round_floats = False, decimal_places = 2, format_links = False, hlx = '', hxl = '', xhl = ''): """ Applys smart_round and format_hyperlink to values in a cell if desired. """ if round_floats: val = smart_round(val, decimal_places = decimal_places) if format_links: val = format_hyperlink(val, hlx, hxl, xhl) return val
python
def format_cell(val, round_floats = False, decimal_places = 2, format_links = False, hlx = '', hxl = '', xhl = ''): """ Applys smart_round and format_hyperlink to values in a cell if desired. """ if round_floats: val = smart_round(val, decimal_places = decimal_places) if format_links: val = format_hyperlink(val, hlx, hxl, xhl) return val
[ "def", "format_cell", "(", "val", ",", "round_floats", "=", "False", ",", "decimal_places", "=", "2", ",", "format_links", "=", "False", ",", "hlx", "=", "''", ",", "hxl", "=", "''", ",", "xhl", "=", "''", ")", ":", "if", "round_floats", ":", "val", ...
Applys smart_round and format_hyperlink to values in a cell if desired.
[ "Applys", "smart_round", "and", "format_hyperlink", "to", "values", "in", "a", "cell", "if", "desired", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/print_tables.py#L119-L129
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/print_tables.py
format_header_cell
def format_header_cell(val): """ Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and all other '_' to spaces. """ return re.sub('_', ' ', re.sub(r'(_Px_)', '(', re.sub(r'(_xP_)', ')', str(val) )))
python
def format_header_cell(val): """ Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and all other '_' to spaces. """ return re.sub('_', ' ', re.sub(r'(_Px_)', '(', re.sub(r'(_xP_)', ')', str(val) )))
[ "def", "format_header_cell", "(", "val", ")", ":", "return", "re", ".", "sub", "(", "'_'", ",", "' '", ",", "re", ".", "sub", "(", "r'(_Px_)'", ",", "'('", ",", "re", ".", "sub", "(", "r'(_xP_)'", ",", "')'", ",", "str", "(", "val", ")", ")", "...
Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and all other '_' to spaces.
[ "Formats", "given", "header", "column", ".", "This", "involves", "changing", "_Px_", "to", "(", "_xP_", "to", ")", "and", "all", "other", "_", "to", "spaces", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/print_tables.py#L131-L136
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/print_tables.py
get_row_data
def get_row_data(row, column_name, cat_time_ns = True): """ Retrieves the requested column's data from the given row. @cat_time_ns: If the column_name has "_time" in it, will concatenate the column with any column having the same name but "_time_ns". """ column_name_ns = re.sub(r'_time', r'_time_ns', column_name) try: rowattrs = [attr for attr in row.__slots__] except AttributeError: rowattrs = [attr for attr in row.__dict__.iterkeys()] if cat_time_ns and "_time" in column_name and column_name_ns in rowattrs: return int(getattr(row, column_name)) + 10**(-9.)*int(getattr(row, column_name_ns)) else: return getattr(row, column_name)
python
def get_row_data(row, column_name, cat_time_ns = True): """ Retrieves the requested column's data from the given row. @cat_time_ns: If the column_name has "_time" in it, will concatenate the column with any column having the same name but "_time_ns". """ column_name_ns = re.sub(r'_time', r'_time_ns', column_name) try: rowattrs = [attr for attr in row.__slots__] except AttributeError: rowattrs = [attr for attr in row.__dict__.iterkeys()] if cat_time_ns and "_time" in column_name and column_name_ns in rowattrs: return int(getattr(row, column_name)) + 10**(-9.)*int(getattr(row, column_name_ns)) else: return getattr(row, column_name)
[ "def", "get_row_data", "(", "row", ",", "column_name", ",", "cat_time_ns", "=", "True", ")", ":", "column_name_ns", "=", "re", ".", "sub", "(", "r'_time'", ",", "r'_time_ns'", ",", "column_name", ")", "try", ":", "rowattrs", "=", "[", "attr", "for", "att...
Retrieves the requested column's data from the given row. @cat_time_ns: If the column_name has "_time" in it, will concatenate the column with any column having the same name but "_time_ns".
[ "Retrieves", "the", "requested", "column", "s", "data", "from", "the", "given", "row", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/print_tables.py#L138-L154
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/print_tables.py
print_tables
def print_tables(xmldoc, output, output_format, tableList = [], columnList = [], round_floats = True, decimal_places = 2, format_links = True, title = None, print_table_names = True, unique_rows = False, row_span_columns = [], rspan_break_columns = []): """ Method to print tables in an xml file in other formats. Input is an xmldoc, output is a file object containing the tables. @xmldoc: document to convert @output: file object to write output to; if None, will write to stdout @output_format: format to convert to @tableList: only convert the listed tables. Default is to convert all the tables found in the xmldoc. Tables not converted will not be included in the returned file object. @columnList: only print the columns listed, in the order given. This applies to all tables (if a table doesn't have a listed column, it's just skipped). To specify a column in a specific table, use table_name:column_name. Default is to print all columns. @round_floats: If turned on, will smart_round floats to specifed number of places. @format_links: If turned on, will convert any html hyperlinks to specified output_format. @decimal_places: If round_floats turned on, will smart_round to this number of decimal places. @title: Add a title to this set of tables. @unique_rows: If two consecutive rows are exactly the same, will condense into one row. @print_table_names: If set to True, will print the name of each table in the caption section. @row_span_columns: For the columns listed, will concatenate consecutive cells with the same values into one cell that spans those rows. Default is to span no rows. @rspan_break_column: Columns listed will prevent all cells from rowspanning across two rows in which values in the columns are diffrent. Default is to have no break columns. """ # get the tables to convert if tableList == []: tableList = [tb.getAttribute("Name") for tb in xmldoc.childNodes[0].getElementsByTagName(u'Table')] # set the output if output is None: output = sys.stdout # get table bits ttx, xtt, tx, xt, capx, xcap, rx, xr, cx, xc, rspx, xrsp, hlx, hxl, xhl = set_output_format( output_format ) # set the title if desired if title is not None: print >> output, "%s%s%s" %(ttx,str(title),xtt) # cycle over the tables in the xmldoc for table_name in tableList: this_table = table.get_table(xmldoc, table_name) if columnList == []: col_names = [ col.getAttribute("Name").split(":")[-1] for col in this_table.getElementsByTagName(u'Column') ] else: requested_columns = [col.split(':')[-1] for col in columnList if not (':' in col and col.split(':')[0] != table_name) ] requested_columns = sorted(set(requested_columns), key=requested_columns.index) actual_columns = [actual_column.getAttribute("Name").split(":")[-1] for actual_column in this_table.getElementsByTagName(u'Column') ] col_names = [col for col in requested_columns if col in actual_columns] # get the relevant row_span/break column indices rspan_indices = [ n for n,col in enumerate(col_names) if col in row_span_columns or ':'.join([table_name,col]) in row_span_columns ] break_indices = [ n for n,col in enumerate(col_names) if col in rspan_break_columns or ':'.join([table_name,col]) in rspan_break_columns ] # start the table and print table name print >> output, tx if print_table_names: print >> output, "%s%s%s" %(capx, table_name, xcap) print >> output, "%s%s%s%s%s" %(rx, cx, (xc+cx).join(format_header_cell(val) for val in col_names), xc, xr) # format the data in the table out_table = [] last_row = '' for row in this_table: out_row = [ str(format_cell( get_row_data(row, col_name), round_floats = round_floats, decimal_places = decimal_places, format_links = format_links, hlx = hlx, hxl = hxl, xhl = xhl )) for col_name in col_names ] if unique_rows and out_row == last_row: continue out_table.append(out_row) last_row = out_row rspan_count = {} for mm, row in enumerate(out_table[::-1]): this_row_idx = len(out_table) - (mm+1) next_row_idx = this_row_idx - 1 # cheack if it's ok to do row-span rspan_ok = rspan_indices != [] and this_row_idx != 0 if rspan_ok: for jj in break_indices: rspan_ok = out_table[this_row_idx][jj] == out_table[next_row_idx][jj] if not rspan_ok: break # cycle over columns in the row setting row span values for nn, val in enumerate(row): # check if this cell should be spanned; # if so, delete it, update rspan_count and go on to next cell if rspan_ok and nn in rspan_indices: if val == out_table[next_row_idx][nn]: out_table[this_row_idx][nn] = '' if (this_row_idx, nn) in rspan_count: rspan_count[(next_row_idx,nn)] = rspan_count[(this_row_idx,nn)] + 1 del rspan_count[(this_row_idx,nn)] else: rspan_count[(next_row_idx,nn)] = 2 elif (this_row_idx, nn) in rspan_count: out_table[this_row_idx][nn] = ''.join([rspx, str(rspan_count[(this_row_idx,nn)]), xrsp, str(val), xc]) else: out_table[this_row_idx][nn] = ''.join([cx, str(val), xc]) continue # format cell appropriately if (this_row_idx, nn) in rspan_count: out_table[this_row_idx][nn] = ''.join([rspx, str(rspan_count[(this_row_idx,nn)]), xrsp, str(val), xc]) else: out_table[this_row_idx][nn] = ''.join([cx, str(val), xc]) # print the table to output for row in out_table: print >> output, "%s%s%s" % (rx, ''.join(row), xr) # close the table and go on to the next print >> output, xt
python
def print_tables(xmldoc, output, output_format, tableList = [], columnList = [], round_floats = True, decimal_places = 2, format_links = True, title = None, print_table_names = True, unique_rows = False, row_span_columns = [], rspan_break_columns = []): """ Method to print tables in an xml file in other formats. Input is an xmldoc, output is a file object containing the tables. @xmldoc: document to convert @output: file object to write output to; if None, will write to stdout @output_format: format to convert to @tableList: only convert the listed tables. Default is to convert all the tables found in the xmldoc. Tables not converted will not be included in the returned file object. @columnList: only print the columns listed, in the order given. This applies to all tables (if a table doesn't have a listed column, it's just skipped). To specify a column in a specific table, use table_name:column_name. Default is to print all columns. @round_floats: If turned on, will smart_round floats to specifed number of places. @format_links: If turned on, will convert any html hyperlinks to specified output_format. @decimal_places: If round_floats turned on, will smart_round to this number of decimal places. @title: Add a title to this set of tables. @unique_rows: If two consecutive rows are exactly the same, will condense into one row. @print_table_names: If set to True, will print the name of each table in the caption section. @row_span_columns: For the columns listed, will concatenate consecutive cells with the same values into one cell that spans those rows. Default is to span no rows. @rspan_break_column: Columns listed will prevent all cells from rowspanning across two rows in which values in the columns are diffrent. Default is to have no break columns. """ # get the tables to convert if tableList == []: tableList = [tb.getAttribute("Name") for tb in xmldoc.childNodes[0].getElementsByTagName(u'Table')] # set the output if output is None: output = sys.stdout # get table bits ttx, xtt, tx, xt, capx, xcap, rx, xr, cx, xc, rspx, xrsp, hlx, hxl, xhl = set_output_format( output_format ) # set the title if desired if title is not None: print >> output, "%s%s%s" %(ttx,str(title),xtt) # cycle over the tables in the xmldoc for table_name in tableList: this_table = table.get_table(xmldoc, table_name) if columnList == []: col_names = [ col.getAttribute("Name").split(":")[-1] for col in this_table.getElementsByTagName(u'Column') ] else: requested_columns = [col.split(':')[-1] for col in columnList if not (':' in col and col.split(':')[0] != table_name) ] requested_columns = sorted(set(requested_columns), key=requested_columns.index) actual_columns = [actual_column.getAttribute("Name").split(":")[-1] for actual_column in this_table.getElementsByTagName(u'Column') ] col_names = [col for col in requested_columns if col in actual_columns] # get the relevant row_span/break column indices rspan_indices = [ n for n,col in enumerate(col_names) if col in row_span_columns or ':'.join([table_name,col]) in row_span_columns ] break_indices = [ n for n,col in enumerate(col_names) if col in rspan_break_columns or ':'.join([table_name,col]) in rspan_break_columns ] # start the table and print table name print >> output, tx if print_table_names: print >> output, "%s%s%s" %(capx, table_name, xcap) print >> output, "%s%s%s%s%s" %(rx, cx, (xc+cx).join(format_header_cell(val) for val in col_names), xc, xr) # format the data in the table out_table = [] last_row = '' for row in this_table: out_row = [ str(format_cell( get_row_data(row, col_name), round_floats = round_floats, decimal_places = decimal_places, format_links = format_links, hlx = hlx, hxl = hxl, xhl = xhl )) for col_name in col_names ] if unique_rows and out_row == last_row: continue out_table.append(out_row) last_row = out_row rspan_count = {} for mm, row in enumerate(out_table[::-1]): this_row_idx = len(out_table) - (mm+1) next_row_idx = this_row_idx - 1 # cheack if it's ok to do row-span rspan_ok = rspan_indices != [] and this_row_idx != 0 if rspan_ok: for jj in break_indices: rspan_ok = out_table[this_row_idx][jj] == out_table[next_row_idx][jj] if not rspan_ok: break # cycle over columns in the row setting row span values for nn, val in enumerate(row): # check if this cell should be spanned; # if so, delete it, update rspan_count and go on to next cell if rspan_ok and nn in rspan_indices: if val == out_table[next_row_idx][nn]: out_table[this_row_idx][nn] = '' if (this_row_idx, nn) in rspan_count: rspan_count[(next_row_idx,nn)] = rspan_count[(this_row_idx,nn)] + 1 del rspan_count[(this_row_idx,nn)] else: rspan_count[(next_row_idx,nn)] = 2 elif (this_row_idx, nn) in rspan_count: out_table[this_row_idx][nn] = ''.join([rspx, str(rspan_count[(this_row_idx,nn)]), xrsp, str(val), xc]) else: out_table[this_row_idx][nn] = ''.join([cx, str(val), xc]) continue # format cell appropriately if (this_row_idx, nn) in rspan_count: out_table[this_row_idx][nn] = ''.join([rspx, str(rspan_count[(this_row_idx,nn)]), xrsp, str(val), xc]) else: out_table[this_row_idx][nn] = ''.join([cx, str(val), xc]) # print the table to output for row in out_table: print >> output, "%s%s%s" % (rx, ''.join(row), xr) # close the table and go on to the next print >> output, xt
[ "def", "print_tables", "(", "xmldoc", ",", "output", ",", "output_format", ",", "tableList", "=", "[", "]", ",", "columnList", "=", "[", "]", ",", "round_floats", "=", "True", ",", "decimal_places", "=", "2", ",", "format_links", "=", "True", ",", "title...
Method to print tables in an xml file in other formats. Input is an xmldoc, output is a file object containing the tables. @xmldoc: document to convert @output: file object to write output to; if None, will write to stdout @output_format: format to convert to @tableList: only convert the listed tables. Default is to convert all the tables found in the xmldoc. Tables not converted will not be included in the returned file object. @columnList: only print the columns listed, in the order given. This applies to all tables (if a table doesn't have a listed column, it's just skipped). To specify a column in a specific table, use table_name:column_name. Default is to print all columns. @round_floats: If turned on, will smart_round floats to specifed number of places. @format_links: If turned on, will convert any html hyperlinks to specified output_format. @decimal_places: If round_floats turned on, will smart_round to this number of decimal places. @title: Add a title to this set of tables. @unique_rows: If two consecutive rows are exactly the same, will condense into one row. @print_table_names: If set to True, will print the name of each table in the caption section. @row_span_columns: For the columns listed, will concatenate consecutive cells with the same values into one cell that spans those rows. Default is to span no rows. @rspan_break_column: Columns listed will prevent all cells from rowspanning across two rows in which values in the columns are diffrent. Default is to have no break columns.
[ "Method", "to", "print", "tables", "in", "an", "xml", "file", "in", "other", "formats", ".", "Input", "is", "an", "xmldoc", "output", "is", "a", "file", "object", "containing", "the", "tables", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/print_tables.py#L163-L288
gwastro/pycbc-glue
setup.py
write_build_info
def write_build_info(): """ Get VCS info from pycbc_glue/generate_vcs_info.py and add build information. Substitute these into pycbc_glue/git_version.py.in to produce pycbc_glue/git_version.py. """ date = branch = tag = author = committer = status = builder_name = build_date = "" id = "1.1.0" try: v = gvcsi.generate_git_version_info() id, date, branch, tag, author = v.id, v.date, b.branch, v.tag, v.author committer, status = v.committer, v.status # determine current time and treat it as the build time build_date = time.strftime('%Y-%m-%d %H:%M:%S +0000', time.gmtime()) # determine builder retcode, builder_name = gvcsi.call_out(('git', 'config', 'user.name')) if retcode: builder_name = "Unknown User" retcode, builder_email = gvcsi.call_out(('git', 'config', 'user.email')) if retcode: builder_email = "" builder = "%s <%s>" % (builder_name, builder_email) except: pass sed_cmd = ('sed', '-e', 's/@ID@/%s/' % id, '-e', 's/@DATE@/%s/' % date, '-e', 's/@BRANCH@/%s/' % branch, '-e', 's/@TAG@/%s/' % tag, '-e', 's/@AUTHOR@/%s/' % author, '-e', 's/@COMMITTER@/%s/' % committer, '-e', 's/@STATUS@/%s/' % status, '-e', 's/@BUILDER@/%s/' % builder_name, '-e', 's/@BUILD_DATE@/%s/' % build_date, 'misc/git_version.py.in') # FIXME: subprocess.check_call becomes available in Python 2.5 sed_retcode = subprocess.call(sed_cmd, stdout=open('pycbc_glue/git_version.py', 'w')) if sed_retcode: raise gvcsi.GitInvocationError return id
python
def write_build_info(): """ Get VCS info from pycbc_glue/generate_vcs_info.py and add build information. Substitute these into pycbc_glue/git_version.py.in to produce pycbc_glue/git_version.py. """ date = branch = tag = author = committer = status = builder_name = build_date = "" id = "1.1.0" try: v = gvcsi.generate_git_version_info() id, date, branch, tag, author = v.id, v.date, b.branch, v.tag, v.author committer, status = v.committer, v.status # determine current time and treat it as the build time build_date = time.strftime('%Y-%m-%d %H:%M:%S +0000', time.gmtime()) # determine builder retcode, builder_name = gvcsi.call_out(('git', 'config', 'user.name')) if retcode: builder_name = "Unknown User" retcode, builder_email = gvcsi.call_out(('git', 'config', 'user.email')) if retcode: builder_email = "" builder = "%s <%s>" % (builder_name, builder_email) except: pass sed_cmd = ('sed', '-e', 's/@ID@/%s/' % id, '-e', 's/@DATE@/%s/' % date, '-e', 's/@BRANCH@/%s/' % branch, '-e', 's/@TAG@/%s/' % tag, '-e', 's/@AUTHOR@/%s/' % author, '-e', 's/@COMMITTER@/%s/' % committer, '-e', 's/@STATUS@/%s/' % status, '-e', 's/@BUILDER@/%s/' % builder_name, '-e', 's/@BUILD_DATE@/%s/' % build_date, 'misc/git_version.py.in') # FIXME: subprocess.check_call becomes available in Python 2.5 sed_retcode = subprocess.call(sed_cmd, stdout=open('pycbc_glue/git_version.py', 'w')) if sed_retcode: raise gvcsi.GitInvocationError return id
[ "def", "write_build_info", "(", ")", ":", "date", "=", "branch", "=", "tag", "=", "author", "=", "committer", "=", "status", "=", "builder_name", "=", "build_date", "=", "\"\"", "id", "=", "\"1.1.0\"", "try", ":", "v", "=", "gvcsi", ".", "generate_git_ve...
Get VCS info from pycbc_glue/generate_vcs_info.py and add build information. Substitute these into pycbc_glue/git_version.py.in to produce pycbc_glue/git_version.py.
[ "Get", "VCS", "info", "from", "pycbc_glue", "/", "generate_vcs_info", ".", "py", "and", "add", "build", "information", ".", "Substitute", "these", "into", "pycbc_glue", "/", "git_version", ".", "py", ".", "in", "to", "produce", "pycbc_glue", "/", "git_version"...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/setup.py#L67-L112
idlesign/srptools
srptools/context.py
SRPContext.pad
def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded
python
def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded
[ "def", "pad", "(", "self", ",", "val", ")", ":", "padding", "=", "len", "(", "int_to_bytes", "(", "self", ".", "_prime", ")", ")", "padded", "=", "int_to_bytes", "(", "val", ")", ".", "rjust", "(", "padding", ",", "b'\\x00'", ")", "return", "padded" ...
:param val: :rtype: bytes
[ ":", "param", "val", ":", ":", "rtype", ":", "bytes" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L64-L71
idlesign/srptools
srptools/context.py
SRPContext.hash
def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest())
python
def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest())
[ "def", "hash", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "joiner", "=", "kwargs", ".", "get", "(", "'joiner'", ",", "''", ")", ".", "encode", "(", "'utf-8'", ")", "as_bytes", "=", "kwargs", ".", "get", "(", "'as_bytes'", "...
:param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes
[ ":", "param", "args", ":", ":", "param", "kwargs", ":", "joiner", "-", "string", "to", "join", "values", "(", "args", ")", "as_bytes", "-", "bool", "to", "return", "hash", "bytes", "instead", "of", "default", "int", ":", "rtype", ":", "int|bytes" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L73-L102
idlesign/srptools
srptools/context.py
SRPContext.generate_random
def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len)
python
def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len)
[ "def", "generate_random", "(", "self", ",", "bits_len", "=", "None", ")", ":", "bits_len", "=", "bits_len", "or", "self", ".", "_bits_random", "return", "random", "(", ")", ".", "getrandbits", "(", "bits_len", ")" ]
Generates a random value. :param int bits_len: :rtype: int
[ "Generates", "a", "random", "value", "." ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L104-L111
idlesign/srptools
srptools/context.py
SRPContext.get_common_secret
def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public))
python
def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public))
[ "def", "get_common_secret", "(", "self", ",", "server_public", ",", "client_public", ")", ":", "return", "self", ".", "hash", "(", "self", ".", "pad", "(", "client_public", ")", ",", "self", ".", "pad", "(", "server_public", ")", ")" ]
u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int
[ "u", "=", "H", "(", "PAD", "(", "A", ")", "|", "PAD", "(", "B", "))" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L120-L127
idlesign/srptools
srptools/context.py
SRPContext.get_client_premaster_secret
def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime)
python
def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime)
[ "def", "get_client_premaster_secret", "(", "self", ",", "password_hash", ",", "server_public", ",", "client_private", ",", "common_secret", ")", ":", "password_verifier", "=", "self", ".", "get_common_password_verifier", "(", "password_hash", ")", "return", "pow", "("...
S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int
[ "S", "=", "(", "B", "-", "(", "k", "*", "g^x", "))", "^", "(", "a", "+", "(", "u", "*", "x", "))", "%", "N" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L129-L141
idlesign/srptools
srptools/context.py
SRPContext.get_server_premaster_secret
def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime)
python
def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime)
[ "def", "get_server_premaster_secret", "(", "self", ",", "password_verifier", ",", "server_private", ",", "client_public", ",", "common_secret", ")", ":", "return", "pow", "(", "(", "client_public", "*", "pow", "(", "password_verifier", ",", "common_secret", ",", "...
S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int
[ "S", "=", "(", "A", "*", "v^u", ")", "^", "b", "%", "N" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L151-L160
idlesign/srptools
srptools/context.py
SRPContext.get_server_public
def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime
python
def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime
[ "def", "get_server_public", "(", "self", ",", "password_verifier", ",", "server_private", ")", ":", "return", "(", "(", "self", ".", "_mult", "*", "password_verifier", ")", "+", "pow", "(", "self", ".", "_gen", ",", "server_private", ",", "self", ".", "_pr...
B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int
[ "B", "=", "(", "k", "*", "v", "+", "g^b", ")", "%", "N" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L184-L191
idlesign/srptools
srptools/context.py
SRPContext.get_common_password_hash
def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':'))
python
def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':'))
[ "def", "get_common_password_hash", "(", "self", ",", "salt", ")", ":", "password", "=", "self", ".", "_password", "if", "password", "is", "None", ":", "raise", "SRPException", "(", "'User password should be in context for this scenario.'", ")", "return", "self", "."...
x = H(s | H(I | ":" | P)) :param int salt: :rtype: int
[ "x", "=", "H", "(", "s", "|", "H", "(", "I", "|", ":", "|", "P", "))" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L193-L203
idlesign/srptools
srptools/context.py
SRPContext.get_common_session_key_proof
def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove
python
def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove
[ "def", "get_common_session_key_proof", "(", "self", ",", "session_key", ",", "salt", ",", "server_public", ",", "client_public", ")", ":", "h", "=", "self", ".", "hash", "prove", "=", "h", "(", "h", "(", "self", ".", "_prime", ")", "^", "h", "(", "self...
M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes
[ "M", "=", "H", "(", "H", "(", "N", ")", "XOR", "H", "(", "g", ")", "|", "H", "(", "U", ")", "|", "s", "|", "A", "|", "B", "|", "K", ")" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L213-L232
idlesign/srptools
srptools/context.py
SRPContext.get_common_session_key_proof_hash
def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True)
python
def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True)
[ "def", "get_common_session_key_proof_hash", "(", "self", ",", "session_key", ",", "session_key_proof", ",", "client_public", ")", ":", "return", "self", ".", "hash", "(", "client_public", ",", "session_key_proof", ",", "session_key", ",", "as_bytes", "=", "True", ...
H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes
[ "H", "(", "A", "|", "M", "|", "K", ")" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L234-L242
idlesign/srptools
srptools/context.py
SRPContext.get_user_data_triplet
def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
python
def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
[ "def", "get_user_data_triplet", "(", "self", ",", "base64", "=", "False", ")", ":", "salt", "=", "self", ".", "generate_salt", "(", ")", "verifier", "=", "self", ".", "get_common_password_verifier", "(", "self", ".", "get_common_password_hash", "(", "salt", ")...
( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple
[ "(", "<_user", ">", "<_password", "verifier", ">", "<salt", ">", ")" ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L244-L256
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorJob.add_input_file
def add_input_file(self, filename): """ Add filename as a necessary input file for this DAG node. @param filename: input filename to add """ if filename not in self.__input_files: self.__input_files.append(filename)
python
def add_input_file(self, filename): """ Add filename as a necessary input file for this DAG node. @param filename: input filename to add """ if filename not in self.__input_files: self.__input_files.append(filename)
[ "def", "add_input_file", "(", "self", ",", "filename", ")", ":", "if", "filename", "not", "in", "self", ".", "__input_files", ":", "self", ".", "__input_files", ".", "append", "(", "filename", ")" ]
Add filename as a necessary input file for this DAG node. @param filename: input filename to add
[ "Add", "filename", "as", "a", "necessary", "input", "file", "for", "this", "DAG", "node", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L501-L508
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorJob.add_output_file
def add_output_file(self, filename): """ Add filename as a output file for this DAG node. @param filename: output filename to add """ if filename not in self.__output_files: self.__output_files.append(filename)
python
def add_output_file(self, filename): """ Add filename as a output file for this DAG node. @param filename: output filename to add """ if filename not in self.__output_files: self.__output_files.append(filename)
[ "def", "add_output_file", "(", "self", ",", "filename", ")", ":", "if", "filename", "not", "in", "self", ".", "__output_files", ":", "self", ".", "__output_files", ".", "append", "(", "filename", ")" ]
Add filename as a output file for this DAG node. @param filename: output filename to add
[ "Add", "filename", "as", "a", "output", "file", "for", "this", "DAG", "node", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L510-L517
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorJob.add_checkpoint_file
def add_checkpoint_file(self, filename): """ Add filename as a checkpoint file for this DAG job. """ if filename not in self.__checkpoint_files: self.__checkpoint_files.append(filename)
python
def add_checkpoint_file(self, filename): """ Add filename as a checkpoint file for this DAG job. """ if filename not in self.__checkpoint_files: self.__checkpoint_files.append(filename)
[ "def", "add_checkpoint_file", "(", "self", ",", "filename", ")", ":", "if", "filename", "not", "in", "self", ".", "__checkpoint_files", ":", "self", ".", "__checkpoint_files", ".", "append", "(", "filename", ")" ]
Add filename as a checkpoint file for this DAG job.
[ "Add", "filename", "as", "a", "checkpoint", "file", "for", "this", "DAG", "job", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L519-L524
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorJob.add_file_arg
def add_file_arg(self, filename): """ Add a file argument to the executable. Arguments are appended after any options and their order is guaranteed. Also adds the file name to the list of required input data for this job. @param filename: file to add as argument. """ self.__arguments.append(filename) if filename not in self.__input_files: self.__input_files.append(filename)
python
def add_file_arg(self, filename): """ Add a file argument to the executable. Arguments are appended after any options and their order is guaranteed. Also adds the file name to the list of required input data for this job. @param filename: file to add as argument. """ self.__arguments.append(filename) if filename not in self.__input_files: self.__input_files.append(filename)
[ "def", "add_file_arg", "(", "self", ",", "filename", ")", ":", "self", ".", "__arguments", ".", "append", "(", "filename", ")", "if", "filename", "not", "in", "self", ".", "__input_files", ":", "self", ".", "__input_files", ".", "append", "(", "filename", ...
Add a file argument to the executable. Arguments are appended after any options and their order is guaranteed. Also adds the file name to the list of required input data for this job. @param filename: file to add as argument.
[ "Add", "a", "file", "argument", "to", "the", "executable", ".", "Arguments", "are", "appended", "after", "any", "options", "and", "their", "order", "is", "guaranteed", ".", "Also", "adds", "the", "file", "name", "to", "the", "list", "of", "required", "inpu...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L552-L561
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorJob.get_opt
def get_opt( self, opt): """ Returns the value associated with the given command line option. Returns None if the option does not exist in the options list. @param opt: command line option """ if self.__options.has_key(opt): return self.__options[opt] return None
python
def get_opt( self, opt): """ Returns the value associated with the given command line option. Returns None if the option does not exist in the options list. @param opt: command line option """ if self.__options.has_key(opt): return self.__options[opt] return None
[ "def", "get_opt", "(", "self", ",", "opt", ")", ":", "if", "self", ".", "__options", ".", "has_key", "(", "opt", ")", ":", "return", "self", ".", "__options", "[", "opt", "]", "return", "None" ]
Returns the value associated with the given command line option. Returns None if the option does not exist in the options list. @param opt: command line option
[ "Returns", "the", "value", "associated", "with", "the", "given", "command", "line", "option", ".", "Returns", "None", "if", "the", "option", "does", "not", "exist", "in", "the", "options", "list", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L581-L589
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorJob.add_file_opt
def add_file_opt(self, opt, filename): """ Add a command line option to the executable. The order that the arguments will be appended to the command line is not guaranteed, but they will always be added before any command line arguments. The name of the option is prefixed with double hyphen and the program is expected to parse it with getopt_long(). @param opt: command line option to add. @param value: value to pass to the option (None for no argument). """ self.__options[opt] = filename if filename not in self.__input_files: self.__input_files.append(filename)
python
def add_file_opt(self, opt, filename): """ Add a command line option to the executable. The order that the arguments will be appended to the command line is not guaranteed, but they will always be added before any command line arguments. The name of the option is prefixed with double hyphen and the program is expected to parse it with getopt_long(). @param opt: command line option to add. @param value: value to pass to the option (None for no argument). """ self.__options[opt] = filename if filename not in self.__input_files: self.__input_files.append(filename)
[ "def", "add_file_opt", "(", "self", ",", "opt", ",", "filename", ")", ":", "self", ".", "__options", "[", "opt", "]", "=", "filename", "if", "filename", "not", "in", "self", ".", "__input_files", ":", "self", ".", "__input_files", ".", "append", "(", "...
Add a command line option to the executable. The order that the arguments will be appended to the command line is not guaranteed, but they will always be added before any command line arguments. The name of the option is prefixed with double hyphen and the program is expected to parse it with getopt_long(). @param opt: command line option to add. @param value: value to pass to the option (None for no argument).
[ "Add", "a", "command", "line", "option", "to", "the", "executable", ".", "The", "order", "that", "the", "arguments", "will", "be", "appended", "to", "the", "command", "line", "is", "not", "guaranteed", "but", "they", "will", "always", "be", "added", "befor...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L591-L603
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorJob.add_ini_opts
def add_ini_opts(self, cp, section): """ Parse command line options from a given section in an ini file and pass to the executable. @param cp: ConfigParser object pointing to the ini file. @param section: section of the ini file to add to the options. """ for opt in cp.options(section): arg = string.strip(cp.get(section,opt)) self.__options[opt] = arg
python
def add_ini_opts(self, cp, section): """ Parse command line options from a given section in an ini file and pass to the executable. @param cp: ConfigParser object pointing to the ini file. @param section: section of the ini file to add to the options. """ for opt in cp.options(section): arg = string.strip(cp.get(section,opt)) self.__options[opt] = arg
[ "def", "add_ini_opts", "(", "self", ",", "cp", ",", "section", ")", ":", "for", "opt", "in", "cp", ".", "options", "(", "section", ")", ":", "arg", "=", "string", ".", "strip", "(", "cp", ".", "get", "(", "section", ",", "opt", ")", ")", "self", ...
Parse command line options from a given section in an ini file and pass to the executable. @param cp: ConfigParser object pointing to the ini file. @param section: section of the ini file to add to the options.
[ "Parse", "command", "line", "options", "from", "a", "given", "section", "in", "an", "ini", "file", "and", "pass", "to", "the", "executable", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L631-L640
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorJob.write_sub_file
def write_sub_file(self): """ Write a submit file for this Condor job. """ if not self.__log_file: raise CondorSubmitError, "Log file not specified." if not self.__err_file: raise CondorSubmitError, "Error file not specified." if not self.__out_file: raise CondorSubmitError, "Output file not specified." if not self.__sub_file_path: raise CondorSubmitError, 'No path for submit file.' try: subfile = open(self.__sub_file_path, 'w') except: raise CondorSubmitError, "Cannot open file " + self.__sub_file_path if self.__universe == 'grid': if self.__grid_type == None: raise CondorSubmitError, 'No grid type specified.' elif self.__grid_type == 'gt2': if self.__grid_server == None: raise CondorSubmitError, 'No server specified for grid resource.' elif self.__grid_type == 'gt4': if self.__grid_server == None: raise CondorSubmitError, 'No server specified for grid resource.' if self.__grid_scheduler == None: raise CondorSubmitError, 'No scheduler specified for grid resource.' else: raise CondorSubmitError, 'Unsupported grid resource.' subfile.write( 'universe = ' + self.__universe + '\n' ) subfile.write( 'executable = ' + self.__executable + '\n' ) if self.__universe == 'grid': if self.__grid_type == 'gt2': subfile.write('grid_resource = %s %s\n' % (self.__grid_type, self.__grid_server)) if self.__grid_type == 'gt4': subfile.write('grid_resource = %s %s %s\n' % (self.__grid_type, self.__grid_server, self.__grid_scheduler)) if self.__universe == 'grid': subfile.write('when_to_transfer_output = ON_EXIT\n') subfile.write('transfer_output_files = $(macrooutput)\n') subfile.write('transfer_input_files = $(macroinput)\n') if self.__options.keys() or self.__short_options.keys() or self.__arguments: subfile.write( 'arguments = "' ) for c in self.__options.keys(): if self.__options[c]: subfile.write( ' --' + c + ' ' + self.__options[c] ) else: subfile.write( ' --' + c ) for c in self.__short_options.keys(): if self.__short_options[c]: subfile.write( ' -' + c + ' ' + self.__short_options[c] ) else: subfile.write( ' -' + c ) for c in self.__arguments: subfile.write( ' ' + c ) subfile.write( ' "\n' ) for cmd in self.__condor_cmds.keys(): subfile.write( str(cmd) + " = " + str(self.__condor_cmds[cmd]) + '\n' ) subfile.write( 'log = ' + self.__log_file + '\n' ) if self.__in_file is not None: subfile.write( 'input = ' + self.__in_file + '\n' ) subfile.write( 'error = ' + self.__err_file + '\n' ) subfile.write( 'output = ' + self.__out_file + '\n' ) if self.__notification: subfile.write( 'notification = ' + self.__notification + '\n' ) subfile.write( 'queue ' + str(self.__queue) + '\n' ) subfile.close()
python
def write_sub_file(self): """ Write a submit file for this Condor job. """ if not self.__log_file: raise CondorSubmitError, "Log file not specified." if not self.__err_file: raise CondorSubmitError, "Error file not specified." if not self.__out_file: raise CondorSubmitError, "Output file not specified." if not self.__sub_file_path: raise CondorSubmitError, 'No path for submit file.' try: subfile = open(self.__sub_file_path, 'w') except: raise CondorSubmitError, "Cannot open file " + self.__sub_file_path if self.__universe == 'grid': if self.__grid_type == None: raise CondorSubmitError, 'No grid type specified.' elif self.__grid_type == 'gt2': if self.__grid_server == None: raise CondorSubmitError, 'No server specified for grid resource.' elif self.__grid_type == 'gt4': if self.__grid_server == None: raise CondorSubmitError, 'No server specified for grid resource.' if self.__grid_scheduler == None: raise CondorSubmitError, 'No scheduler specified for grid resource.' else: raise CondorSubmitError, 'Unsupported grid resource.' subfile.write( 'universe = ' + self.__universe + '\n' ) subfile.write( 'executable = ' + self.__executable + '\n' ) if self.__universe == 'grid': if self.__grid_type == 'gt2': subfile.write('grid_resource = %s %s\n' % (self.__grid_type, self.__grid_server)) if self.__grid_type == 'gt4': subfile.write('grid_resource = %s %s %s\n' % (self.__grid_type, self.__grid_server, self.__grid_scheduler)) if self.__universe == 'grid': subfile.write('when_to_transfer_output = ON_EXIT\n') subfile.write('transfer_output_files = $(macrooutput)\n') subfile.write('transfer_input_files = $(macroinput)\n') if self.__options.keys() or self.__short_options.keys() or self.__arguments: subfile.write( 'arguments = "' ) for c in self.__options.keys(): if self.__options[c]: subfile.write( ' --' + c + ' ' + self.__options[c] ) else: subfile.write( ' --' + c ) for c in self.__short_options.keys(): if self.__short_options[c]: subfile.write( ' -' + c + ' ' + self.__short_options[c] ) else: subfile.write( ' -' + c ) for c in self.__arguments: subfile.write( ' ' + c ) subfile.write( ' "\n' ) for cmd in self.__condor_cmds.keys(): subfile.write( str(cmd) + " = " + str(self.__condor_cmds[cmd]) + '\n' ) subfile.write( 'log = ' + self.__log_file + '\n' ) if self.__in_file is not None: subfile.write( 'input = ' + self.__in_file + '\n' ) subfile.write( 'error = ' + self.__err_file + '\n' ) subfile.write( 'output = ' + self.__out_file + '\n' ) if self.__notification: subfile.write( 'notification = ' + self.__notification + '\n' ) subfile.write( 'queue ' + str(self.__queue) + '\n' ) subfile.close()
[ "def", "write_sub_file", "(", "self", ")", ":", "if", "not", "self", ".", "__log_file", ":", "raise", "CondorSubmitError", ",", "\"Log file not specified.\"", "if", "not", "self", ".", "__err_file", ":", "raise", "CondorSubmitError", ",", "\"Error file not specified...
Write a submit file for this Condor job.
[ "Write", "a", "submit", "file", "for", "this", "Condor", "job", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L710-L786
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGJob.set_grid_site
def set_grid_site(self,site): """ Set the grid site to run on. If not specified, will not give hint to Pegasus """ self.__grid_site=str(site) if site != 'local': self.set_executable_installed(False)
python
def set_grid_site(self,site): """ Set the grid site to run on. If not specified, will not give hint to Pegasus """ self.__grid_site=str(site) if site != 'local': self.set_executable_installed(False)
[ "def", "set_grid_site", "(", "self", ",", "site", ")", ":", "self", ".", "__grid_site", "=", "str", "(", "site", ")", "if", "site", "!=", "'local'", ":", "self", ".", "set_executable_installed", "(", "False", ")" ]
Set the grid site to run on. If not specified, will not give hint to Pegasus
[ "Set", "the", "grid", "site", "to", "run", "on", ".", "If", "not", "specified", "will", "not", "give", "hint", "to", "Pegasus" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L821-L828
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGJob.add_var_opt
def add_var_opt(self, opt, short=False): """ Add a variable (or macro) option to the condor job. The option is added to the submit file and a different argument to the option can be set for each node in the DAG. @param opt: name of option to add. """ if opt not in self.__var_opts: self.__var_opts.append(opt) macro = self.__bad_macro_chars.sub( r'', opt ) if short: self.add_short_opt(opt,'$(macro' + macro + ')') else: self.add_opt(opt,'$(macro' + macro + ')')
python
def add_var_opt(self, opt, short=False): """ Add a variable (or macro) option to the condor job. The option is added to the submit file and a different argument to the option can be set for each node in the DAG. @param opt: name of option to add. """ if opt not in self.__var_opts: self.__var_opts.append(opt) macro = self.__bad_macro_chars.sub( r'', opt ) if short: self.add_short_opt(opt,'$(macro' + macro + ')') else: self.add_opt(opt,'$(macro' + macro + ')')
[ "def", "add_var_opt", "(", "self", ",", "opt", ",", "short", "=", "False", ")", ":", "if", "opt", "not", "in", "self", ".", "__var_opts", ":", "self", ".", "__var_opts", ".", "append", "(", "opt", ")", "macro", "=", "self", ".", "__bad_macro_chars", ...
Add a variable (or macro) option to the condor job. The option is added to the submit file and a different argument to the option can be set for each node in the DAG. @param opt: name of option to add.
[ "Add", "a", "variable", "(", "or", "macro", ")", "option", "to", "the", "condor", "job", ".", "The", "option", "is", "added", "to", "the", "submit", "file", "and", "a", "different", "argument", "to", "the", "option", "can", "be", "set", "for", "each", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L848-L861
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGJob.add_var_condor_cmd
def add_var_condor_cmd(self, command): """ Add a condor command to the submit file that allows variable (macro) arguments to be passes to the executable. """ if command not in self.__var_cmds: self.__var_cmds.append(command) macro = self.__bad_macro_chars.sub( r'', command ) self.add_condor_cmd(command, '$(macro' + macro + ')')
python
def add_var_condor_cmd(self, command): """ Add a condor command to the submit file that allows variable (macro) arguments to be passes to the executable. """ if command not in self.__var_cmds: self.__var_cmds.append(command) macro = self.__bad_macro_chars.sub( r'', command ) self.add_condor_cmd(command, '$(macro' + macro + ')')
[ "def", "add_var_condor_cmd", "(", "self", ",", "command", ")", ":", "if", "command", "not", "in", "self", ".", "__var_cmds", ":", "self", ".", "__var_cmds", ".", "append", "(", "command", ")", "macro", "=", "self", ".", "__bad_macro_chars", ".", "sub", "...
Add a condor command to the submit file that allows variable (macro) arguments to be passes to the executable.
[ "Add", "a", "condor", "command", "to", "the", "submit", "file", "that", "allows", "variable", "(", "macro", ")", "arguments", "to", "be", "passes", "to", "the", "executable", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L863-L871
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGJob.add_var_arg
def add_var_arg(self,arg_index): """ Add a command to the submit file to allow variable (macro) arguments to be passed to the executable. """ try: self.__var_args[arg_index] except IndexError: if arg_index != self.__arg_index: raise CondorDAGJobError, "mismatch between job and node var_arg index" self.__var_args.append('$(macroargument%s)' % str(arg_index)) self.add_arg(self.__var_args[self.__arg_index]) self.__arg_index += 1
python
def add_var_arg(self,arg_index): """ Add a command to the submit file to allow variable (macro) arguments to be passed to the executable. """ try: self.__var_args[arg_index] except IndexError: if arg_index != self.__arg_index: raise CondorDAGJobError, "mismatch between job and node var_arg index" self.__var_args.append('$(macroargument%s)' % str(arg_index)) self.add_arg(self.__var_args[self.__arg_index]) self.__arg_index += 1
[ "def", "add_var_arg", "(", "self", ",", "arg_index", ")", ":", "try", ":", "self", ".", "__var_args", "[", "arg_index", "]", "except", "IndexError", ":", "if", "arg_index", "!=", "self", ".", "__arg_index", ":", "raise", "CondorDAGJobError", ",", "\"mismatch...
Add a command to the submit file to allow variable (macro) arguments to be passed to the executable.
[ "Add", "a", "command", "to", "the", "submit", "file", "to", "allow", "variable", "(", "macro", ")", "arguments", "to", "be", "passed", "to", "the", "executable", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L873-L885
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_pegasus_profile
def add_pegasus_profile(self, namespace, key, value): """ Add a Pegasus profile to this job which will be written to the dax as <profile namespace="NAMESPACE" key="KEY">VALUE</profile> This can be used to add classads to particular jobs in the DAX @param namespace: A valid Pegasus namespace, e.g. condor. @param key: The name of the attribute. @param value: The value of the attribute. """ self.__pegasus_profile.append((str(namespace),str(key),str(value)))
python
def add_pegasus_profile(self, namespace, key, value): """ Add a Pegasus profile to this job which will be written to the dax as <profile namespace="NAMESPACE" key="KEY">VALUE</profile> This can be used to add classads to particular jobs in the DAX @param namespace: A valid Pegasus namespace, e.g. condor. @param key: The name of the attribute. @param value: The value of the attribute. """ self.__pegasus_profile.append((str(namespace),str(key),str(value)))
[ "def", "add_pegasus_profile", "(", "self", ",", "namespace", ",", "key", ",", "value", ")", ":", "self", ".", "__pegasus_profile", ".", "append", "(", "(", "str", "(", "namespace", ")", ",", "str", "(", "key", ")", ",", "str", "(", "value", ")", ")",...
Add a Pegasus profile to this job which will be written to the dax as <profile namespace="NAMESPACE" key="KEY">VALUE</profile> This can be used to add classads to particular jobs in the DAX @param namespace: A valid Pegasus namespace, e.g. condor. @param key: The name of the attribute. @param value: The value of the attribute.
[ "Add", "a", "Pegasus", "profile", "to", "this", "job", "which", "will", "be", "written", "to", "the", "dax", "as", "<profile", "namespace", "=", "NAMESPACE", "key", "=", "KEY", ">", "VALUE<", "/", "profile", ">", "This", "can", "be", "used", "to", "add...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1043-L1052
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_input_file
def add_input_file(self, filename): """ Add filename as a necessary input file for this DAG node. @param filename: input filename to add """ if filename not in self.__input_files: self.__input_files.append(filename) if not isinstance(self.job(), CondorDAGManJob): if self.job().get_universe() == 'grid': self.add_input_macro(filename)
python
def add_input_file(self, filename): """ Add filename as a necessary input file for this DAG node. @param filename: input filename to add """ if filename not in self.__input_files: self.__input_files.append(filename) if not isinstance(self.job(), CondorDAGManJob): if self.job().get_universe() == 'grid': self.add_input_macro(filename)
[ "def", "add_input_file", "(", "self", ",", "filename", ")", ":", "if", "filename", "not", "in", "self", ".", "__input_files", ":", "self", ".", "__input_files", ".", "append", "(", "filename", ")", "if", "not", "isinstance", "(", "self", ".", "job", "(",...
Add filename as a necessary input file for this DAG node. @param filename: input filename to add
[ "Add", "filename", "as", "a", "necessary", "input", "file", "for", "this", "DAG", "node", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1155-L1165
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_output_file
def add_output_file(self, filename): """ Add filename as a output file for this DAG node. @param filename: output filename to add """ if filename not in self.__output_files: self.__output_files.append(filename) if not isinstance(self.job(), CondorDAGManJob): if self.job().get_universe() == 'grid': self.add_output_macro(filename)
python
def add_output_file(self, filename): """ Add filename as a output file for this DAG node. @param filename: output filename to add """ if filename not in self.__output_files: self.__output_files.append(filename) if not isinstance(self.job(), CondorDAGManJob): if self.job().get_universe() == 'grid': self.add_output_macro(filename)
[ "def", "add_output_file", "(", "self", ",", "filename", ")", ":", "if", "filename", "not", "in", "self", ".", "__output_files", ":", "self", ".", "__output_files", ".", "append", "(", "filename", ")", "if", "not", "isinstance", "(", "self", ".", "job", "...
Add filename as a output file for this DAG node. @param filename: output filename to add
[ "Add", "filename", "as", "a", "output", "file", "for", "this", "DAG", "node", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1167-L1177
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_checkpoint_file
def add_checkpoint_file(self,filename): """ Add filename as a checkpoint file for this DAG node @param filename: checkpoint filename to add """ if filename not in self.__checkpoint_files: self.__checkpoint_files.append(filename) if not isinstance(self.job(), CondorDAGManJob): if self.job().get_universe() == 'grid': self.add_checkpoint_macro(filename)
python
def add_checkpoint_file(self,filename): """ Add filename as a checkpoint file for this DAG node @param filename: checkpoint filename to add """ if filename not in self.__checkpoint_files: self.__checkpoint_files.append(filename) if not isinstance(self.job(), CondorDAGManJob): if self.job().get_universe() == 'grid': self.add_checkpoint_macro(filename)
[ "def", "add_checkpoint_file", "(", "self", ",", "filename", ")", ":", "if", "filename", "not", "in", "self", ".", "__checkpoint_files", ":", "self", ".", "__checkpoint_files", ".", "append", "(", "filename", ")", "if", "not", "isinstance", "(", "self", ".", ...
Add filename as a checkpoint file for this DAG node @param filename: checkpoint filename to add
[ "Add", "filename", "as", "a", "checkpoint", "file", "for", "this", "DAG", "node" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1179-L1188
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.get_input_files
def get_input_files(self): """ Return list of input files for this DAG node and its job. """ input_files = list(self.__input_files) if isinstance(self.job(), CondorDAGJob): input_files = input_files + self.job().get_input_files() return input_files
python
def get_input_files(self): """ Return list of input files for this DAG node and its job. """ input_files = list(self.__input_files) if isinstance(self.job(), CondorDAGJob): input_files = input_files + self.job().get_input_files() return input_files
[ "def", "get_input_files", "(", "self", ")", ":", "input_files", "=", "list", "(", "self", ".", "__input_files", ")", "if", "isinstance", "(", "self", ".", "job", "(", ")", ",", "CondorDAGJob", ")", ":", "input_files", "=", "input_files", "+", "self", "."...
Return list of input files for this DAG node and its job.
[ "Return", "list", "of", "input", "files", "for", "this", "DAG", "node", "and", "its", "job", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1190-L1197
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.get_output_files
def get_output_files(self): """ Return list of output files for this DAG node and its job. """ output_files = list(self.__output_files) if isinstance(self.job(), CondorDAGJob): output_files = output_files + self.job().get_output_files() return output_files
python
def get_output_files(self): """ Return list of output files for this DAG node and its job. """ output_files = list(self.__output_files) if isinstance(self.job(), CondorDAGJob): output_files = output_files + self.job().get_output_files() return output_files
[ "def", "get_output_files", "(", "self", ")", ":", "output_files", "=", "list", "(", "self", ".", "__output_files", ")", "if", "isinstance", "(", "self", ".", "job", "(", ")", ",", "CondorDAGJob", ")", ":", "output_files", "=", "output_files", "+", "self", ...
Return list of output files for this DAG node and its job.
[ "Return", "list", "of", "output", "files", "for", "this", "DAG", "node", "and", "its", "job", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1199-L1206
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.get_checkpoint_files
def get_checkpoint_files(self): """ Return a list of checkpoint files for this DAG node and its job. """ checkpoint_files = list(self.__checkpoint_files) if isinstance(self.job(), CondorDAGJob): checkpoint_files = checkpoint_files + self.job().get_checkpoint_files() return checkpoint_files
python
def get_checkpoint_files(self): """ Return a list of checkpoint files for this DAG node and its job. """ checkpoint_files = list(self.__checkpoint_files) if isinstance(self.job(), CondorDAGJob): checkpoint_files = checkpoint_files + self.job().get_checkpoint_files() return checkpoint_files
[ "def", "get_checkpoint_files", "(", "self", ")", ":", "checkpoint_files", "=", "list", "(", "self", ".", "__checkpoint_files", ")", "if", "isinstance", "(", "self", ".", "job", "(", ")", ",", "CondorDAGJob", ")", ":", "checkpoint_files", "=", "checkpoint_files...
Return a list of checkpoint files for this DAG node and its job.
[ "Return", "a", "list", "of", "checkpoint", "files", "for", "this", "DAG", "node", "and", "its", "job", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1208-L1215
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_macro
def add_macro(self,name,value): """ Add a variable (macro) for this node. This can be different for each node in the DAG, even if they use the same CondorJob. Within the CondorJob, the value of the macro can be referenced as '$(name)' -- for instance, to define a unique output or error file for each node. @param name: macro name. @param value: value of the macro for this node in the DAG """ macro = self.__bad_macro_chars.sub( r'', name ) self.__opts[macro] = value
python
def add_macro(self,name,value): """ Add a variable (macro) for this node. This can be different for each node in the DAG, even if they use the same CondorJob. Within the CondorJob, the value of the macro can be referenced as '$(name)' -- for instance, to define a unique output or error file for each node. @param name: macro name. @param value: value of the macro for this node in the DAG """ macro = self.__bad_macro_chars.sub( r'', name ) self.__opts[macro] = value
[ "def", "add_macro", "(", "self", ",", "name", ",", "value", ")", ":", "macro", "=", "self", ".", "__bad_macro_chars", ".", "sub", "(", "r''", ",", "name", ")", "self", ".", "__opts", "[", "macro", "]", "=", "value" ]
Add a variable (macro) for this node. This can be different for each node in the DAG, even if they use the same CondorJob. Within the CondorJob, the value of the macro can be referenced as '$(name)' -- for instance, to define a unique output or error file for each node. @param name: macro name. @param value: value of the macro for this node in the DAG
[ "Add", "a", "variable", "(", "macro", ")", "for", "this", "node", ".", "This", "can", "be", "different", "for", "each", "node", "in", "the", "DAG", "even", "if", "they", "use", "the", "same", "CondorJob", ".", "Within", "the", "CondorJob", "the", "valu...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1242-L1253
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_io_macro
def add_io_macro(self,io,filename): """ Add a variable (macro) for storing the input/output files associated with this node. @param io: macroinput or macrooutput @param filename: filename of input/output file """ io = self.__bad_macro_chars.sub( r'', io ) if io not in self.__opts: self.__opts[io] = filename else: if filename not in self.__opts[io]: self.__opts[io] += ',%s' % filename
python
def add_io_macro(self,io,filename): """ Add a variable (macro) for storing the input/output files associated with this node. @param io: macroinput or macrooutput @param filename: filename of input/output file """ io = self.__bad_macro_chars.sub( r'', io ) if io not in self.__opts: self.__opts[io] = filename else: if filename not in self.__opts[io]: self.__opts[io] += ',%s' % filename
[ "def", "add_io_macro", "(", "self", ",", "io", ",", "filename", ")", ":", "io", "=", "self", ".", "__bad_macro_chars", ".", "sub", "(", "r''", ",", "io", ")", "if", "io", "not", "in", "self", ".", "__opts", ":", "self", ".", "__opts", "[", "io", ...
Add a variable (macro) for storing the input/output files associated with this node. @param io: macroinput or macrooutput @param filename: filename of input/output file
[ "Add", "a", "variable", "(", "macro", ")", "for", "storing", "the", "input", "/", "output", "files", "associated", "with", "this", "node", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1255-L1267
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_var_condor_cmd
def add_var_condor_cmd(self, command, value): """ Add a variable (macro) condor command for this node. If the command specified does not exist in the CondorJob, it is added so the submit file will be correct. PLEASE NOTE: AS with other add_var commands, the variable must be set for all nodes that use the CondorJob instance. @param command: command name @param value: Value of the command for this node in the DAG/DAX. """ macro = self.__bad_macro_chars.sub( r'', command ) self.__macros['macro' + macro] = value self.__job.add_var_condor_cmd(command)
python
def add_var_condor_cmd(self, command, value): """ Add a variable (macro) condor command for this node. If the command specified does not exist in the CondorJob, it is added so the submit file will be correct. PLEASE NOTE: AS with other add_var commands, the variable must be set for all nodes that use the CondorJob instance. @param command: command name @param value: Value of the command for this node in the DAG/DAX. """ macro = self.__bad_macro_chars.sub( r'', command ) self.__macros['macro' + macro] = value self.__job.add_var_condor_cmd(command)
[ "def", "add_var_condor_cmd", "(", "self", ",", "command", ",", "value", ")", ":", "macro", "=", "self", ".", "__bad_macro_chars", ".", "sub", "(", "r''", ",", "command", ")", "self", ".", "__macros", "[", "'macro'", "+", "macro", "]", "=", "value", "se...
Add a variable (macro) condor command for this node. If the command specified does not exist in the CondorJob, it is added so the submit file will be correct. PLEASE NOTE: AS with other add_var commands, the variable must be set for all nodes that use the CondorJob instance. @param command: command name @param value: Value of the command for this node in the DAG/DAX.
[ "Add", "a", "variable", "(", "macro", ")", "condor", "command", "for", "this", "node", ".", "If", "the", "command", "specified", "does", "not", "exist", "in", "the", "CondorJob", "it", "is", "added", "so", "the", "submit", "file", "will", "be", "correct"...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1296-L1308
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_var_opt
def add_var_opt(self,opt,value,short=False): """ Add a variable (macro) option for this node. If the option specified does not exist in the CondorJob, it is added so the submit file will be correct when written. @param opt: option name. @param value: value of the option for this node in the DAG. """ macro = self.__bad_macro_chars.sub( r'', opt ) self.__opts['macro' + macro] = value self.__job.add_var_opt(opt,short)
python
def add_var_opt(self,opt,value,short=False): """ Add a variable (macro) option for this node. If the option specified does not exist in the CondorJob, it is added so the submit file will be correct when written. @param opt: option name. @param value: value of the option for this node in the DAG. """ macro = self.__bad_macro_chars.sub( r'', opt ) self.__opts['macro' + macro] = value self.__job.add_var_opt(opt,short)
[ "def", "add_var_opt", "(", "self", ",", "opt", ",", "value", ",", "short", "=", "False", ")", ":", "macro", "=", "self", ".", "__bad_macro_chars", ".", "sub", "(", "r''", ",", "opt", ")", "self", ".", "__opts", "[", "'macro'", "+", "macro", "]", "=...
Add a variable (macro) option for this node. If the option specified does not exist in the CondorJob, it is added so the submit file will be correct when written. @param opt: option name. @param value: value of the option for this node in the DAG.
[ "Add", "a", "variable", "(", "macro", ")", "option", "for", "this", "node", ".", "If", "the", "option", "specified", "does", "not", "exist", "in", "the", "CondorJob", "it", "is", "added", "so", "the", "submit", "file", "will", "be", "correct", "when", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1310-L1320
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_file_opt
def add_file_opt(self,opt,filename,file_is_output_file=False): """ Add a variable (macro) option for this node. If the option specified does not exist in the CondorJob, it is added so the submit file will be correct when written. The value of the option is also added to the list of input files for the DAX. @param opt: option name. @param value: value of the option for this node in the DAG. @param file_is_output_file: A boolean if the file will be an output file instead of an input file. The default is to have it be an input. """ self.add_var_opt(opt,filename) if file_is_output_file: self.add_output_file(filename) else: self.add_input_file(filename)
python
def add_file_opt(self,opt,filename,file_is_output_file=False): """ Add a variable (macro) option for this node. If the option specified does not exist in the CondorJob, it is added so the submit file will be correct when written. The value of the option is also added to the list of input files for the DAX. @param opt: option name. @param value: value of the option for this node in the DAG. @param file_is_output_file: A boolean if the file will be an output file instead of an input file. The default is to have it be an input. """ self.add_var_opt(opt,filename) if file_is_output_file: self.add_output_file(filename) else: self.add_input_file(filename)
[ "def", "add_file_opt", "(", "self", ",", "opt", ",", "filename", ",", "file_is_output_file", "=", "False", ")", ":", "self", ".", "add_var_opt", "(", "opt", ",", "filename", ")", "if", "file_is_output_file", ":", "self", ".", "add_output_file", "(", "filenam...
Add a variable (macro) option for this node. If the option specified does not exist in the CondorJob, it is added so the submit file will be correct when written. The value of the option is also added to the list of input files for the DAX. @param opt: option name. @param value: value of the option for this node in the DAG. @param file_is_output_file: A boolean if the file will be an output file instead of an input file. The default is to have it be an input.
[ "Add", "a", "variable", "(", "macro", ")", "option", "for", "this", "node", ".", "If", "the", "option", "specified", "does", "not", "exist", "in", "the", "CondorJob", "it", "is", "added", "so", "the", "submit", "file", "will", "be", "correct", "when", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1322-L1335
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_var_arg
def add_var_arg(self, arg): """ Add a variable (or macro) argument to the condor job. The argument is added to the submit file and a different value of the argument can be set for each node in the DAG. @param arg: name of option to add. """ self.__args.append(arg) self.__job.add_var_arg(self.__arg_index) self.__arg_index += 1
python
def add_var_arg(self, arg): """ Add a variable (or macro) argument to the condor job. The argument is added to the submit file and a different value of the argument can be set for each node in the DAG. @param arg: name of option to add. """ self.__args.append(arg) self.__job.add_var_arg(self.__arg_index) self.__arg_index += 1
[ "def", "add_var_arg", "(", "self", ",", "arg", ")", ":", "self", ".", "__args", ".", "append", "(", "arg", ")", "self", ".", "__job", ".", "add_var_arg", "(", "self", ".", "__arg_index", ")", "self", ".", "__arg_index", "+=", "1" ]
Add a variable (or macro) argument to the condor job. The argument is added to the submit file and a different value of the argument can be set for each node in the DAG. @param arg: name of option to add.
[ "Add", "a", "variable", "(", "or", "macro", ")", "argument", "to", "the", "condor", "job", ".", "The", "argument", "is", "added", "to", "the", "submit", "file", "and", "a", "different", "value", "of", "the", "argument", "can", "be", "set", "for", "each...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1337-L1346
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.write_job
def write_job(self,fh): """ Write the DAG entry for this node's job to the DAG file descriptor. @param fh: descriptor of open DAG file. """ if isinstance(self.job(),CondorDAGManJob): # create an external subdag from this dag fh.write( ' '.join( ['SUBDAG EXTERNAL', self.__name, self.__job.get_sub_file()]) ) if self.job().get_dag_directory(): fh.write( ' DIR ' + self.job().get_dag_directory() ) else: # write a regular condor job fh.write( 'JOB ' + self.__name + ' ' + self.__job.get_sub_file() ) fh.write( '\n') fh.write( 'RETRY ' + self.__name + ' ' + str(self.__retry) + '\n' )
python
def write_job(self,fh): """ Write the DAG entry for this node's job to the DAG file descriptor. @param fh: descriptor of open DAG file. """ if isinstance(self.job(),CondorDAGManJob): # create an external subdag from this dag fh.write( ' '.join( ['SUBDAG EXTERNAL', self.__name, self.__job.get_sub_file()]) ) if self.job().get_dag_directory(): fh.write( ' DIR ' + self.job().get_dag_directory() ) else: # write a regular condor job fh.write( 'JOB ' + self.__name + ' ' + self.__job.get_sub_file() ) fh.write( '\n') fh.write( 'RETRY ' + self.__name + ' ' + str(self.__retry) + '\n' )
[ "def", "write_job", "(", "self", ",", "fh", ")", ":", "if", "isinstance", "(", "self", ".", "job", "(", ")", ",", "CondorDAGManJob", ")", ":", "# create an external subdag from this dag", "fh", ".", "write", "(", "' '", ".", "join", "(", "[", "'SUBDAG EXTE...
Write the DAG entry for this node's job to the DAG file descriptor. @param fh: descriptor of open DAG file.
[ "Write", "the", "DAG", "entry", "for", "this", "node", "s", "job", "to", "the", "DAG", "file", "descriptor", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1381-L1397
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.write_vars
def write_vars(self,fh): """ Write the variable (macro) options and arguments to the DAG file descriptor. @param fh: descriptor of open DAG file. """ if self.__macros.keys() or self.__opts.keys() or self.__args: fh.write( 'VARS ' + self.__name ) for k in self.__macros.keys(): fh.write( ' ' + str(k) + '="' + str(self.__macros[k]) + '"' ) for k in self.__opts.keys(): fh.write( ' ' + str(k) + '="' + str(self.__opts[k]) + '"' ) if self.__args: for i in range(self.__arg_index): fh.write( ' macroargument' + str(i) + '="' + self.__args[i] + '"' ) fh.write( '\n' )
python
def write_vars(self,fh): """ Write the variable (macro) options and arguments to the DAG file descriptor. @param fh: descriptor of open DAG file. """ if self.__macros.keys() or self.__opts.keys() or self.__args: fh.write( 'VARS ' + self.__name ) for k in self.__macros.keys(): fh.write( ' ' + str(k) + '="' + str(self.__macros[k]) + '"' ) for k in self.__opts.keys(): fh.write( ' ' + str(k) + '="' + str(self.__opts[k]) + '"' ) if self.__args: for i in range(self.__arg_index): fh.write( ' macroargument' + str(i) + '="' + self.__args[i] + '"' ) fh.write( '\n' )
[ "def", "write_vars", "(", "self", ",", "fh", ")", ":", "if", "self", ".", "__macros", ".", "keys", "(", ")", "or", "self", ".", "__opts", ".", "keys", "(", ")", "or", "self", ".", "__args", ":", "fh", ".", "write", "(", "'VARS '", "+", "self", ...
Write the variable (macro) options and arguments to the DAG file descriptor. @param fh: descriptor of open DAG file.
[ "Write", "the", "variable", "(", "macro", ")", "options", "and", "arguments", "to", "the", "DAG", "file", "descriptor", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1413-L1428
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.write_parents
def write_parents(self,fh): """ Write the parent/child relations for this job to the DAG file descriptor. @param fh: descriptor of open DAG file. """ for parent in self.__parents: fh.write( 'PARENT ' + str(parent) + ' CHILD ' + str(self) + '\n' )
python
def write_parents(self,fh): """ Write the parent/child relations for this job to the DAG file descriptor. @param fh: descriptor of open DAG file. """ for parent in self.__parents: fh.write( 'PARENT ' + str(parent) + ' CHILD ' + str(self) + '\n' )
[ "def", "write_parents", "(", "self", ",", "fh", ")", ":", "for", "parent", "in", "self", ".", "__parents", ":", "fh", ".", "write", "(", "'PARENT '", "+", "str", "(", "parent", ")", "+", "' CHILD '", "+", "str", "(", "self", ")", "+", "'\\n'", ")" ...
Write the parent/child relations for this job to the DAG file descriptor. @param fh: descriptor of open DAG file.
[ "Write", "the", "parent", "/", "child", "relations", "for", "this", "job", "to", "the", "DAG", "file", "descriptor", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1430-L1436
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.write_pre_script
def write_pre_script(self,fh): """ Write the pre script for the job, if there is one @param fh: descriptor of open DAG file. """ if self.__pre_script: fh.write( 'SCRIPT PRE ' + str(self) + ' ' + self.__pre_script + ' ' + ' '.join(self.__pre_script_args) + '\n' )
python
def write_pre_script(self,fh): """ Write the pre script for the job, if there is one @param fh: descriptor of open DAG file. """ if self.__pre_script: fh.write( 'SCRIPT PRE ' + str(self) + ' ' + self.__pre_script + ' ' + ' '.join(self.__pre_script_args) + '\n' )
[ "def", "write_pre_script", "(", "self", ",", "fh", ")", ":", "if", "self", ".", "__pre_script", ":", "fh", ".", "write", "(", "'SCRIPT PRE '", "+", "str", "(", "self", ")", "+", "' '", "+", "self", ".", "__pre_script", "+", "' '", "+", "' '", ".", ...
Write the pre script for the job, if there is one @param fh: descriptor of open DAG file.
[ "Write", "the", "pre", "script", "for", "the", "job", "if", "there", "is", "one" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1438-L1445
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.write_post_script
def write_post_script(self,fh): """ Write the post script for the job, if there is one @param fh: descriptor of open DAG file. """ if self.__post_script: fh.write( 'SCRIPT POST ' + str(self) + ' ' + self.__post_script + ' ' + ' '.join(self.__post_script_args) + '\n' )
python
def write_post_script(self,fh): """ Write the post script for the job, if there is one @param fh: descriptor of open DAG file. """ if self.__post_script: fh.write( 'SCRIPT POST ' + str(self) + ' ' + self.__post_script + ' ' + ' '.join(self.__post_script_args) + '\n' )
[ "def", "write_post_script", "(", "self", ",", "fh", ")", ":", "if", "self", ".", "__post_script", ":", "fh", ".", "write", "(", "'SCRIPT POST '", "+", "str", "(", "self", ")", "+", "' '", "+", "self", ".", "__post_script", "+", "' '", "+", "' '", "."...
Write the post script for the job, if there is one @param fh: descriptor of open DAG file.
[ "Write", "the", "post", "script", "for", "the", "job", "if", "there", "is", "one" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1447-L1454
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.write_input_files
def write_input_files(self, fh): """ Write as a comment into the DAG file the list of input files for this DAG node. @param fh: descriptor of open DAG file. """ for f in self.__input_files: print >>fh, "## Job %s requires input file %s" % (self.__name, f)
python
def write_input_files(self, fh): """ Write as a comment into the DAG file the list of input files for this DAG node. @param fh: descriptor of open DAG file. """ for f in self.__input_files: print >>fh, "## Job %s requires input file %s" % (self.__name, f)
[ "def", "write_input_files", "(", "self", ",", "fh", ")", ":", "for", "f", "in", "self", ".", "__input_files", ":", "print", ">>", "fh", ",", "\"## Job %s requires input file %s\"", "%", "(", "self", ".", "__name", ",", "f", ")" ]
Write as a comment into the DAG file the list of input files for this DAG node. @param fh: descriptor of open DAG file.
[ "Write", "as", "a", "comment", "into", "the", "DAG", "file", "the", "list", "of", "input", "files", "for", "this", "DAG", "node", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1456-L1464
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.write_output_files
def write_output_files(self, fh): """ Write as a comment into the DAG file the list of output files for this DAG node. @param fh: descriptor of open DAG file. """ for f in self.__output_files: print >>fh, "## Job %s generates output file %s" % (self.__name, f)
python
def write_output_files(self, fh): """ Write as a comment into the DAG file the list of output files for this DAG node. @param fh: descriptor of open DAG file. """ for f in self.__output_files: print >>fh, "## Job %s generates output file %s" % (self.__name, f)
[ "def", "write_output_files", "(", "self", ",", "fh", ")", ":", "for", "f", "in", "self", ".", "__output_files", ":", "print", ">>", "fh", ",", "\"## Job %s generates output file %s\"", "%", "(", "self", ".", "__name", ",", "f", ")" ]
Write as a comment into the DAG file the list of output files for this DAG node. @param fh: descriptor of open DAG file.
[ "Write", "as", "a", "comment", "into", "the", "DAG", "file", "the", "list", "of", "output", "files", "for", "this", "DAG", "node", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1466-L1474
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.add_parent
def add_parent(self,node): """ Add a parent to this node. This node will not be executed until the parent node has run sucessfully. @param node: CondorDAGNode to add as a parent. """ if not isinstance(node, (CondorDAGNode,CondorDAGManNode) ): raise CondorDAGNodeError, "Parent must be a CondorDAGNode or a CondorDAGManNode" self.__parents.append( node )
python
def add_parent(self,node): """ Add a parent to this node. This node will not be executed until the parent node has run sucessfully. @param node: CondorDAGNode to add as a parent. """ if not isinstance(node, (CondorDAGNode,CondorDAGManNode) ): raise CondorDAGNodeError, "Parent must be a CondorDAGNode or a CondorDAGManNode" self.__parents.append( node )
[ "def", "add_parent", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "(", "CondorDAGNode", ",", "CondorDAGManNode", ")", ")", ":", "raise", "CondorDAGNodeError", ",", "\"Parent must be a CondorDAGNode or a CondorDAGManNode\"", "self"...
Add a parent to this node. This node will not be executed until the parent node has run sucessfully. @param node: CondorDAGNode to add as a parent.
[ "Add", "a", "parent", "to", "this", "node", ".", "This", "node", "will", "not", "be", "executed", "until", "the", "parent", "node", "has", "run", "sucessfully", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1483-L1491
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.get_cmd_tuple_list
def get_cmd_tuple_list(self): """ Return a list of tuples containg the command line arguments """ # pattern to find DAGman macros pat = re.compile(r'\$\((.+)\)') argpat = re.compile(r'\d+') # first parse the options and replace macros with values options = self.job().get_opts() macros = self.get_opts() cmd_list = [] for k in options: val = options[k] m = pat.match(val) if m: key = m.group(1) value = macros[key] cmd_list.append(("--%s" % k, str(value))) else: cmd_list.append(("--%s" % k, str(val))) # second parse the short options and replace macros with values options = self.job().get_short_opts() for k in options: val = options[k] m = pat.match(val) if m: key = m.group(1) value = macros[key] cmd_list.append(("-%s" % k, str(value))) else: cmd_list.append(("-%s" % k, str(val))) # lastly parse the arguments and replace macros with values args = self.job().get_args() macros = self.get_args() for a in args: m = pat.match(a) if m: arg_index = int(argpat.findall(a)[0]) try: cmd_list.append(("%s" % macros[arg_index], "")) except IndexError: cmd_list.append("") else: cmd_list.append(("%s" % a, "")) return cmd_list
python
def get_cmd_tuple_list(self): """ Return a list of tuples containg the command line arguments """ # pattern to find DAGman macros pat = re.compile(r'\$\((.+)\)') argpat = re.compile(r'\d+') # first parse the options and replace macros with values options = self.job().get_opts() macros = self.get_opts() cmd_list = [] for k in options: val = options[k] m = pat.match(val) if m: key = m.group(1) value = macros[key] cmd_list.append(("--%s" % k, str(value))) else: cmd_list.append(("--%s" % k, str(val))) # second parse the short options and replace macros with values options = self.job().get_short_opts() for k in options: val = options[k] m = pat.match(val) if m: key = m.group(1) value = macros[key] cmd_list.append(("-%s" % k, str(value))) else: cmd_list.append(("-%s" % k, str(val))) # lastly parse the arguments and replace macros with values args = self.job().get_args() macros = self.get_args() for a in args: m = pat.match(a) if m: arg_index = int(argpat.findall(a)[0]) try: cmd_list.append(("%s" % macros[arg_index], "")) except IndexError: cmd_list.append("") else: cmd_list.append(("%s" % a, "")) return cmd_list
[ "def", "get_cmd_tuple_list", "(", "self", ")", ":", "# pattern to find DAGman macros", "pat", "=", "re", ".", "compile", "(", "r'\\$\\((.+)\\)'", ")", "argpat", "=", "re", ".", "compile", "(", "r'\\d+'", ")", "# first parse the options and replace macros with values", ...
Return a list of tuples containg the command line arguments
[ "Return", "a", "list", "of", "tuples", "containg", "the", "command", "line", "arguments" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1493-L1548
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGNode.get_cmd_line
def get_cmd_line(self): """ Return the full command line that will be used when this node is run by DAGman. """ cmd = "" cmd_list = self.get_cmd_tuple_list() for argument in cmd_list: cmd += ' '.join(argument) + " " return cmd
python
def get_cmd_line(self): """ Return the full command line that will be used when this node is run by DAGman. """ cmd = "" cmd_list = self.get_cmd_tuple_list() for argument in cmd_list: cmd += ' '.join(argument) + " " return cmd
[ "def", "get_cmd_line", "(", "self", ")", ":", "cmd", "=", "\"\"", "cmd_list", "=", "self", ".", "get_cmd_tuple_list", "(", ")", "for", "argument", "in", "cmd_list", ":", "cmd", "+=", "' '", ".", "join", "(", "argument", ")", "+", "\" \"", "return", "cm...
Return the full command line that will be used when this node is run by DAGman.
[ "Return", "the", "full", "command", "line", "that", "will", "be", "used", "when", "this", "node", "is", "run", "by", "DAGman", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1550-L1561
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAGManNode.add_maxjobs_category
def add_maxjobs_category(self,categoryName,maxJobsNum): """ Add a category to this DAG called categoryName with a maxjobs of maxJobsNum. @param node: Add (categoryName,maxJobsNum) tuple to CondorDAG.__maxjobs_categories. """ self.__maxjobs_categories.append((str(categoryName),str(maxJobsNum)))
python
def add_maxjobs_category(self,categoryName,maxJobsNum): """ Add a category to this DAG called categoryName with a maxjobs of maxJobsNum. @param node: Add (categoryName,maxJobsNum) tuple to CondorDAG.__maxjobs_categories. """ self.__maxjobs_categories.append((str(categoryName),str(maxJobsNum)))
[ "def", "add_maxjobs_category", "(", "self", ",", "categoryName", ",", "maxJobsNum", ")", ":", "self", ".", "__maxjobs_categories", ".", "append", "(", "(", "str", "(", "categoryName", ")", ",", "str", "(", "maxJobsNum", ")", ")", ")" ]
Add a category to this DAG called categoryName with a maxjobs of maxJobsNum. @param node: Add (categoryName,maxJobsNum) tuple to CondorDAG.__maxjobs_categories.
[ "Add", "a", "category", "to", "this", "DAG", "called", "categoryName", "with", "a", "maxjobs", "of", "maxJobsNum", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1602-L1607
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAG.add_node
def add_node(self,node): """ Add a CondorDAGNode to this DAG. The CondorJob that the node uses is also added to the list of Condor jobs in the DAG so that a list of the submit files needed by the DAG can be maintained. Each unique CondorJob will be added once to prevent duplicate submit files being written. @param node: CondorDAGNode to add to the CondorDAG. """ if not isinstance(node, CondorDAGNode): raise CondorDAGError, "Nodes must be class CondorDAGNode or subclass" if not isinstance(node.job(), CondorDAGManJob): node.set_log_file(self.__log_file_path) self.__nodes.append(node) if self.__integer_node_names: node.set_name(str(self.__node_count)) self.__node_count += 1 if node.job() not in self.__jobs: self.__jobs.append(node.job())
python
def add_node(self,node): """ Add a CondorDAGNode to this DAG. The CondorJob that the node uses is also added to the list of Condor jobs in the DAG so that a list of the submit files needed by the DAG can be maintained. Each unique CondorJob will be added once to prevent duplicate submit files being written. @param node: CondorDAGNode to add to the CondorDAG. """ if not isinstance(node, CondorDAGNode): raise CondorDAGError, "Nodes must be class CondorDAGNode or subclass" if not isinstance(node.job(), CondorDAGManJob): node.set_log_file(self.__log_file_path) self.__nodes.append(node) if self.__integer_node_names: node.set_name(str(self.__node_count)) self.__node_count += 1 if node.job() not in self.__jobs: self.__jobs.append(node.job())
[ "def", "add_node", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "CondorDAGNode", ")", ":", "raise", "CondorDAGError", ",", "\"Nodes must be class CondorDAGNode or subclass\"", "if", "not", "isinstance", "(", "node", ".", "job"...
Add a CondorDAGNode to this DAG. The CondorJob that the node uses is also added to the list of Condor jobs in the DAG so that a list of the submit files needed by the DAG can be maintained. Each unique CondorJob will be added once to prevent duplicate submit files being written. @param node: CondorDAGNode to add to the CondorDAG.
[ "Add", "a", "CondorDAGNode", "to", "this", "DAG", ".", "The", "CondorJob", "that", "the", "node", "uses", "is", "also", "added", "to", "the", "list", "of", "Condor", "jobs", "in", "the", "DAG", "so", "that", "a", "list", "of", "the", "submit", "files",...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1737-L1754
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAG.write_maxjobs
def write_maxjobs(self,fh,category): """ Write the DAG entry for this category's maxjobs to the DAG file descriptor. @param fh: descriptor of open DAG file. @param category: tuple containing type of jobs to set a maxjobs limit for and the maximum number of jobs of that type to run at once. """ fh.write( 'MAXJOBS ' + str(category[0]) + ' ' + str(category[1]) + '\n' )
python
def write_maxjobs(self,fh,category): """ Write the DAG entry for this category's maxjobs to the DAG file descriptor. @param fh: descriptor of open DAG file. @param category: tuple containing type of jobs to set a maxjobs limit for and the maximum number of jobs of that type to run at once. """ fh.write( 'MAXJOBS ' + str(category[0]) + ' ' + str(category[1]) + '\n' )
[ "def", "write_maxjobs", "(", "self", ",", "fh", ",", "category", ")", ":", "fh", ".", "write", "(", "'MAXJOBS '", "+", "str", "(", "category", "[", "0", "]", ")", "+", "' '", "+", "str", "(", "category", "[", "1", "]", ")", "+", "'\\n'", ")" ]
Write the DAG entry for this category's maxjobs to the DAG file descriptor. @param fh: descriptor of open DAG file. @param category: tuple containing type of jobs to set a maxjobs limit for and the maximum number of jobs of that type to run at once.
[ "Write", "the", "DAG", "entry", "for", "this", "category", "s", "maxjobs", "to", "the", "DAG", "file", "descriptor", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1782-L1789
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAG.write_sub_files
def write_sub_files(self): """ Write all the submit files used by the dag to disk. Each submit file is written to the file name set in the CondorJob. """ if not self.__nodes_finalized: for node in self.__nodes: node.finalize() if not self.is_dax(): for job in self.__jobs: job.write_sub_file()
python
def write_sub_files(self): """ Write all the submit files used by the dag to disk. Each submit file is written to the file name set in the CondorJob. """ if not self.__nodes_finalized: for node in self.__nodes: node.finalize() if not self.is_dax(): for job in self.__jobs: job.write_sub_file()
[ "def", "write_sub_files", "(", "self", ")", ":", "if", "not", "self", ".", "__nodes_finalized", ":", "for", "node", "in", "self", ".", "__nodes", ":", "node", ".", "finalize", "(", ")", "if", "not", "self", ".", "is_dax", "(", ")", ":", "for", "job",...
Write all the submit files used by the dag to disk. Each submit file is written to the file name set in the CondorJob.
[ "Write", "all", "the", "submit", "files", "used", "by", "the", "dag", "to", "disk", ".", "Each", "submit", "file", "is", "written", "to", "the", "file", "name", "set", "in", "the", "CondorJob", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1791-L1801
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAG.write_concrete_dag
def write_concrete_dag(self): """ Write all the nodes in the DAG to the DAG file. """ if not self.__dag_file_path: raise CondorDAGError, "No path for DAG file" try: dagfile = open( self.__dag_file_path, 'w' ) except: raise CondorDAGError, "Cannot open file " + self.__dag_file_path for node in self.__nodes: node.write_job(dagfile) node.write_vars(dagfile) if node.get_category(): node.write_category(dagfile) if node.get_priority(): node.write_priority(dagfile) node.write_pre_script(dagfile) node.write_post_script(dagfile) node.write_input_files(dagfile) node.write_output_files(dagfile) for node in self.__nodes: node.write_parents(dagfile) for category in self.__maxjobs_categories: self.write_maxjobs(dagfile, category) dagfile.close()
python
def write_concrete_dag(self): """ Write all the nodes in the DAG to the DAG file. """ if not self.__dag_file_path: raise CondorDAGError, "No path for DAG file" try: dagfile = open( self.__dag_file_path, 'w' ) except: raise CondorDAGError, "Cannot open file " + self.__dag_file_path for node in self.__nodes: node.write_job(dagfile) node.write_vars(dagfile) if node.get_category(): node.write_category(dagfile) if node.get_priority(): node.write_priority(dagfile) node.write_pre_script(dagfile) node.write_post_script(dagfile) node.write_input_files(dagfile) node.write_output_files(dagfile) for node in self.__nodes: node.write_parents(dagfile) for category in self.__maxjobs_categories: self.write_maxjobs(dagfile, category) dagfile.close()
[ "def", "write_concrete_dag", "(", "self", ")", ":", "if", "not", "self", ".", "__dag_file_path", ":", "raise", "CondorDAGError", ",", "\"No path for DAG file\"", "try", ":", "dagfile", "=", "open", "(", "self", ".", "__dag_file_path", ",", "'w'", ")", "except"...
Write all the nodes in the DAG to the DAG file.
[ "Write", "all", "the", "nodes", "in", "the", "DAG", "to", "the", "DAG", "file", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1816-L1841
gwastro/pycbc-glue
pycbc_glue/pipeline.py
CondorDAG.write_abstract_dag
def write_abstract_dag(self): """ Write all the nodes in the workflow to the DAX file. """ # keep track of if we are using stampede at TACC using_stampede = False if not self.__dax_file_path: # this workflow is not dax-compatible, so don't write a dax return import Pegasus.DAX3 # create the workflow object dax_name = os.path.split(self.__dax_file_path)[-1] dax_basename = '.'.join(dax_name.split('.')[0:-1]) workflow = Pegasus.DAX3.ADAG( dax_basename ) # we save the ID number to DAG node name mapping so that # we can easily write out the child/parent relationship # later node_job_object_dict = {} # FIXME disctionary of executables and pfns in the workflow # Pegasus should take care of this so we don't have to workflow_executable_dict = {} workflow_pfn_dict = {} # Add PFN caches for this workflow for pfn_tuple in self.get_pfn_cache(): workflow_pfn_dict[pfn_tuple[0]] = pfn_tuple if self.get_pegasus_worker(): # write the executable into the dax worker_package = Pegasus.DAX3.Executable( namespace="pegasus", name="worker", os="linux", arch="x86_64", installed=False) worker_package.addPFN(Pegasus.DAX3.PFN(self.get_pegasus_worker(),"local")) workflow_executable_dict['pegasus-pegasus_worker'] = worker_package # check for the pegasus-cluster package for path in os.environ["PATH"].split(":"): cluster_path = os.path.join(path,"pegasus-cluster") if os.path.exists(cluster_path): # and add to the dax if it exists seqexec_package = Pegasus.DAX3.Executable( namespace="pegasus", name="seqexec", os="linux", arch="x86_64", installed=True) seqexec_package.addPFN(Pegasus.DAX3.PFN(cluster_path,"local")) workflow_executable_dict['pegasus-pegasus_seqexec'] = seqexec_package id = 0 for node in self.__nodes: if self.is_dax() and isinstance(node, LSCDataFindNode): pass elif isinstance(node.job(), CondorDAGManJob): id += 1 id_tag = "ID%06d" % id node_name = node._CondorDAGNode__name if node.job().get_dax() is None: # write this node as a sub-dag subdag_name = os.path.split(node.job().get_dag())[-1] try: subdag_exec_path = os.path.join( os.getcwd(),node.job().get_dag_directory()) except AttributeError: subdag_exec_path = os.getcwd() subdag = Pegasus.DAX3.DAG(subdag_name,id=id_tag) subdag.addProfile(Pegasus.DAX3.Profile("dagman","DIR",subdag_exec_path)) subdag_file = Pegasus.DAX3.File(subdag_name) subdag_file.addPFN(Pegasus.DAX3.PFN(os.path.join(subdag_exec_path,subdag_name),"local")) workflow.addFile(subdag_file) workflow.addDAG(subdag) node_job_object_dict[node_name] = subdag else: # write this node as a sub-dax subdax_name = os.path.split(node.job().get_dax())[-1] dax_subdir = node.job().get_dag_directory() if dax_subdir: subdax_path = os.path.join( os.getcwd(),node.job().get_dag_directory(),subdax_name) else: subdax_path = os.path.join(os.getcwd(),subdax_name) dax_subdir = '.' subdax = Pegasus.DAX3.DAX(subdax_name,id=id_tag) # FIXME pegasus should ensure these are unique for pfn_tuple in node.job().get_pfn_cache(): workflow_pfn_dict[pfn_tuple[0]] = pfn_tuple # set the storage, execute, and output directory locations pegasus_args = """--dir %s """ % dax_subdir pegasus_args += """--output-dir %s """ % dax_subdir # set the maxjobs categories for the subdax # FIXME pegasus should expose this in the dax, so it can # be handled like the MAXJOBS keyword in dag files for maxjobcat in node.get_maxjobs_categories(): pegasus_args += "-Dpegasus.dagman." + maxjobcat[0] + ".maxjobs=" + maxjobcat[1] + " " if not self.is_dax(): pegasus_args += "--nocleanup " if node.get_cluster_jobs(): pegasus_args += "--cluster " + node.get_cluster_jobs() + " " if node.get_reduce_dax() is False: pegasus_args += " --force " if node.get_static_pfn_cache(): pegasus_args += " --cache " + node.get_static_pfn_cache() + " " pegasus_args += "--output-site local -vvvvvv" subdax.addArguments(pegasus_args) subdax_file = Pegasus.DAX3.File(subdax_name) subdax_file.addPFN(Pegasus.DAX3.PFN(subdax_path,"local")) workflow.addFile(subdax_file) workflow.addDAX(subdax) node_job_object_dict[node_name] = subdax else: # write this job as a regular node executable = node.job()._CondorJob__executable node_name = node._CondorDAGNode__name id += 1 id_tag = "ID%06d" % id node_job_object_dict[node_name] = id_tag # get the name of the executable executable_namespace = 'ligo-' + str(node.job().__class__.__name__).lower() executable_base = os.path.basename(executable) workflow_job = Pegasus.DAX3.Job( namespace=executable_namespace, name=executable_base, version="1.0", id=id_tag) cmd_line = node.get_cmd_tuple_list() # loop through all filenames looking for them in the command # line so that they can be replaced appropriately by xml tags input_node_file_dict = {} for f in node.get_input_files(): input_node_file_dict[f] = 1 for f in input_node_file_dict.keys(): workflow_job.uses(Pegasus.DAX3.File(os.path.basename(f)),link=Pegasus.DAX3.Link.INPUT,register=False,transfer=True) output_node_file_dict = {} for f in node.get_output_files(): output_node_file_dict[f] = 1 checkpoint_node_file_dict = {} for f in node.get_checkpoint_files(): checkpoint_node_file_dict[f] = 1 for f in output_node_file_dict.keys(): workflow_job.uses(Pegasus.DAX3.File(os.path.basename(f)),link=Pegasus.DAX3.Link.OUTPUT,register=False,transfer=True) for f in checkpoint_node_file_dict.keys(): workflow_job.uses(Pegasus.DAX3.File(os.path.basename(f)),link=Pegasus.DAX3.Link.CHECKPOINT,register=False,transfer=True) node_file_dict = dict( input_node_file_dict.items() + output_node_file_dict.items() + checkpoint_node_file_dict.items() ) for job_arg in cmd_line: try: if node_file_dict.has_key(job_arg[0]): workflow_job.addArguments(Pegasus.DAX3.File(os.path.basename(job_arg[0]))) elif node_file_dict.has_key(job_arg[1]): workflow_job.addArguments(job_arg[0], Pegasus.DAX3.File(os.path.basename(job_arg[1]))) elif len(job_arg[1].split(' ')) != 1: args = [job_arg[0]] for arg in job_arg[1].split(' '): if node_file_dict.has_key(arg): args.append(Pegasus.DAX3.File(os.path.basename(arg))) else: args.append(arg) workflow_job.addArguments(*args) else: workflow_job.addArguments(job_arg[0], job_arg[1]) except IndexError: pass # Check for desired grid site if node.job().get_grid_site(): this_grid_site = node.job().get_grid_site() workflow_job.addProfile(Pegasus.DAX3.Profile('hints','execution.site',this_grid_site)) if this_grid_site == 'stampede-dev' or this_grid_site=='stampede': using_stampede = True # write the executable into the dax job_executable = Pegasus.DAX3.Executable( namespace=executable_namespace, name=executable_base, version="1.0", os="linux", arch="x86_64", installed=node.job().get_executable_installed()) executable_path = os.path.join(os.getcwd(),executable) job_executable.addPFN(Pegasus.DAX3.PFN(executable_path,"local")) workflow_executable_dict[executable_namespace + executable_base] = job_executable # write the mpi cluster parameter for the job if node.job().get_dax_mpi_cluster(): workflow_job.addProfile(Pegasus.DAX3.Profile("pegasus","job.aggregator","mpiexec")) workflow_job.addProfile(Pegasus.DAX3.Profile("pegasus","clusters.size",str(node.job().get_dax_mpi_cluster()))) # write the grid start parameter for this node # if the grid start is not None if node.get_grid_start(): workflow_job.addProfile(Pegasus.DAX3.Profile("pegasus","gridstart",node.get_grid_start())) # write the bundle parameter if this node has one if node.get_dax_collapse(): workflow_job.addProfile(Pegasus.DAX3.Profile("pegasus","clusters.size",str(node.get_dax_collapse()))) # write number of times the node should be retried if node.get_retry(): workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","retry",str(node.get_retry()))) # write the post script for this node if node.get_post_script(): post_script_base = os.path.basename(node.get_post_script()) post_script_path = os.path.join(os.getcwd(),node.get_post_script()) workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","post",post_script_base)) workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","post.path." + post_script_base,post_script_path)) # write the post script for this node if node.get_post_script_arg(): workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","post.arguments",' '.join(node.get_post_script_arg()))) # write the dag node category if this node has one if node.get_category(): workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","category",str(node.get_category()))) # write the dag node priority if this node has one if node.get_priority(): workflow_job.addProfile(Pegasus.DAX3.Profile("condor","priority",str(node.get_priority()))) # write the universe that this job should run in to the dax if node.get_dax_collapse(): # collapsed jobs must run in the vanilla universe workflow_job.addProfile(Pegasus.DAX3.Profile("condor","universe","vanilla")) else: workflow_job.addProfile(Pegasus.DAX3.Profile("condor","universe",node.job().get_universe())) # add any other user specified condor commands or classads for p in node.get_pegasus_profile(): workflow_job.addProfile(Pegasus.DAX3.Profile(p[0],p[1],p[2])) # finally add this job to the workflow workflow.addJob(workflow_job) node_job_object_dict[node_name] = workflow_job # print parent-child relationships to DAX for node in self.__nodes: if self.is_dax() and isinstance(node, LSCDataFindNode): pass elif self.is_dax() and ( len(node._CondorDAGNode__parents) == 1 ) and isinstance(node._CondorDAGNode__parents[0], LSCDataFindNode): pass else: child_job_object = node_job_object_dict[str(node)] if node._CondorDAGNode__parents: for parent in node._CondorDAGNode__parents: if self.is_dax() and isinstance(parent, LSCDataFindNode): pass else: parent_job_object = node_job_object_dict[str(parent)] workflow.addDependency(Pegasus.DAX3.Dependency(parent=parent_job_object, child=child_job_object)) # FIXME put all the executables in the workflow for exec_key in workflow_executable_dict.keys(): workflow.addExecutable(workflow_executable_dict[exec_key]) # FIXME if we are running on stampede, add the mpi wrapper job if using_stampede: prod_mpiexec = Pegasus.DAX3.Executable(namespace="pegasus", name="mpiexec", os="linux", arch="x86_64", installed="true") prod_mpiexec.addPFN(Pegasus.DAX3.PFN("file:///home1/02796/dabrown/bin/mpi-cluster-wrapper-impi.sh","stampede")) workflow.addExecutable(prod_mpiexec) dev_mpiexec = Pegasus.DAX3.Executable(namespace="pegasus", name="mpiexec", os="linux", arch="x86_64", installed="true") dev_mpiexec.addPFN(Pegasus.DAX3.PFN("file:///home1/02796/dabrown/bin/mpi-cluster-wrapper-impi.sh","stampede-dev")) workflow.addExecutable(dev_mpiexec) # FIXME put all the pfns in the workflow for pfn_key in workflow_pfn_dict.keys(): f = Pegasus.DAX3.File(workflow_pfn_dict[pfn_key][0]) f.addPFN(Pegasus.DAX3.PFN(workflow_pfn_dict[pfn_key][1],workflow_pfn_dict[pfn_key][2])) workflow.addFile(f) f = open(self.__dax_file_path,"w") workflow.writeXML(f) f.close()
python
def write_abstract_dag(self): """ Write all the nodes in the workflow to the DAX file. """ # keep track of if we are using stampede at TACC using_stampede = False if not self.__dax_file_path: # this workflow is not dax-compatible, so don't write a dax return import Pegasus.DAX3 # create the workflow object dax_name = os.path.split(self.__dax_file_path)[-1] dax_basename = '.'.join(dax_name.split('.')[0:-1]) workflow = Pegasus.DAX3.ADAG( dax_basename ) # we save the ID number to DAG node name mapping so that # we can easily write out the child/parent relationship # later node_job_object_dict = {} # FIXME disctionary of executables and pfns in the workflow # Pegasus should take care of this so we don't have to workflow_executable_dict = {} workflow_pfn_dict = {} # Add PFN caches for this workflow for pfn_tuple in self.get_pfn_cache(): workflow_pfn_dict[pfn_tuple[0]] = pfn_tuple if self.get_pegasus_worker(): # write the executable into the dax worker_package = Pegasus.DAX3.Executable( namespace="pegasus", name="worker", os="linux", arch="x86_64", installed=False) worker_package.addPFN(Pegasus.DAX3.PFN(self.get_pegasus_worker(),"local")) workflow_executable_dict['pegasus-pegasus_worker'] = worker_package # check for the pegasus-cluster package for path in os.environ["PATH"].split(":"): cluster_path = os.path.join(path,"pegasus-cluster") if os.path.exists(cluster_path): # and add to the dax if it exists seqexec_package = Pegasus.DAX3.Executable( namespace="pegasus", name="seqexec", os="linux", arch="x86_64", installed=True) seqexec_package.addPFN(Pegasus.DAX3.PFN(cluster_path,"local")) workflow_executable_dict['pegasus-pegasus_seqexec'] = seqexec_package id = 0 for node in self.__nodes: if self.is_dax() and isinstance(node, LSCDataFindNode): pass elif isinstance(node.job(), CondorDAGManJob): id += 1 id_tag = "ID%06d" % id node_name = node._CondorDAGNode__name if node.job().get_dax() is None: # write this node as a sub-dag subdag_name = os.path.split(node.job().get_dag())[-1] try: subdag_exec_path = os.path.join( os.getcwd(),node.job().get_dag_directory()) except AttributeError: subdag_exec_path = os.getcwd() subdag = Pegasus.DAX3.DAG(subdag_name,id=id_tag) subdag.addProfile(Pegasus.DAX3.Profile("dagman","DIR",subdag_exec_path)) subdag_file = Pegasus.DAX3.File(subdag_name) subdag_file.addPFN(Pegasus.DAX3.PFN(os.path.join(subdag_exec_path,subdag_name),"local")) workflow.addFile(subdag_file) workflow.addDAG(subdag) node_job_object_dict[node_name] = subdag else: # write this node as a sub-dax subdax_name = os.path.split(node.job().get_dax())[-1] dax_subdir = node.job().get_dag_directory() if dax_subdir: subdax_path = os.path.join( os.getcwd(),node.job().get_dag_directory(),subdax_name) else: subdax_path = os.path.join(os.getcwd(),subdax_name) dax_subdir = '.' subdax = Pegasus.DAX3.DAX(subdax_name,id=id_tag) # FIXME pegasus should ensure these are unique for pfn_tuple in node.job().get_pfn_cache(): workflow_pfn_dict[pfn_tuple[0]] = pfn_tuple # set the storage, execute, and output directory locations pegasus_args = """--dir %s """ % dax_subdir pegasus_args += """--output-dir %s """ % dax_subdir # set the maxjobs categories for the subdax # FIXME pegasus should expose this in the dax, so it can # be handled like the MAXJOBS keyword in dag files for maxjobcat in node.get_maxjobs_categories(): pegasus_args += "-Dpegasus.dagman." + maxjobcat[0] + ".maxjobs=" + maxjobcat[1] + " " if not self.is_dax(): pegasus_args += "--nocleanup " if node.get_cluster_jobs(): pegasus_args += "--cluster " + node.get_cluster_jobs() + " " if node.get_reduce_dax() is False: pegasus_args += " --force " if node.get_static_pfn_cache(): pegasus_args += " --cache " + node.get_static_pfn_cache() + " " pegasus_args += "--output-site local -vvvvvv" subdax.addArguments(pegasus_args) subdax_file = Pegasus.DAX3.File(subdax_name) subdax_file.addPFN(Pegasus.DAX3.PFN(subdax_path,"local")) workflow.addFile(subdax_file) workflow.addDAX(subdax) node_job_object_dict[node_name] = subdax else: # write this job as a regular node executable = node.job()._CondorJob__executable node_name = node._CondorDAGNode__name id += 1 id_tag = "ID%06d" % id node_job_object_dict[node_name] = id_tag # get the name of the executable executable_namespace = 'ligo-' + str(node.job().__class__.__name__).lower() executable_base = os.path.basename(executable) workflow_job = Pegasus.DAX3.Job( namespace=executable_namespace, name=executable_base, version="1.0", id=id_tag) cmd_line = node.get_cmd_tuple_list() # loop through all filenames looking for them in the command # line so that they can be replaced appropriately by xml tags input_node_file_dict = {} for f in node.get_input_files(): input_node_file_dict[f] = 1 for f in input_node_file_dict.keys(): workflow_job.uses(Pegasus.DAX3.File(os.path.basename(f)),link=Pegasus.DAX3.Link.INPUT,register=False,transfer=True) output_node_file_dict = {} for f in node.get_output_files(): output_node_file_dict[f] = 1 checkpoint_node_file_dict = {} for f in node.get_checkpoint_files(): checkpoint_node_file_dict[f] = 1 for f in output_node_file_dict.keys(): workflow_job.uses(Pegasus.DAX3.File(os.path.basename(f)),link=Pegasus.DAX3.Link.OUTPUT,register=False,transfer=True) for f in checkpoint_node_file_dict.keys(): workflow_job.uses(Pegasus.DAX3.File(os.path.basename(f)),link=Pegasus.DAX3.Link.CHECKPOINT,register=False,transfer=True) node_file_dict = dict( input_node_file_dict.items() + output_node_file_dict.items() + checkpoint_node_file_dict.items() ) for job_arg in cmd_line: try: if node_file_dict.has_key(job_arg[0]): workflow_job.addArguments(Pegasus.DAX3.File(os.path.basename(job_arg[0]))) elif node_file_dict.has_key(job_arg[1]): workflow_job.addArguments(job_arg[0], Pegasus.DAX3.File(os.path.basename(job_arg[1]))) elif len(job_arg[1].split(' ')) != 1: args = [job_arg[0]] for arg in job_arg[1].split(' '): if node_file_dict.has_key(arg): args.append(Pegasus.DAX3.File(os.path.basename(arg))) else: args.append(arg) workflow_job.addArguments(*args) else: workflow_job.addArguments(job_arg[0], job_arg[1]) except IndexError: pass # Check for desired grid site if node.job().get_grid_site(): this_grid_site = node.job().get_grid_site() workflow_job.addProfile(Pegasus.DAX3.Profile('hints','execution.site',this_grid_site)) if this_grid_site == 'stampede-dev' or this_grid_site=='stampede': using_stampede = True # write the executable into the dax job_executable = Pegasus.DAX3.Executable( namespace=executable_namespace, name=executable_base, version="1.0", os="linux", arch="x86_64", installed=node.job().get_executable_installed()) executable_path = os.path.join(os.getcwd(),executable) job_executable.addPFN(Pegasus.DAX3.PFN(executable_path,"local")) workflow_executable_dict[executable_namespace + executable_base] = job_executable # write the mpi cluster parameter for the job if node.job().get_dax_mpi_cluster(): workflow_job.addProfile(Pegasus.DAX3.Profile("pegasus","job.aggregator","mpiexec")) workflow_job.addProfile(Pegasus.DAX3.Profile("pegasus","clusters.size",str(node.job().get_dax_mpi_cluster()))) # write the grid start parameter for this node # if the grid start is not None if node.get_grid_start(): workflow_job.addProfile(Pegasus.DAX3.Profile("pegasus","gridstart",node.get_grid_start())) # write the bundle parameter if this node has one if node.get_dax_collapse(): workflow_job.addProfile(Pegasus.DAX3.Profile("pegasus","clusters.size",str(node.get_dax_collapse()))) # write number of times the node should be retried if node.get_retry(): workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","retry",str(node.get_retry()))) # write the post script for this node if node.get_post_script(): post_script_base = os.path.basename(node.get_post_script()) post_script_path = os.path.join(os.getcwd(),node.get_post_script()) workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","post",post_script_base)) workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","post.path." + post_script_base,post_script_path)) # write the post script for this node if node.get_post_script_arg(): workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","post.arguments",' '.join(node.get_post_script_arg()))) # write the dag node category if this node has one if node.get_category(): workflow_job.addProfile(Pegasus.DAX3.Profile("dagman","category",str(node.get_category()))) # write the dag node priority if this node has one if node.get_priority(): workflow_job.addProfile(Pegasus.DAX3.Profile("condor","priority",str(node.get_priority()))) # write the universe that this job should run in to the dax if node.get_dax_collapse(): # collapsed jobs must run in the vanilla universe workflow_job.addProfile(Pegasus.DAX3.Profile("condor","universe","vanilla")) else: workflow_job.addProfile(Pegasus.DAX3.Profile("condor","universe",node.job().get_universe())) # add any other user specified condor commands or classads for p in node.get_pegasus_profile(): workflow_job.addProfile(Pegasus.DAX3.Profile(p[0],p[1],p[2])) # finally add this job to the workflow workflow.addJob(workflow_job) node_job_object_dict[node_name] = workflow_job # print parent-child relationships to DAX for node in self.__nodes: if self.is_dax() and isinstance(node, LSCDataFindNode): pass elif self.is_dax() and ( len(node._CondorDAGNode__parents) == 1 ) and isinstance(node._CondorDAGNode__parents[0], LSCDataFindNode): pass else: child_job_object = node_job_object_dict[str(node)] if node._CondorDAGNode__parents: for parent in node._CondorDAGNode__parents: if self.is_dax() and isinstance(parent, LSCDataFindNode): pass else: parent_job_object = node_job_object_dict[str(parent)] workflow.addDependency(Pegasus.DAX3.Dependency(parent=parent_job_object, child=child_job_object)) # FIXME put all the executables in the workflow for exec_key in workflow_executable_dict.keys(): workflow.addExecutable(workflow_executable_dict[exec_key]) # FIXME if we are running on stampede, add the mpi wrapper job if using_stampede: prod_mpiexec = Pegasus.DAX3.Executable(namespace="pegasus", name="mpiexec", os="linux", arch="x86_64", installed="true") prod_mpiexec.addPFN(Pegasus.DAX3.PFN("file:///home1/02796/dabrown/bin/mpi-cluster-wrapper-impi.sh","stampede")) workflow.addExecutable(prod_mpiexec) dev_mpiexec = Pegasus.DAX3.Executable(namespace="pegasus", name="mpiexec", os="linux", arch="x86_64", installed="true") dev_mpiexec.addPFN(Pegasus.DAX3.PFN("file:///home1/02796/dabrown/bin/mpi-cluster-wrapper-impi.sh","stampede-dev")) workflow.addExecutable(dev_mpiexec) # FIXME put all the pfns in the workflow for pfn_key in workflow_pfn_dict.keys(): f = Pegasus.DAX3.File(workflow_pfn_dict[pfn_key][0]) f.addPFN(Pegasus.DAX3.PFN(workflow_pfn_dict[pfn_key][1],workflow_pfn_dict[pfn_key][2])) workflow.addFile(f) f = open(self.__dax_file_path,"w") workflow.writeXML(f) f.close()
[ "def", "write_abstract_dag", "(", "self", ")", ":", "# keep track of if we are using stampede at TACC", "using_stampede", "=", "False", "if", "not", "self", ".", "__dax_file_path", ":", "# this workflow is not dax-compatible, so don't write a dax", "return", "import", "Pegasus"...
Write all the nodes in the workflow to the DAX file.
[ "Write", "all", "the", "nodes", "in", "the", "workflow", "to", "the", "DAX", "file", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1843-L2144