nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexing.py
python
maybe_convert_ix
(*args)
We likely want to take the cross-product.
We likely want to take the cross-product.
[ "We", "likely", "want", "to", "take", "the", "cross", "-", "product", "." ]
def maybe_convert_ix(*args): """ We likely want to take the cross-product. """ ixify = True for arg in args: if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)): ixify = False if ixify: return np.ix_(*args) else: return args
[ "def", "maybe_convert_ix", "(", "*", "args", ")", ":", "ixify", "=", "True", "for", "arg", "in", "args", ":", "if", "not", "isinstance", "(", "arg", ",", "(", "np", ".", "ndarray", ",", "list", ",", "ABCSeries", ",", "Index", ")", ")", ":", "ixify", "=", "False", "if", "ixify", ":", "return", "np", ".", "ix_", "(", "*", "args", ")", "else", ":", "return", "args" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexing.py#L2361-L2373
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/rulerctrl.py
python
Indicator.GetPosition
(self)
return xpos, ypos
Returns the position at which we should draw the indicator bitmap.
Returns the position at which we should draw the indicator bitmap.
[ "Returns", "the", "position", "at", "which", "we", "should", "draw", "the", "indicator", "bitmap", "." ]
def GetPosition(self): """ Returns the position at which we should draw the indicator bitmap. """ orient = self._parent._orientation flip = self._parent._flip left, top, right, bottom = self._parent.GetBounds() minval = self._parent._min maxval = self._parent._max value = self._value if self._parent._log: value = math.log10(value) maxval = math.log10(maxval) minval = math.log10(minval) pos = float(value-minval)/abs(maxval - minval) if orient == wx.HORIZONTAL: xpos = int(pos*right) - self._img.GetWidth()/2 if flip: ypos = top else: ypos = bottom - self._img.GetHeight() else: ypos = int(pos*bottom) - self._img.GetHeight()/2 if flip: xpos = left else: xpos = right - self._img.GetWidth() return xpos, ypos
[ "def", "GetPosition", "(", "self", ")", ":", "orient", "=", "self", ".", "_parent", ".", "_orientation", "flip", "=", "self", ".", "_parent", ".", "_flip", "left", ",", "top", ",", "right", ",", "bottom", "=", "self", ".", "_parent", ".", "GetBounds", "(", ")", "minval", "=", "self", ".", "_parent", ".", "_min", "maxval", "=", "self", ".", "_parent", ".", "_max", "value", "=", "self", ".", "_value", "if", "self", ".", "_parent", ".", "_log", ":", "value", "=", "math", ".", "log10", "(", "value", ")", "maxval", "=", "math", ".", "log10", "(", "maxval", ")", "minval", "=", "math", ".", "log10", "(", "minval", ")", "pos", "=", "float", "(", "value", "-", "minval", ")", "/", "abs", "(", "maxval", "-", "minval", ")", "if", "orient", "==", "wx", ".", "HORIZONTAL", ":", "xpos", "=", "int", "(", "pos", "*", "right", ")", "-", "self", ".", "_img", ".", "GetWidth", "(", ")", "/", "2", "if", "flip", ":", "ypos", "=", "top", "else", ":", "ypos", "=", "bottom", "-", "self", ".", "_img", ".", "GetHeight", "(", ")", "else", ":", "ypos", "=", "int", "(", "pos", "*", "bottom", ")", "-", "self", ".", "_img", ".", "GetHeight", "(", ")", "/", "2", "if", "flip", ":", "xpos", "=", "left", "else", ":", "xpos", "=", "right", "-", "self", ".", "_img", ".", "GetWidth", "(", ")", "return", "xpos", ",", "ypos" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/rulerctrl.py#L401-L432
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/unicycler.py
python
main
()
Script execution starts here.
Script execution starts here.
[ "Script", "execution", "starts", "here", "." ]
def main(): """ Script execution starts here. """ random.seed(0) # Fixed seed so the program produces the same output every time it's run. full_command = ' '.join(('"' + x + '"' if ' ' in x else x) for x in sys.argv) args = get_arguments() out_dir_message = make_output_directory(args.out, args.verbosity) short_reads_available = bool(args.short1) or bool(args.unpaired) long_reads_available = bool(args.long) check_input_files(args) print_intro_message(args, full_command, out_dir_message) check_dependencies(args, short_reads_available, long_reads_available) counter = itertools.count(start=1) # Files are numbered in chronological order. bridges = [] if short_reads_available: # Produce a SPAdes assembly graph with a k-mer that balances contig length and connectivity. spades_graph_prefix = gfa_path(args.out, next(counter), 'spades_graph')[:-4] best_spades_graph = gfa_path(args.out, next(counter), 'depth_filter') if os.path.isfile(best_spades_graph): log.log('\nSPAdes graph already exists. Will use this graph instead of running ' 'SPAdes:\n ' + best_spades_graph) graph = AssemblyGraph(best_spades_graph, None) else: graph = get_best_spades_graph(args.short1, args.short2, args.unpaired, args.out, args.depth_filter, args.verbosity, args.spades_path, args.threads, args.keep, args.kmer_count, args.min_kmer_frac, args.max_kmer_frac, args.kmers, args.linear_seqs, args.largest_component, spades_graph_prefix, args.spades_options) determine_copy_depth(graph) if args.keep > 0 and not os.path.isfile(best_spades_graph): graph.save_to_gfa(best_spades_graph, save_copy_depth_info=True, newline=True, include_insert_size=True) clean_up_spades_graph(graph) if args.keep > 0: overlap_removed_graph_filename = gfa_path(args.out, next(counter), 'overlaps_removed') graph.save_to_gfa(overlap_removed_graph_filename, save_copy_depth_info=True, newline=True, include_insert_size=True) anchor_segments = get_anchor_segments(graph, args.min_anchor_seg_len) # Make an initial set of bridges using the SPAdes contig paths. This step is skipped when # using conservative bridging mode (in that case we don't trust SPAdes contig paths at all). if args.mode != 0: bridges += create_spades_contig_bridges(graph, anchor_segments) bridges += create_loop_unrolling_bridges(graph, anchor_segments) if not bridges: log.log('none found', 1) graph.paths = {} # Now that we've made short read bridges, we no longer need the paths. else: # short reads not available graph = None anchor_segments = [] scoring_scheme = AlignmentScoringScheme(args.scores) if long_reads_available: read_dict, read_names, long_read_filename = load_long_reads(args.long, output_dir=args.out) read_nicknames = get_read_nickname_dict(read_names) else: read_dict, read_names, long_read_filename, read_nicknames = {}, [], '', {} if long_reads_available and not args.no_miniasm: string_graph = make_miniasm_string_graph(graph, read_dict, long_read_filename, scoring_scheme, read_nicknames, counter, args, anchor_segments, args.existing_long_read_assembly) else: string_graph = None if not short_reads_available and string_graph is None: quit_with_error('miniasm assembly failed') if short_reads_available and long_reads_available: if string_graph is not None and not args.no_miniasm: bridges += create_miniasm_bridges(graph, string_graph, anchor_segments, scoring_scheme, args.verbosity, args.min_bridge_qual) if not args.no_simple_bridges: bridges += create_simple_long_read_bridges(graph, args.out, args.keep, args.threads, read_dict, long_read_filename, scoring_scheme, anchor_segments) if not args.no_long_read_alignment: read_names, min_scaled_score, min_alignment_length = \ align_long_reads_to_assembly_graph(graph, anchor_segments, args, full_command, read_dict, read_names, long_read_filename) expected_linear_seqs = args.linear_seqs > 0 bridges += create_long_read_bridges(graph, read_dict, read_names, anchor_segments, args.verbosity, min_scaled_score, args.threads, scoring_scheme, min_alignment_length, expected_linear_seqs, args.min_bridge_qual) if short_reads_available: seg_nums_used_in_bridges = graph.apply_bridges(bridges, args.verbosity, args.min_bridge_qual) if args.keep > 0: graph.save_to_gfa(gfa_path(args.out, next(counter), 'bridges_applied'), save_seg_type_info=True, save_copy_depth_info=True, newline=True) graph.clean_up_after_bridging_1(anchor_segments, seg_nums_used_in_bridges) graph.clean_up_after_bridging_2(seg_nums_used_in_bridges, args.min_component_size, args.min_dead_end_size, graph, anchor_segments) if args.keep > 2: log.log('', 2) graph.save_to_gfa(gfa_path(args.out, next(counter), 'cleaned'), save_seg_type_info=True, save_copy_depth_info=True) graph.merge_all_possible(anchor_segments, args.mode) if args.keep > 2: graph.save_to_gfa(gfa_path(args.out, next(counter), 'merged')) log.log_section_header('Bridged assembly graph') log.log_explanation('The assembly is now mostly finished and no more structural changes ' 'will be made. Ideally the assembly graph should now have one contig ' 'per replicon and no erroneous contigs (i.e. a complete assembly). ' 'If there are more contigs, then the assembly is not complete.', verbosity=1) graph.final_clean() if args.keep > 0: graph.save_to_gfa(gfa_path(args.out, next(counter), 'final_clean')) log.log('') graph.print_component_table() else: # only long reads available graph = string_graph if not args.no_rotate: rotate_completed_replicons(graph, args, counter) log.log_section_header('Assembly complete') final_assembly_fasta = os.path.join(args.out, 'assembly.fasta') final_assembly_gfa = os.path.join(args.out, 'assembly.gfa') graph.save_to_gfa(final_assembly_gfa) graph.save_to_fasta(final_assembly_fasta, min_length=args.min_fasta_length) log.log('')
[ "def", "main", "(", ")", ":", "random", ".", "seed", "(", "0", ")", "# Fixed seed so the program produces the same output every time it's run.", "full_command", "=", "' '", ".", "join", "(", "(", "'\"'", "+", "x", "+", "'\"'", "if", "' '", "in", "x", "else", "x", ")", "for", "x", "in", "sys", ".", "argv", ")", "args", "=", "get_arguments", "(", ")", "out_dir_message", "=", "make_output_directory", "(", "args", ".", "out", ",", "args", ".", "verbosity", ")", "short_reads_available", "=", "bool", "(", "args", ".", "short1", ")", "or", "bool", "(", "args", ".", "unpaired", ")", "long_reads_available", "=", "bool", "(", "args", ".", "long", ")", "check_input_files", "(", "args", ")", "print_intro_message", "(", "args", ",", "full_command", ",", "out_dir_message", ")", "check_dependencies", "(", "args", ",", "short_reads_available", ",", "long_reads_available", ")", "counter", "=", "itertools", ".", "count", "(", "start", "=", "1", ")", "# Files are numbered in chronological order.", "bridges", "=", "[", "]", "if", "short_reads_available", ":", "# Produce a SPAdes assembly graph with a k-mer that balances contig length and connectivity.", "spades_graph_prefix", "=", "gfa_path", "(", "args", ".", "out", ",", "next", "(", "counter", ")", ",", "'spades_graph'", ")", "[", ":", "-", "4", "]", "best_spades_graph", "=", "gfa_path", "(", "args", ".", "out", ",", "next", "(", "counter", ")", ",", "'depth_filter'", ")", "if", "os", ".", "path", ".", "isfile", "(", "best_spades_graph", ")", ":", "log", ".", "log", "(", "'\\nSPAdes graph already exists. Will use this graph instead of running '", "'SPAdes:\\n '", "+", "best_spades_graph", ")", "graph", "=", "AssemblyGraph", "(", "best_spades_graph", ",", "None", ")", "else", ":", "graph", "=", "get_best_spades_graph", "(", "args", ".", "short1", ",", "args", ".", "short2", ",", "args", ".", "unpaired", ",", "args", ".", "out", ",", "args", ".", "depth_filter", ",", "args", ".", "verbosity", ",", "args", ".", "spades_path", ",", "args", ".", "threads", ",", "args", ".", "keep", ",", "args", ".", "kmer_count", ",", "args", ".", "min_kmer_frac", ",", "args", ".", "max_kmer_frac", ",", "args", ".", "kmers", ",", "args", ".", "linear_seqs", ",", "args", ".", "largest_component", ",", "spades_graph_prefix", ",", "args", ".", "spades_options", ")", "determine_copy_depth", "(", "graph", ")", "if", "args", ".", "keep", ">", "0", "and", "not", "os", ".", "path", ".", "isfile", "(", "best_spades_graph", ")", ":", "graph", ".", "save_to_gfa", "(", "best_spades_graph", ",", "save_copy_depth_info", "=", "True", ",", "newline", "=", "True", ",", "include_insert_size", "=", "True", ")", "clean_up_spades_graph", "(", "graph", ")", "if", "args", ".", "keep", ">", "0", ":", "overlap_removed_graph_filename", "=", "gfa_path", "(", "args", ".", "out", ",", "next", "(", "counter", ")", ",", "'overlaps_removed'", ")", "graph", ".", "save_to_gfa", "(", "overlap_removed_graph_filename", ",", "save_copy_depth_info", "=", "True", ",", "newline", "=", "True", ",", "include_insert_size", "=", "True", ")", "anchor_segments", "=", "get_anchor_segments", "(", "graph", ",", "args", ".", "min_anchor_seg_len", ")", "# Make an initial set of bridges using the SPAdes contig paths. This step is skipped when", "# using conservative bridging mode (in that case we don't trust SPAdes contig paths at all).", "if", "args", ".", "mode", "!=", "0", ":", "bridges", "+=", "create_spades_contig_bridges", "(", "graph", ",", "anchor_segments", ")", "bridges", "+=", "create_loop_unrolling_bridges", "(", "graph", ",", "anchor_segments", ")", "if", "not", "bridges", ":", "log", ".", "log", "(", "'none found'", ",", "1", ")", "graph", ".", "paths", "=", "{", "}", "# Now that we've made short read bridges, we no longer need the paths.", "else", ":", "# short reads not available", "graph", "=", "None", "anchor_segments", "=", "[", "]", "scoring_scheme", "=", "AlignmentScoringScheme", "(", "args", ".", "scores", ")", "if", "long_reads_available", ":", "read_dict", ",", "read_names", ",", "long_read_filename", "=", "load_long_reads", "(", "args", ".", "long", ",", "output_dir", "=", "args", ".", "out", ")", "read_nicknames", "=", "get_read_nickname_dict", "(", "read_names", ")", "else", ":", "read_dict", ",", "read_names", ",", "long_read_filename", ",", "read_nicknames", "=", "{", "}", ",", "[", "]", ",", "''", ",", "{", "}", "if", "long_reads_available", "and", "not", "args", ".", "no_miniasm", ":", "string_graph", "=", "make_miniasm_string_graph", "(", "graph", ",", "read_dict", ",", "long_read_filename", ",", "scoring_scheme", ",", "read_nicknames", ",", "counter", ",", "args", ",", "anchor_segments", ",", "args", ".", "existing_long_read_assembly", ")", "else", ":", "string_graph", "=", "None", "if", "not", "short_reads_available", "and", "string_graph", "is", "None", ":", "quit_with_error", "(", "'miniasm assembly failed'", ")", "if", "short_reads_available", "and", "long_reads_available", ":", "if", "string_graph", "is", "not", "None", "and", "not", "args", ".", "no_miniasm", ":", "bridges", "+=", "create_miniasm_bridges", "(", "graph", ",", "string_graph", ",", "anchor_segments", ",", "scoring_scheme", ",", "args", ".", "verbosity", ",", "args", ".", "min_bridge_qual", ")", "if", "not", "args", ".", "no_simple_bridges", ":", "bridges", "+=", "create_simple_long_read_bridges", "(", "graph", ",", "args", ".", "out", ",", "args", ".", "keep", ",", "args", ".", "threads", ",", "read_dict", ",", "long_read_filename", ",", "scoring_scheme", ",", "anchor_segments", ")", "if", "not", "args", ".", "no_long_read_alignment", ":", "read_names", ",", "min_scaled_score", ",", "min_alignment_length", "=", "align_long_reads_to_assembly_graph", "(", "graph", ",", "anchor_segments", ",", "args", ",", "full_command", ",", "read_dict", ",", "read_names", ",", "long_read_filename", ")", "expected_linear_seqs", "=", "args", ".", "linear_seqs", ">", "0", "bridges", "+=", "create_long_read_bridges", "(", "graph", ",", "read_dict", ",", "read_names", ",", "anchor_segments", ",", "args", ".", "verbosity", ",", "min_scaled_score", ",", "args", ".", "threads", ",", "scoring_scheme", ",", "min_alignment_length", ",", "expected_linear_seqs", ",", "args", ".", "min_bridge_qual", ")", "if", "short_reads_available", ":", "seg_nums_used_in_bridges", "=", "graph", ".", "apply_bridges", "(", "bridges", ",", "args", ".", "verbosity", ",", "args", ".", "min_bridge_qual", ")", "if", "args", ".", "keep", ">", "0", ":", "graph", ".", "save_to_gfa", "(", "gfa_path", "(", "args", ".", "out", ",", "next", "(", "counter", ")", ",", "'bridges_applied'", ")", ",", "save_seg_type_info", "=", "True", ",", "save_copy_depth_info", "=", "True", ",", "newline", "=", "True", ")", "graph", ".", "clean_up_after_bridging_1", "(", "anchor_segments", ",", "seg_nums_used_in_bridges", ")", "graph", ".", "clean_up_after_bridging_2", "(", "seg_nums_used_in_bridges", ",", "args", ".", "min_component_size", ",", "args", ".", "min_dead_end_size", ",", "graph", ",", "anchor_segments", ")", "if", "args", ".", "keep", ">", "2", ":", "log", ".", "log", "(", "''", ",", "2", ")", "graph", ".", "save_to_gfa", "(", "gfa_path", "(", "args", ".", "out", ",", "next", "(", "counter", ")", ",", "'cleaned'", ")", ",", "save_seg_type_info", "=", "True", ",", "save_copy_depth_info", "=", "True", ")", "graph", ".", "merge_all_possible", "(", "anchor_segments", ",", "args", ".", "mode", ")", "if", "args", ".", "keep", ">", "2", ":", "graph", ".", "save_to_gfa", "(", "gfa_path", "(", "args", ".", "out", ",", "next", "(", "counter", ")", ",", "'merged'", ")", ")", "log", ".", "log_section_header", "(", "'Bridged assembly graph'", ")", "log", ".", "log_explanation", "(", "'The assembly is now mostly finished and no more structural changes '", "'will be made. Ideally the assembly graph should now have one contig '", "'per replicon and no erroneous contigs (i.e. a complete assembly). '", "'If there are more contigs, then the assembly is not complete.'", ",", "verbosity", "=", "1", ")", "graph", ".", "final_clean", "(", ")", "if", "args", ".", "keep", ">", "0", ":", "graph", ".", "save_to_gfa", "(", "gfa_path", "(", "args", ".", "out", ",", "next", "(", "counter", ")", ",", "'final_clean'", ")", ")", "log", ".", "log", "(", "''", ")", "graph", ".", "print_component_table", "(", ")", "else", ":", "# only long reads available", "graph", "=", "string_graph", "if", "not", "args", ".", "no_rotate", ":", "rotate_completed_replicons", "(", "graph", ",", "args", ",", "counter", ")", "log", ".", "log_section_header", "(", "'Assembly complete'", ")", "final_assembly_fasta", "=", "os", ".", "path", ".", "join", "(", "args", ".", "out", ",", "'assembly.fasta'", ")", "final_assembly_gfa", "=", "os", ".", "path", ".", "join", "(", "args", ".", "out", ",", "'assembly.gfa'", ")", "graph", ".", "save_to_gfa", "(", "final_assembly_gfa", ")", "graph", ".", "save_to_fasta", "(", "final_assembly_fasta", ",", "min_length", "=", "args", ".", "min_fasta_length", ")", "log", ".", "log", "(", "''", ")" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/unicycler.py#L48-L189
emsesp/EMS-ESP
65c4a381bf8df61d1e18ba00223b1a55933fc547
scripts/esptool.py
python
ESPLoader.run_spiflash_command
(self, spiflash_command, data=b"", read_bits=0)
return status
Run an arbitrary SPI flash command. This function uses the "USR_COMMAND" functionality in the ESP SPI hardware, rather than the precanned commands supported by hardware. So the value of spiflash_command is an actual command byte, sent over the wire. After writing command byte, writes 'data' to MOSI and then reads back 'read_bits' of reply on MISO. Result is a number.
Run an arbitrary SPI flash command.
[ "Run", "an", "arbitrary", "SPI", "flash", "command", "." ]
def run_spiflash_command(self, spiflash_command, data=b"", read_bits=0): """Run an arbitrary SPI flash command. This function uses the "USR_COMMAND" functionality in the ESP SPI hardware, rather than the precanned commands supported by hardware. So the value of spiflash_command is an actual command byte, sent over the wire. After writing command byte, writes 'data' to MOSI and then reads back 'read_bits' of reply on MISO. Result is a number. """ # SPI_USR register flags SPI_USR_COMMAND = (1 << 31) SPI_USR_MISO = (1 << 28) SPI_USR_MOSI = (1 << 27) # SPI registers, base address differs ESP32 vs 8266 base = self.SPI_REG_BASE SPI_CMD_REG = base + 0x00 SPI_USR_REG = base + 0x1C SPI_USR1_REG = base + 0x20 SPI_USR2_REG = base + 0x24 SPI_W0_REG = base + self.SPI_W0_OFFS # following two registers are ESP32 only if self.SPI_HAS_MOSI_DLEN_REG: # ESP32 has a more sophisticated wayto set up "user" commands def set_data_lengths(mosi_bits, miso_bits): SPI_MOSI_DLEN_REG = base + 0x28 SPI_MISO_DLEN_REG = base + 0x2C if mosi_bits > 0: self.write_reg(SPI_MOSI_DLEN_REG, mosi_bits - 1) if miso_bits > 0: self.write_reg(SPI_MISO_DLEN_REG, miso_bits - 1) else: def set_data_lengths(mosi_bits, miso_bits): SPI_DATA_LEN_REG = SPI_USR1_REG SPI_MOSI_BITLEN_S = 17 SPI_MISO_BITLEN_S = 8 mosi_mask = 0 if (mosi_bits == 0) else (mosi_bits - 1) miso_mask = 0 if (miso_bits == 0) else (miso_bits - 1) self.write_reg(SPI_DATA_LEN_REG, (miso_mask << SPI_MISO_BITLEN_S) | ( mosi_mask << SPI_MOSI_BITLEN_S)) # SPI peripheral "command" bitmasks for SPI_CMD_REG SPI_CMD_USR = (1 << 18) # shift values SPI_USR2_DLEN_SHIFT = 28 if read_bits > 32: raise FatalError("Reading more than 32 bits back from a SPI flash operation is unsupported") if len(data) > 64: raise FatalError("Writing more than 64 bytes of data with one SPI command is unsupported") data_bits = len(data) * 8 old_spi_usr = self.read_reg(SPI_USR_REG) old_spi_usr2 = self.read_reg(SPI_USR2_REG) flags = SPI_USR_COMMAND if read_bits > 0: flags |= SPI_USR_MISO if data_bits > 0: flags |= SPI_USR_MOSI set_data_lengths(data_bits, read_bits) self.write_reg(SPI_USR_REG, flags) self.write_reg(SPI_USR2_REG, (7 << SPI_USR2_DLEN_SHIFT) | spiflash_command) if data_bits == 0: self.write_reg(SPI_W0_REG, 0) # clear data register before we read it else: data = pad_to(data, 4, b'\00') # pad to 32-bit multiple words = struct.unpack("I" * (len(data) // 4), data) next_reg = SPI_W0_REG for word in words: self.write_reg(next_reg, word) next_reg += 4 self.write_reg(SPI_CMD_REG, SPI_CMD_USR) def wait_done(): for _ in range(10): if (self.read_reg(SPI_CMD_REG) & SPI_CMD_USR) == 0: return raise FatalError("SPI command did not complete in time") wait_done() status = self.read_reg(SPI_W0_REG) # restore some SPI controller registers self.write_reg(SPI_USR_REG, old_spi_usr) self.write_reg(SPI_USR2_REG, old_spi_usr2) return status
[ "def", "run_spiflash_command", "(", "self", ",", "spiflash_command", ",", "data", "=", "b\"\"", ",", "read_bits", "=", "0", ")", ":", "# SPI_USR register flags", "SPI_USR_COMMAND", "=", "(", "1", "<<", "31", ")", "SPI_USR_MISO", "=", "(", "1", "<<", "28", ")", "SPI_USR_MOSI", "=", "(", "1", "<<", "27", ")", "# SPI registers, base address differs ESP32 vs 8266", "base", "=", "self", ".", "SPI_REG_BASE", "SPI_CMD_REG", "=", "base", "+", "0x00", "SPI_USR_REG", "=", "base", "+", "0x1C", "SPI_USR1_REG", "=", "base", "+", "0x20", "SPI_USR2_REG", "=", "base", "+", "0x24", "SPI_W0_REG", "=", "base", "+", "self", ".", "SPI_W0_OFFS", "# following two registers are ESP32 only", "if", "self", ".", "SPI_HAS_MOSI_DLEN_REG", ":", "# ESP32 has a more sophisticated wayto set up \"user\" commands", "def", "set_data_lengths", "(", "mosi_bits", ",", "miso_bits", ")", ":", "SPI_MOSI_DLEN_REG", "=", "base", "+", "0x28", "SPI_MISO_DLEN_REG", "=", "base", "+", "0x2C", "if", "mosi_bits", ">", "0", ":", "self", ".", "write_reg", "(", "SPI_MOSI_DLEN_REG", ",", "mosi_bits", "-", "1", ")", "if", "miso_bits", ">", "0", ":", "self", ".", "write_reg", "(", "SPI_MISO_DLEN_REG", ",", "miso_bits", "-", "1", ")", "else", ":", "def", "set_data_lengths", "(", "mosi_bits", ",", "miso_bits", ")", ":", "SPI_DATA_LEN_REG", "=", "SPI_USR1_REG", "SPI_MOSI_BITLEN_S", "=", "17", "SPI_MISO_BITLEN_S", "=", "8", "mosi_mask", "=", "0", "if", "(", "mosi_bits", "==", "0", ")", "else", "(", "mosi_bits", "-", "1", ")", "miso_mask", "=", "0", "if", "(", "miso_bits", "==", "0", ")", "else", "(", "miso_bits", "-", "1", ")", "self", ".", "write_reg", "(", "SPI_DATA_LEN_REG", ",", "(", "miso_mask", "<<", "SPI_MISO_BITLEN_S", ")", "|", "(", "mosi_mask", "<<", "SPI_MOSI_BITLEN_S", ")", ")", "# SPI peripheral \"command\" bitmasks for SPI_CMD_REG", "SPI_CMD_USR", "=", "(", "1", "<<", "18", ")", "# shift values", "SPI_USR2_DLEN_SHIFT", "=", "28", "if", "read_bits", ">", "32", ":", "raise", "FatalError", "(", "\"Reading more than 32 bits back from a SPI flash operation is unsupported\"", ")", "if", "len", "(", "data", ")", ">", "64", ":", "raise", "FatalError", "(", "\"Writing more than 64 bytes of data with one SPI command is unsupported\"", ")", "data_bits", "=", "len", "(", "data", ")", "*", "8", "old_spi_usr", "=", "self", ".", "read_reg", "(", "SPI_USR_REG", ")", "old_spi_usr2", "=", "self", ".", "read_reg", "(", "SPI_USR2_REG", ")", "flags", "=", "SPI_USR_COMMAND", "if", "read_bits", ">", "0", ":", "flags", "|=", "SPI_USR_MISO", "if", "data_bits", ">", "0", ":", "flags", "|=", "SPI_USR_MOSI", "set_data_lengths", "(", "data_bits", ",", "read_bits", ")", "self", ".", "write_reg", "(", "SPI_USR_REG", ",", "flags", ")", "self", ".", "write_reg", "(", "SPI_USR2_REG", ",", "(", "7", "<<", "SPI_USR2_DLEN_SHIFT", ")", "|", "spiflash_command", ")", "if", "data_bits", "==", "0", ":", "self", ".", "write_reg", "(", "SPI_W0_REG", ",", "0", ")", "# clear data register before we read it", "else", ":", "data", "=", "pad_to", "(", "data", ",", "4", ",", "b'\\00'", ")", "# pad to 32-bit multiple", "words", "=", "struct", ".", "unpack", "(", "\"I\"", "*", "(", "len", "(", "data", ")", "//", "4", ")", ",", "data", ")", "next_reg", "=", "SPI_W0_REG", "for", "word", "in", "words", ":", "self", ".", "write_reg", "(", "next_reg", ",", "word", ")", "next_reg", "+=", "4", "self", ".", "write_reg", "(", "SPI_CMD_REG", ",", "SPI_CMD_USR", ")", "def", "wait_done", "(", ")", ":", "for", "_", "in", "range", "(", "10", ")", ":", "if", "(", "self", ".", "read_reg", "(", "SPI_CMD_REG", ")", "&", "SPI_CMD_USR", ")", "==", "0", ":", "return", "raise", "FatalError", "(", "\"SPI command did not complete in time\"", ")", "wait_done", "(", ")", "status", "=", "self", ".", "read_reg", "(", "SPI_W0_REG", ")", "# restore some SPI controller registers", "self", ".", "write_reg", "(", "SPI_USR_REG", ",", "old_spi_usr", ")", "self", ".", "write_reg", "(", "SPI_USR2_REG", ",", "old_spi_usr2", ")", "return", "status" ]
https://github.com/emsesp/EMS-ESP/blob/65c4a381bf8df61d1e18ba00223b1a55933fc547/scripts/esptool.py#L753-L845
akai-katto/dandere2x
bf1a46d5c9f9ffc8145a412c3571b283345b8512
src/dandere2x/dandere2xlib/wrappers/frame_new/__init__.py
python
Frame.from_file_wait
(cls, file_path: str, controller=Dandere2xController())
Repeatedly calls the "from_file" method until the image is properly loaded - this is a result of window's file handler labeling a file as ready-to-be-read but not actually, thus resulting in a string of potential errors. @param file_path: Location of the file on disk @param controller: Controller to revoke the wait function if the current dandere2x session is killed.
Repeatedly calls the "from_file" method until the image is properly loaded - this is a result of window's file handler labeling a file as ready-to-be-read but not actually, thus resulting in a string of potential errors.
[ "Repeatedly", "calls", "the", "from_file", "method", "until", "the", "image", "is", "properly", "loaded", "-", "this", "is", "a", "result", "of", "window", "s", "file", "handler", "labeling", "a", "file", "as", "ready", "-", "to", "-", "be", "-", "read", "but", "not", "actually", "thus", "resulting", "in", "a", "string", "of", "potential", "errors", "." ]
def from_file_wait(cls, file_path: str, controller=Dandere2xController()): """ Repeatedly calls the "from_file" method until the image is properly loaded - this is a result of window's file handler labeling a file as ready-to-be-read but not actually, thus resulting in a string of potential errors. @param file_path: Location of the file on disk @param controller: Controller to revoke the wait function if the current dandere2x session is killed. """ logger = logging.getLogger(__name__) pass
[ "def", "from_file_wait", "(", "cls", ",", "file_path", ":", "str", ",", "controller", "=", "Dandere2xController", "(", ")", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "pass" ]
https://github.com/akai-katto/dandere2x/blob/bf1a46d5c9f9ffc8145a412c3571b283345b8512/src/dandere2x/dandere2xlib/wrappers/frame_new/__init__.py#L51-L62
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/fill.py
python
_fill_op_tbe
()
return
FillD TBE register
FillD TBE register
[ "FillD", "TBE", "register" ]
def _fill_op_tbe(): """FillD TBE register""" return
[ "def", "_fill_op_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/fill.py#L54-L56
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Utilities/Scripts/SlicerWizard/Utilities.py
python
createEmptyRepo
(path, tool=None)
return git.Repo.init(path)
Create a repository in an empty or nonexistent location. :param path: Location which should contain the newly created repository. :type path: :class:`str` :param tool: Name of the |VCS| tool to use to create the repository (e.g. ``'git'``). If ``None``, a default tool (git) is used. :type tool: :class:`str` or ``None`` :raises: :exc:`~exceptions.Exception` if ``location`` exists and is not empty, or if the specified |VCS| tool is not supported. This creates a new repository using the specified ``tool`` at ``location``, first creating ``location`` (and any parents) as necessary. This function is meant to be passed as the ``create`` argument to :func:`.getRepo`. .. note:: Only ``'git'`` repositories are supported at this time.
Create a repository in an empty or nonexistent location.
[ "Create", "a", "repository", "in", "an", "empty", "or", "nonexistent", "location", "." ]
def createEmptyRepo(path, tool=None): """Create a repository in an empty or nonexistent location. :param path: Location which should contain the newly created repository. :type path: :class:`str` :param tool: Name of the |VCS| tool to use to create the repository (e.g. ``'git'``). If ``None``, a default tool (git) is used. :type tool: :class:`str` or ``None`` :raises: :exc:`~exceptions.Exception` if ``location`` exists and is not empty, or if the specified |VCS| tool is not supported. This creates a new repository using the specified ``tool`` at ``location``, first creating ``location`` (and any parents) as necessary. This function is meant to be passed as the ``create`` argument to :func:`.getRepo`. .. note:: Only ``'git'`` repositories are supported at this time. """ # Check that the requested tool is supported if not haveGit() or tool not in (None, "git"): raise Exception("unable to create %r repository" % tool) # Create a repository at the specified location if os.path.exists(path) and len(os.listdir(path)): raise Exception("refusing to create repository in non-empty directory") os.makedirs(path) import git return git.Repo.init(path)
[ "def", "createEmptyRepo", "(", "path", ",", "tool", "=", "None", ")", ":", "# Check that the requested tool is supported", "if", "not", "haveGit", "(", ")", "or", "tool", "not", "in", "(", "None", ",", "\"git\"", ")", ":", "raise", "Exception", "(", "\"unable to create %r repository\"", "%", "tool", ")", "# Create a repository at the specified location", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "len", "(", "os", ".", "listdir", "(", "path", ")", ")", ":", "raise", "Exception", "(", "\"refusing to create repository in non-empty directory\"", ")", "os", ".", "makedirs", "(", "path", ")", "import", "git", "return", "git", ".", "Repo", ".", "init", "(", "path", ")" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Utilities/Scripts/SlicerWizard/Utilities.py#L298-L334
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/msvs_emulation.py
python
PrecompiledHeader.GetObjDependencies
(self, sources, objs)
return []
Given a list of sources files and the corresponding object files, returns a list of the pch files that should be depended upon. The additional wrapping in the return value is for interface compatability with make.py on Mac, and xcode_emulation.py.
Given a list of sources files and the corresponding object files, returns a list of the pch files that should be depended upon. The additional wrapping in the return value is for interface compatability with make.py on Mac, and xcode_emulation.py.
[ "Given", "a", "list", "of", "sources", "files", "and", "the", "corresponding", "object", "files", "returns", "a", "list", "of", "the", "pch", "files", "that", "should", "be", "depended", "upon", ".", "The", "additional", "wrapping", "in", "the", "return", "value", "is", "for", "interface", "compatability", "with", "make", ".", "py", "on", "Mac", "and", "xcode_emulation", ".", "py", "." ]
def GetObjDependencies(self, sources, objs): """Given a list of sources files and the corresponding object files, returns a list of the pch files that should be depended upon. The additional wrapping in the return value is for interface compatability with make.py on Mac, and xcode_emulation.py.""" if not self._PchHeader(): return [] source = self._PchSource() assert source pch_ext = os.path.splitext(self._PchSource())[1] for source in sources: if _LanguageMatchesForPch(os.path.splitext(source)[1], pch_ext): return [(None, None, self._PchOutput())] return []
[ "def", "GetObjDependencies", "(", "self", ",", "sources", ",", "objs", ")", ":", "if", "not", "self", ".", "_PchHeader", "(", ")", ":", "return", "[", "]", "source", "=", "self", ".", "_PchSource", "(", ")", "assert", "source", "pch_ext", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "_PchSource", "(", ")", ")", "[", "1", "]", "for", "source", "in", "sources", ":", "if", "_LanguageMatchesForPch", "(", "os", ".", "path", ".", "splitext", "(", "source", ")", "[", "1", "]", ",", "pch_ext", ")", ":", "return", "[", "(", "None", ",", "None", ",", "self", ".", "_PchOutput", "(", ")", ")", "]", "return", "[", "]" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/msvs_emulation.py#L577-L590
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
syzygy/scripts/graph/graph.py
python
GenerateGraph
(info, file_name, width, height, dpi, data_start=None, categorize=None)
Generates a graph from collected information. Args: info: a dictionary of pid->_ProcessFault instances. file_name: output file name, or None to show the graph interactively. width: the width (in inches) of the generated graph. height: the height (in inches) of the generated graph. dpi: the DPI of the generated graph. data_start: dict of of rva_start addresses keyed by module name (default: {}). categorize: function that receives (process_id, module_id, thread_id) and returns a key used to group faults (default: None).
Generates a graph from collected information.
[ "Generates", "a", "graph", "from", "collected", "information", "." ]
def GenerateGraph(info, file_name, width, height, dpi, data_start=None, categorize=None): """Generates a graph from collected information. Args: info: a dictionary of pid->_ProcessFault instances. file_name: output file name, or None to show the graph interactively. width: the width (in inches) of the generated graph. height: the height (in inches) of the generated graph. dpi: the DPI of the generated graph. data_start: dict of of rva_start addresses keyed by module name (default: {}). categorize: function that receives (process_id, module_id, thread_id) and returns a key used to group faults (default: None). """ fig = pyplot.figure(figsize=(width, height), dpi=dpi) ax = fig.add_axes([0.1, 0.2, 0.75, 0.7]) ax_cpf = fig.add_axes([0.1, 0.1, 0.75, 0.1]) ax_bar = fig.add_axes([0.85, 0.1, 0.05, 0.8]) if categorize == None: categorize = lambda p, m, t: 0 if data_start == None: data_start = {} # Get the earliest start time across all processes. start_time = None for process_faults in info.itervalues(): if not start_time or process_faults.start_time < start_time: start_time = process_faults.start_time max_addr = 0 max_time = 0 fault_times = {} start_times = {} faults = {} for fault_type in ['hard_code', 'hard_data', 'soft_code', 'soft_data']: faults[fault_type] = {} # Categorize the faults and calculate summary information. for process_faults in info.itervalues(): process_id = process_faults.process_id for module_faults in process_faults.modules.itervalues(): module_id = module_faults.file_name for (thread_id, time, kind, address, size) in module_faults.page_faults: time = time + process_faults.start_time - start_time max_addr = max(max_addr, address + size) max_time = max(max_time, time) # Categorize the fault event. category = categorize(process_id, module_id, thread_id) # Classify the fault type. hard = kind in ['HardFault', 'Hard'] code = True if data_start.has_key(module_id): code = address < data_start[module_id] fault_type = ('hard_' if hard else 'soft_') fault_type += ('code' if code else 'data') if not faults[fault_type].has_key(category): faults[fault_type][category] = [] faults[fault_type][category].append((time, address)) # Keep track of earliest start time per category. if not start_times.has_key(category): start_times[category] = time start_times[category] = min(time, start_times[category]) # We are only interested in hard code faults for the cumulative # display. So keep track of the set of unique times across all # categories for this fault type. if hard and code: fault_times[time] = True # A small set of preferred colors that we use for consistent coloring. When # this is exhausted we start generating random colors. pref_colors = ['red', 'blue', 'green', 'orange', 'magenta', 'brown'] # Get the categories as a list, sorted by start time. categories = map(lambda x: x[0], sorted(start_times.items(), lambda x, y: cmp(x[1], y[1]))) # Assign category colors. category_colors = {} pref_color_index = 0 for category in categories: if pref_color_index < len(pref_colors): category_colors[category] = pref_colors[pref_color_index] else: category_colors[category] = (random.random(), random.random(), random.random()) pref_color_index += 1 # Display data_start lines as horizontal pale yellow marker lines. for module_id, rva in data_start.items(): if rva < max_addr: ax.axhline(y=(rva), color=WhitenColor('y', 0.8), zorder=0) # Plot the fault events. size_data = 3 size_code = 5 marker_soft = 'o' marker_hard = 's' data_whiten = 0.5 soft_whiten = 0.7 for category in categories: color = WhitenColor(category_colors[category], 1 - data_whiten * soft_whiten) for (time, address) in faults['soft_data'].get(category, []): ax.plot(time, address, markeredgecolor=color, markeredgewidth=0.5, marker=marker_soft, markersize=size_data, markerfacecolor='None', zorder=1) color = WhitenColor(category_colors[category], 1 - data_whiten) for (time, address) in faults['hard_data'].get(category, []): ax.plot(time, address, markeredgecolor=color, markeredgewidth=0.5, marker=marker_hard, markersize=size_data, markerfacecolor='None', zorder=2) color = WhitenColor(category_colors[category], 1 - soft_whiten) for (time, address) in faults['soft_code'].get(category, []): ax.plot(time, address, markeredgecolor=color, markeredgewidth=0.5, marker=marker_soft, markersize=size_code, markerfacecolor='None', zorder=3) color = category_colors[category] for (time, address) in faults['hard_code'].get(category, []): ax.plot(time, address, markeredgecolor=color, markeredgewidth=0.5, marker=marker_hard, markersize=size_code, markerfacecolor='None', zorder=4) # Build and plot the cumulative hard_code plots. fault_times = sorted(fault_times.keys()) fault_counts = [0] * len(fault_times) zorder = 0 for category in categories: fault_sum = 0 fault_dict = {} for (time, address) in faults['hard_code'].get(category, []): fault_dict[time] = fault_dict.get(time, 0) + 1 fault_sum = 0 for time_index in range(len(fault_counts)): time = fault_times[time_index] delta = fault_dict.get(time, 0) fault_sum += delta fault_counts[time_index] += fault_sum ax_cpf.fill_between(fault_times, fault_counts, color=category_colors[category], zorder=zorder) zorder -= 1 # Display the process start times as vertical yellow marker lines. for process_faults in info.itervalues(): time = process_faults.start_time - start_time if time > 0: ax.axvline(x=(process_faults.start_time - start_time), color="y", label="PID: %d" % process_faults.process_id, zorder=5) ax_cpf.axvline(x=(process_faults.start_time - start_time), color="y", zorder=5) # Do the bar plots of total faults. hard = 0 soft = 0 hard_code = 0 hard_data = 0 for category in categories: hc = len(faults['hard_code'].get(category, [])) hd = len(faults['hard_data'].get(category, [])) soft += len(faults['soft_code'].get(category, [])) + \ len(faults['soft_data'].get(category, [])) hard += hc + hd hard_code += hc hard_data += hd PlotStackedBar(ax_bar, 0.5, (hard_code, hard_data), labels=('hard code', 'hard data'), annotate=' (%d)') PlotStackedBar(ax_bar, 1.5, (hard, soft), labels=('hard', 'soft'), annotate=' (%d)') ax_cpf.set_xlim(0, max_time) ax_cpf.set_xlabel('Time (s)') ax_cpf.set_ylabel('Hard code faults') ax.set_xlim(0, max_time) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.set_ylabel('Address') ax.set_ylim(0, max_addr) ax.yaxis.tick_left() formatter = ticker.FormatStrFormatter('0x%08X') ax.yaxis.set_major_formatter(formatter) for label in ax.yaxis.get_ticklabels(): label.set_rotation(-45) label.set_verticalalignment('bottom') ax_bar.set_ylim(0, 100.0) ax_bar.yaxis.tick_right() ax_bar.yaxis.set_major_formatter(ticker.FormatStrFormatter('%d%%')) ax_bar.set_xlim(0, 2) ax_bar.xaxis.set_major_locator(ticker.NullLocator()) ax_bar.xaxis.set_major_formatter(ticker.NullFormatter()) if file_name: pyplot.savefig(file_name) else: pyplot.show()
[ "def", "GenerateGraph", "(", "info", ",", "file_name", ",", "width", ",", "height", ",", "dpi", ",", "data_start", "=", "None", ",", "categorize", "=", "None", ")", ":", "fig", "=", "pyplot", ".", "figure", "(", "figsize", "=", "(", "width", ",", "height", ")", ",", "dpi", "=", "dpi", ")", "ax", "=", "fig", ".", "add_axes", "(", "[", "0.1", ",", "0.2", ",", "0.75", ",", "0.7", "]", ")", "ax_cpf", "=", "fig", ".", "add_axes", "(", "[", "0.1", ",", "0.1", ",", "0.75", ",", "0.1", "]", ")", "ax_bar", "=", "fig", ".", "add_axes", "(", "[", "0.85", ",", "0.1", ",", "0.05", ",", "0.8", "]", ")", "if", "categorize", "==", "None", ":", "categorize", "=", "lambda", "p", ",", "m", ",", "t", ":", "0", "if", "data_start", "==", "None", ":", "data_start", "=", "{", "}", "# Get the earliest start time across all processes.", "start_time", "=", "None", "for", "process_faults", "in", "info", ".", "itervalues", "(", ")", ":", "if", "not", "start_time", "or", "process_faults", ".", "start_time", "<", "start_time", ":", "start_time", "=", "process_faults", ".", "start_time", "max_addr", "=", "0", "max_time", "=", "0", "fault_times", "=", "{", "}", "start_times", "=", "{", "}", "faults", "=", "{", "}", "for", "fault_type", "in", "[", "'hard_code'", ",", "'hard_data'", ",", "'soft_code'", ",", "'soft_data'", "]", ":", "faults", "[", "fault_type", "]", "=", "{", "}", "# Categorize the faults and calculate summary information.", "for", "process_faults", "in", "info", ".", "itervalues", "(", ")", ":", "process_id", "=", "process_faults", ".", "process_id", "for", "module_faults", "in", "process_faults", ".", "modules", ".", "itervalues", "(", ")", ":", "module_id", "=", "module_faults", ".", "file_name", "for", "(", "thread_id", ",", "time", ",", "kind", ",", "address", ",", "size", ")", "in", "module_faults", ".", "page_faults", ":", "time", "=", "time", "+", "process_faults", ".", "start_time", "-", "start_time", "max_addr", "=", "max", "(", "max_addr", ",", "address", "+", "size", ")", "max_time", "=", "max", "(", "max_time", ",", "time", ")", "# Categorize the fault event.", "category", "=", "categorize", "(", "process_id", ",", "module_id", ",", "thread_id", ")", "# Classify the fault type.", "hard", "=", "kind", "in", "[", "'HardFault'", ",", "'Hard'", "]", "code", "=", "True", "if", "data_start", ".", "has_key", "(", "module_id", ")", ":", "code", "=", "address", "<", "data_start", "[", "module_id", "]", "fault_type", "=", "(", "'hard_'", "if", "hard", "else", "'soft_'", ")", "fault_type", "+=", "(", "'code'", "if", "code", "else", "'data'", ")", "if", "not", "faults", "[", "fault_type", "]", ".", "has_key", "(", "category", ")", ":", "faults", "[", "fault_type", "]", "[", "category", "]", "=", "[", "]", "faults", "[", "fault_type", "]", "[", "category", "]", ".", "append", "(", "(", "time", ",", "address", ")", ")", "# Keep track of earliest start time per category.", "if", "not", "start_times", ".", "has_key", "(", "category", ")", ":", "start_times", "[", "category", "]", "=", "time", "start_times", "[", "category", "]", "=", "min", "(", "time", ",", "start_times", "[", "category", "]", ")", "# We are only interested in hard code faults for the cumulative", "# display. So keep track of the set of unique times across all", "# categories for this fault type.", "if", "hard", "and", "code", ":", "fault_times", "[", "time", "]", "=", "True", "# A small set of preferred colors that we use for consistent coloring. When", "# this is exhausted we start generating random colors.", "pref_colors", "=", "[", "'red'", ",", "'blue'", ",", "'green'", ",", "'orange'", ",", "'magenta'", ",", "'brown'", "]", "# Get the categories as a list, sorted by start time.", "categories", "=", "map", "(", "lambda", "x", ":", "x", "[", "0", "]", ",", "sorted", "(", "start_times", ".", "items", "(", ")", ",", "lambda", "x", ",", "y", ":", "cmp", "(", "x", "[", "1", "]", ",", "y", "[", "1", "]", ")", ")", ")", "# Assign category colors.", "category_colors", "=", "{", "}", "pref_color_index", "=", "0", "for", "category", "in", "categories", ":", "if", "pref_color_index", "<", "len", "(", "pref_colors", ")", ":", "category_colors", "[", "category", "]", "=", "pref_colors", "[", "pref_color_index", "]", "else", ":", "category_colors", "[", "category", "]", "=", "(", "random", ".", "random", "(", ")", ",", "random", ".", "random", "(", ")", ",", "random", ".", "random", "(", ")", ")", "pref_color_index", "+=", "1", "# Display data_start lines as horizontal pale yellow marker lines.", "for", "module_id", ",", "rva", "in", "data_start", ".", "items", "(", ")", ":", "if", "rva", "<", "max_addr", ":", "ax", ".", "axhline", "(", "y", "=", "(", "rva", ")", ",", "color", "=", "WhitenColor", "(", "'y'", ",", "0.8", ")", ",", "zorder", "=", "0", ")", "# Plot the fault events.", "size_data", "=", "3", "size_code", "=", "5", "marker_soft", "=", "'o'", "marker_hard", "=", "'s'", "data_whiten", "=", "0.5", "soft_whiten", "=", "0.7", "for", "category", "in", "categories", ":", "color", "=", "WhitenColor", "(", "category_colors", "[", "category", "]", ",", "1", "-", "data_whiten", "*", "soft_whiten", ")", "for", "(", "time", ",", "address", ")", "in", "faults", "[", "'soft_data'", "]", ".", "get", "(", "category", ",", "[", "]", ")", ":", "ax", ".", "plot", "(", "time", ",", "address", ",", "markeredgecolor", "=", "color", ",", "markeredgewidth", "=", "0.5", ",", "marker", "=", "marker_soft", ",", "markersize", "=", "size_data", ",", "markerfacecolor", "=", "'None'", ",", "zorder", "=", "1", ")", "color", "=", "WhitenColor", "(", "category_colors", "[", "category", "]", ",", "1", "-", "data_whiten", ")", "for", "(", "time", ",", "address", ")", "in", "faults", "[", "'hard_data'", "]", ".", "get", "(", "category", ",", "[", "]", ")", ":", "ax", ".", "plot", "(", "time", ",", "address", ",", "markeredgecolor", "=", "color", ",", "markeredgewidth", "=", "0.5", ",", "marker", "=", "marker_hard", ",", "markersize", "=", "size_data", ",", "markerfacecolor", "=", "'None'", ",", "zorder", "=", "2", ")", "color", "=", "WhitenColor", "(", "category_colors", "[", "category", "]", ",", "1", "-", "soft_whiten", ")", "for", "(", "time", ",", "address", ")", "in", "faults", "[", "'soft_code'", "]", ".", "get", "(", "category", ",", "[", "]", ")", ":", "ax", ".", "plot", "(", "time", ",", "address", ",", "markeredgecolor", "=", "color", ",", "markeredgewidth", "=", "0.5", ",", "marker", "=", "marker_soft", ",", "markersize", "=", "size_code", ",", "markerfacecolor", "=", "'None'", ",", "zorder", "=", "3", ")", "color", "=", "category_colors", "[", "category", "]", "for", "(", "time", ",", "address", ")", "in", "faults", "[", "'hard_code'", "]", ".", "get", "(", "category", ",", "[", "]", ")", ":", "ax", ".", "plot", "(", "time", ",", "address", ",", "markeredgecolor", "=", "color", ",", "markeredgewidth", "=", "0.5", ",", "marker", "=", "marker_hard", ",", "markersize", "=", "size_code", ",", "markerfacecolor", "=", "'None'", ",", "zorder", "=", "4", ")", "# Build and plot the cumulative hard_code plots.", "fault_times", "=", "sorted", "(", "fault_times", ".", "keys", "(", ")", ")", "fault_counts", "=", "[", "0", "]", "*", "len", "(", "fault_times", ")", "zorder", "=", "0", "for", "category", "in", "categories", ":", "fault_sum", "=", "0", "fault_dict", "=", "{", "}", "for", "(", "time", ",", "address", ")", "in", "faults", "[", "'hard_code'", "]", ".", "get", "(", "category", ",", "[", "]", ")", ":", "fault_dict", "[", "time", "]", "=", "fault_dict", ".", "get", "(", "time", ",", "0", ")", "+", "1", "fault_sum", "=", "0", "for", "time_index", "in", "range", "(", "len", "(", "fault_counts", ")", ")", ":", "time", "=", "fault_times", "[", "time_index", "]", "delta", "=", "fault_dict", ".", "get", "(", "time", ",", "0", ")", "fault_sum", "+=", "delta", "fault_counts", "[", "time_index", "]", "+=", "fault_sum", "ax_cpf", ".", "fill_between", "(", "fault_times", ",", "fault_counts", ",", "color", "=", "category_colors", "[", "category", "]", ",", "zorder", "=", "zorder", ")", "zorder", "-=", "1", "# Display the process start times as vertical yellow marker lines.", "for", "process_faults", "in", "info", ".", "itervalues", "(", ")", ":", "time", "=", "process_faults", ".", "start_time", "-", "start_time", "if", "time", ">", "0", ":", "ax", ".", "axvline", "(", "x", "=", "(", "process_faults", ".", "start_time", "-", "start_time", ")", ",", "color", "=", "\"y\"", ",", "label", "=", "\"PID: %d\"", "%", "process_faults", ".", "process_id", ",", "zorder", "=", "5", ")", "ax_cpf", ".", "axvline", "(", "x", "=", "(", "process_faults", ".", "start_time", "-", "start_time", ")", ",", "color", "=", "\"y\"", ",", "zorder", "=", "5", ")", "# Do the bar plots of total faults.", "hard", "=", "0", "soft", "=", "0", "hard_code", "=", "0", "hard_data", "=", "0", "for", "category", "in", "categories", ":", "hc", "=", "len", "(", "faults", "[", "'hard_code'", "]", ".", "get", "(", "category", ",", "[", "]", ")", ")", "hd", "=", "len", "(", "faults", "[", "'hard_data'", "]", ".", "get", "(", "category", ",", "[", "]", ")", ")", "soft", "+=", "len", "(", "faults", "[", "'soft_code'", "]", ".", "get", "(", "category", ",", "[", "]", ")", ")", "+", "len", "(", "faults", "[", "'soft_data'", "]", ".", "get", "(", "category", ",", "[", "]", ")", ")", "hard", "+=", "hc", "+", "hd", "hard_code", "+=", "hc", "hard_data", "+=", "hd", "PlotStackedBar", "(", "ax_bar", ",", "0.5", ",", "(", "hard_code", ",", "hard_data", ")", ",", "labels", "=", "(", "'hard code'", ",", "'hard data'", ")", ",", "annotate", "=", "' (%d)'", ")", "PlotStackedBar", "(", "ax_bar", ",", "1.5", ",", "(", "hard", ",", "soft", ")", ",", "labels", "=", "(", "'hard'", ",", "'soft'", ")", ",", "annotate", "=", "' (%d)'", ")", "ax_cpf", ".", "set_xlim", "(", "0", ",", "max_time", ")", "ax_cpf", ".", "set_xlabel", "(", "'Time (s)'", ")", "ax_cpf", ".", "set_ylabel", "(", "'Hard code faults'", ")", "ax", ".", "set_xlim", "(", "0", ",", "max_time", ")", "ax", ".", "xaxis", ".", "set_major_formatter", "(", "ticker", ".", "NullFormatter", "(", ")", ")", "ax", ".", "set_ylabel", "(", "'Address'", ")", "ax", ".", "set_ylim", "(", "0", ",", "max_addr", ")", "ax", ".", "yaxis", ".", "tick_left", "(", ")", "formatter", "=", "ticker", ".", "FormatStrFormatter", "(", "'0x%08X'", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "formatter", ")", "for", "label", "in", "ax", ".", "yaxis", ".", "get_ticklabels", "(", ")", ":", "label", ".", "set_rotation", "(", "-", "45", ")", "label", ".", "set_verticalalignment", "(", "'bottom'", ")", "ax_bar", ".", "set_ylim", "(", "0", ",", "100.0", ")", "ax_bar", ".", "yaxis", ".", "tick_right", "(", ")", "ax_bar", ".", "yaxis", ".", "set_major_formatter", "(", "ticker", ".", "FormatStrFormatter", "(", "'%d%%'", ")", ")", "ax_bar", ".", "set_xlim", "(", "0", ",", "2", ")", "ax_bar", ".", "xaxis", ".", "set_major_locator", "(", "ticker", ".", "NullLocator", "(", ")", ")", "ax_bar", ".", "xaxis", ".", "set_major_formatter", "(", "ticker", ".", "NullFormatter", "(", ")", ")", "if", "file_name", ":", "pyplot", ".", "savefig", "(", "file_name", ")", "else", ":", "pyplot", ".", "show", "(", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/syzygy/scripts/graph/graph.py#L333-L540
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/prompt.py
python
_prompt_r
(attr)
return '\r'
A carriage return.
A carriage return.
[ "A", "carriage", "return", "." ]
def _prompt_r(attr): "A carriage return." return '\r'
[ "def", "_prompt_r", "(", "attr", ")", ":", "return", "'\\r'" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/prompt.py#L66-L68
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/xcodeproj_file.py
python
PBXProject.RootGroupsTakeOverOnlyChildren
(self, recurse=False)
Calls TakeOverOnlyChild for all groups in the main group.
Calls TakeOverOnlyChild for all groups in the main group.
[ "Calls", "TakeOverOnlyChild", "for", "all", "groups", "in", "the", "main", "group", "." ]
def RootGroupsTakeOverOnlyChildren(self, recurse=False): """Calls TakeOverOnlyChild for all groups in the main group.""" for group in self._properties['mainGroup']._properties['children']: if isinstance(group, PBXGroup): group.TakeOverOnlyChild(recurse)
[ "def", "RootGroupsTakeOverOnlyChildren", "(", "self", ",", "recurse", "=", "False", ")", ":", "for", "group", "in", "self", ".", "_properties", "[", "'mainGroup'", "]", ".", "_properties", "[", "'children'", "]", ":", "if", "isinstance", "(", "group", ",", "PBXGroup", ")", ":", "group", ".", "TakeOverOnlyChild", "(", "recurse", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/xcodeproj_file.py#L2694-L2699
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py
python
IMAP4.xatom
(self, name, *args)
return self._simple_command(name, *args)
Allow simple extension commands notified by server in CAPABILITY response. Assumes command is legal in current state. (typ, [data]) = <instance>.xatom(name, arg, ...) Returns response appropriate to extension command `name'.
Allow simple extension commands notified by server in CAPABILITY response.
[ "Allow", "simple", "extension", "commands", "notified", "by", "server", "in", "CAPABILITY", "response", "." ]
def xatom(self, name, *args): """Allow simple extension commands notified by server in CAPABILITY response. Assumes command is legal in current state. (typ, [data]) = <instance>.xatom(name, arg, ...) Returns response appropriate to extension command `name'. """ name = name.upper() #if not name in self.capabilities: # Let the server decide! # raise self.error('unknown extension command: %s' % name) if not name in Commands: Commands[name] = (self.state,) return self._simple_command(name, *args)
[ "def", "xatom", "(", "self", ",", "name", ",", "*", "args", ")", ":", "name", "=", "name", ".", "upper", "(", ")", "#if not name in self.capabilities: # Let the server decide!", "# raise self.error('unknown extension command: %s' % name)", "if", "not", "name", "in", "Commands", ":", "Commands", "[", "name", "]", "=", "(", "self", ".", "state", ",", ")", "return", "self", ".", "_simple_command", "(", "name", ",", "*", "args", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py#L895-L910
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
source/engine/strategy_engine.py
python
StrategyEngine.get_all_positions
(self)
return list(self.positions.values())
Get all position data.
Get all position data.
[ "Get", "all", "position", "data", "." ]
def get_all_positions(self): """ Get all position data. """ return list(self.positions.values())
[ "def", "get_all_positions", "(", "self", ")", ":", "return", "list", "(", "self", ".", "positions", ".", "values", "(", ")", ")" ]
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/source/engine/strategy_engine.py#L913-L917
alibaba/MNN
c4d9566171d589c3ded23aa18ffb197016995a12
pymnn/pip_package/MNN/tools/mnnconvert.py
python
main
()
return 0
main funcion
main funcion
[ "main", "funcion" ]
def main(): """ main funcion """ Tools.mnnconvert(sys.argv) arg_dict = parse_args() if mnn_logger is not None: if "modelFile" not in arg_dict.keys() or "MNNModel" not in arg_dict.keys(): return 0 log_dict = {} log_dict["tool"] = "mnnconvert_python" log_dict["model_guid"] = MNN.get_model_uuid(arg_dict["MNNModel"]) src_model_size = os.path.getsize(arg_dict["modelFile"]) / 1024.0 / 1024.0 dst_model_size = os.path.getsize(arg_dict["MNNModel"]) / 1024.0 / 1024.0 compress_rate = src_model_size / dst_model_size arg_dict.pop("modelFile") arg_dict.pop("MNNModel") log_dict["detail"] = {"args": arg_dict, "src_model_size": src_model_size, "dst_model_size": dst_model_size, "compress_rate": compress_rate} mnn_logger.put_log(log_dict, "convert") return 0
[ "def", "main", "(", ")", ":", "Tools", ".", "mnnconvert", "(", "sys", ".", "argv", ")", "arg_dict", "=", "parse_args", "(", ")", "if", "mnn_logger", "is", "not", "None", ":", "if", "\"modelFile\"", "not", "in", "arg_dict", ".", "keys", "(", ")", "or", "\"MNNModel\"", "not", "in", "arg_dict", ".", "keys", "(", ")", ":", "return", "0", "log_dict", "=", "{", "}", "log_dict", "[", "\"tool\"", "]", "=", "\"mnnconvert_python\"", "log_dict", "[", "\"model_guid\"", "]", "=", "MNN", ".", "get_model_uuid", "(", "arg_dict", "[", "\"MNNModel\"", "]", ")", "src_model_size", "=", "os", ".", "path", ".", "getsize", "(", "arg_dict", "[", "\"modelFile\"", "]", ")", "/", "1024.0", "/", "1024.0", "dst_model_size", "=", "os", ".", "path", ".", "getsize", "(", "arg_dict", "[", "\"MNNModel\"", "]", ")", "/", "1024.0", "/", "1024.0", "compress_rate", "=", "src_model_size", "/", "dst_model_size", "arg_dict", ".", "pop", "(", "\"modelFile\"", ")", "arg_dict", ".", "pop", "(", "\"MNNModel\"", ")", "log_dict", "[", "\"detail\"", "]", "=", "{", "\"args\"", ":", "arg_dict", ",", "\"src_model_size\"", ":", "src_model_size", ",", "\"dst_model_size\"", ":", "dst_model_size", ",", "\"compress_rate\"", ":", "compress_rate", "}", "mnn_logger", ".", "put_log", "(", "log_dict", ",", "\"convert\"", ")", "return", "0" ]
https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/tools/mnnconvert.py#L35-L56
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlNode.addContent
(self, content)
Append the extra substring to the node content. NOTE: In contrast to xmlNodeSetContent(), @content is supposed to be raw text, so unescaped XML special chars are allowed, entity references are not supported.
Append the extra substring to the node content. NOTE: In contrast to xmlNodeSetContent(),
[ "Append", "the", "extra", "substring", "to", "the", "node", "content", ".", "NOTE", ":", "In", "contrast", "to", "xmlNodeSetContent", "()" ]
def addContent(self, content): """Append the extra substring to the node content. NOTE: In contrast to xmlNodeSetContent(), @content is supposed to be raw text, so unescaped XML special chars are allowed, entity references are not supported. """ libxml2mod.xmlNodeAddContent(self._o, content)
[ "def", "addContent", "(", "self", ",", "content", ")", ":", "libxml2mod", ".", "xmlNodeAddContent", "(", "self", ".", "_o", ",", "content", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L2312-L2317
rampageX/firmware-mod-kit
c94cd6aeee50d92ec5280a6dba6d74828fd3606b
src/binwalk-2.1.1/src/binwalk/core/module.py
python
process_kwargs
(obj, kwargs)
return kwargs
Convenience wrapper around binwalk.core.module.Modules.kwargs. @obj - The class object (an instance of a sub-class of binwalk.core.module.Module). @kwargs - The kwargs provided to the object's __init__ method. Returns None.
Convenience wrapper around binwalk.core.module.Modules.kwargs.
[ "Convenience", "wrapper", "around", "binwalk", ".", "core", ".", "module", ".", "Modules", ".", "kwargs", "." ]
def process_kwargs(obj, kwargs): ''' Convenience wrapper around binwalk.core.module.Modules.kwargs. @obj - The class object (an instance of a sub-class of binwalk.core.module.Module). @kwargs - The kwargs provided to the object's __init__ method. Returns None. ''' with Modules() as m: kwargs = m.kwargs(obj, kwargs) return kwargs
[ "def", "process_kwargs", "(", "obj", ",", "kwargs", ")", ":", "with", "Modules", "(", ")", "as", "m", ":", "kwargs", "=", "m", ".", "kwargs", "(", "obj", ",", "kwargs", ")", "return", "kwargs" ]
https://github.com/rampageX/firmware-mod-kit/blob/c94cd6aeee50d92ec5280a6dba6d74828fd3606b/src/binwalk-2.1.1/src/binwalk/core/module.py#L930-L941
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/operators/activation.py
python
Elu
(inputs, alpha=1.0, **kwargs)
return output
Exponential Linear Unit function, introduces by `[Clevert et.al, 2015] <https://arxiv.org/abs/1511.07289>`_. Parameters ---------- inputs : Tensor The input tensor. alpha : float The alpha. Returns ------- Tensor The output tensor, calculated as: |elu_function|
Exponential Linear Unit function, introduces by `[Clevert et.al, 2015] <https://arxiv.org/abs/1511.07289>`_.
[ "Exponential", "Linear", "Unit", "function", "introduces", "by", "[", "Clevert", "et", ".", "al", "2015", "]", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1511", ".", "07289", ">", "_", "." ]
def Elu(inputs, alpha=1.0, **kwargs): """Exponential Linear Unit function, introduces by `[Clevert et.al, 2015] <https://arxiv.org/abs/1511.07289>`_. Parameters ---------- inputs : Tensor The input tensor. alpha : float The alpha. Returns ------- Tensor The output tensor, calculated as: |elu_function| """ CheckInputs(inputs, 1) arguments = ParseArguments(locals()) output = Tensor.CreateOperator(nout=1, op_type='Elu', **arguments) if inputs.shape is not None: output.shape = inputs.shape[:] return output
[ "def", "Elu", "(", "inputs", ",", "alpha", "=", "1.0", ",", "*", "*", "kwargs", ")", ":", "CheckInputs", "(", "inputs", ",", "1", ")", "arguments", "=", "ParseArguments", "(", "locals", "(", ")", ")", "output", "=", "Tensor", ".", "CreateOperator", "(", "nout", "=", "1", ",", "op_type", "=", "'Elu'", ",", "*", "*", "arguments", ")", "if", "inputs", ".", "shape", "is", "not", "None", ":", "output", ".", "shape", "=", "inputs", ".", "shape", "[", ":", "]", "return", "output" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/operators/activation.py#L95-L119
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/xrc.py
python
XmlResource.CompareVersion
(*args, **kwargs)
return _xrc.XmlResource_CompareVersion(*args, **kwargs)
CompareVersion(self, int major, int minor, int release, int revision) -> int
CompareVersion(self, int major, int minor, int release, int revision) -> int
[ "CompareVersion", "(", "self", "int", "major", "int", "minor", "int", "release", "int", "revision", ")", "-", ">", "int" ]
def CompareVersion(*args, **kwargs): """CompareVersion(self, int major, int minor, int release, int revision) -> int""" return _xrc.XmlResource_CompareVersion(*args, **kwargs)
[ "def", "CompareVersion", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlResource_CompareVersion", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/xrc.py#L196-L198
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/sumolib/geomhelper.py
python
polygonOffsetWithMinimumDistanceToPoint
(point, polygon, perpendicular=False)
return polygonOffsetAndDistanceToPoint(point, polygon, perpendicular)[0]
Return the offset from the polygon start where the distance to the point is minimal
Return the offset from the polygon start where the distance to the point is minimal
[ "Return", "the", "offset", "from", "the", "polygon", "start", "where", "the", "distance", "to", "the", "point", "is", "minimal" ]
def polygonOffsetWithMinimumDistanceToPoint(point, polygon, perpendicular=False): """Return the offset from the polygon start where the distance to the point is minimal""" return polygonOffsetAndDistanceToPoint(point, polygon, perpendicular)[0]
[ "def", "polygonOffsetWithMinimumDistanceToPoint", "(", "point", ",", "polygon", ",", "perpendicular", "=", "False", ")", ":", "return", "polygonOffsetAndDistanceToPoint", "(", "point", ",", "polygon", ",", "perpendicular", ")", "[", "0", "]" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/sumolib/geomhelper.py#L108-L110
mysql/mysql-router
cc0179f982bb9739a834eb6fd205a56224616133
ext/gmock/scripts/upload.py
python
VersionControlSystem.GetUnknownFiles
(self)
Return a list of files unknown to the VCS.
Return a list of files unknown to the VCS.
[ "Return", "a", "list", "of", "files", "unknown", "to", "the", "VCS", "." ]
def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__)
[ "def", "GetUnknownFiles", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__", ")" ]
https://github.com/mysql/mysql-router/blob/cc0179f982bb9739a834eb6fd205a56224616133/ext/gmock/scripts/upload.py#L608-L611
jiangxiluning/FOTS.PyTorch
b1851c170b4f1ad18406766352cb5171648ce603
FOTS/utils/eval_tools/icdar2015/script.py
python
default_evaluation_params
()
return { 'IOU_CONSTRAINT' :0.5, 'AREA_PRECISION_CONSTRAINT' :0.5, 'WORD_SPOTTING' :False, 'MIN_LENGTH_CARE_WORD' :3, 'GT_SAMPLE_NAME_2_ID':'gt_img_([0-9]+).txt', 'DET_SAMPLE_NAME_2_ID':'res_img_([0-9]+).txt', 'LTRB':False, #LTRB:2points(left,top,right,bottom) or 4 points(x1,y1,x2,y2,x3,y3,x4,y4) 'CRLF':False, # Lines are delimited by Windows CRLF format 'CONFIDENCES':False, #Detections must include confidence value. AP will be calculated, 'SPECIAL_CHARACTERS':'!?.:,*"()·[]/\'', 'ONLY_REMOVE_FIRST_LAST_CHARACTER' : True }
default_evaluation_params: Default parameters to use for the validation and evaluation.
default_evaluation_params: Default parameters to use for the validation and evaluation.
[ "default_evaluation_params", ":", "Default", "parameters", "to", "use", "for", "the", "validation", "and", "evaluation", "." ]
def default_evaluation_params(): """ default_evaluation_params: Default parameters to use for the validation and evaluation. """ return { 'IOU_CONSTRAINT' :0.5, 'AREA_PRECISION_CONSTRAINT' :0.5, 'WORD_SPOTTING' :False, 'MIN_LENGTH_CARE_WORD' :3, 'GT_SAMPLE_NAME_2_ID':'gt_img_([0-9]+).txt', 'DET_SAMPLE_NAME_2_ID':'res_img_([0-9]+).txt', 'LTRB':False, #LTRB:2points(left,top,right,bottom) or 4 points(x1,y1,x2,y2,x3,y3,x4,y4) 'CRLF':False, # Lines are delimited by Windows CRLF format 'CONFIDENCES':False, #Detections must include confidence value. AP will be calculated, 'SPECIAL_CHARACTERS':'!?.:,*"()·[]/\'', 'ONLY_REMOVE_FIRST_LAST_CHARACTER' : True }
[ "def", "default_evaluation_params", "(", ")", ":", "return", "{", "'IOU_CONSTRAINT'", ":", "0.5", ",", "'AREA_PRECISION_CONSTRAINT'", ":", "0.5", ",", "'WORD_SPOTTING'", ":", "False", ",", "'MIN_LENGTH_CARE_WORD'", ":", "3", ",", "'GT_SAMPLE_NAME_2_ID'", ":", "'gt_img_([0-9]+).txt'", ",", "'DET_SAMPLE_NAME_2_ID'", ":", "'res_img_([0-9]+).txt'", ",", "'LTRB'", ":", "False", ",", "#LTRB:2points(left,top,right,bottom) or 4 points(x1,y1,x2,y2,x3,y3,x4,y4)", "'CRLF'", ":", "False", ",", "# Lines are delimited by Windows CRLF format", "'CONFIDENCES'", ":", "False", ",", "#Detections must include confidence value. AP will be calculated,", "'SPECIAL_CHARACTERS'", ":", "'!?.:,*\"()·[]/\\'',", "", "'ONLY_REMOVE_FIRST_LAST_CHARACTER'", ":", "True", "}" ]
https://github.com/jiangxiluning/FOTS.PyTorch/blob/b1851c170b4f1ad18406766352cb5171648ce603/FOTS/utils/eval_tools/icdar2015/script.py#L27-L43
CaoWGG/TensorRT-YOLOv4
4d7c2edce99e8794a4cb4ea3540d51ce91158a36
onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py
python
Type.is_volatile_qualified
(self)
return conf.lib.clang_isVolatileQualifiedType(self)
Determine whether a Type has the "volatile" qualifier set. This does not look through typedefs that may have added "volatile" at a different level.
Determine whether a Type has the "volatile" qualifier set.
[ "Determine", "whether", "a", "Type", "has", "the", "volatile", "qualifier", "set", "." ]
def is_volatile_qualified(self): """Determine whether a Type has the "volatile" qualifier set. This does not look through typedefs that may have added "volatile" at a different level. """ return conf.lib.clang_isVolatileQualifiedType(self)
[ "def", "is_volatile_qualified", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isVolatileQualifiedType", "(", "self", ")" ]
https://github.com/CaoWGG/TensorRT-YOLOv4/blob/4d7c2edce99e8794a4cb4ea3540d51ce91158a36/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L2016-L2022
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/iam/connection.py
python
IAMConnection.list_saml_providers
(self)
return self.get_response('ListSAMLProviders', {}, list_marker='SAMLProviderList')
Lists the SAML providers in the account. This operation requires `Signature Version 4`_.
Lists the SAML providers in the account. This operation requires `Signature Version 4`_.
[ "Lists", "the", "SAML", "providers", "in", "the", "account", ".", "This", "operation", "requires", "Signature", "Version", "4", "_", "." ]
def list_saml_providers(self): """ Lists the SAML providers in the account. This operation requires `Signature Version 4`_. """ return self.get_response('ListSAMLProviders', {}, list_marker='SAMLProviderList')
[ "def", "list_saml_providers", "(", "self", ")", ":", "return", "self", ".", "get_response", "(", "'ListSAMLProviders'", ",", "{", "}", ",", "list_marker", "=", "'SAMLProviderList'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/iam/connection.py#L1438-L1443
microsoft/LightGBM
904b2d5158703c4900b68008617951dd2f9ff21b
python-package/lightgbm/basic.py
python
Dataset.get_init_score
(self)
return self.init_score
Get the initial score of the Dataset. Returns ------- init_score : numpy array or None Init score of Booster.
Get the initial score of the Dataset.
[ "Get", "the", "initial", "score", "of", "the", "Dataset", "." ]
def get_init_score(self): """Get the initial score of the Dataset. Returns ------- init_score : numpy array or None Init score of Booster. """ if self.init_score is None: self.init_score = self.get_field('init_score') return self.init_score
[ "def", "get_init_score", "(", "self", ")", ":", "if", "self", ".", "init_score", "is", "None", ":", "self", ".", "init_score", "=", "self", ".", "get_field", "(", "'init_score'", ")", "return", "self", ".", "init_score" ]
https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/python-package/lightgbm/basic.py#L2277-L2287
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
llvm/utils/lit/lit/worker.py
python
execute
(test)
return test
Run one test in a multiprocessing.Pool Side effects in this function and functions it calls are not visible in the main lit process. Arguments and results of this function are pickled, so they should be cheap to copy.
Run one test in a multiprocessing.Pool
[ "Run", "one", "test", "in", "a", "multiprocessing", ".", "Pool" ]
def execute(test): """Run one test in a multiprocessing.Pool Side effects in this function and functions it calls are not visible in the main lit process. Arguments and results of this function are pickled, so they should be cheap to copy. """ with _get_parallelism_semaphore(test): result = _execute(test, _lit_config) test.setResult(result) return test
[ "def", "execute", "(", "test", ")", ":", "with", "_get_parallelism_semaphore", "(", "test", ")", ":", "result", "=", "_execute", "(", "test", ",", "_lit_config", ")", "test", ".", "setResult", "(", "result", ")", "return", "test" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/llvm/utils/lit/lit/worker.py#L35-L48
PaddlePaddle/PaddleOCR
b756bf5f8c90142e0d89d3db0163965c686b6ffe
ppocr/modeling/heads/rec_nrtr_head.py
python
TransformerEncoderLayer.forward
(self, src, src_mask=None, src_key_padding_mask=None)
return src
Pass the input through the endocder layer. Args: src: the sequnce to the encoder layer (required). src_mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional).
Pass the input through the endocder layer. Args: src: the sequnce to the encoder layer (required). src_mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional).
[ "Pass", "the", "input", "through", "the", "endocder", "layer", ".", "Args", ":", "src", ":", "the", "sequnce", "to", "the", "encoder", "layer", "(", "required", ")", ".", "src_mask", ":", "the", "mask", "for", "the", "src", "sequence", "(", "optional", ")", ".", "src_key_padding_mask", ":", "the", "mask", "for", "the", "src", "keys", "per", "batch", "(", "optional", ")", "." ]
def forward(self, src, src_mask=None, src_key_padding_mask=None): """Pass the input through the endocder layer. Args: src: the sequnce to the encoder layer (required). src_mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional). """ src2 = self.self_attn( src, src, src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask) src = src + self.dropout1(src2) src = self.norm1(src) src = paddle.transpose(src, [1, 2, 0]) src = paddle.unsqueeze(src, 2) src2 = self.conv2(F.relu(self.conv1(src))) src2 = paddle.squeeze(src2, 2) src2 = paddle.transpose(src2, [2, 0, 1]) src = paddle.squeeze(src, 2) src = paddle.transpose(src, [2, 0, 1]) src = src + self.dropout2(src2) src = self.norm2(src) return src
[ "def", "forward", "(", "self", ",", "src", ",", "src_mask", "=", "None", ",", "src_key_padding_mask", "=", "None", ")", ":", "src2", "=", "self", ".", "self_attn", "(", "src", ",", "src", ",", "src", ",", "attn_mask", "=", "src_mask", ",", "key_padding_mask", "=", "src_key_padding_mask", ")", "src", "=", "src", "+", "self", ".", "dropout1", "(", "src2", ")", "src", "=", "self", ".", "norm1", "(", "src", ")", "src", "=", "paddle", ".", "transpose", "(", "src", ",", "[", "1", ",", "2", ",", "0", "]", ")", "src", "=", "paddle", ".", "unsqueeze", "(", "src", ",", "2", ")", "src2", "=", "self", ".", "conv2", "(", "F", ".", "relu", "(", "self", ".", "conv1", "(", "src", ")", ")", ")", "src2", "=", "paddle", ".", "squeeze", "(", "src2", ",", "2", ")", "src2", "=", "paddle", ".", "transpose", "(", "src2", ",", "[", "2", ",", "0", ",", "1", "]", ")", "src", "=", "paddle", ".", "squeeze", "(", "src", ",", "2", ")", "src", "=", "paddle", ".", "transpose", "(", "src", ",", "[", "2", ",", "0", ",", "1", "]", ")", "src", "=", "src", "+", "self", ".", "dropout2", "(", "src2", ")", "src", "=", "self", ".", "norm2", "(", "src", ")", "return", "src" ]
https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/modeling/heads/rec_nrtr_head.py#L486-L512
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
driver/python/pysequoiadb/collectionspace.py
python
collectionspace.drop_collection
(self, cl_name)
Drop the specified collection in current collection space. Parameters: Name Type Info: cl_name str The collection name. Exceptions: pysequoiadb.error.SDBTypeError pysequoiadb.error.SDBBaseError
Drop the specified collection in current collection space.
[ "Drop", "the", "specified", "collection", "in", "current", "collection", "space", "." ]
def drop_collection(self, cl_name): """Drop the specified collection in current collection space. Parameters: Name Type Info: cl_name str The collection name. Exceptions: pysequoiadb.error.SDBTypeError pysequoiadb.error.SDBBaseError """ if not isinstance(cl_name, str_type): raise SDBTypeError("collection must be an instance of str_type") rc = sdb.cs_drop_collection(self._cs, cl_name) raise_if_error(rc, "Failed to drop collection")
[ "def", "drop_collection", "(", "self", ",", "cl_name", ")", ":", "if", "not", "isinstance", "(", "cl_name", ",", "str_type", ")", ":", "raise", "SDBTypeError", "(", "\"collection must be an instance of str_type\"", ")", "rc", "=", "sdb", ".", "cs_drop_collection", "(", "self", ".", "_cs", ",", "cl_name", ")", "raise_if_error", "(", "rc", ",", "\"Failed to drop collection\"", ")" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/pysequoiadb/collectionspace.py#L191-L205
Komnomnomnom/swigibpy
cfd307fdbfaffabc69a2dc037538d7e34a8b8daf
examples/contractdetails.py
python
ContractDetailsExample.openOrderEnd
(self)
Always called by TWS but not relevant for our example
Always called by TWS but not relevant for our example
[ "Always", "called", "by", "TWS", "but", "not", "relevant", "for", "our", "example" ]
def openOrderEnd(self): '''Always called by TWS but not relevant for our example''' pass
[ "def", "openOrderEnd", "(", "self", ")", ":", "pass" ]
https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/examples/contractdetails.py#L39-L41
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/context.py
python
create_standalone_context
(require=None, share=False, **settings)
return ctx
Create a standalone/headless ModernGL context. The preferred way of making a context is through :py:func:`moderngl.create_context`. Example:: # Create a context with highest possible supported version ctx = moderngl.create_context() # Require at least OpenGL 4.3 ctx = moderngl.create_context(require=430) Keyword Arguments: require (int): OpenGL version code. Returns: :py:class:`Context` object
Create a standalone/headless ModernGL context. The preferred way of making a context is through :py:func:`moderngl.create_context`.
[ "Create", "a", "standalone", "/", "headless", "ModernGL", "context", ".", "The", "preferred", "way", "of", "making", "a", "context", "is", "through", ":", "py", ":", "func", ":", "moderngl", ".", "create_context", "." ]
def create_standalone_context(require=None, share=False, **settings) -> 'Context': ''' Create a standalone/headless ModernGL context. The preferred way of making a context is through :py:func:`moderngl.create_context`. Example:: # Create a context with highest possible supported version ctx = moderngl.create_context() # Require at least OpenGL 4.3 ctx = moderngl.create_context(require=430) Keyword Arguments: require (int): OpenGL version code. Returns: :py:class:`Context` object ''' if require is None: require = 330 mode = 'share' if share is True else 'standalone' ctx = Context.__new__(Context) ctx.mglo, ctx.version_code = mgl.create_context(glversion=require, mode=mode, **settings) ctx._screen = None ctx.fbo = None ctx._info = None ctx._extensions = None ctx.extra = None ctx._gc_mode = "auto" if require is not None and ctx.version_code < require: raise ValueError('Requested OpenGL version {}, got version {}'.format( require, ctx.version_code)) return ctx
[ "def", "create_standalone_context", "(", "require", "=", "None", ",", "share", "=", "False", ",", "*", "*", "settings", ")", "->", "'Context'", ":", "if", "require", "is", "None", ":", "require", "=", "330", "mode", "=", "'share'", "if", "share", "is", "True", "else", "'standalone'", "ctx", "=", "Context", ".", "__new__", "(", "Context", ")", "ctx", ".", "mglo", ",", "ctx", ".", "version_code", "=", "mgl", ".", "create_context", "(", "glversion", "=", "require", ",", "mode", "=", "mode", ",", "*", "*", "settings", ")", "ctx", ".", "_screen", "=", "None", "ctx", ".", "fbo", "=", "None", "ctx", ".", "_info", "=", "None", "ctx", ".", "_extensions", "=", "None", "ctx", ".", "extra", "=", "None", "ctx", ".", "_gc_mode", "=", "\"auto\"", "if", "require", "is", "not", "None", "and", "ctx", ".", "version_code", "<", "require", ":", "raise", "ValueError", "(", "'Requested OpenGL version {}, got version {}'", ".", "format", "(", "require", ",", "ctx", ".", "version_code", ")", ")", "return", "ctx" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/context.py#L1823-L1860
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/pyserial/serial/__init__.py
python
serial_for_url
(url, *args, **kwargs)
return instance
\ Get an instance of the Serial class, depending on port/url. The port is not opened when the keyword parameter 'do_not_open' is true, by default it is. All other parameters are directly passed to the __init__ method when the port is instantiated. The list of package names that is searched for protocol handlers is kept in ``protocol_handler_packages``. e.g. we want to support a URL ``foobar://``. A module ``my_handlers.protocol_foobar`` is provided by the user. Then ``protocol_handler_packages.append("my_handlers")`` would extend the search path so that ``serial_for_url("foobar://"))`` would work.
\ Get an instance of the Serial class, depending on port/url. The port is not opened when the keyword parameter 'do_not_open' is true, by default it is. All other parameters are directly passed to the __init__ method when the port is instantiated.
[ "\\", "Get", "an", "instance", "of", "the", "Serial", "class", "depending", "on", "port", "/", "url", ".", "The", "port", "is", "not", "opened", "when", "the", "keyword", "parameter", "do_not_open", "is", "true", "by", "default", "it", "is", ".", "All", "other", "parameters", "are", "directly", "passed", "to", "the", "__init__", "method", "when", "the", "port", "is", "instantiated", "." ]
def serial_for_url(url, *args, **kwargs): """\ Get an instance of the Serial class, depending on port/url. The port is not opened when the keyword parameter 'do_not_open' is true, by default it is. All other parameters are directly passed to the __init__ method when the port is instantiated. The list of package names that is searched for protocol handlers is kept in ``protocol_handler_packages``. e.g. we want to support a URL ``foobar://``. A module ``my_handlers.protocol_foobar`` is provided by the user. Then ``protocol_handler_packages.append("my_handlers")`` would extend the search path so that ``serial_for_url("foobar://"))`` would work. """ # check remove extra parameter to not confuse the Serial class do_open = 'do_not_open' not in kwargs or not kwargs['do_not_open'] if 'do_not_open' in kwargs: del kwargs['do_not_open'] # the default is to use the native version klass = Serial # 'native' implementation # check port type and get class try: url_nocase = url.lower() except AttributeError: # it's not a string, use default pass else: if '://' in url_nocase: protocol = url_nocase.split('://', 1)[0] for package_name in protocol_handler_packages: module_name = '%s.protocol_%s' % (package_name, protocol,) try: handler_module = __import__(module_name) except ImportError: pass else: klass = sys.modules[module_name].Serial break else: raise ValueError('invalid URL, protocol %r not known' % (protocol,)) else: klass = Serial # 'native' implementation # instantiate and open when desired instance = klass(None, *args, **kwargs) instance.port = url if do_open: instance.open() return instance
[ "def", "serial_for_url", "(", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# check remove extra parameter to not confuse the Serial class", "do_open", "=", "'do_not_open'", "not", "in", "kwargs", "or", "not", "kwargs", "[", "'do_not_open'", "]", "if", "'do_not_open'", "in", "kwargs", ":", "del", "kwargs", "[", "'do_not_open'", "]", "# the default is to use the native version", "klass", "=", "Serial", "# 'native' implementation", "# check port type and get class", "try", ":", "url_nocase", "=", "url", ".", "lower", "(", ")", "except", "AttributeError", ":", "# it's not a string, use default", "pass", "else", ":", "if", "'://'", "in", "url_nocase", ":", "protocol", "=", "url_nocase", ".", "split", "(", "'://'", ",", "1", ")", "[", "0", "]", "for", "package_name", "in", "protocol_handler_packages", ":", "module_name", "=", "'%s.protocol_%s'", "%", "(", "package_name", ",", "protocol", ",", ")", "try", ":", "handler_module", "=", "__import__", "(", "module_name", ")", "except", "ImportError", ":", "pass", "else", ":", "klass", "=", "sys", ".", "modules", "[", "module_name", "]", ".", "Serial", "break", "else", ":", "raise", "ValueError", "(", "'invalid URL, protocol %r not known'", "%", "(", "protocol", ",", ")", ")", "else", ":", "klass", "=", "Serial", "# 'native' implementation", "# instantiate and open when desired", "instance", "=", "klass", "(", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", "instance", ".", "port", "=", "url", "if", "do_open", ":", "instance", ".", "open", "(", ")", "return", "instance" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/__init__.py#L32-L79
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/bisect_fyi.py
python
_StartBisectFYIJob
(test_name, bisect_config)
return bisect_result
Re-starts a bisect-job after modifying it's config based on run count. Args: test_name: Name of the test case. bisect_job: TryJob entity with initialized bot name and config. Returns: If successful, a dict containing "issue_id" and "issue_url" for the bisect job. Otherwise, a dict containing "error", with some description of the reason why a job wasn't started.
Re-starts a bisect-job after modifying it's config based on run count.
[ "Re", "-", "starts", "a", "bisect", "-", "job", "after", "modifying", "it", "s", "config", "based", "on", "run", "count", "." ]
def _StartBisectFYIJob(test_name, bisect_config): """Re-starts a bisect-job after modifying it's config based on run count. Args: test_name: Name of the test case. bisect_job: TryJob entity with initialized bot name and config. Returns: If successful, a dict containing "issue_id" and "issue_url" for the bisect job. Otherwise, a dict containing "error", with some description of the reason why a job wasn't started. """ try: bisect_job = _MakeBisectFYITryJob(test_name, bisect_config) except auto_bisect.NotBisectableError as e: return {'error': e.message} try: bisect_result = start_try_job.PerformBisect(bisect_job) except request_handler.InvalidInputError as e: bisect_result = {'error': e.message} if 'error' in bisect_result: if bisect_job.key: bisect_job.key.delete() return bisect_result
[ "def", "_StartBisectFYIJob", "(", "test_name", ",", "bisect_config", ")", ":", "try", ":", "bisect_job", "=", "_MakeBisectFYITryJob", "(", "test_name", ",", "bisect_config", ")", "except", "auto_bisect", ".", "NotBisectableError", "as", "e", ":", "return", "{", "'error'", ":", "e", ".", "message", "}", "try", ":", "bisect_result", "=", "start_try_job", ".", "PerformBisect", "(", "bisect_job", ")", "except", "request_handler", ".", "InvalidInputError", "as", "e", ":", "bisect_result", "=", "{", "'error'", ":", "e", ".", "message", "}", "if", "'error'", "in", "bisect_result", ":", "if", "bisect_job", ".", "key", ":", "bisect_job", ".", "key", ".", "delete", "(", ")", "return", "bisect_result" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/bisect_fyi.py#L58-L81
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/optimizer/qgt/qgt_jacobian_pytree_logic.py
python
_vjp
(oks: PyTree, w: Array)
return jax.tree_map(lambda x: mpi.mpi_sum_jax(x)[0], res)
Compute the vector-matrix product between the vector w and the pytree jacobian oks
Compute the vector-matrix product between the vector w and the pytree jacobian oks
[ "Compute", "the", "vector", "-", "matrix", "product", "between", "the", "vector", "w", "and", "the", "pytree", "jacobian", "oks" ]
def _vjp(oks: PyTree, w: Array) -> PyTree: """ Compute the vector-matrix product between the vector w and the pytree jacobian oks """ res = jax.tree_map(partial(jnp.tensordot, w, axes=1), oks) return jax.tree_map(lambda x: mpi.mpi_sum_jax(x)[0], res)
[ "def", "_vjp", "(", "oks", ":", "PyTree", ",", "w", ":", "Array", ")", "->", "PyTree", ":", "res", "=", "jax", ".", "tree_map", "(", "partial", "(", "jnp", ".", "tensordot", ",", "w", ",", "axes", "=", "1", ")", ",", "oks", ")", "return", "jax", ".", "tree_map", "(", "lambda", "x", ":", "mpi", ".", "mpi_sum_jax", "(", "x", ")", "[", "0", "]", ",", "res", ")" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/optimizer/qgt/qgt_jacobian_pytree_logic.py#L182-L187
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/metrics_impl.py
python
false_negatives
(labels, predictions, weights=None, metrics_collections=None, updates_collections=None, name=None)
Computes the total number of false negatives. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: value_tensor: A `Tensor` representing the current value of the metric. update_op: An operation that accumulates the error from a batch of data. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple.
Computes the total number of false negatives.
[ "Computes", "the", "total", "number", "of", "false", "negatives", "." ]
def false_negatives(labels, predictions, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the total number of false negatives. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: value_tensor: A `Tensor` representing the current value of the metric. update_op: An operation that accumulates the error from a batch of data. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope( name, 'false_negatives', (predictions, labels, weights)): predictions, labels, weights = _remove_squeezable_dimensions( predictions=math_ops.cast(predictions, dtype=dtypes.bool), labels=math_ops.cast(labels, dtype=dtypes.bool), weights=weights) is_false_negative = math_ops.logical_and(math_ops.equal(labels, True), math_ops.equal(predictions, False)) return _count_condition(is_false_negative, weights, metrics_collections, updates_collections)
[ "def", "false_negatives", "(", "labels", ",", "predictions", ",", "weights", "=", "None", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")", ":", "with", "variable_scope", ".", "variable_scope", "(", "name", ",", "'false_negatives'", ",", "(", "predictions", ",", "labels", ",", "weights", ")", ")", ":", "predictions", ",", "labels", ",", "weights", "=", "_remove_squeezable_dimensions", "(", "predictions", "=", "math_ops", ".", "cast", "(", "predictions", ",", "dtype", "=", "dtypes", ".", "bool", ")", ",", "labels", "=", "math_ops", ".", "cast", "(", "labels", ",", "dtype", "=", "dtypes", ".", "bool", ")", ",", "weights", "=", "weights", ")", "is_false_negative", "=", "math_ops", ".", "logical_and", "(", "math_ops", ".", "equal", "(", "labels", ",", "True", ")", ",", "math_ops", ".", "equal", "(", "predictions", ",", "False", ")", ")", "return", "_count_condition", "(", "is_false_negative", ",", "weights", ",", "metrics_collections", ",", "updates_collections", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/metrics_impl.py#L1272-L1313
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/maya/scripts/walterPanel/mergeExpressions.py
python
MergeExpressions.diff
(self, i, j)
Compare sub-strings and return the expression that matches both parts of the sub-strings. :param int i: The number of the symbol of the first string to compare. :param int j: The number of the symbol of the second string to compare. :returns: The expression that matches both parts of the sub-strings. :rtype: string
Compare sub-strings and return the expression that matches both parts of the sub-strings.
[ "Compare", "sub", "-", "strings", "and", "return", "the", "expression", "that", "matches", "both", "parts", "of", "the", "sub", "-", "strings", "." ]
def diff(self, i, j): """ Compare sub-strings and return the expression that matches both parts of the sub-strings. :param int i: The number of the symbol of the first string to compare. :param int j: The number of the symbol of the second string to compare. :returns: The expression that matches both parts of the sub-strings. :rtype: string """ if i > 0 and j > 0 and self.first[i-1] == self.second[j-1]: # Match return self.diff(i - 1, j - 1) + self.first[i-1] else: # Mismatch if j > 0 and (i == 0 or self.table[i][j-1] >= self.table[i-1][j]): # We need to add a letter second[j-1] to the sequence expression = self.diff(i, j - 1) elif i > 0 and (j == 0 or self.table[i][j-1] < self.table[i-1][j]): # We need to remove a letter first[i-1] to the sequence expression = self.diff(i - 1, j) else: # The recursion is finished return "" # A small trick to avoid producing several stars in a row. if not expression or expression[-1] != "*": expression += ".*" return expression
[ "def", "diff", "(", "self", ",", "i", ",", "j", ")", ":", "if", "i", ">", "0", "and", "j", ">", "0", "and", "self", ".", "first", "[", "i", "-", "1", "]", "==", "self", ".", "second", "[", "j", "-", "1", "]", ":", "# Match", "return", "self", ".", "diff", "(", "i", "-", "1", ",", "j", "-", "1", ")", "+", "self", ".", "first", "[", "i", "-", "1", "]", "else", ":", "# Mismatch", "if", "j", ">", "0", "and", "(", "i", "==", "0", "or", "self", ".", "table", "[", "i", "]", "[", "j", "-", "1", "]", ">=", "self", ".", "table", "[", "i", "-", "1", "]", "[", "j", "]", ")", ":", "# We need to add a letter second[j-1] to the sequence", "expression", "=", "self", ".", "diff", "(", "i", ",", "j", "-", "1", ")", "elif", "i", ">", "0", "and", "(", "j", "==", "0", "or", "self", ".", "table", "[", "i", "]", "[", "j", "-", "1", "]", "<", "self", ".", "table", "[", "i", "-", "1", "]", "[", "j", "]", ")", ":", "# We need to remove a letter first[i-1] to the sequence", "expression", "=", "self", ".", "diff", "(", "i", "-", "1", ",", "j", ")", "else", ":", "# The recursion is finished", "return", "\"\"", "# A small trick to avoid producing several stars in a row.", "if", "not", "expression", "or", "expression", "[", "-", "1", "]", "!=", "\"*\"", ":", "expression", "+=", "\".*\"", "return", "expression" ]
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/walterPanel/mergeExpressions.py#L36-L65
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_grad/grad_nn_ops.py
python
get_bprop_avg_pool_grad
(self)
return bprop
Grad definition for `AvgPool` operation.
Grad definition for `AvgPool` operation.
[ "Grad", "definition", "for", "AvgPool", "operation", "." ]
def get_bprop_avg_pool_grad(self): """Grad definition for `AvgPool` operation.""" avgpool_grad = G.AvgPoolGrad( kernel_size=self.kernel_size, strides=self.strides, pad_mode=self.pad_mode, data_format=self.format) def bprop(x, out, dout): dx = avgpool_grad(x, out, dout) return (dx,) return bprop
[ "def", "get_bprop_avg_pool_grad", "(", "self", ")", ":", "avgpool_grad", "=", "G", ".", "AvgPoolGrad", "(", "kernel_size", "=", "self", ".", "kernel_size", ",", "strides", "=", "self", ".", "strides", ",", "pad_mode", "=", "self", ".", "pad_mode", ",", "data_format", "=", "self", ".", "format", ")", "def", "bprop", "(", "x", ",", "out", ",", "dout", ")", ":", "dx", "=", "avgpool_grad", "(", "x", ",", "out", ",", "dout", ")", "return", "(", "dx", ",", ")", "return", "bprop" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_nn_ops.py#L308-L320
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PyComboBoxEditor._SetSelf
(*args, **kwargs)
return _propgrid.PyComboBoxEditor__SetSelf(*args, **kwargs)
_SetSelf(self, PyObject self)
_SetSelf(self, PyObject self)
[ "_SetSelf", "(", "self", "PyObject", "self", ")" ]
def _SetSelf(*args, **kwargs): """_SetSelf(self, PyObject self)""" return _propgrid.PyComboBoxEditor__SetSelf(*args, **kwargs)
[ "def", "_SetSelf", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PyComboBoxEditor__SetSelf", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L3977-L3979
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/rnn/large_word_lm/custom_module.py
python
CustomModule.load
(prefix, epoch, load_optimizer_states=False, symbol=None, **kwargs)
return mod
Creates a model from previously saved checkpoint. Parameters ---------- prefix : str path prefix of saved model files. You should have "prefix-symbol.json", "prefix-xxxx.params", and optionally "prefix-xxxx.states", where xxxx is the epoch number. epoch : int epoch to load. load_optimizer_states : bool whether to load optimizer states. Checkpoint needs to have been made with save_optimizer_states=True. data_names : list of str Default is `('data')` for a typical model used in image classification. label_names : list of str Default is `('softmax_label')` for a typical model used in image classification. logger : Logger Default is `logging`. context : Context or list of Context Default is ``cpu()``. work_load_list : list of number Default ``None``, indicating uniform workload. fixed_param_names: list of str Default ``None``, indicating no network parameters are fixed.
Creates a model from previously saved checkpoint.
[ "Creates", "a", "model", "from", "previously", "saved", "checkpoint", "." ]
def load(prefix, epoch, load_optimizer_states=False, symbol=None, **kwargs): """Creates a model from previously saved checkpoint. Parameters ---------- prefix : str path prefix of saved model files. You should have "prefix-symbol.json", "prefix-xxxx.params", and optionally "prefix-xxxx.states", where xxxx is the epoch number. epoch : int epoch to load. load_optimizer_states : bool whether to load optimizer states. Checkpoint needs to have been made with save_optimizer_states=True. data_names : list of str Default is `('data')` for a typical model used in image classification. label_names : list of str Default is `('softmax_label')` for a typical model used in image classification. logger : Logger Default is `logging`. context : Context or list of Context Default is ``cpu()``. work_load_list : list of number Default ``None``, indicating uniform workload. fixed_param_names: list of str Default ``None``, indicating no network parameters are fixed. """ sym, args, auxs = load_checkpoint(prefix, epoch) sym = sym if symbol is None else symbol mod = CustomModule(symbol=sym, **kwargs) mod._arg_params = args mod._aux_params = auxs mod.params_initialized = True if load_optimizer_states: mod._preload_opt_states = '%s-%04d.states'%(prefix, epoch) return mod
[ "def", "load", "(", "prefix", ",", "epoch", ",", "load_optimizer_states", "=", "False", ",", "symbol", "=", "None", ",", "*", "*", "kwargs", ")", ":", "sym", ",", "args", ",", "auxs", "=", "load_checkpoint", "(", "prefix", ",", "epoch", ")", "sym", "=", "sym", "if", "symbol", "is", "None", "else", "symbol", "mod", "=", "CustomModule", "(", "symbol", "=", "sym", ",", "*", "*", "kwargs", ")", "mod", ".", "_arg_params", "=", "args", "mod", ".", "_aux_params", "=", "auxs", "mod", ".", "params_initialized", "=", "True", "if", "load_optimizer_states", ":", "mod", ".", "_preload_opt_states", "=", "'%s-%04d.states'", "%", "(", "prefix", ",", "epoch", ")", "return", "mod" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/rnn/large_word_lm/custom_module.py#L63-L100
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/uploader.py
python
ResourceGroupUploader.execute_uploader_pre_hooks
(self)
Calls the upload_resource_group_pre_content methods defined by uploader hook modules. The methods are called with the context, and this uploader as their only parameters. Uploader hook modules are defined by upload.py files in the project's AWS directory and in resource group directories.
Calls the upload_resource_group_pre_content methods defined by uploader hook modules.
[ "Calls", "the", "upload_resource_group_pre_content", "methods", "defined", "by", "uploader", "hook", "modules", "." ]
def execute_uploader_pre_hooks(self): """Calls the upload_resource_group_pre_content methods defined by uploader hook modules. The methods are called with the context, and this uploader as their only parameters. Uploader hook modules are defined by upload.py files in the project's AWS directory and in resource group directories.""" self._execute_uploader_hooks('upload_resource_group_content_pre')
[ "def", "execute_uploader_pre_hooks", "(", "self", ")", ":", "self", ".", "_execute_uploader_hooks", "(", "'upload_resource_group_content_pre'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/uploader.py#L732-L740
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/tz/tz.py
python
datetime_ambiguous
(dt, tz=None)
return not (same_offset and same_dst)
Given a datetime and a time zone, determine whether or not a given datetime is ambiguous (i.e if there are two times differentiated only by their DST status). :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` is provided.) :param tz: A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If ``None`` or not provided, the datetime's own time zone will be used. :return: Returns a boolean value whether or not the "wall time" is ambiguous in ``tz``. .. versionadded:: 2.6.0
Given a datetime and a time zone, determine whether or not a given datetime is ambiguous (i.e if there are two times differentiated only by their DST status).
[ "Given", "a", "datetime", "and", "a", "time", "zone", "determine", "whether", "or", "not", "a", "given", "datetime", "is", "ambiguous", "(", "i", ".", "e", "if", "there", "are", "two", "times", "differentiated", "only", "by", "their", "DST", "status", ")", "." ]
def datetime_ambiguous(dt, tz=None): """ Given a datetime and a time zone, determine whether or not a given datetime is ambiguous (i.e if there are two times differentiated only by their DST status). :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` is provided.) :param tz: A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If ``None`` or not provided, the datetime's own time zone will be used. :return: Returns a boolean value whether or not the "wall time" is ambiguous in ``tz``. .. versionadded:: 2.6.0 """ if tz is None: if dt.tzinfo is None: raise ValueError('Datetime is naive and no time zone provided.') tz = dt.tzinfo # If a time zone defines its own "is_ambiguous" function, we'll use that. is_ambiguous_fn = getattr(tz, 'is_ambiguous', None) if is_ambiguous_fn is not None: try: return tz.is_ambiguous(dt) except Exception: pass # If it doesn't come out and tell us it's ambiguous, we'll just check if # the fold attribute has any effect on this particular date and time. dt = dt.replace(tzinfo=tz) wall_0 = enfold(dt, fold=0) wall_1 = enfold(dt, fold=1) same_offset = wall_0.utcoffset() == wall_1.utcoffset() same_dst = wall_0.dst() == wall_1.dst() return not (same_offset and same_dst)
[ "def", "datetime_ambiguous", "(", "dt", ",", "tz", "=", "None", ")", ":", "if", "tz", "is", "None", ":", "if", "dt", ".", "tzinfo", "is", "None", ":", "raise", "ValueError", "(", "'Datetime is naive and no time zone provided.'", ")", "tz", "=", "dt", ".", "tzinfo", "# If a time zone defines its own \"is_ambiguous\" function, we'll use that.", "is_ambiguous_fn", "=", "getattr", "(", "tz", ",", "'is_ambiguous'", ",", "None", ")", "if", "is_ambiguous_fn", "is", "not", "None", ":", "try", ":", "return", "tz", ".", "is_ambiguous", "(", "dt", ")", "except", "Exception", ":", "pass", "# If it doesn't come out and tell us it's ambiguous, we'll just check if", "# the fold attribute has any effect on this particular date and time.", "dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "tz", ")", "wall_0", "=", "enfold", "(", "dt", ",", "fold", "=", "0", ")", "wall_1", "=", "enfold", "(", "dt", ",", "fold", "=", "1", ")", "same_offset", "=", "wall_0", ".", "utcoffset", "(", ")", "==", "wall_1", ".", "utcoffset", "(", ")", "same_dst", "=", "wall_0", ".", "dst", "(", ")", "==", "wall_1", ".", "dst", "(", ")", "return", "not", "(", "same_offset", "and", "same_dst", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/tz/tz.py#L1717-L1760
plumonito/dtslam
5994bb9cf7a11981b830370db206bceb654c085d
3rdparty/opencv-git/3rdparty/jinja2/environment.py
python
Template.stream
(self, *args, **kwargs)
return TemplateStream(self.generate(*args, **kwargs))
Works exactly like :meth:`generate` but returns a :class:`TemplateStream`.
Works exactly like :meth:`generate` but returns a :class:`TemplateStream`.
[ "Works", "exactly", "like", ":", "meth", ":", "generate", "but", "returns", "a", ":", "class", ":", "TemplateStream", "." ]
def stream(self, *args, **kwargs): """Works exactly like :meth:`generate` but returns a :class:`TemplateStream`. """ return TemplateStream(self.generate(*args, **kwargs))
[ "def", "stream", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "TemplateStream", "(", "self", ".", "generate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/environment.py#L971-L975
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/dataview.py
python
DataViewEvent.SetDataBuffer
(*args, **kwargs)
return _dataview.DataViewEvent_SetDataBuffer(*args, **kwargs)
SetDataBuffer(self, void buf)
SetDataBuffer(self, void buf)
[ "SetDataBuffer", "(", "self", "void", "buf", ")" ]
def SetDataBuffer(*args, **kwargs): """SetDataBuffer(self, void buf)""" return _dataview.DataViewEvent_SetDataBuffer(*args, **kwargs)
[ "def", "SetDataBuffer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewEvent_SetDataBuffer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1991-L1993
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/core/serde/cloudpickle.py
python
CloudPickler.inject_timeseries
(self)
Handle bugs with pickling scikits timeseries
Handle bugs with pickling scikits timeseries
[ "Handle", "bugs", "with", "pickling", "scikits", "timeseries" ]
def inject_timeseries(self): """Handle bugs with pickling scikits timeseries""" tseries = sys.modules.get('scikits.timeseries.tseries') if not tseries or not hasattr(tseries, 'Timeseries'): return self.dispatch[tseries.Timeseries] = self.__class__.save_timeseries
[ "def", "inject_timeseries", "(", "self", ")", ":", "tseries", "=", "sys", ".", "modules", ".", "get", "(", "'scikits.timeseries.tseries'", ")", "if", "not", "tseries", "or", "not", "hasattr", "(", "tseries", ",", "'Timeseries'", ")", ":", "return", "self", ".", "dispatch", "[", "tseries", ".", "Timeseries", "]", "=", "self", ".", "__class__", ".", "save_timeseries" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/core/serde/cloudpickle.py#L752-L757
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/typeinfer.py
python
fold_arg_vars
(typevars, args, vararg, kws)
return pos_args, kw_args
Fold and resolve the argument variables of a function call.
Fold and resolve the argument variables of a function call.
[ "Fold", "and", "resolve", "the", "argument", "variables", "of", "a", "function", "call", "." ]
def fold_arg_vars(typevars, args, vararg, kws): """ Fold and resolve the argument variables of a function call. """ # Fetch all argument types, bail if any is unknown n_pos_args = len(args) kwds = [kw for (kw, var) in kws] argtypes = [typevars[a.name] for a in args] argtypes += [typevars[var.name] for (kw, var) in kws] if vararg is not None: argtypes.append(typevars[vararg.name]) if not all(a.defined for a in argtypes): return args = tuple(a.getone() for a in argtypes) pos_args = args[:n_pos_args] if vararg is not None: errmsg = "*args in function call should be a tuple, got %s" # Handle constant literal used for `*args` if isinstance(args[-1], types.Literal): const_val = args[-1].literal_value # Is the constant value a tuple? if not isinstance(const_val, tuple): raise TypeError(errmsg % (args[-1],)) # Append the elements in the const tuple to the positional args pos_args += const_val # Handle non-constant elif not isinstance(args[-1], types.BaseTuple): # Unsuitable for *args # (Python is more lenient and accepts all iterables) raise TypeError(errmsg % (args[-1],)) else: # Append the elements in the tuple to the positional args pos_args += args[-1].types # Drop the last arg args = args[:-1] kw_args = dict(zip(kwds, args[n_pos_args:])) return pos_args, kw_args
[ "def", "fold_arg_vars", "(", "typevars", ",", "args", ",", "vararg", ",", "kws", ")", ":", "# Fetch all argument types, bail if any is unknown", "n_pos_args", "=", "len", "(", "args", ")", "kwds", "=", "[", "kw", "for", "(", "kw", ",", "var", ")", "in", "kws", "]", "argtypes", "=", "[", "typevars", "[", "a", ".", "name", "]", "for", "a", "in", "args", "]", "argtypes", "+=", "[", "typevars", "[", "var", ".", "name", "]", "for", "(", "kw", ",", "var", ")", "in", "kws", "]", "if", "vararg", "is", "not", "None", ":", "argtypes", ".", "append", "(", "typevars", "[", "vararg", ".", "name", "]", ")", "if", "not", "all", "(", "a", ".", "defined", "for", "a", "in", "argtypes", ")", ":", "return", "args", "=", "tuple", "(", "a", ".", "getone", "(", ")", "for", "a", "in", "argtypes", ")", "pos_args", "=", "args", "[", ":", "n_pos_args", "]", "if", "vararg", "is", "not", "None", ":", "errmsg", "=", "\"*args in function call should be a tuple, got %s\"", "# Handle constant literal used for `*args`", "if", "isinstance", "(", "args", "[", "-", "1", "]", ",", "types", ".", "Literal", ")", ":", "const_val", "=", "args", "[", "-", "1", "]", ".", "literal_value", "# Is the constant value a tuple?", "if", "not", "isinstance", "(", "const_val", ",", "tuple", ")", ":", "raise", "TypeError", "(", "errmsg", "%", "(", "args", "[", "-", "1", "]", ",", ")", ")", "# Append the elements in the const tuple to the positional args", "pos_args", "+=", "const_val", "# Handle non-constant", "elif", "not", "isinstance", "(", "args", "[", "-", "1", "]", ",", "types", ".", "BaseTuple", ")", ":", "# Unsuitable for *args", "# (Python is more lenient and accepts all iterables)", "raise", "TypeError", "(", "errmsg", "%", "(", "args", "[", "-", "1", "]", ",", ")", ")", "else", ":", "# Append the elements in the tuple to the positional args", "pos_args", "+=", "args", "[", "-", "1", "]", ".", "types", "# Drop the last arg", "args", "=", "args", "[", ":", "-", "1", "]", "kw_args", "=", "dict", "(", "zip", "(", "kwds", ",", "args", "[", "n_pos_args", ":", "]", ")", ")", "return", "pos_args", ",", "kw_args" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/typeinfer.py#L416-L455
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py
python
insert
(arr, obj, values, axis=None)
return new
Insert values along the given axis before the given indices. Parameters ---------- arr : array_like Input array. obj : int, slice or sequence of ints Object that defines the index or indices before which `values` is inserted. .. versionadded:: 1.8.0 Support for multiple insertions when `obj` is a single scalar or a sequence with one element (similar to calling insert multiple times). values : array_like Values to insert into `arr`. If the type of `values` is different from that of `arr`, `values` is converted to the type of `arr`. `values` should be shaped so that ``arr[...,obj,...] = values`` is legal. axis : int, optional Axis along which to insert `values`. If `axis` is None then `arr` is flattened first. Returns ------- out : ndarray A copy of `arr` with `values` inserted. Note that `insert` does not occur in-place: a new array is returned. If `axis` is None, `out` is a flattened array. See Also -------- append : Append elements at the end of an array. concatenate : Join a sequence of arrays along an existing axis. delete : Delete elements from an array. Notes ----- Note that for higher dimensional inserts `obj=0` behaves very different from `obj=[0]` just like `arr[:,0,:] = values` is different from `arr[:,[0],:] = values`. Examples -------- >>> a = np.array([[1, 1], [2, 2], [3, 3]]) >>> a array([[1, 1], [2, 2], [3, 3]]) >>> np.insert(a, 1, 5) array([1, 5, 1, ..., 2, 3, 3]) >>> np.insert(a, 1, 5, axis=1) array([[1, 5, 1], [2, 5, 2], [3, 5, 3]]) Difference between sequence and scalars: >>> np.insert(a, [1], [[1],[2],[3]], axis=1) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1), ... np.insert(a, [1], [[1],[2],[3]], axis=1)) True >>> b = a.flatten() >>> b array([1, 1, 2, 2, 3, 3]) >>> np.insert(b, [2, 2], [5, 6]) array([1, 1, 5, ..., 2, 3, 3]) >>> np.insert(b, slice(2, 4), [5, 6]) array([1, 1, 5, ..., 2, 3, 3]) >>> np.insert(b, [2, 2], [7.13, False]) # type casting array([1, 1, 7, ..., 2, 3, 3]) >>> x = np.arange(8).reshape(2, 4) >>> idx = (1, 3) >>> np.insert(x, idx, 999, axis=1) array([[ 0, 999, 1, 2, 999, 3], [ 4, 999, 5, 6, 999, 7]])
Insert values along the given axis before the given indices.
[ "Insert", "values", "along", "the", "given", "axis", "before", "the", "given", "indices", "." ]
def insert(arr, obj, values, axis=None): """ Insert values along the given axis before the given indices. Parameters ---------- arr : array_like Input array. obj : int, slice or sequence of ints Object that defines the index or indices before which `values` is inserted. .. versionadded:: 1.8.0 Support for multiple insertions when `obj` is a single scalar or a sequence with one element (similar to calling insert multiple times). values : array_like Values to insert into `arr`. If the type of `values` is different from that of `arr`, `values` is converted to the type of `arr`. `values` should be shaped so that ``arr[...,obj,...] = values`` is legal. axis : int, optional Axis along which to insert `values`. If `axis` is None then `arr` is flattened first. Returns ------- out : ndarray A copy of `arr` with `values` inserted. Note that `insert` does not occur in-place: a new array is returned. If `axis` is None, `out` is a flattened array. See Also -------- append : Append elements at the end of an array. concatenate : Join a sequence of arrays along an existing axis. delete : Delete elements from an array. Notes ----- Note that for higher dimensional inserts `obj=0` behaves very different from `obj=[0]` just like `arr[:,0,:] = values` is different from `arr[:,[0],:] = values`. Examples -------- >>> a = np.array([[1, 1], [2, 2], [3, 3]]) >>> a array([[1, 1], [2, 2], [3, 3]]) >>> np.insert(a, 1, 5) array([1, 5, 1, ..., 2, 3, 3]) >>> np.insert(a, 1, 5, axis=1) array([[1, 5, 1], [2, 5, 2], [3, 5, 3]]) Difference between sequence and scalars: >>> np.insert(a, [1], [[1],[2],[3]], axis=1) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1), ... np.insert(a, [1], [[1],[2],[3]], axis=1)) True >>> b = a.flatten() >>> b array([1, 1, 2, 2, 3, 3]) >>> np.insert(b, [2, 2], [5, 6]) array([1, 1, 5, ..., 2, 3, 3]) >>> np.insert(b, slice(2, 4), [5, 6]) array([1, 1, 5, ..., 2, 3, 3]) >>> np.insert(b, [2, 2], [7.13, False]) # type casting array([1, 1, 7, ..., 2, 3, 3]) >>> x = np.arange(8).reshape(2, 4) >>> idx = (1, 3) >>> np.insert(x, idx, 999, axis=1) array([[ 0, 999, 1, 2, 999, 3], [ 4, 999, 5, 6, 999, 7]]) """ wrap = None if type(arr) is not ndarray: try: wrap = arr.__array_wrap__ except AttributeError: pass arr = asarray(arr) ndim = arr.ndim arrorder = 'F' if arr.flags.fnc else 'C' if axis is None: if ndim != 1: arr = arr.ravel() ndim = arr.ndim axis = ndim - 1 elif ndim == 0: # 2013-09-24, 1.9 warnings.warn( "in the future the special handling of scalars will be removed " "from insert and raise an error", DeprecationWarning, stacklevel=3) arr = arr.copy(order=arrorder) arr[...] = values if wrap: return wrap(arr) else: return arr else: axis = normalize_axis_index(axis, ndim) slobj = [slice(None)]*ndim N = arr.shape[axis] newshape = list(arr.shape) if isinstance(obj, slice): # turn it into a range object indices = arange(*obj.indices(N), **{'dtype': intp}) else: # need to copy obj, because indices will be changed in-place indices = np.array(obj) if indices.dtype == bool: # See also delete warnings.warn( "in the future insert will treat boolean arrays and " "array-likes as a boolean index instead of casting it to " "integer", FutureWarning, stacklevel=3) indices = indices.astype(intp) # Code after warning period: #if obj.ndim != 1: # raise ValueError('boolean array argument obj to insert ' # 'must be one dimensional') #indices = np.flatnonzero(obj) elif indices.ndim > 1: raise ValueError( "index array argument obj to insert must be one dimensional " "or scalar") if indices.size == 1: index = indices.item() if index < -N or index > N: raise IndexError( "index %i is out of bounds for axis %i with " "size %i" % (obj, axis, N)) if (index < 0): index += N # There are some object array corner cases here, but we cannot avoid # that: values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype) if indices.ndim == 0: # broadcasting is very different here, since a[:,0,:] = ... behaves # very different from a[:,[0],:] = ...! This changes values so that # it works likes the second case. (here a[:,0:1,:]) values = np.moveaxis(values, 0, axis) numnew = values.shape[axis] newshape[axis] += numnew new = empty(newshape, arr.dtype, arrorder) slobj[axis] = slice(None, index) new[tuple(slobj)] = arr[tuple(slobj)] slobj[axis] = slice(index, index+numnew) new[tuple(slobj)] = values slobj[axis] = slice(index+numnew, None) slobj2 = [slice(None)] * ndim slobj2[axis] = slice(index, None) new[tuple(slobj)] = arr[tuple(slobj2)] if wrap: return wrap(new) return new elif indices.size == 0 and not isinstance(obj, np.ndarray): # Can safely cast the empty list to intp indices = indices.astype(intp) if not np.can_cast(indices, intp, 'same_kind'): # 2013-09-24, 1.9 warnings.warn( "using a non-integer array as obj in insert will result in an " "error in the future", DeprecationWarning, stacklevel=3) indices = indices.astype(intp) indices[indices < 0] += N numnew = len(indices) order = indices.argsort(kind='mergesort') # stable sort indices[order] += np.arange(numnew) newshape[axis] += numnew old_mask = ones(newshape[axis], dtype=bool) old_mask[indices] = False new = empty(newshape, arr.dtype, arrorder) slobj2 = [slice(None)]*ndim slobj[axis] = indices slobj2[axis] = old_mask new[tuple(slobj)] = values new[tuple(slobj2)] = arr if wrap: return wrap(new) return new
[ "def", "insert", "(", "arr", ",", "obj", ",", "values", ",", "axis", "=", "None", ")", ":", "wrap", "=", "None", "if", "type", "(", "arr", ")", "is", "not", "ndarray", ":", "try", ":", "wrap", "=", "arr", ".", "__array_wrap__", "except", "AttributeError", ":", "pass", "arr", "=", "asarray", "(", "arr", ")", "ndim", "=", "arr", ".", "ndim", "arrorder", "=", "'F'", "if", "arr", ".", "flags", ".", "fnc", "else", "'C'", "if", "axis", "is", "None", ":", "if", "ndim", "!=", "1", ":", "arr", "=", "arr", ".", "ravel", "(", ")", "ndim", "=", "arr", ".", "ndim", "axis", "=", "ndim", "-", "1", "elif", "ndim", "==", "0", ":", "# 2013-09-24, 1.9", "warnings", ".", "warn", "(", "\"in the future the special handling of scalars will be removed \"", "\"from insert and raise an error\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ")", "arr", "=", "arr", ".", "copy", "(", "order", "=", "arrorder", ")", "arr", "[", "...", "]", "=", "values", "if", "wrap", ":", "return", "wrap", "(", "arr", ")", "else", ":", "return", "arr", "else", ":", "axis", "=", "normalize_axis_index", "(", "axis", ",", "ndim", ")", "slobj", "=", "[", "slice", "(", "None", ")", "]", "*", "ndim", "N", "=", "arr", ".", "shape", "[", "axis", "]", "newshape", "=", "list", "(", "arr", ".", "shape", ")", "if", "isinstance", "(", "obj", ",", "slice", ")", ":", "# turn it into a range object", "indices", "=", "arange", "(", "*", "obj", ".", "indices", "(", "N", ")", ",", "*", "*", "{", "'dtype'", ":", "intp", "}", ")", "else", ":", "# need to copy obj, because indices will be changed in-place", "indices", "=", "np", ".", "array", "(", "obj", ")", "if", "indices", ".", "dtype", "==", "bool", ":", "# See also delete", "warnings", ".", "warn", "(", "\"in the future insert will treat boolean arrays and \"", "\"array-likes as a boolean index instead of casting it to \"", "\"integer\"", ",", "FutureWarning", ",", "stacklevel", "=", "3", ")", "indices", "=", "indices", ".", "astype", "(", "intp", ")", "# Code after warning period:", "#if obj.ndim != 1:", "# raise ValueError('boolean array argument obj to insert '", "# 'must be one dimensional')", "#indices = np.flatnonzero(obj)", "elif", "indices", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"index array argument obj to insert must be one dimensional \"", "\"or scalar\"", ")", "if", "indices", ".", "size", "==", "1", ":", "index", "=", "indices", ".", "item", "(", ")", "if", "index", "<", "-", "N", "or", "index", ">", "N", ":", "raise", "IndexError", "(", "\"index %i is out of bounds for axis %i with \"", "\"size %i\"", "%", "(", "obj", ",", "axis", ",", "N", ")", ")", "if", "(", "index", "<", "0", ")", ":", "index", "+=", "N", "# There are some object array corner cases here, but we cannot avoid", "# that:", "values", "=", "array", "(", "values", ",", "copy", "=", "False", ",", "ndmin", "=", "arr", ".", "ndim", ",", "dtype", "=", "arr", ".", "dtype", ")", "if", "indices", ".", "ndim", "==", "0", ":", "# broadcasting is very different here, since a[:,0,:] = ... behaves", "# very different from a[:,[0],:] = ...! This changes values so that", "# it works likes the second case. (here a[:,0:1,:])", "values", "=", "np", ".", "moveaxis", "(", "values", ",", "0", ",", "axis", ")", "numnew", "=", "values", ".", "shape", "[", "axis", "]", "newshape", "[", "axis", "]", "+=", "numnew", "new", "=", "empty", "(", "newshape", ",", "arr", ".", "dtype", ",", "arrorder", ")", "slobj", "[", "axis", "]", "=", "slice", "(", "None", ",", "index", ")", "new", "[", "tuple", "(", "slobj", ")", "]", "=", "arr", "[", "tuple", "(", "slobj", ")", "]", "slobj", "[", "axis", "]", "=", "slice", "(", "index", ",", "index", "+", "numnew", ")", "new", "[", "tuple", "(", "slobj", ")", "]", "=", "values", "slobj", "[", "axis", "]", "=", "slice", "(", "index", "+", "numnew", ",", "None", ")", "slobj2", "=", "[", "slice", "(", "None", ")", "]", "*", "ndim", "slobj2", "[", "axis", "]", "=", "slice", "(", "index", ",", "None", ")", "new", "[", "tuple", "(", "slobj", ")", "]", "=", "arr", "[", "tuple", "(", "slobj2", ")", "]", "if", "wrap", ":", "return", "wrap", "(", "new", ")", "return", "new", "elif", "indices", ".", "size", "==", "0", "and", "not", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "# Can safely cast the empty list to intp", "indices", "=", "indices", ".", "astype", "(", "intp", ")", "if", "not", "np", ".", "can_cast", "(", "indices", ",", "intp", ",", "'same_kind'", ")", ":", "# 2013-09-24, 1.9", "warnings", ".", "warn", "(", "\"using a non-integer array as obj in insert will result in an \"", "\"error in the future\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ")", "indices", "=", "indices", ".", "astype", "(", "intp", ")", "indices", "[", "indices", "<", "0", "]", "+=", "N", "numnew", "=", "len", "(", "indices", ")", "order", "=", "indices", ".", "argsort", "(", "kind", "=", "'mergesort'", ")", "# stable sort", "indices", "[", "order", "]", "+=", "np", ".", "arange", "(", "numnew", ")", "newshape", "[", "axis", "]", "+=", "numnew", "old_mask", "=", "ones", "(", "newshape", "[", "axis", "]", ",", "dtype", "=", "bool", ")", "old_mask", "[", "indices", "]", "=", "False", "new", "=", "empty", "(", "newshape", ",", "arr", ".", "dtype", ",", "arrorder", ")", "slobj2", "=", "[", "slice", "(", "None", ")", "]", "*", "ndim", "slobj", "[", "axis", "]", "=", "indices", "slobj2", "[", "axis", "]", "=", "old_mask", "new", "[", "tuple", "(", "slobj", ")", "]", "=", "values", "new", "[", "tuple", "(", "slobj2", ")", "]", "=", "arr", "if", "wrap", ":", "return", "wrap", "(", "new", ")", "return", "new" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py#L4430-L4633
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
FSFile.GetAnchor
(*args, **kwargs)
return _core_.FSFile_GetAnchor(*args, **kwargs)
GetAnchor(self) -> String
GetAnchor(self) -> String
[ "GetAnchor", "(", "self", ")", "-", ">", "String" ]
def GetAnchor(*args, **kwargs): """GetAnchor(self) -> String""" return _core_.FSFile_GetAnchor(*args, **kwargs)
[ "def", "GetAnchor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "FSFile_GetAnchor", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L2307-L2309
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
doc/doxygen_cxx/build.py
python
_generate_doxygen_header
(*, doxygen, temp_dir)
Creates Drake's header.html based on a patch to Doxygen's default header template.
Creates Drake's header.html based on a patch to Doxygen's default header template.
[ "Creates", "Drake", "s", "header", ".", "html", "based", "on", "a", "patch", "to", "Doxygen", "s", "default", "header", "template", "." ]
def _generate_doxygen_header(*, doxygen, temp_dir): """Creates Drake's header.html based on a patch to Doxygen's default header template. """ # This matches Doxyfile_CXX. header_path = f"{temp_dir}/drake/doc/doxygen_cxx/header.html" # Extract the default templates from the Doxygen binary. We only want the # header, but it forces us to create all three in this exact order. scratch_files = [ "header.html.orig", "footer.html.orig", "customdoxygen.css.orig", ] check_call([doxygen, "-w", "html"] + scratch_files, cwd=temp_dir) shutil.copy(f"{temp_dir}/header.html.orig", header_path) for orig in scratch_files: os.remove(f"{temp_dir}/{orig}") # Apply our patch. patch_file = f"{header_path}.patch" check_call(["/usr/bin/patch", header_path, patch_file])
[ "def", "_generate_doxygen_header", "(", "*", ",", "doxygen", ",", "temp_dir", ")", ":", "# This matches Doxyfile_CXX.", "header_path", "=", "f\"{temp_dir}/drake/doc/doxygen_cxx/header.html\"", "# Extract the default templates from the Doxygen binary. We only want the", "# header, but it forces us to create all three in this exact order.", "scratch_files", "=", "[", "\"header.html.orig\"", ",", "\"footer.html.orig\"", ",", "\"customdoxygen.css.orig\"", ",", "]", "check_call", "(", "[", "doxygen", ",", "\"-w\"", ",", "\"html\"", "]", "+", "scratch_files", ",", "cwd", "=", "temp_dir", ")", "shutil", ".", "copy", "(", "f\"{temp_dir}/header.html.orig\"", ",", "header_path", ")", "for", "orig", "in", "scratch_files", ":", "os", ".", "remove", "(", "f\"{temp_dir}/{orig}\"", ")", "# Apply our patch.", "patch_file", "=", "f\"{header_path}.patch\"", "check_call", "(", "[", "\"/usr/bin/patch\"", ",", "header_path", ",", "patch_file", "]", ")" ]
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/doc/doxygen_cxx/build.py#L105-L126
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
platforms/nuttx/Debug/Nuttx.py
python
NX_register_set.mon_reg_call
(self,register)
register is the register as a string e.g. 'pc' return integer containing the value of the register
register is the register as a string e.g. 'pc' return integer containing the value of the register
[ "register", "is", "the", "register", "as", "a", "string", "e", ".", "g", ".", "pc", "return", "integer", "containing", "the", "value", "of", "the", "register" ]
def mon_reg_call(self,register): """ register is the register as a string e.g. 'pc' return integer containing the value of the register """ str_to_eval = "info registers "+register resp = gdb.execute(str_to_eval,to_string = True) content = resp.split()[-1] try: return int(content) except: return 0
[ "def", "mon_reg_call", "(", "self", ",", "register", ")", ":", "str_to_eval", "=", "\"info registers \"", "+", "register", "resp", "=", "gdb", ".", "execute", "(", "str_to_eval", ",", "to_string", "=", "True", ")", "content", "=", "resp", ".", "split", "(", ")", "[", "-", "1", "]", "try", ":", "return", "int", "(", "content", ")", "except", ":", "return", "0" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/platforms/nuttx/Debug/Nuttx.py#L89-L100
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/resolvelib/reporters.py
python
BaseReporter.adding_requirement
(self, requirement, parent)
Called when adding a new requirement into the resolve criteria. :param requirement: The additional requirement to be applied to filter the available candidaites. :param parent: The candidate that requires ``requirement`` as a dependency, or None if ``requirement`` is one of the root requirements passed in from ``Resolver.resolve()``.
Called when adding a new requirement into the resolve criteria.
[ "Called", "when", "adding", "a", "new", "requirement", "into", "the", "resolve", "criteria", "." ]
def adding_requirement(self, requirement, parent): """Called when adding a new requirement into the resolve criteria. :param requirement: The additional requirement to be applied to filter the available candidaites. :param parent: The candidate that requires ``requirement`` as a dependency, or None if ``requirement`` is one of the root requirements passed in from ``Resolver.resolve()``. """
[ "def", "adding_requirement", "(", "self", ",", "requirement", ",", "parent", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/resolvelib/reporters.py#L23-L31
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/prod.py
python
Prod._column_grad
(self, value)
return np.prod(value) / value
Gives the (sub/super)gradient of the atom w.r.t. a column argument. Matrix expressions are vectorized, so the gradient is a matrix. Args: value: A numeric value for a column. Returns: A NumPy ndarray or None.
Gives the (sub/super)gradient of the atom w.r.t. a column argument.
[ "Gives", "the", "(", "sub", "/", "super", ")", "gradient", "of", "the", "atom", "w", ".", "r", ".", "t", ".", "a", "column", "argument", "." ]
def _column_grad(self, value): """Gives the (sub/super)gradient of the atom w.r.t. a column argument. Matrix expressions are vectorized, so the gradient is a matrix. Args: value: A numeric value for a column. Returns: A NumPy ndarray or None. """ return np.prod(value) / value
[ "def", "_column_grad", "(", "self", ",", "value", ")", ":", "return", "np", ".", "prod", "(", "value", ")", "/", "value" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/prod.py#L94-L105
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/distribution/normal.py
python
Normal._log_prob
(self, value, mean=None, sd=None)
return unnormalized_log_prob + neg_normalization
r""" Evaluate log probability. Args: value (Tensor): The value to be evaluated. mean (Tensor): The mean of the distribution. Default: self._mean_value. sd (Tensor): The standard deviation the distribution. Default: self._sd_value. .. math:: L(x) = -1* \frac{(x - \mu)^2}{2. * \sigma^2} - \log(\sqrt(2* \pi * \sigma^2))
r""" Evaluate log probability.
[ "r", "Evaluate", "log", "probability", "." ]
def _log_prob(self, value, mean=None, sd=None): r""" Evaluate log probability. Args: value (Tensor): The value to be evaluated. mean (Tensor): The mean of the distribution. Default: self._mean_value. sd (Tensor): The standard deviation the distribution. Default: self._sd_value. .. math:: L(x) = -1* \frac{(x - \mu)^2}{2. * \sigma^2} - \log(\sqrt(2* \pi * \sigma^2)) """ value = self._check_value(value, 'value') value = self.cast(value, self.dtype) mean, sd = self._check_param_type(mean, sd) unnormalized_log_prob = -1. * \ (self.sq(value - mean)) / (2. * self.sq(sd)) neg_normalization = -1. * \ self.log(self.const(2. * np.pi)) / 2. - self.log(sd) return unnormalized_log_prob + neg_normalization
[ "def", "_log_prob", "(", "self", ",", "value", ",", "mean", "=", "None", ",", "sd", "=", "None", ")", ":", "value", "=", "self", ".", "_check_value", "(", "value", ",", "'value'", ")", "value", "=", "self", ".", "cast", "(", "value", ",", "self", ".", "dtype", ")", "mean", ",", "sd", "=", "self", ".", "_check_param_type", "(", "mean", ",", "sd", ")", "unnormalized_log_prob", "=", "-", "1.", "*", "(", "self", ".", "sq", "(", "value", "-", "mean", ")", ")", "/", "(", "2.", "*", "self", ".", "sq", "(", "sd", ")", ")", "neg_normalization", "=", "-", "1.", "*", "self", ".", "log", "(", "self", ".", "const", "(", "2.", "*", "np", ".", "pi", ")", ")", "/", "2.", "-", "self", ".", "log", "(", "sd", ")", "return", "unnormalized_log_prob", "+", "neg_normalization" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/normal.py#L263-L282
google/fhir
d77f57706c1a168529b0b87ca7ccb1c0113e83c2
py/google/fhir/fhir_errors.py
python
ListErrorReporter.report_fhir_path_warning
(self, element_path: str, fhir_path_constraint: str, msg: str)
Logs to the `warning` context and stores `msg` in `warnings`.
Logs to the `warning` context and stores `msg` in `warnings`.
[ "Logs", "to", "the", "warning", "context", "and", "stores", "msg", "in", "warnings", "." ]
def report_fhir_path_warning(self, element_path: str, fhir_path_constraint: str, msg: str) -> None: """Logs to the `warning` context and stores `msg` in `warnings`.""" logging.warning('%s:%s; %s', element_path, fhir_path_constraint, msg) self.warnings.append(msg)
[ "def", "report_fhir_path_warning", "(", "self", ",", "element_path", ":", "str", ",", "fhir_path_constraint", ":", "str", ",", "msg", ":", "str", ")", "->", "None", ":", "logging", ".", "warning", "(", "'%s:%s; %s'", ",", "element_path", ",", "fhir_path_constraint", ",", "msg", ")", "self", ".", "warnings", ".", "append", "(", "msg", ")" ]
https://github.com/google/fhir/blob/d77f57706c1a168529b0b87ca7ccb1c0113e83c2/py/google/fhir/fhir_errors.py#L143-L147
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
dali/python/nvidia/dali/tensors.py
python
_tensor_to_string
(self)
return _join_string(params, False, 0, ',\n' + indent)
Returns string representation of Tensor.
Returns string representation of Tensor.
[ "Returns", "string", "representation", "of", "Tensor", "." ]
def _tensor_to_string(self): """ Returns string representation of Tensor.""" import numpy as np type_name = type(self).__name__ indent = ' ' * 4 layout = self.layout() data = np.array(_transfer_to_cpu(self, type_name[-3:])) data_str = np.array2string(data, prefix=indent, edgeitems=2) params = [f'{type_name}(\n{indent}{data_str}', f'dtype={self.dtype}'] + \ ([f'layout={layout}'] if layout else []) + \ [f'shape={self.shape()})'] return _join_string(params, False, 0, ',\n' + indent)
[ "def", "_tensor_to_string", "(", "self", ")", ":", "import", "numpy", "as", "np", "type_name", "=", "type", "(", "self", ")", ".", "__name__", "indent", "=", "' '", "*", "4", "layout", "=", "self", ".", "layout", "(", ")", "data", "=", "np", ".", "array", "(", "_transfer_to_cpu", "(", "self", ",", "type_name", "[", "-", "3", ":", "]", ")", ")", "data_str", "=", "np", ".", "array2string", "(", "data", ",", "prefix", "=", "indent", ",", "edgeitems", "=", "2", ")", "params", "=", "[", "f'{type_name}(\\n{indent}{data_str}'", ",", "f'dtype={self.dtype}'", "]", "+", "(", "[", "f'layout={layout}'", "]", "if", "layout", "else", "[", "]", ")", "+", "[", "f'shape={self.shape()})'", "]", "return", "_join_string", "(", "params", ",", "False", ",", "0", ",", "',\\n'", "+", "indent", ")" ]
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/dali/python/nvidia/dali/tensors.py#L36-L50
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/framemanager.py
python
AuiManager.DoDropLayer
(self, docks, target, dock_direction)
return self.ProcessDockResult(target, drop)
Handles the situation in which `target` is a single dock guide. :param `docks`: a list of :class:`AuiDockInfo` classes; :param AuiPaneInfo `target`: the target pane; :param integer `dock_direction`: the docking direction.
Handles the situation in which `target` is a single dock guide.
[ "Handles", "the", "situation", "in", "which", "target", "is", "a", "single", "dock", "guide", "." ]
def DoDropLayer(self, docks, target, dock_direction): """ Handles the situation in which `target` is a single dock guide. :param `docks`: a list of :class:`AuiDockInfo` classes; :param AuiPaneInfo `target`: the target pane; :param integer `dock_direction`: the docking direction. """ drop = self.CopyTarget(target) if dock_direction == AUI_DOCK_LEFT: drop.Dock().Left() drop_new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_LEFT), GetMaxLayer(docks, AUI_DOCK_BOTTOM)), GetMaxLayer(docks, AUI_DOCK_TOP)) + 1 elif dock_direction == AUI_DOCK_TOP: drop.Dock().Top() drop_new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_TOP), GetMaxLayer(docks, AUI_DOCK_LEFT)), GetMaxLayer(docks, AUI_DOCK_RIGHT)) + 1 elif dock_direction == AUI_DOCK_RIGHT: drop.Dock().Right() drop_new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_RIGHT), GetMaxLayer(docks, AUI_DOCK_TOP)), GetMaxLayer(docks, AUI_DOCK_BOTTOM)) + 1 elif dock_direction == AUI_DOCK_BOTTOM: drop.Dock().Bottom() drop_new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_BOTTOM), GetMaxLayer(docks, AUI_DOCK_LEFT)), GetMaxLayer(docks, AUI_DOCK_RIGHT)) + 1 else: return False, target drop.Dock().Layer(drop_new_layer) return self.ProcessDockResult(target, drop)
[ "def", "DoDropLayer", "(", "self", ",", "docks", ",", "target", ",", "dock_direction", ")", ":", "drop", "=", "self", ".", "CopyTarget", "(", "target", ")", "if", "dock_direction", "==", "AUI_DOCK_LEFT", ":", "drop", ".", "Dock", "(", ")", ".", "Left", "(", ")", "drop_new_layer", "=", "max", "(", "max", "(", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_LEFT", ")", ",", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_BOTTOM", ")", ")", ",", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_TOP", ")", ")", "+", "1", "elif", "dock_direction", "==", "AUI_DOCK_TOP", ":", "drop", ".", "Dock", "(", ")", ".", "Top", "(", ")", "drop_new_layer", "=", "max", "(", "max", "(", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_TOP", ")", ",", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_LEFT", ")", ")", ",", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_RIGHT", ")", ")", "+", "1", "elif", "dock_direction", "==", "AUI_DOCK_RIGHT", ":", "drop", ".", "Dock", "(", ")", ".", "Right", "(", ")", "drop_new_layer", "=", "max", "(", "max", "(", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_RIGHT", ")", ",", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_TOP", ")", ")", ",", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_BOTTOM", ")", ")", "+", "1", "elif", "dock_direction", "==", "AUI_DOCK_BOTTOM", ":", "drop", ".", "Dock", "(", ")", ".", "Bottom", "(", ")", "drop_new_layer", "=", "max", "(", "max", "(", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_BOTTOM", ")", ",", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_LEFT", ")", ")", ",", "GetMaxLayer", "(", "docks", ",", "AUI_DOCK_RIGHT", ")", ")", "+", "1", "else", ":", "return", "False", ",", "target", "drop", ".", "Dock", "(", ")", ".", "Layer", "(", "drop_new_layer", ")", "return", "self", ".", "ProcessDockResult", "(", "target", ",", "drop", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L7983-L8023
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/dataset.py
python
DatasetBase.set_hdfs_config
(self, fs_name, fs_ugi)
Set hdfs config: fs name ad ugi Examples: .. code-block:: python import paddle.fluid as fluid dataset = fluid.DatasetFactory().create_dataset() dataset.set_hdfs_config("my_fs_name", "my_fs_ugi") Args: fs_name(str): fs name fs_ugi(str): fs ugi
Set hdfs config: fs name ad ugi
[ "Set", "hdfs", "config", ":", "fs", "name", "ad", "ugi" ]
def set_hdfs_config(self, fs_name, fs_ugi): """ Set hdfs config: fs name ad ugi Examples: .. code-block:: python import paddle.fluid as fluid dataset = fluid.DatasetFactory().create_dataset() dataset.set_hdfs_config("my_fs_name", "my_fs_ugi") Args: fs_name(str): fs name fs_ugi(str): fs ugi """ self.dataset.set_hdfs_config(fs_name, fs_ugi)
[ "def", "set_hdfs_config", "(", "self", ",", "fs_name", ",", "fs_ugi", ")", ":", "self", ".", "dataset", ".", "set_hdfs_config", "(", "fs_name", ",", "fs_ugi", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dataset.py#L280-L295
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
syzygy/agent/asan/generate_memory_interceptors.py
python
MacroAssembler.get_value
(self, key, args, kwargs)
return super(MacroAssembler, self).get_value(key, args, kwargs)
Override to inject macro definitions.
Override to inject macro definitions.
[ "Override", "to", "inject", "macro", "definitions", "." ]
def get_value(self, key, args, kwargs): """Override to inject macro definitions.""" if key in _MACROS: macro = _MACROS[key].format(*args, **kwargs) # Trim leading whitespace to allow natural use of AsanXXX macros. macro = macro.lstrip() return macro return super(MacroAssembler, self).get_value(key, args, kwargs)
[ "def", "get_value", "(", "self", ",", "key", ",", "args", ",", "kwargs", ")", ":", "if", "key", "in", "_MACROS", ":", "macro", "=", "_MACROS", "[", "key", "]", ".", "format", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Trim leading whitespace to allow natural use of AsanXXX macros.", "macro", "=", "macro", ".", "lstrip", "(", ")", "return", "macro", "return", "super", "(", "MacroAssembler", ",", "self", ")", ".", "get_value", "(", "key", ",", "args", ",", "kwargs", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/syzygy/agent/asan/generate_memory_interceptors.py#L612-L619
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/tensor.py
python
eltwise_mult
(lhs, rhs, ret=None)
Elementi-wise multiplication. Args: lhs (Tensor): lhs tensor rhs (Tensor): rhs tensor ret (Tensor, optional): if not None, the result is stored in it; otherwise, a new Tensor would be created for the result. Returns: the result Tensor
Elementi-wise multiplication.
[ "Elementi", "-", "wise", "multiplication", "." ]
def eltwise_mult(lhs, rhs, ret=None): '''Elementi-wise multiplication. Args: lhs (Tensor): lhs tensor rhs (Tensor): rhs tensor ret (Tensor, optional): if not None, the result is stored in it; otherwise, a new Tensor would be created for the result. Returns: the result Tensor ''' if ret is None: # call Tensor.__mul__() return lhs * rhs else: if isinstance(rhs, Tensor): singa.EltwiseMult(lhs.data, rhs.data, ret.data) else: singa.EltwiseMultFloatWithRet(lhs.data, rhs, ret.data) return ret
[ "def", "eltwise_mult", "(", "lhs", ",", "rhs", ",", "ret", "=", "None", ")", ":", "if", "ret", "is", "None", ":", "# call Tensor.__mul__()", "return", "lhs", "*", "rhs", "else", ":", "if", "isinstance", "(", "rhs", ",", "Tensor", ")", ":", "singa", ".", "EltwiseMult", "(", "lhs", ".", "data", ",", "rhs", ".", "data", ",", "ret", ".", "data", ")", "else", ":", "singa", ".", "EltwiseMultFloatWithRet", "(", "lhs", ".", "data", ",", "rhs", ",", "ret", ".", "data", ")", "return", "ret" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/tensor.py#L1278-L1299
lilypond/lilypond
2a14759372979f5b796ee802b0ee3bc15d28b06b
release/binaries/lib/build.py
python
Package.license_files
(self)
return []
Return the list of license files for this package
Return the list of license files for this package
[ "Return", "the", "list", "of", "license", "files", "for", "this", "package" ]
def license_files(self) -> List[str]: """Return the list of license files for this package""" return []
[ "def", "license_files", "(", "self", ")", "->", "List", "[", "str", "]", ":", "return", "[", "]" ]
https://github.com/lilypond/lilypond/blob/2a14759372979f5b796ee802b0ee3bc15d28b06b/release/binaries/lib/build.py#L225-L227
taichi-dev/taichi
973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6
python/taichi/lang/struct.py
python
Struct.fill
(self, val)
return self.element_wise_writeback_binary(assign_renamed, val)
Fills the Struct with a specific value in Taichi scope. Args: val (Union[int, float]): Value to fill.
Fills the Struct with a specific value in Taichi scope.
[ "Fills", "the", "Struct", "with", "a", "specific", "value", "in", "Taichi", "scope", "." ]
def fill(self, val): """Fills the Struct with a specific value in Taichi scope. Args: val (Union[int, float]): Value to fill. """ def assign_renamed(x, y): return ops.assign(x, y) return self.element_wise_writeback_binary(assign_renamed, val)
[ "def", "fill", "(", "self", ",", "val", ")", ":", "def", "assign_renamed", "(", "x", ",", "y", ")", ":", "return", "ops", ".", "assign", "(", "x", ",", "y", ")", "return", "self", ".", "element_wise_writeback_binary", "(", "assign_renamed", ",", "val", ")" ]
https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/lang/struct.py#L168-L177
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/sNMR/mrs.py
python
MRS.run
(self, verbose=True, uncertainty=False, **kwargs)
Easiest variant doing all (create fop and inv) in one call.
Easiest variant doing all (create fop and inv) in one call.
[ "Easiest", "variant", "doing", "all", "(", "create", "fop", "and", "inv", ")", "in", "one", "call", "." ]
def run(self, verbose=True, uncertainty=False, **kwargs): """Easiest variant doing all (create fop and inv) in one call.""" self.invert(verbose=verbose, **kwargs) if uncertainty: if verbose: print("Computing uncertainty...") self.modelL, self.modelU = iterateBounds( self.INV, dchi2=self.INV.chi2() / 2, change=1.2) if verbose: print("ready")
[ "def", "run", "(", "self", ",", "verbose", "=", "True", ",", "uncertainty", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "invert", "(", "verbose", "=", "verbose", ",", "*", "*", "kwargs", ")", "if", "uncertainty", ":", "if", "verbose", ":", "print", "(", "\"Computing uncertainty...\"", ")", "self", ".", "modelL", ",", "self", ".", "modelU", "=", "iterateBounds", "(", "self", ".", "INV", ",", "dchi2", "=", "self", ".", "INV", ".", "chi2", "(", ")", "/", "2", ",", "change", "=", "1.2", ")", "if", "verbose", ":", "print", "(", "\"ready\"", ")" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/sNMR/mrs.py#L433-L442
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.SetSelectionStart
(*args, **kwargs)
return _stc.StyledTextCtrl_SetSelectionStart(*args, **kwargs)
SetSelectionStart(self, int pos) Sets the position that starts the selection - this becomes the anchor.
SetSelectionStart(self, int pos)
[ "SetSelectionStart", "(", "self", "int", "pos", ")" ]
def SetSelectionStart(*args, **kwargs): """ SetSelectionStart(self, int pos) Sets the position that starts the selection - this becomes the anchor. """ return _stc.StyledTextCtrl_SetSelectionStart(*args, **kwargs)
[ "def", "SetSelectionStart", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetSelectionStart", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L3428-L3434
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/rexec.py
python
RExec.s_reload
(self, *args)
return self.s_apply(self.r_reload, args)
Reload the module object, re-parsing and re-initializing it. This method is implicitly called by code executing in the restricted environment. Overriding this method in a subclass is used to change the policies enforced by a restricted environment. Similar to the r_reload() method, but has access to restricted versions of the standard I/O streams sys.stdin, sys.stderr, and sys.stdout.
Reload the module object, re-parsing and re-initializing it.
[ "Reload", "the", "module", "object", "re", "-", "parsing", "and", "re", "-", "initializing", "it", "." ]
def s_reload(self, *args): """Reload the module object, re-parsing and re-initializing it. This method is implicitly called by code executing in the restricted environment. Overriding this method in a subclass is used to change the policies enforced by a restricted environment. Similar to the r_reload() method, but has access to restricted versions of the standard I/O streams sys.stdin, sys.stderr, and sys.stdout. """ return self.s_apply(self.r_reload, args)
[ "def", "s_reload", "(", "self", ",", "*", "args", ")", ":", "return", "self", ".", "s_apply", "(", "self", ".", "r_reload", ",", "args", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/rexec.py#L477-L489
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/transforms/partial_optimize.py
python
PartialProblem.is_imag
(self)
return False
Is the Leaf imaginary?
Is the Leaf imaginary?
[ "Is", "the", "Leaf", "imaginary?" ]
def is_imag(self) -> bool: """Is the Leaf imaginary? """ return False
[ "def", "is_imag", "(", "self", ")", "->", "bool", ":", "return", "False" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/transforms/partial_optimize.py#L175-L178
apple/swift-clang
d7403439fc6641751840b723e7165fb02f52db95
bindings/python/clang/cindex.py
python
Cursor.get_template_argument_type
(self, num)
return conf.lib.clang_Cursor_getTemplateArgumentType(self, num)
Returns the CXType for the indicated template argument.
Returns the CXType for the indicated template argument.
[ "Returns", "the", "CXType", "for", "the", "indicated", "template", "argument", "." ]
def get_template_argument_type(self, num): """Returns the CXType for the indicated template argument.""" return conf.lib.clang_Cursor_getTemplateArgumentType(self, num)
[ "def", "get_template_argument_type", "(", "self", ",", "num", ")", ":", "return", "conf", ".", "lib", ".", "clang_Cursor_getTemplateArgumentType", "(", "self", ",", "num", ")" ]
https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L1815-L1817
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/globe_cutter_app.py
python
GlobeBuilder.ConvertPolygonToQtNodes
(self, polygon_level, is_mercator=False)
Convert polygon into a set of qt nodes at given level.
Convert polygon into a set of qt nodes at given level.
[ "Convert", "polygon", "into", "a", "set", "of", "qt", "nodes", "at", "given", "level", "." ]
def ConvertPolygonToQtNodes(self, polygon_level, is_mercator=False): """Convert polygon into a set of qt nodes at given level.""" self.Status("Convert polygon to quadtree nodes ...") try: os.remove(self.qtnodes_file) except OSError: pass # Ok, if file isn't there. os_cmd = ("%s/gepolygontoqtnodes --qt_nodes_file=\"%s\" " "--kml_polygon_file=\"%s\" --max_level=%d" % (COMMAND_DIR, self.qtnodes_file, self.polygon_file, polygon_level)) if is_mercator: os_cmd += " --mercator" common.utils.ExecuteCmd(os_cmd, self.logger) fp = open(self.qtnodes_file) self.Status("%d qtnodes" % len(fp.readlines())) fp.close()
[ "def", "ConvertPolygonToQtNodes", "(", "self", ",", "polygon_level", ",", "is_mercator", "=", "False", ")", ":", "self", ".", "Status", "(", "\"Convert polygon to quadtree nodes ...\"", ")", "try", ":", "os", ".", "remove", "(", "self", ".", "qtnodes_file", ")", "except", "OSError", ":", "pass", "# Ok, if file isn't there.", "os_cmd", "=", "(", "\"%s/gepolygontoqtnodes --qt_nodes_file=\\\"%s\\\" \"", "\"--kml_polygon_file=\\\"%s\\\" --max_level=%d\"", "%", "(", "COMMAND_DIR", ",", "self", ".", "qtnodes_file", ",", "self", ".", "polygon_file", ",", "polygon_level", ")", ")", "if", "is_mercator", ":", "os_cmd", "+=", "\" --mercator\"", "common", ".", "utils", ".", "ExecuteCmd", "(", "os_cmd", ",", "self", ".", "logger", ")", "fp", "=", "open", "(", "self", ".", "qtnodes_file", ")", "self", ".", "Status", "(", "\"%d qtnodes\"", "%", "len", "(", "fp", ".", "readlines", "(", ")", ")", ")", "fp", ".", "close", "(", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/globe_cutter_app.py#L224-L242
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
tools/scripts/update-pr-base-branch.py
python
update_base_branch
(prs, newbase, token)
Updates the base branch of each PR to newbas :param prs: A list of PullRequest objects :param newbase: A string giving the new base for each pull request :param token: An authorization token for GitHub
Updates the base branch of each PR to newbas :param prs: A list of PullRequest objects :param newbase: A string giving the new base for each pull request :param token: An authorization token for GitHub
[ "Updates", "the", "base", "branch", "of", "each", "PR", "to", "newbas", ":", "param", "prs", ":", "A", "list", "of", "PullRequest", "objects", ":", "param", "newbase", ":", "A", "string", "giving", "the", "new", "base", "for", "each", "pull", "request", ":", "param", "token", ":", "An", "authorization", "token", "for", "GitHub" ]
def update_base_branch(prs, newbase, token): """ Updates the base branch of each PR to newbas :param prs: A list of PullRequest objects :param newbase: A string giving the new base for each pull request :param token: An authorization token for GitHub """ for pr in prs: update_pr_base_branch(pr, newbase, token)
[ "def", "update_base_branch", "(", "prs", ",", "newbase", ",", "token", ")", ":", "for", "pr", "in", "prs", ":", "update_pr_base_branch", "(", "pr", ",", "newbase", ",", "token", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/tools/scripts/update-pr-base-branch.py#L123-L131
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/cmdline.py
python
CoverageScript.command_line
(self, argv)
return OK
The bulk of the command line interface to Coverage. `argv` is the argument list to process. Returns 0 if all is well, 1 if something went wrong.
The bulk of the command line interface to Coverage.
[ "The", "bulk", "of", "the", "command", "line", "interface", "to", "Coverage", "." ]
def command_line(self, argv): """The bulk of the command line interface to Coverage. `argv` is the argument list to process. Returns 0 if all is well, 1 if something went wrong. """ # Collect the command-line options. if not argv: self.help_fn(topic='minimum_help') return OK # The command syntax we parse depends on the first argument. Classic # syntax always starts with an option. classic = argv[0].startswith('-') if classic: parser = ClassicOptionParser() else: parser = CMDS.get(argv[0]) if not parser: self.help_fn("Unknown command: '%s'" % argv[0]) return ERR argv = argv[1:] parser.help_fn = self.help_fn ok, options, args = parser.parse_args(argv) if not ok: return ERR # Handle help. if options.help: if classic: self.help_fn(topic='help') else: self.help_fn(parser=parser) return OK if "help" in options.actions: if args: for a in args: parser = CMDS.get(a) if parser: self.help_fn(parser=parser) else: self.help_fn(topic=a) else: self.help_fn(topic='help') return OK # Handle version. if options.version: self.help_fn(topic='version') return OK # Check for conflicts and problems in the options. for i in ['erase', 'execute']: for j in ['annotate', 'html', 'report', 'combine']: if (i in options.actions) and (j in options.actions): self.help_fn("You can't specify the '%s' and '%s' " "options at the same time." % (i, j)) return ERR if not options.actions: self.help_fn( "You must specify at least one of -e, -x, -c, -r, -a, or -b." ) return ERR args_allowed = ( 'execute' in options.actions or 'annotate' in options.actions or 'html' in options.actions or 'debug' in options.actions or 'report' in options.actions or 'xml' in options.actions ) if not args_allowed and args: self.help_fn("Unexpected arguments: %s" % " ".join(args)) return ERR if 'execute' in options.actions and not args: self.help_fn("Nothing to do.") return ERR # Listify the list options. source = unshell_list(options.source) omit = unshell_list(options.omit) include = unshell_list(options.include) # Do something. self.coverage = self.covpkg.coverage( data_suffix = options.parallel_mode, cover_pylib = options.pylib, timid = options.timid, branch = options.branch, config_file = options.rcfile, source = source, omit = omit, include = include, ) if 'debug' in options.actions: if not args: self.help_fn("What information would you like: data, sys?") return ERR for info in args: if info == 'sys': print("-- sys ----------------------------------------") for label, info in self.coverage.sysinfo(): if info == []: info = "-none-" if isinstance(info, list): print("%15s:" % label) for e in info: print("%15s %s" % ("", e)) else: print("%15s: %s" % (label, info)) elif info == 'data': print("-- data ---------------------------------------") self.coverage.load() print("path: %s" % self.coverage.data.filename) print("has_arcs: %r" % self.coverage.data.has_arcs()) summary = self.coverage.data.summary(fullpath=True) if summary: filenames = sorted(summary.keys()) print("\n%d files:" % len(filenames)) for f in filenames: print("%s: %d lines" % (f, summary[f])) else: print("No data collected") else: self.help_fn("Don't know what you mean by %r" % info) return ERR return OK if 'erase' in options.actions or options.erase_first: self.coverage.erase() else: self.coverage.load() if 'execute' in options.actions: # Run the script. self.coverage.start() code_ran = True try: try: if options.module: self.run_python_module(args[0], args) else: self.run_python_file(args[0], args) except NoSource: code_ran = False raise finally: if code_ran: self.coverage.stop() self.coverage.save() if 'combine' in options.actions: self.coverage.combine() self.coverage.save() # Remaining actions are reporting, with some common options. report_args = dict( morfs = args, ignore_errors = options.ignore_errors, omit = omit, include = include, ) if 'report' in options.actions: self.coverage.report( show_missing=options.show_missing, **report_args) if 'annotate' in options.actions: self.coverage.annotate( directory=options.directory, **report_args) if 'html' in options.actions: self.coverage.html_report( directory=options.directory, **report_args) if 'xml' in options.actions: outfile = options.outfile self.coverage.xml_report(outfile=outfile, **report_args) return OK
[ "def", "command_line", "(", "self", ",", "argv", ")", ":", "# Collect the command-line options.", "if", "not", "argv", ":", "self", ".", "help_fn", "(", "topic", "=", "'minimum_help'", ")", "return", "OK", "# The command syntax we parse depends on the first argument. Classic", "# syntax always starts with an option.", "classic", "=", "argv", "[", "0", "]", ".", "startswith", "(", "'-'", ")", "if", "classic", ":", "parser", "=", "ClassicOptionParser", "(", ")", "else", ":", "parser", "=", "CMDS", ".", "get", "(", "argv", "[", "0", "]", ")", "if", "not", "parser", ":", "self", ".", "help_fn", "(", "\"Unknown command: '%s'\"", "%", "argv", "[", "0", "]", ")", "return", "ERR", "argv", "=", "argv", "[", "1", ":", "]", "parser", ".", "help_fn", "=", "self", ".", "help_fn", "ok", ",", "options", ",", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "if", "not", "ok", ":", "return", "ERR", "# Handle help.", "if", "options", ".", "help", ":", "if", "classic", ":", "self", ".", "help_fn", "(", "topic", "=", "'help'", ")", "else", ":", "self", ".", "help_fn", "(", "parser", "=", "parser", ")", "return", "OK", "if", "\"help\"", "in", "options", ".", "actions", ":", "if", "args", ":", "for", "a", "in", "args", ":", "parser", "=", "CMDS", ".", "get", "(", "a", ")", "if", "parser", ":", "self", ".", "help_fn", "(", "parser", "=", "parser", ")", "else", ":", "self", ".", "help_fn", "(", "topic", "=", "a", ")", "else", ":", "self", ".", "help_fn", "(", "topic", "=", "'help'", ")", "return", "OK", "# Handle version.", "if", "options", ".", "version", ":", "self", ".", "help_fn", "(", "topic", "=", "'version'", ")", "return", "OK", "# Check for conflicts and problems in the options.", "for", "i", "in", "[", "'erase'", ",", "'execute'", "]", ":", "for", "j", "in", "[", "'annotate'", ",", "'html'", ",", "'report'", ",", "'combine'", "]", ":", "if", "(", "i", "in", "options", ".", "actions", ")", "and", "(", "j", "in", "options", ".", "actions", ")", ":", "self", ".", "help_fn", "(", "\"You can't specify the '%s' and '%s' \"", "\"options at the same time.\"", "%", "(", "i", ",", "j", ")", ")", "return", "ERR", "if", "not", "options", ".", "actions", ":", "self", ".", "help_fn", "(", "\"You must specify at least one of -e, -x, -c, -r, -a, or -b.\"", ")", "return", "ERR", "args_allowed", "=", "(", "'execute'", "in", "options", ".", "actions", "or", "'annotate'", "in", "options", ".", "actions", "or", "'html'", "in", "options", ".", "actions", "or", "'debug'", "in", "options", ".", "actions", "or", "'report'", "in", "options", ".", "actions", "or", "'xml'", "in", "options", ".", "actions", ")", "if", "not", "args_allowed", "and", "args", ":", "self", ".", "help_fn", "(", "\"Unexpected arguments: %s\"", "%", "\" \"", ".", "join", "(", "args", ")", ")", "return", "ERR", "if", "'execute'", "in", "options", ".", "actions", "and", "not", "args", ":", "self", ".", "help_fn", "(", "\"Nothing to do.\"", ")", "return", "ERR", "# Listify the list options.", "source", "=", "unshell_list", "(", "options", ".", "source", ")", "omit", "=", "unshell_list", "(", "options", ".", "omit", ")", "include", "=", "unshell_list", "(", "options", ".", "include", ")", "# Do something.", "self", ".", "coverage", "=", "self", ".", "covpkg", ".", "coverage", "(", "data_suffix", "=", "options", ".", "parallel_mode", ",", "cover_pylib", "=", "options", ".", "pylib", ",", "timid", "=", "options", ".", "timid", ",", "branch", "=", "options", ".", "branch", ",", "config_file", "=", "options", ".", "rcfile", ",", "source", "=", "source", ",", "omit", "=", "omit", ",", "include", "=", "include", ",", ")", "if", "'debug'", "in", "options", ".", "actions", ":", "if", "not", "args", ":", "self", ".", "help_fn", "(", "\"What information would you like: data, sys?\"", ")", "return", "ERR", "for", "info", "in", "args", ":", "if", "info", "==", "'sys'", ":", "print", "(", "\"-- sys ----------------------------------------\"", ")", "for", "label", ",", "info", "in", "self", ".", "coverage", ".", "sysinfo", "(", ")", ":", "if", "info", "==", "[", "]", ":", "info", "=", "\"-none-\"", "if", "isinstance", "(", "info", ",", "list", ")", ":", "print", "(", "\"%15s:\"", "%", "label", ")", "for", "e", "in", "info", ":", "print", "(", "\"%15s %s\"", "%", "(", "\"\"", ",", "e", ")", ")", "else", ":", "print", "(", "\"%15s: %s\"", "%", "(", "label", ",", "info", ")", ")", "elif", "info", "==", "'data'", ":", "print", "(", "\"-- data ---------------------------------------\"", ")", "self", ".", "coverage", ".", "load", "(", ")", "print", "(", "\"path: %s\"", "%", "self", ".", "coverage", ".", "data", ".", "filename", ")", "print", "(", "\"has_arcs: %r\"", "%", "self", ".", "coverage", ".", "data", ".", "has_arcs", "(", ")", ")", "summary", "=", "self", ".", "coverage", ".", "data", ".", "summary", "(", "fullpath", "=", "True", ")", "if", "summary", ":", "filenames", "=", "sorted", "(", "summary", ".", "keys", "(", ")", ")", "print", "(", "\"\\n%d files:\"", "%", "len", "(", "filenames", ")", ")", "for", "f", "in", "filenames", ":", "print", "(", "\"%s: %d lines\"", "%", "(", "f", ",", "summary", "[", "f", "]", ")", ")", "else", ":", "print", "(", "\"No data collected\"", ")", "else", ":", "self", ".", "help_fn", "(", "\"Don't know what you mean by %r\"", "%", "info", ")", "return", "ERR", "return", "OK", "if", "'erase'", "in", "options", ".", "actions", "or", "options", ".", "erase_first", ":", "self", ".", "coverage", ".", "erase", "(", ")", "else", ":", "self", ".", "coverage", ".", "load", "(", ")", "if", "'execute'", "in", "options", ".", "actions", ":", "# Run the script.", "self", ".", "coverage", ".", "start", "(", ")", "code_ran", "=", "True", "try", ":", "try", ":", "if", "options", ".", "module", ":", "self", ".", "run_python_module", "(", "args", "[", "0", "]", ",", "args", ")", "else", ":", "self", ".", "run_python_file", "(", "args", "[", "0", "]", ",", "args", ")", "except", "NoSource", ":", "code_ran", "=", "False", "raise", "finally", ":", "if", "code_ran", ":", "self", ".", "coverage", ".", "stop", "(", ")", "self", ".", "coverage", ".", "save", "(", ")", "if", "'combine'", "in", "options", ".", "actions", ":", "self", ".", "coverage", ".", "combine", "(", ")", "self", ".", "coverage", ".", "save", "(", ")", "# Remaining actions are reporting, with some common options.", "report_args", "=", "dict", "(", "morfs", "=", "args", ",", "ignore_errors", "=", "options", ".", "ignore_errors", ",", "omit", "=", "omit", ",", "include", "=", "include", ",", ")", "if", "'report'", "in", "options", ".", "actions", ":", "self", ".", "coverage", ".", "report", "(", "show_missing", "=", "options", ".", "show_missing", ",", "*", "*", "report_args", ")", "if", "'annotate'", "in", "options", ".", "actions", ":", "self", ".", "coverage", ".", "annotate", "(", "directory", "=", "options", ".", "directory", ",", "*", "*", "report_args", ")", "if", "'html'", "in", "options", ".", "actions", ":", "self", ".", "coverage", ".", "html_report", "(", "directory", "=", "options", ".", "directory", ",", "*", "*", "report_args", ")", "if", "'xml'", "in", "options", ".", "actions", ":", "outfile", "=", "options", ".", "outfile", "self", ".", "coverage", ".", "xml_report", "(", "outfile", "=", "outfile", ",", "*", "*", "report_args", ")", "return", "OK" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/cmdline.py#L370-L554
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Type.argument_types
(self)
return ArgumentsIterator(self)
Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance.
Retrieve a container for the non-variadic arguments for this type.
[ "Retrieve", "a", "container", "for", "the", "non", "-", "variadic", "arguments", "for", "this", "type", "." ]
def argument_types(self): """Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance. """ class ArgumentsIterator(collections.Sequence): def __init__(self, parent): self.parent = parent self.length = None def __len__(self): if self.length is None: self.length = conf.lib.clang_getNumArgTypes(self.parent) return self.length def __getitem__(self, key): # FIXME Support slice objects. if not isinstance(key, int): raise TypeError("Must supply a non-negative int.") if key < 0: raise IndexError("Only non-negative indexes are accepted.") if key >= len(self): raise IndexError("Index greater than container length: " "%d > %d" % ( key, len(self) )) result = conf.lib.clang_getArgType(self.parent, key) if result.kind == TypeKind.INVALID: raise IndexError("Argument could not be retrieved.") return result assert self.kind == TypeKind.FUNCTIONPROTO return ArgumentsIterator(self)
[ "def", "argument_types", "(", "self", ")", ":", "class", "ArgumentsIterator", "(", "collections", ".", "Sequence", ")", ":", "def", "__init__", "(", "self", ",", "parent", ")", ":", "self", ".", "parent", "=", "parent", "self", ".", "length", "=", "None", "def", "__len__", "(", "self", ")", ":", "if", "self", ".", "length", "is", "None", ":", "self", ".", "length", "=", "conf", ".", "lib", ".", "clang_getNumArgTypes", "(", "self", ".", "parent", ")", "return", "self", ".", "length", "def", "__getitem__", "(", "self", ",", "key", ")", ":", "# FIXME Support slice objects.", "if", "not", "isinstance", "(", "key", ",", "int", ")", ":", "raise", "TypeError", "(", "\"Must supply a non-negative int.\"", ")", "if", "key", "<", "0", ":", "raise", "IndexError", "(", "\"Only non-negative indexes are accepted.\"", ")", "if", "key", ">=", "len", "(", "self", ")", ":", "raise", "IndexError", "(", "\"Index greater than container length: \"", "\"%d > %d\"", "%", "(", "key", ",", "len", "(", "self", ")", ")", ")", "result", "=", "conf", ".", "lib", ".", "clang_getArgType", "(", "self", ".", "parent", ",", "key", ")", "if", "result", ".", "kind", "==", "TypeKind", ".", "INVALID", ":", "raise", "IndexError", "(", "\"Argument could not be retrieved.\"", ")", "return", "result", "assert", "self", ".", "kind", "==", "TypeKind", ".", "FUNCTIONPROTO", "return", "ArgumentsIterator", "(", "self", ")" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1465-L1501
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/utils/extmath.py
python
randomized_svd
(M, n_components, n_oversamples=10, n_iter='auto', power_iteration_normalizer='auto', transpose='auto', flip_sign=True, random_state=0)
Computes a truncated randomized SVD Parameters ---------- M: ndarray or sparse matrix Matrix to decompose n_components: int Number of singular values and vectors to extract. n_oversamples: int (default is 10) Additional number of random vectors to sample the range of M so as to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of approximation of singular vectors and singular values. n_iter: int or 'auto' (default is 'auto') Number of power iterations. It can be used to deal with very noisy problems. When 'auto', it is set to 4, unless `n_components` is small (< .1 * min(X.shape)) `n_iter` in which case is set to 7. This improves precision with few components. .. versionchanged:: 0.18 power_iteration_normalizer: 'auto' (default), 'QR', 'LU', 'none' Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), 'none' (the fastest but numerically unstable when `n_iter` is large, e.g. typically 5 or larger), or 'LU' factorization (numerically stable but can lose slightly in accuracy). The 'auto' mode applies no normalization if `n_iter`<=2 and switches to LU otherwise. .. versionadded:: 0.18 transpose: True, False or 'auto' (default) Whether the algorithm should be applied to M.T instead of M. The result should approximately be the same. The 'auto' mode will trigger the transposition if M.shape[1] > M.shape[0] since this implementation of randomized SVD tend to be a little faster in that case. .. versionchanged:: 0.18 flip_sign: boolean, (True by default) The output of a singular value decomposition is only unique up to a permutation of the signs of the singular vectors. If `flip_sign` is set to `True`, the sign ambiguity is resolved by making the largest loadings for each component in the left singular vectors positive. random_state: RandomState or an int seed (0 by default) A random number generator instance to make behavior Notes ----- This algorithm finds a (usually very good) approximate truncated singular value decomposition using randomization to speed up the computations. It is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, `n_iter` can be set <=2 (at the cost of loss of precision). References ---------- * Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 http://arxiv.org/abs/arXiv:0909.4061 * A randomized algorithm for the decomposition of matrices Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert * An implementation of a randomized algorithm for principal component analysis A. Szlam et al. 2014
Computes a truncated randomized SVD
[ "Computes", "a", "truncated", "randomized", "SVD" ]
def randomized_svd(M, n_components, n_oversamples=10, n_iter='auto', power_iteration_normalizer='auto', transpose='auto', flip_sign=True, random_state=0): """Computes a truncated randomized SVD Parameters ---------- M: ndarray or sparse matrix Matrix to decompose n_components: int Number of singular values and vectors to extract. n_oversamples: int (default is 10) Additional number of random vectors to sample the range of M so as to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of approximation of singular vectors and singular values. n_iter: int or 'auto' (default is 'auto') Number of power iterations. It can be used to deal with very noisy problems. When 'auto', it is set to 4, unless `n_components` is small (< .1 * min(X.shape)) `n_iter` in which case is set to 7. This improves precision with few components. .. versionchanged:: 0.18 power_iteration_normalizer: 'auto' (default), 'QR', 'LU', 'none' Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), 'none' (the fastest but numerically unstable when `n_iter` is large, e.g. typically 5 or larger), or 'LU' factorization (numerically stable but can lose slightly in accuracy). The 'auto' mode applies no normalization if `n_iter`<=2 and switches to LU otherwise. .. versionadded:: 0.18 transpose: True, False or 'auto' (default) Whether the algorithm should be applied to M.T instead of M. The result should approximately be the same. The 'auto' mode will trigger the transposition if M.shape[1] > M.shape[0] since this implementation of randomized SVD tend to be a little faster in that case. .. versionchanged:: 0.18 flip_sign: boolean, (True by default) The output of a singular value decomposition is only unique up to a permutation of the signs of the singular vectors. If `flip_sign` is set to `True`, the sign ambiguity is resolved by making the largest loadings for each component in the left singular vectors positive. random_state: RandomState or an int seed (0 by default) A random number generator instance to make behavior Notes ----- This algorithm finds a (usually very good) approximate truncated singular value decomposition using randomization to speed up the computations. It is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, `n_iter` can be set <=2 (at the cost of loss of precision). References ---------- * Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 http://arxiv.org/abs/arXiv:0909.4061 * A randomized algorithm for the decomposition of matrices Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert * An implementation of a randomized algorithm for principal component analysis A. Szlam et al. 2014 """ random_state = check_random_state(random_state) n_random = n_components + n_oversamples n_samples, n_features = M.shape if n_iter == 'auto': # Checks if the number of iterations is explicitely specified # Adjust n_iter. 7 was found a good compromise for PCA. See #5299 n_iter = 7 if n_components < .1 * min(M.shape) else 4 if transpose == 'auto': transpose = n_samples < n_features if transpose: # this implementation is a bit faster with smaller shape[1] M = M.T Q = randomized_range_finder(M, n_random, n_iter, power_iteration_normalizer, random_state) # project M to the (k + p) dimensional space using the basis vectors B = safe_sparse_dot(Q.T, M) # compute the SVD on the thin matrix: (k + p) wide Uhat, s, V = linalg.svd(B, full_matrices=False) del B U = np.dot(Q, Uhat) if flip_sign: if not transpose: U, V = svd_flip(U, V) else: # In case of transpose u_based_decision=false # to actually flip based on u and not v. U, V = svd_flip(U, V, u_based_decision=False) if transpose: # transpose back the results according to the input convention return V[:n_components, :].T, s[:n_components], U[:, :n_components].T else: return U[:, :n_components], s[:n_components], V[:n_components, :]
[ "def", "randomized_svd", "(", "M", ",", "n_components", ",", "n_oversamples", "=", "10", ",", "n_iter", "=", "'auto'", ",", "power_iteration_normalizer", "=", "'auto'", ",", "transpose", "=", "'auto'", ",", "flip_sign", "=", "True", ",", "random_state", "=", "0", ")", ":", "random_state", "=", "check_random_state", "(", "random_state", ")", "n_random", "=", "n_components", "+", "n_oversamples", "n_samples", ",", "n_features", "=", "M", ".", "shape", "if", "n_iter", "==", "'auto'", ":", "# Checks if the number of iterations is explicitely specified", "# Adjust n_iter. 7 was found a good compromise for PCA. See #5299", "n_iter", "=", "7", "if", "n_components", "<", ".1", "*", "min", "(", "M", ".", "shape", ")", "else", "4", "if", "transpose", "==", "'auto'", ":", "transpose", "=", "n_samples", "<", "n_features", "if", "transpose", ":", "# this implementation is a bit faster with smaller shape[1]", "M", "=", "M", ".", "T", "Q", "=", "randomized_range_finder", "(", "M", ",", "n_random", ",", "n_iter", ",", "power_iteration_normalizer", ",", "random_state", ")", "# project M to the (k + p) dimensional space using the basis vectors", "B", "=", "safe_sparse_dot", "(", "Q", ".", "T", ",", "M", ")", "# compute the SVD on the thin matrix: (k + p) wide", "Uhat", ",", "s", ",", "V", "=", "linalg", ".", "svd", "(", "B", ",", "full_matrices", "=", "False", ")", "del", "B", "U", "=", "np", ".", "dot", "(", "Q", ",", "Uhat", ")", "if", "flip_sign", ":", "if", "not", "transpose", ":", "U", ",", "V", "=", "svd_flip", "(", "U", ",", "V", ")", "else", ":", "# In case of transpose u_based_decision=false", "# to actually flip based on u and not v.", "U", ",", "V", "=", "svd_flip", "(", "U", ",", "V", ",", "u_based_decision", "=", "False", ")", "if", "transpose", ":", "# transpose back the results according to the input convention", "return", "V", "[", ":", "n_components", ",", ":", "]", ".", "T", ",", "s", "[", ":", "n_components", "]", ",", "U", "[", ":", ",", ":", "n_components", "]", ".", "T", "else", ":", "return", "U", "[", ":", ",", ":", "n_components", "]", ",", "s", "[", ":", "n_components", "]", ",", "V", "[", ":", "n_components", ",", ":", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/extmath.py#L270-L386
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/decimal.py
python
Decimal._round
(self, places, rounding)
return ans
Round a nonzero, nonspecial Decimal to a fixed number of significant figures, using the given rounding mode. Infinities, NaNs and zeros are returned unaltered. This operation is quiet: it raises no flags, and uses no information from the context.
Round a nonzero, nonspecial Decimal to a fixed number of significant figures, using the given rounding mode.
[ "Round", "a", "nonzero", "nonspecial", "Decimal", "to", "a", "fixed", "number", "of", "significant", "figures", "using", "the", "given", "rounding", "mode", "." ]
def _round(self, places, rounding): """Round a nonzero, nonspecial Decimal to a fixed number of significant figures, using the given rounding mode. Infinities, NaNs and zeros are returned unaltered. This operation is quiet: it raises no flags, and uses no information from the context. """ if places <= 0: raise ValueError("argument should be at least 1 in _round") if self._is_special or not self: return Decimal(self) ans = self._rescale(self.adjusted()+1-places, rounding) # it can happen that the rescale alters the adjusted exponent; # for example when rounding 99.97 to 3 significant figures. # When this happens we end up with an extra 0 at the end of # the number; a second rescale fixes this. if ans.adjusted() != self.adjusted(): ans = ans._rescale(ans.adjusted()+1-places, rounding) return ans
[ "def", "_round", "(", "self", ",", "places", ",", "rounding", ")", ":", "if", "places", "<=", "0", ":", "raise", "ValueError", "(", "\"argument should be at least 1 in _round\"", ")", "if", "self", ".", "_is_special", "or", "not", "self", ":", "return", "Decimal", "(", "self", ")", "ans", "=", "self", ".", "_rescale", "(", "self", ".", "adjusted", "(", ")", "+", "1", "-", "places", ",", "rounding", ")", "# it can happen that the rescale alters the adjusted exponent;", "# for example when rounding 99.97 to 3 significant figures.", "# When this happens we end up with an extra 0 at the end of", "# the number; a second rescale fixes this.", "if", "ans", ".", "adjusted", "(", ")", "!=", "self", ".", "adjusted", "(", ")", ":", "ans", "=", "ans", ".", "_rescale", "(", "ans", ".", "adjusted", "(", ")", "+", "1", "-", "places", ",", "rounding", ")", "return", "ans" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L2387-L2408
fasiondog/hikyuu
842751aa25283f9fdafc6f560ea262f79e67a307
hikyuu/data/pytdx_to_h5.py
python
import_data
(connect, market, ktype, quotations, api, dest_dir, startDate=199012190000, progress=ProgressBar)
return add_record_count
导入通达信指定盘后数据路径中的K线数据。注:只导入基础信息数据库中存在的股票。 :param connect : sqlit3链接 :param market : 'SH' | 'SZ' :param ktype : 'DAY' | '1MIN' | '5MIN' :param quotations: 'stock' | 'fund' | 'bond' :param src_dir : 盘后K线数据路径,如上证5分钟线:D:\\Tdx\\vipdoc\\sh\\fzline :param dest_dir : HDF5数据文件所在目录 :param progress : 进度显示函数 :return: 导入记录数
导入通达信指定盘后数据路径中的K线数据。注:只导入基础信息数据库中存在的股票。
[ "导入通达信指定盘后数据路径中的K线数据。注:只导入基础信息数据库中存在的股票。" ]
def import_data(connect, market, ktype, quotations, api, dest_dir, startDate=199012190000, progress=ProgressBar): """导入通达信指定盘后数据路径中的K线数据。注:只导入基础信息数据库中存在的股票。 :param connect : sqlit3链接 :param market : 'SH' | 'SZ' :param ktype : 'DAY' | '1MIN' | '5MIN' :param quotations: 'stock' | 'fund' | 'bond' :param src_dir : 盘后K线数据路径,如上证5分钟线:D:\\Tdx\\vipdoc\\sh\\fzline :param dest_dir : HDF5数据文件所在目录 :param progress : 进度显示函数 :return: 导入记录数 """ add_record_count = 0 market = market.upper() h5file = open_h5file(dest_dir, market, ktype) stock_list = get_stock_list(connect, market, quotations) total = len(stock_list) for i, stock in enumerate(stock_list): if stock[3] == 0: if progress: progress(i, total) continue this_count = import_one_stock_data(connect, api, h5file, market, ktype, stock, startDate) add_record_count += this_count if this_count > 0: if ktype == 'DAY': update_hdf5_extern_data(h5file, market.upper() + stock[2], 'DAY') elif ktype == '5MIN': update_hdf5_extern_data(h5file, market.upper() + stock[2], '5MIN') if progress: progress(i, total) connect.commit() h5file.close() return add_record_count
[ "def", "import_data", "(", "connect", ",", "market", ",", "ktype", ",", "quotations", ",", "api", ",", "dest_dir", ",", "startDate", "=", "199012190000", ",", "progress", "=", "ProgressBar", ")", ":", "add_record_count", "=", "0", "market", "=", "market", ".", "upper", "(", ")", "h5file", "=", "open_h5file", "(", "dest_dir", ",", "market", ",", "ktype", ")", "stock_list", "=", "get_stock_list", "(", "connect", ",", "market", ",", "quotations", ")", "total", "=", "len", "(", "stock_list", ")", "for", "i", ",", "stock", "in", "enumerate", "(", "stock_list", ")", ":", "if", "stock", "[", "3", "]", "==", "0", ":", "if", "progress", ":", "progress", "(", "i", ",", "total", ")", "continue", "this_count", "=", "import_one_stock_data", "(", "connect", ",", "api", ",", "h5file", ",", "market", ",", "ktype", ",", "stock", ",", "startDate", ")", "add_record_count", "+=", "this_count", "if", "this_count", ">", "0", ":", "if", "ktype", "==", "'DAY'", ":", "update_hdf5_extern_data", "(", "h5file", ",", "market", ".", "upper", "(", ")", "+", "stock", "[", "2", "]", ",", "'DAY'", ")", "elif", "ktype", "==", "'5MIN'", ":", "update_hdf5_extern_data", "(", "h5file", ",", "market", ".", "upper", "(", ")", "+", "stock", "[", "2", "]", ",", "'5MIN'", ")", "if", "progress", ":", "progress", "(", "i", ",", "total", ")", "connect", ".", "commit", "(", ")", "h5file", ".", "close", "(", ")", "return", "add_record_count" ]
https://github.com/fasiondog/hikyuu/blob/842751aa25283f9fdafc6f560ea262f79e67a307/hikyuu/data/pytdx_to_h5.py#L283-L320
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/saving/utils_v1/export_output.py
python
ExportOutput._wrap_and_check_outputs
( self, outputs, single_output_default_name, error_label=None)
return output_dict
Wraps raw tensors as dicts and checks type. Note that we create a new dict here so that we can overwrite the keys if necessary. Args: outputs: A `Tensor` or a dict of string to `Tensor`. single_output_default_name: A string key for use in the output dict if the provided `outputs` is a raw tensor. error_label: descriptive string for use in error messages. If none, single_output_default_name will be used. Returns: A dict of tensors Raises: ValueError: if the outputs dict keys are not strings or tuples of strings or the values are not Tensors.
Wraps raw tensors as dicts and checks type.
[ "Wraps", "raw", "tensors", "as", "dicts", "and", "checks", "type", "." ]
def _wrap_and_check_outputs( self, outputs, single_output_default_name, error_label=None): """Wraps raw tensors as dicts and checks type. Note that we create a new dict here so that we can overwrite the keys if necessary. Args: outputs: A `Tensor` or a dict of string to `Tensor`. single_output_default_name: A string key for use in the output dict if the provided `outputs` is a raw tensor. error_label: descriptive string for use in error messages. If none, single_output_default_name will be used. Returns: A dict of tensors Raises: ValueError: if the outputs dict keys are not strings or tuples of strings or the values are not Tensors. """ if not isinstance(outputs, dict): outputs = {single_output_default_name: outputs} output_dict = {} for key, value in outputs.items(): error_name = error_label or single_output_default_name key = self._check_output_key(key, error_name) if not isinstance(value, ops.Tensor): raise ValueError( '{} output value must be a Tensor; got {}.'.format( error_name, value)) output_dict[key] = value return output_dict
[ "def", "_wrap_and_check_outputs", "(", "self", ",", "outputs", ",", "single_output_default_name", ",", "error_label", "=", "None", ")", ":", "if", "not", "isinstance", "(", "outputs", ",", "dict", ")", ":", "outputs", "=", "{", "single_output_default_name", ":", "outputs", "}", "output_dict", "=", "{", "}", "for", "key", ",", "value", "in", "outputs", ".", "items", "(", ")", ":", "error_name", "=", "error_label", "or", "single_output_default_name", "key", "=", "self", ".", "_check_output_key", "(", "key", ",", "error_name", ")", "if", "not", "isinstance", "(", "value", ",", "ops", ".", "Tensor", ")", ":", "raise", "ValueError", "(", "'{} output value must be a Tensor; got {}.'", ".", "format", "(", "error_name", ",", "value", ")", ")", "output_dict", "[", "key", "]", "=", "value", "return", "output_dict" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/saving/utils_v1/export_output.py#L61-L95
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/linalg.py
python
dot_3_mm
(context, builder, sig, args)
return impl_ret_borrowed(context, builder, sig.return_type, out._getvalue())
np.dot(matrix, matrix, out)
np.dot(matrix, matrix, out)
[ "np", ".", "dot", "(", "matrix", "matrix", "out", ")" ]
def dot_3_mm(context, builder, sig, args): """ np.dot(matrix, matrix, out) """ xty, yty, outty = sig.args assert outty == sig.return_type dtype = xty.dtype x = make_array(xty)(context, builder, args[0]) y = make_array(yty)(context, builder, args[1]) out = make_array(outty)(context, builder, args[2]) x_shapes = cgutils.unpack_tuple(builder, x.shape) y_shapes = cgutils.unpack_tuple(builder, y.shape) out_shapes = cgutils.unpack_tuple(builder, out.shape) m, k = x_shapes _k, n = y_shapes # The only case Numpy supports assert outty.layout == 'C' def check_args(a, b, out): m, k = a.shape _k, n = b.shape if k != _k: raise ValueError("incompatible array sizes for np.dot(a, b) " "(matrix * matrix)") if out.shape != (m, n): raise ValueError("incompatible output array size for " "np.dot(a, b, out) (matrix * matrix)") context.compile_internal(builder, check_args, signature(types.none, *sig.args), args) check_c_int(context, builder, m) check_c_int(context, builder, k) check_c_int(context, builder, n) x_data = x.data y_data = y.data out_data = out.data # Check whether any of the operands is really a 1-d vector represented # as a (1, k) or (k, 1) 2-d array. In those cases, it is pessimal # to call the generic matrix * matrix product BLAS function. one = ir.Constant(intp_t, 1) is_left_vec = builder.icmp_signed('==', m, one) is_right_vec = builder.icmp_signed('==', n, one) with builder.if_else(is_right_vec) as (r_vec, r_mat): with r_vec: with builder.if_else(is_left_vec) as (v_v, m_v): with v_v: # V * V call_xxdot(context, builder, False, dtype, k, x_data, y_data, out_data) with m_v: # M * V do_trans = xty.layout == outty.layout call_xxgemv(context, builder, do_trans, xty, x_shapes, x_data, y_data, out_data) with r_mat: with builder.if_else(is_left_vec) as (v_m, m_m): with v_m: # V * M do_trans = yty.layout != outty.layout call_xxgemv(context, builder, do_trans, yty, y_shapes, y_data, x_data, out_data) with m_m: # M * M call_xxgemm(context, builder, xty, x_shapes, x_data, yty, y_shapes, y_data, outty, out_shapes, out_data) return impl_ret_borrowed(context, builder, sig.return_type, out._getvalue())
[ "def", "dot_3_mm", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "xty", ",", "yty", ",", "outty", "=", "sig", ".", "args", "assert", "outty", "==", "sig", ".", "return_type", "dtype", "=", "xty", ".", "dtype", "x", "=", "make_array", "(", "xty", ")", "(", "context", ",", "builder", ",", "args", "[", "0", "]", ")", "y", "=", "make_array", "(", "yty", ")", "(", "context", ",", "builder", ",", "args", "[", "1", "]", ")", "out", "=", "make_array", "(", "outty", ")", "(", "context", ",", "builder", ",", "args", "[", "2", "]", ")", "x_shapes", "=", "cgutils", ".", "unpack_tuple", "(", "builder", ",", "x", ".", "shape", ")", "y_shapes", "=", "cgutils", ".", "unpack_tuple", "(", "builder", ",", "y", ".", "shape", ")", "out_shapes", "=", "cgutils", ".", "unpack_tuple", "(", "builder", ",", "out", ".", "shape", ")", "m", ",", "k", "=", "x_shapes", "_k", ",", "n", "=", "y_shapes", "# The only case Numpy supports", "assert", "outty", ".", "layout", "==", "'C'", "def", "check_args", "(", "a", ",", "b", ",", "out", ")", ":", "m", ",", "k", "=", "a", ".", "shape", "_k", ",", "n", "=", "b", ".", "shape", "if", "k", "!=", "_k", ":", "raise", "ValueError", "(", "\"incompatible array sizes for np.dot(a, b) \"", "\"(matrix * matrix)\"", ")", "if", "out", ".", "shape", "!=", "(", "m", ",", "n", ")", ":", "raise", "ValueError", "(", "\"incompatible output array size for \"", "\"np.dot(a, b, out) (matrix * matrix)\"", ")", "context", ".", "compile_internal", "(", "builder", ",", "check_args", ",", "signature", "(", "types", ".", "none", ",", "*", "sig", ".", "args", ")", ",", "args", ")", "check_c_int", "(", "context", ",", "builder", ",", "m", ")", "check_c_int", "(", "context", ",", "builder", ",", "k", ")", "check_c_int", "(", "context", ",", "builder", ",", "n", ")", "x_data", "=", "x", ".", "data", "y_data", "=", "y", ".", "data", "out_data", "=", "out", ".", "data", "# Check whether any of the operands is really a 1-d vector represented", "# as a (1, k) or (k, 1) 2-d array. In those cases, it is pessimal", "# to call the generic matrix * matrix product BLAS function.", "one", "=", "ir", ".", "Constant", "(", "intp_t", ",", "1", ")", "is_left_vec", "=", "builder", ".", "icmp_signed", "(", "'=='", ",", "m", ",", "one", ")", "is_right_vec", "=", "builder", ".", "icmp_signed", "(", "'=='", ",", "n", ",", "one", ")", "with", "builder", ".", "if_else", "(", "is_right_vec", ")", "as", "(", "r_vec", ",", "r_mat", ")", ":", "with", "r_vec", ":", "with", "builder", ".", "if_else", "(", "is_left_vec", ")", "as", "(", "v_v", ",", "m_v", ")", ":", "with", "v_v", ":", "# V * V", "call_xxdot", "(", "context", ",", "builder", ",", "False", ",", "dtype", ",", "k", ",", "x_data", ",", "y_data", ",", "out_data", ")", "with", "m_v", ":", "# M * V", "do_trans", "=", "xty", ".", "layout", "==", "outty", ".", "layout", "call_xxgemv", "(", "context", ",", "builder", ",", "do_trans", ",", "xty", ",", "x_shapes", ",", "x_data", ",", "y_data", ",", "out_data", ")", "with", "r_mat", ":", "with", "builder", ".", "if_else", "(", "is_left_vec", ")", "as", "(", "v_m", ",", "m_m", ")", ":", "with", "v_m", ":", "# V * M", "do_trans", "=", "yty", ".", "layout", "!=", "outty", ".", "layout", "call_xxgemv", "(", "context", ",", "builder", ",", "do_trans", ",", "yty", ",", "y_shapes", ",", "y_data", ",", "x_data", ",", "out_data", ")", "with", "m_m", ":", "# M * M", "call_xxgemm", "(", "context", ",", "builder", ",", "xty", ",", "x_shapes", ",", "x_data", ",", "yty", ",", "y_shapes", ",", "y_data", ",", "outty", ",", "out_shapes", ",", "out_data", ")", "return", "impl_ret_borrowed", "(", "context", ",", "builder", ",", "sig", ".", "return_type", ",", "out", ".", "_getvalue", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/linalg.py#L626-L700
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py
python
SubstitutionEnvironment.MergeFlags
(self, args, unique=1, dict=None)
return self
Merge the dict in args into the construction variables of this env, or the passed-in dict. If args is not a dict, it is converted into a dict using ParseFlags. If unique is not set, the flags are appended rather than merged.
Merge the dict in args into the construction variables of this env, or the passed-in dict. If args is not a dict, it is converted into a dict using ParseFlags. If unique is not set, the flags are appended rather than merged.
[ "Merge", "the", "dict", "in", "args", "into", "the", "construction", "variables", "of", "this", "env", "or", "the", "passed", "-", "in", "dict", ".", "If", "args", "is", "not", "a", "dict", "it", "is", "converted", "into", "a", "dict", "using", "ParseFlags", ".", "If", "unique", "is", "not", "set", "the", "flags", "are", "appended", "rather", "than", "merged", "." ]
def MergeFlags(self, args, unique=1, dict=None): """ Merge the dict in args into the construction variables of this env, or the passed-in dict. If args is not a dict, it is converted into a dict using ParseFlags. If unique is not set, the flags are appended rather than merged. """ if dict is None: dict = self if not SCons.Util.is_Dict(args): args = self.ParseFlags(args) if not unique: self.Append(**args) return self for key, value in args.items(): if not value: continue try: orig = self[key] except KeyError: orig = value else: if not orig: orig = value elif value: # Add orig and value. The logic here was lifted from # part of env.Append() (see there for a lot of comments # about the order in which things are tried) and is # used mainly to handle coercion of strings to CLVar to # "do the right thing" given (e.g.) an original CCFLAGS # string variable like '-pipe -Wall'. try: orig = orig + value except (KeyError, TypeError): try: add_to_orig = orig.append except AttributeError: value.insert(0, orig) orig = value else: add_to_orig(value) t = [] if key[-4:] == 'PATH': ### keep left-most occurence for v in orig: if v not in t: t.append(v) else: ### keep right-most occurence orig.reverse() for v in orig: if v not in t: t.insert(0, v) self[key] = t return self
[ "def", "MergeFlags", "(", "self", ",", "args", ",", "unique", "=", "1", ",", "dict", "=", "None", ")", ":", "if", "dict", "is", "None", ":", "dict", "=", "self", "if", "not", "SCons", ".", "Util", ".", "is_Dict", "(", "args", ")", ":", "args", "=", "self", ".", "ParseFlags", "(", "args", ")", "if", "not", "unique", ":", "self", ".", "Append", "(", "*", "*", "args", ")", "return", "self", "for", "key", ",", "value", "in", "args", ".", "items", "(", ")", ":", "if", "not", "value", ":", "continue", "try", ":", "orig", "=", "self", "[", "key", "]", "except", "KeyError", ":", "orig", "=", "value", "else", ":", "if", "not", "orig", ":", "orig", "=", "value", "elif", "value", ":", "# Add orig and value. The logic here was lifted from", "# part of env.Append() (see there for a lot of comments", "# about the order in which things are tried) and is", "# used mainly to handle coercion of strings to CLVar to", "# \"do the right thing\" given (e.g.) an original CCFLAGS", "# string variable like '-pipe -Wall'.", "try", ":", "orig", "=", "orig", "+", "value", "except", "(", "KeyError", ",", "TypeError", ")", ":", "try", ":", "add_to_orig", "=", "orig", ".", "append", "except", "AttributeError", ":", "value", ".", "insert", "(", "0", ",", "orig", ")", "orig", "=", "value", "else", ":", "add_to_orig", "(", "value", ")", "t", "=", "[", "]", "if", "key", "[", "-", "4", ":", "]", "==", "'PATH'", ":", "### keep left-most occurence", "for", "v", "in", "orig", ":", "if", "v", "not", "in", "t", ":", "t", ".", "append", "(", "v", ")", "else", ":", "### keep right-most occurence", "orig", ".", "reverse", "(", ")", "for", "v", "in", "orig", ":", "if", "v", "not", "in", "t", ":", "t", ".", "insert", "(", "0", ",", "v", ")", "self", "[", "key", "]", "=", "t", "return", "self" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py#L803-L858
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests_toolbelt/multipart/decoder.py
python
BodyPart.text
(self)
return self.content.decode(self.encoding)
Content of the ``BodyPart`` in unicode.
Content of the ``BodyPart`` in unicode.
[ "Content", "of", "the", "BodyPart", "in", "unicode", "." ]
def text(self): """Content of the ``BodyPart`` in unicode.""" return self.content.decode(self.encoding)
[ "def", "text", "(", "self", ")", ":", "return", "self", ".", "content", ".", "decode", "(", "self", ".", "encoding", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests_toolbelt/multipart/decoder.py#L69-L71
osrf/gazebo
f570338107862253229a0514ffea10deab4f4517
tools/cpplint.py
python
CheckForNewlineAtEOF
(filename, lines, error)
Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Logs an error if there is no newline char at the end of the file.
[ "Logs", "an", "error", "if", "there", "is", "no", "newline", "char", "at", "the", "end", "of", "the", "file", "." ]
def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.')
[ "def", "CheckForNewlineAtEOF", "(", "filename", ",", "lines", ",", "error", ")", ":", "# The array lines() was created by adding two newlines to the", "# original file (go figure), then splitting on \\n.", "# To verify that the file ends in \\n, we just have to make sure the", "# last-but-two element of lines() exists and is empty.", "if", "len", "(", "lines", ")", "<", "3", "or", "lines", "[", "-", "2", "]", ":", "error", "(", "filename", ",", "len", "(", "lines", ")", "-", "2", ",", "'whitespace/ending_newline'", ",", "5", ",", "'Could not find a newline character at the end of the file.'", ")" ]
https://github.com/osrf/gazebo/blob/f570338107862253229a0514ffea10deab4f4517/tools/cpplint.py#L1119-L1134
dicecco1/fpga_caffe
7a191704efd7873071cfef35772d7e7bf3e3cfd6
scripts/cpp_lint.py
python
FileInfo.FullName
(self)
return os.path.abspath(self._filename).replace('\\', '/')
Make Windows paths like Unix.
Make Windows paths like Unix.
[ "Make", "Windows", "paths", "like", "Unix", "." ]
def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/')
[ "def", "FullName", "(", "self", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "self", ".", "_filename", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")" ]
https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/scripts/cpp_lint.py#L885-L887
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/schema.py
python
Struct.get
(self, item, default_value)
return getattr(self, item, default_value)
similar to python's dictionary get method, return field of item if found (i.e. self.item is valid) or otherwise return default_value it's a syntax suger of python's builtin getattr method
similar to python's dictionary get method, return field of item if found (i.e. self.item is valid) or otherwise return default_value
[ "similar", "to", "python", "s", "dictionary", "get", "method", "return", "field", "of", "item", "if", "found", "(", "i", ".", "e", ".", "self", ".", "item", "is", "valid", ")", "or", "otherwise", "return", "default_value" ]
def get(self, item, default_value): """ similar to python's dictionary get method, return field of item if found (i.e. self.item is valid) or otherwise return default_value it's a syntax suger of python's builtin getattr method """ return getattr(self, item, default_value)
[ "def", "get", "(", "self", ",", "item", ",", "default_value", ")", ":", "return", "getattr", "(", "self", ",", "item", ",", "default_value", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/schema.py#L535-L542
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py
python
IPv6Address.packed
(self)
return v6_int_to_packed(self._ip)
The binary representation of this address.
The binary representation of this address.
[ "The", "binary", "representation", "of", "this", "address", "." ]
def packed(self): """The binary representation of this address.""" return v6_int_to_packed(self._ip)
[ "def", "packed", "(", "self", ")", ":", "return", "v6_int_to_packed", "(", "self", ".", "_ip", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py#L1914-L1916
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/factorization/python/ops/kmeans.py
python
KMeansClustering.__init__
(self, num_clusters, model_dir=None, initial_clusters=clustering_ops.RANDOM_INIT, distance_metric=clustering_ops.SQUARED_EUCLIDEAN_DISTANCE, random_seed=0, use_mini_batch=True, kmeans_plus_plus_num_retries=2, config=None)
Creates a model for running KMeans training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. initial_clusters: specifies how to initialize the clusters for training. See clustering_ops.kmeans for the possible values. distance_metric: the distance metric used for clustering. See clustering_ops.kmeans for the possible values. random_seed: Python integer. Seed for PRNG used to initialize centers. use_mini_batch: If true, use the mini-batch k-means algorithm. Else assume full batch. kmeans_plus_plus_num_retries: For each point that is sampled during kmeans++ initialization, this parameter specifies the number of additional points to draw from the current distribution before selecting the best. If a negative value is specified, a heuristic is used to sample O(log(num_to_sample)) additional points. config: See Estimator
Creates a model for running KMeans training and inference.
[ "Creates", "a", "model", "for", "running", "KMeans", "training", "and", "inference", "." ]
def __init__(self, num_clusters, model_dir=None, initial_clusters=clustering_ops.RANDOM_INIT, distance_metric=clustering_ops.SQUARED_EUCLIDEAN_DISTANCE, random_seed=0, use_mini_batch=True, kmeans_plus_plus_num_retries=2, config=None): """Creates a model for running KMeans training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. initial_clusters: specifies how to initialize the clusters for training. See clustering_ops.kmeans for the possible values. distance_metric: the distance metric used for clustering. See clustering_ops.kmeans for the possible values. random_seed: Python integer. Seed for PRNG used to initialize centers. use_mini_batch: If true, use the mini-batch k-means algorithm. Else assume full batch. kmeans_plus_plus_num_retries: For each point that is sampled during kmeans++ initialization, this parameter specifies the number of additional points to draw from the current distribution before selecting the best. If a negative value is specified, a heuristic is used to sample O(log(num_to_sample)) additional points. config: See Estimator """ super(KMeansClustering, self).__init__( model_dir=model_dir, config=config) self.kmeans_plus_plus_num_retries = kmeans_plus_plus_num_retries self._num_clusters = num_clusters self._training_initial_clusters = initial_clusters self._training_graph = None self._distance_metric = distance_metric self._use_mini_batch = use_mini_batch self._random_seed = random_seed self._initialized = False
[ "def", "__init__", "(", "self", ",", "num_clusters", ",", "model_dir", "=", "None", ",", "initial_clusters", "=", "clustering_ops", ".", "RANDOM_INIT", ",", "distance_metric", "=", "clustering_ops", ".", "SQUARED_EUCLIDEAN_DISTANCE", ",", "random_seed", "=", "0", ",", "use_mini_batch", "=", "True", ",", "kmeans_plus_plus_num_retries", "=", "2", ",", "config", "=", "None", ")", ":", "super", "(", "KMeansClustering", ",", "self", ")", ".", "__init__", "(", "model_dir", "=", "model_dir", ",", "config", "=", "config", ")", "self", ".", "kmeans_plus_plus_num_retries", "=", "kmeans_plus_plus_num_retries", "self", ".", "_num_clusters", "=", "num_clusters", "self", ".", "_training_initial_clusters", "=", "initial_clusters", "self", ".", "_training_graph", "=", "None", "self", ".", "_distance_metric", "=", "distance_metric", "self", ".", "_use_mini_batch", "=", "use_mini_batch", "self", ".", "_random_seed", "=", "random_seed", "self", ".", "_initialized", "=", "False" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/factorization/python/ops/kmeans.py#L51-L89
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
Slider.SetSelection
(*args, **kwargs)
return _controls_.Slider_SetSelection(*args, **kwargs)
SetSelection(self, int min, int max)
SetSelection(self, int min, int max)
[ "SetSelection", "(", "self", "int", "min", "int", "max", ")" ]
def SetSelection(*args, **kwargs): """SetSelection(self, int min, int max)""" return _controls_.Slider_SetSelection(*args, **kwargs)
[ "def", "SetSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "Slider_SetSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L2923-L2925
Tokutek/mongo
0653eabe2c5b9d12b4814617cb7fb2d799937a0f
src/third_party/v8/tools/stats-viewer.py
python
UiCounter.__init__
(self, var, format)
Creates a new ui counter. Args: var: the Tkinter string variable for updating the ui format: the format string used to format this counter
Creates a new ui counter.
[ "Creates", "a", "new", "ui", "counter", "." ]
def __init__(self, var, format): """Creates a new ui counter. Args: var: the Tkinter string variable for updating the ui format: the format string used to format this counter """ self.var = var self.format = format self.last_value = None
[ "def", "__init__", "(", "self", ",", "var", ",", "format", ")", ":", "self", ".", "var", "=", "var", "self", ".", "format", "=", "format", "self", ".", "last_value", "=", "None" ]
https://github.com/Tokutek/mongo/blob/0653eabe2c5b9d12b4814617cb7fb2d799937a0f/src/third_party/v8/tools/stats-viewer.py#L271-L280
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
HelpEvent.__init__
(self, *args, **kwargs)
__init__(self, EventType type=wxEVT_NULL, int winid=0, Point pt=DefaultPosition, int origin=Origin_Unknown) -> HelpEvent
__init__(self, EventType type=wxEVT_NULL, int winid=0, Point pt=DefaultPosition, int origin=Origin_Unknown) -> HelpEvent
[ "__init__", "(", "self", "EventType", "type", "=", "wxEVT_NULL", "int", "winid", "=", "0", "Point", "pt", "=", "DefaultPosition", "int", "origin", "=", "Origin_Unknown", ")", "-", ">", "HelpEvent" ]
def __init__(self, *args, **kwargs): """ __init__(self, EventType type=wxEVT_NULL, int winid=0, Point pt=DefaultPosition, int origin=Origin_Unknown) -> HelpEvent """ _controls_.HelpEvent_swiginit(self,_controls_.new_HelpEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_controls_", ".", "HelpEvent_swiginit", "(", "self", ",", "_controls_", ".", "new_HelpEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L6046-L6051
hszhao/PSPNet
cf7e5a99ba37e46118026e96be5821a9bc63bde0
tools/extra/parse_log.py
python
save_csv_files
(logfile_path, output_dir, train_dict_list, test_dict_list, delimiter=',', verbose=False)
Save CSV files to output_dir If the input log file is, e.g., caffe.INFO, the names will be caffe.INFO.train and caffe.INFO.test
Save CSV files to output_dir
[ "Save", "CSV", "files", "to", "output_dir" ]
def save_csv_files(logfile_path, output_dir, train_dict_list, test_dict_list, delimiter=',', verbose=False): """Save CSV files to output_dir If the input log file is, e.g., caffe.INFO, the names will be caffe.INFO.train and caffe.INFO.test """ log_basename = os.path.basename(logfile_path) train_filename = os.path.join(output_dir, log_basename + '.train') write_csv(train_filename, train_dict_list, delimiter, verbose) test_filename = os.path.join(output_dir, log_basename + '.test') write_csv(test_filename, test_dict_list, delimiter, verbose)
[ "def", "save_csv_files", "(", "logfile_path", ",", "output_dir", ",", "train_dict_list", ",", "test_dict_list", ",", "delimiter", "=", "','", ",", "verbose", "=", "False", ")", ":", "log_basename", "=", "os", ".", "path", ".", "basename", "(", "logfile_path", ")", "train_filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "log_basename", "+", "'.train'", ")", "write_csv", "(", "train_filename", ",", "train_dict_list", ",", "delimiter", ",", "verbose", ")", "test_filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "log_basename", "+", "'.test'", ")", "write_csv", "(", "test_filename", ",", "test_dict_list", ",", "delimiter", ",", "verbose", ")" ]
https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/tools/extra/parse_log.py#L132-L145
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/dir_util.py
python
create_tree
(base_dir, files, mode=0o777, verbose=1, dry_run=0)
Create all the empty directories under 'base_dir' needed to put 'files' there. 'base_dir' is just the name of a directory which doesn't necessarily exist yet; 'files' is a list of filenames to be interpreted relative to 'base_dir'. 'base_dir' + the directory portion of every file in 'files' will be created if it doesn't already exist. 'mode', 'verbose' and 'dry_run' flags are as for 'mkpath()'.
Create all the empty directories under 'base_dir' needed to put 'files' there.
[ "Create", "all", "the", "empty", "directories", "under", "base_dir", "needed", "to", "put", "files", "there", "." ]
def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0): """Create all the empty directories under 'base_dir' needed to put 'files' there. 'base_dir' is just the name of a directory which doesn't necessarily exist yet; 'files' is a list of filenames to be interpreted relative to 'base_dir'. 'base_dir' + the directory portion of every file in 'files' will be created if it doesn't already exist. 'mode', 'verbose' and 'dry_run' flags are as for 'mkpath()'. """ # First get the list of directories to create need_dir = set() for file in files: need_dir.add(os.path.join(base_dir, os.path.dirname(file))) # Now create them for dir in sorted(need_dir): mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
[ "def", "create_tree", "(", "base_dir", ",", "files", ",", "mode", "=", "0o777", ",", "verbose", "=", "1", ",", "dry_run", "=", "0", ")", ":", "# First get the list of directories to create", "need_dir", "=", "set", "(", ")", "for", "file", "in", "files", ":", "need_dir", ".", "add", "(", "os", ".", "path", ".", "join", "(", "base_dir", ",", "os", ".", "path", ".", "dirname", "(", "file", ")", ")", ")", "# Now create them", "for", "dir", "in", "sorted", "(", "need_dir", ")", ":", "mkpath", "(", "dir", ",", "mode", ",", "verbose", "=", "verbose", ",", "dry_run", "=", "dry_run", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/dir_util.py#L80-L97
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py
python
IdleConfParser.Get
(self, section, option, type=None, default=None, raw=False)
Get an option value for given section/option or return default. If type is specified, return as type.
Get an option value for given section/option or return default. If type is specified, return as type.
[ "Get", "an", "option", "value", "for", "given", "section", "/", "option", "or", "return", "default", ".", "If", "type", "is", "specified", "return", "as", "type", "." ]
def Get(self, section, option, type=None, default=None, raw=False): """ Get an option value for given section/option or return default. If type is specified, return as type. """ if not self.has_option(section, option): return default if type=='bool': return self.getboolean(section, option) elif type=='int': return self.getint(section, option) else: return self.get(section, option, raw=raw)
[ "def", "Get", "(", "self", ",", "section", ",", "option", ",", "type", "=", "None", ",", "default", "=", "None", ",", "raw", "=", "False", ")", ":", "if", "not", "self", ".", "has_option", "(", "section", ",", "option", ")", ":", "return", "default", "if", "type", "==", "'bool'", ":", "return", "self", ".", "getboolean", "(", "section", ",", "option", ")", "elif", "type", "==", "'int'", ":", "return", "self", ".", "getint", "(", "section", ",", "option", ")", "else", ":", "return", "self", ".", "get", "(", "section", ",", "option", ",", "raw", "=", "raw", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py#L42-L54
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewModel.IsContainer
(*args, **kwargs)
return _dataview.DataViewModel_IsContainer(*args, **kwargs)
IsContainer(self, DataViewItem item) -> bool Override this to indicate whether an item is a container, in other words, if it is a parent item that can have children.
IsContainer(self, DataViewItem item) -> bool
[ "IsContainer", "(", "self", "DataViewItem", "item", ")", "-", ">", "bool" ]
def IsContainer(*args, **kwargs): """ IsContainer(self, DataViewItem item) -> bool Override this to indicate whether an item is a container, in other words, if it is a parent item that can have children. """ return _dataview.DataViewModel_IsContainer(*args, **kwargs)
[ "def", "IsContainer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewModel_IsContainer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L537-L544
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/getpass.py
python
unix_getpass
(prompt='Password: ', stream=None)
Prompt for a password, with echo turned off. Args: prompt: Written on stream to ask for the input. Default: 'Password: ' stream: A writable file object to display the prompt. Defaults to the tty. If no tty is available defaults to sys.stderr. Returns: The seKr3t input. Raises: EOFError: If our input tty or stdin was closed. GetPassWarning: When we were unable to turn echo off on the input. Always restores terminal settings before returning.
Prompt for a password, with echo turned off.
[ "Prompt", "for", "a", "password", "with", "echo", "turned", "off", "." ]
def unix_getpass(prompt='Password: ', stream=None): """Prompt for a password, with echo turned off. Args: prompt: Written on stream to ask for the input. Default: 'Password: ' stream: A writable file object to display the prompt. Defaults to the tty. If no tty is available defaults to sys.stderr. Returns: The seKr3t input. Raises: EOFError: If our input tty or stdin was closed. GetPassWarning: When we were unable to turn echo off on the input. Always restores terminal settings before returning. """ passwd = None with contextlib.ExitStack() as stack: try: # Always try reading and writing directly on the tty first. fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY) tty = io.FileIO(fd, 'w+') stack.enter_context(tty) input = io.TextIOWrapper(tty) stack.enter_context(input) if not stream: stream = input except OSError as e: # If that fails, see if stdin can be controlled. stack.close() try: fd = sys.stdin.fileno() except (AttributeError, ValueError): fd = None passwd = fallback_getpass(prompt, stream) input = sys.stdin if not stream: stream = sys.stderr if fd is not None: try: old = termios.tcgetattr(fd) # a copy to save new = old[:] new[3] &= ~termios.ECHO # 3 == 'lflags' tcsetattr_flags = termios.TCSAFLUSH if hasattr(termios, 'TCSASOFT'): tcsetattr_flags |= termios.TCSASOFT try: termios.tcsetattr(fd, tcsetattr_flags, new) passwd = _raw_input(prompt, stream, input=input) finally: termios.tcsetattr(fd, tcsetattr_flags, old) stream.flush() # issue7208 except termios.error: if passwd is not None: # _raw_input succeeded. The final tcsetattr failed. Reraise # instead of leaving the terminal in an unknown state. raise # We can't control the tty or stdin. Give up and use normal IO. # fallback_getpass() raises an appropriate warning. if stream is not input: # clean up unused file objects before blocking stack.close() passwd = fallback_getpass(prompt, stream) stream.write('\n') return passwd
[ "def", "unix_getpass", "(", "prompt", "=", "'Password: '", ",", "stream", "=", "None", ")", ":", "passwd", "=", "None", "with", "contextlib", ".", "ExitStack", "(", ")", "as", "stack", ":", "try", ":", "# Always try reading and writing directly on the tty first.", "fd", "=", "os", ".", "open", "(", "'/dev/tty'", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_NOCTTY", ")", "tty", "=", "io", ".", "FileIO", "(", "fd", ",", "'w+'", ")", "stack", ".", "enter_context", "(", "tty", ")", "input", "=", "io", ".", "TextIOWrapper", "(", "tty", ")", "stack", ".", "enter_context", "(", "input", ")", "if", "not", "stream", ":", "stream", "=", "input", "except", "OSError", "as", "e", ":", "# If that fails, see if stdin can be controlled.", "stack", ".", "close", "(", ")", "try", ":", "fd", "=", "sys", ".", "stdin", ".", "fileno", "(", ")", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "fd", "=", "None", "passwd", "=", "fallback_getpass", "(", "prompt", ",", "stream", ")", "input", "=", "sys", ".", "stdin", "if", "not", "stream", ":", "stream", "=", "sys", ".", "stderr", "if", "fd", "is", "not", "None", ":", "try", ":", "old", "=", "termios", ".", "tcgetattr", "(", "fd", ")", "# a copy to save", "new", "=", "old", "[", ":", "]", "new", "[", "3", "]", "&=", "~", "termios", ".", "ECHO", "# 3 == 'lflags'", "tcsetattr_flags", "=", "termios", ".", "TCSAFLUSH", "if", "hasattr", "(", "termios", ",", "'TCSASOFT'", ")", ":", "tcsetattr_flags", "|=", "termios", ".", "TCSASOFT", "try", ":", "termios", ".", "tcsetattr", "(", "fd", ",", "tcsetattr_flags", ",", "new", ")", "passwd", "=", "_raw_input", "(", "prompt", ",", "stream", ",", "input", "=", "input", ")", "finally", ":", "termios", ".", "tcsetattr", "(", "fd", ",", "tcsetattr_flags", ",", "old", ")", "stream", ".", "flush", "(", ")", "# issue7208", "except", "termios", ".", "error", ":", "if", "passwd", "is", "not", "None", ":", "# _raw_input succeeded. The final tcsetattr failed. Reraise", "# instead of leaving the terminal in an unknown state.", "raise", "# We can't control the tty or stdin. Give up and use normal IO.", "# fallback_getpass() raises an appropriate warning.", "if", "stream", "is", "not", "input", ":", "# clean up unused file objects before blocking", "stack", ".", "close", "(", ")", "passwd", "=", "fallback_getpass", "(", "prompt", ",", "stream", ")", "stream", ".", "write", "(", "'\\n'", ")", "return", "passwd" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/getpass.py#L29-L94
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
Flatten.__init__
(self, axis=1)
Args: axis (int): Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [-r, r], where r is the rank of the input tensor. Negative value means counting dimensions from the back. When axis = 0, the shape of the output tensor is `(1, (d_0 X d_1 ... d_n)`, where the shape of the input tensor is `(d_0, d_1, ... d_n)`. Returns: the result CTensor
Args: axis (int): Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [-r, r], where r is the rank of the input tensor. Negative value means counting dimensions from the back. When axis = 0, the shape of the output tensor is `(1, (d_0 X d_1 ... d_n)`, where the shape of the input tensor is `(d_0, d_1, ... d_n)`. Returns: the result CTensor
[ "Args", ":", "axis", "(", "int", ")", ":", "Indicate", "up", "to", "which", "input", "dimensions", "(", "exclusive", ")", "should", "be", "flattened", "to", "the", "outer", "dimension", "of", "the", "output", ".", "The", "value", "for", "axis", "must", "be", "in", "the", "range", "[", "-", "r", "r", "]", "where", "r", "is", "the", "rank", "of", "the", "input", "tensor", ".", "Negative", "value", "means", "counting", "dimensions", "from", "the", "back", ".", "When", "axis", "=", "0", "the", "shape", "of", "the", "output", "tensor", "is", "(", "1", "(", "d_0", "X", "d_1", "...", "d_n", ")", "where", "the", "shape", "of", "the", "input", "tensor", "is", "(", "d_0", "d_1", "...", "d_n", ")", ".", "Returns", ":", "the", "result", "CTensor" ]
def __init__(self, axis=1): """ Args: axis (int): Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [-r, r], where r is the rank of the input tensor. Negative value means counting dimensions from the back. When axis = 0, the shape of the output tensor is `(1, (d_0 X d_1 ... d_n)`, where the shape of the input tensor is `(d_0, d_1, ... d_n)`. Returns: the result CTensor """ super(Flatten, self).__init__() self.axis = axis
[ "def", "__init__", "(", "self", ",", "axis", "=", "1", ")", ":", "super", "(", "Flatten", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "axis", "=", "axis" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L1379-L1393
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
chrome/tools/extract_actions.py
python
AddExtensionActions
(actions)
Add actions reported by extensions via chrome.metricsPrivate API. Arguments: actions: set of actions to add to.
Add actions reported by extensions via chrome.metricsPrivate API.
[ "Add", "actions", "reported", "by", "extensions", "via", "chrome", ".", "metricsPrivate", "API", "." ]
def AddExtensionActions(actions): """Add actions reported by extensions via chrome.metricsPrivate API. Arguments: actions: set of actions to add to. """ # Actions sent by Chrome OS File Browser. actions.add('FileBrowser.CreateNewFolder') actions.add('FileBrowser.PhotoEditor.Edit') actions.add('FileBrowser.PhotoEditor.View')
[ "def", "AddExtensionActions", "(", "actions", ")", ":", "# Actions sent by Chrome OS File Browser.", "actions", ".", "add", "(", "'FileBrowser.CreateNewFolder'", ")", "actions", ".", "add", "(", "'FileBrowser.PhotoEditor.Edit'", ")", "actions", ".", "add", "(", "'FileBrowser.PhotoEditor.View'", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/tools/extract_actions.py#L226-L235
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/win_tool.py
python
WinTool.ExecStamp
(self, path)
Simple stamp command.
Simple stamp command.
[ "Simple", "stamp", "command", "." ]
def ExecStamp(self, path): """Simple stamp command.""" open(path, 'w').close()
[ "def", "ExecStamp", "(", "self", ",", "path", ")", ":", "open", "(", "path", ",", "'w'", ")", ".", "close", "(", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/win_tool.py#L88-L90
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Misc.update
(self)
Enter event loop until all pending events have been processed by Tcl.
Enter event loop until all pending events have been processed by Tcl.
[ "Enter", "event", "loop", "until", "all", "pending", "events", "have", "been", "processed", "by", "Tcl", "." ]
def update(self): """Enter event loop until all pending events have been processed by Tcl.""" self.tk.call('update')
[ "def", "update", "(", "self", ")", ":", "self", ".", "tk", ".", "call", "(", "'update'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L1175-L1177
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/cookielib.py
python
time2isoz
(t=None)
return "%04d-%02d-%02d %02d:%02d:%02dZ" % ( year, mon, mday, hour, min, sec)
Return a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ", representing Universal Time (UTC, aka GMT). An example of this format is: 1994-11-24 08:49:37Z
Return a string representing time in seconds since epoch, t.
[ "Return", "a", "string", "representing", "time", "in", "seconds", "since", "epoch", "t", "." ]
def time2isoz(t=None): """Return a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ", representing Universal Time (UTC, aka GMT). An example of this format is: 1994-11-24 08:49:37Z """ if t is None: t = time.time() year, mon, mday, hour, min, sec = time.gmtime(t)[:6] return "%04d-%02d-%02d %02d:%02d:%02dZ" % ( year, mon, mday, hour, min, sec)
[ "def", "time2isoz", "(", "t", "=", "None", ")", ":", "if", "t", "is", "None", ":", "t", "=", "time", ".", "time", "(", ")", "year", ",", "mon", ",", "mday", ",", "hour", ",", "min", ",", "sec", "=", "time", ".", "gmtime", "(", "t", ")", "[", ":", "6", "]", "return", "\"%04d-%02d-%02d %02d:%02d:%02dZ\"", "%", "(", "year", ",", "mon", ",", "mday", ",", "hour", ",", "min", ",", "sec", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/cookielib.py#L86-L101
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/demo/life.py
python
LifeBoard.erase
(self)
Clear the entire board and update the board display
Clear the entire board and update the board display
[ "Clear", "the", "entire", "board", "and", "update", "the", "board", "display" ]
def erase(self): """Clear the entire board and update the board display""" self.state = {} self.display(update_board=False)
[ "def", "erase", "(", "self", ")", ":", "self", ".", "state", "=", "{", "}", "self", ".", "display", "(", "update_board", "=", "False", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/demo/life.py#L84-L87
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/telnetlib.py
python
Telnet.write
(self, buffer)
Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise socket.error if the connection is closed.
Write a string to the socket, doubling any IAC characters.
[ "Write", "a", "string", "to", "the", "socket", "doubling", "any", "IAC", "characters", "." ]
def write(self, buffer): """Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise socket.error if the connection is closed. """ if IAC in buffer: buffer = buffer.replace(IAC, IAC+IAC) self.msg("send %r", buffer) self.sock.sendall(buffer)
[ "def", "write", "(", "self", ",", "buffer", ")", ":", "if", "IAC", "in", "buffer", ":", "buffer", "=", "buffer", ".", "replace", "(", "IAC", ",", "IAC", "+", "IAC", ")", "self", ".", "msg", "(", "\"send %r\"", ",", "buffer", ")", "self", ".", "sock", ".", "sendall", "(", "buffer", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/telnetlib.py#L272-L282
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/package/package_exporter.py
python
PackageExporter.close
(self)
Write the package to the filesystem. Any calls after :meth:`close` are now invalid. It is preferable to use resource guard syntax instead:: with PackageExporter("file.zip") as e: ...
Write the package to the filesystem. Any calls after :meth:`close` are now invalid. It is preferable to use resource guard syntax instead::
[ "Write", "the", "package", "to", "the", "filesystem", ".", "Any", "calls", "after", ":", "meth", ":", "close", "are", "now", "invalid", ".", "It", "is", "preferable", "to", "use", "resource", "guard", "syntax", "instead", "::" ]
def close(self): """Write the package to the filesystem. Any calls after :meth:`close` are now invalid. It is preferable to use resource guard syntax instead:: with PackageExporter("file.zip") as e: ... """ self._execute_dependency_graph() self.script_module_serializer.write_files() self._finalize_zip()
[ "def", "close", "(", "self", ")", ":", "self", ".", "_execute_dependency_graph", "(", ")", "self", ".", "script_module_serializer", ".", "write_files", "(", ")", "self", ".", "_finalize_zip", "(", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/package/package_exporter.py#L1008-L1018
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
lesion_detector_3DCE/rcnn/dataset/imdb.py
python
IMDB.cache_path
(self)
return cache_path
make a directory to store all caches :return: cache path
make a directory to store all caches :return: cache path
[ "make", "a", "directory", "to", "store", "all", "caches", ":", "return", ":", "cache", "path" ]
def cache_path(self): """ make a directory to store all caches :return: cache path """ cache_path = os.path.join(self.root_path, 'cache') if not os.path.exists(cache_path): os.mkdir(cache_path) return cache_path
[ "def", "cache_path", "(", "self", ")", ":", "cache_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_path", ",", "'cache'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cache_path", ")", ":", "os", ".", "mkdir", "(", "cache_path", ")", "return", "cache_path" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/lesion_detector_3DCE/rcnn/dataset/imdb.py#L50-L58
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
priority_queue/minheap.py
python
MinHeap.swim
(self, index)
swim moves element at index upward to maintain heap invariant
swim moves element at index upward to maintain heap invariant
[ "swim", "moves", "element", "at", "index", "upward", "to", "maintain", "heap", "invariant" ]
def swim(self, index): """ swim moves element at index upward to maintain heap invariant """ if index <= 1: return parent = index // 2 if self.data[parent] > self.data[index]: self.data[parent], self.data[index] = self.data[index], self.data[parent] self.swim(parent)
[ "def", "swim", "(", "self", ",", "index", ")", ":", "if", "index", "<=", "1", ":", "return", "parent", "=", "index", "//", "2", "if", "self", ".", "data", "[", "parent", "]", ">", "self", ".", "data", "[", "index", "]", ":", "self", ".", "data", "[", "parent", "]", ",", "self", ".", "data", "[", "index", "]", "=", "self", ".", "data", "[", "index", "]", ",", "self", ".", "data", "[", "parent", "]", "self", ".", "swim", "(", "parent", ")" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/priority_queue/minheap.py#L49-L57
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
StatusBarPane.SetStyle
(*args, **kwargs)
return _windows_.StatusBarPane_SetStyle(*args, **kwargs)
SetStyle(self, int style)
SetStyle(self, int style)
[ "SetStyle", "(", "self", "int", "style", ")" ]
def SetStyle(*args, **kwargs): """SetStyle(self, int style)""" return _windows_.StatusBarPane_SetStyle(*args, **kwargs)
[ "def", "SetStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "StatusBarPane_SetStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L1205-L1207
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py
python
parse_ns_headers
(ns_headers)
return result
Ad-hoc parser for Netscape protocol cookie-attributes. The old Netscape cookie format for Set-Cookie can for instance contain an unquoted "," in the expires field, so we have to use this ad-hoc parser instead of split_header_words. XXX This may not make the best possible effort to parse all the crap that Netscape Cookie headers contain. Ronald Tschalar's HTTPClient parser is probably better, so could do worse than following that if this ever gives any trouble. Currently, this is also used for parsing RFC 2109 cookies.
Ad-hoc parser for Netscape protocol cookie-attributes.
[ "Ad", "-", "hoc", "parser", "for", "Netscape", "protocol", "cookie", "-", "attributes", "." ]
def parse_ns_headers(ns_headers): """Ad-hoc parser for Netscape protocol cookie-attributes. The old Netscape cookie format for Set-Cookie can for instance contain an unquoted "," in the expires field, so we have to use this ad-hoc parser instead of split_header_words. XXX This may not make the best possible effort to parse all the crap that Netscape Cookie headers contain. Ronald Tschalar's HTTPClient parser is probably better, so could do worse than following that if this ever gives any trouble. Currently, this is also used for parsing RFC 2109 cookies. """ known_attrs = ("expires", "domain", "path", "secure", # RFC 2109 attrs (may turn up in Netscape cookies, too) "version", "port", "max-age") result = [] for ns_header in ns_headers: pairs = [] version_set = False for ii, param in enumerate(re.split(r";\s*", ns_header)): param = param.rstrip() if param == "": continue if "=" not in param: k, v = param, None else: k, v = re.split(r"\s*=\s*", param, 1) k = k.lstrip() if ii != 0: lc = k.lower() if lc in known_attrs: k = lc if k == "version": # This is an RFC 2109 cookie. v = _strip_quotes(v) version_set = True if k == "expires": # convert expires date to seconds since epoch v = http2time(_strip_quotes(v)) # None if invalid pairs.append((k, v)) if pairs: if not version_set: pairs.append(("version", "0")) result.append(pairs) return result
[ "def", "parse_ns_headers", "(", "ns_headers", ")", ":", "known_attrs", "=", "(", "\"expires\"", ",", "\"domain\"", ",", "\"path\"", ",", "\"secure\"", ",", "# RFC 2109 attrs (may turn up in Netscape cookies, too)", "\"version\"", ",", "\"port\"", ",", "\"max-age\"", ")", "result", "=", "[", "]", "for", "ns_header", "in", "ns_headers", ":", "pairs", "=", "[", "]", "version_set", "=", "False", "for", "ii", ",", "param", "in", "enumerate", "(", "re", ".", "split", "(", "r\";\\s*\"", ",", "ns_header", ")", ")", ":", "param", "=", "param", ".", "rstrip", "(", ")", "if", "param", "==", "\"\"", ":", "continue", "if", "\"=\"", "not", "in", "param", ":", "k", ",", "v", "=", "param", ",", "None", "else", ":", "k", ",", "v", "=", "re", ".", "split", "(", "r\"\\s*=\\s*\"", ",", "param", ",", "1", ")", "k", "=", "k", ".", "lstrip", "(", ")", "if", "ii", "!=", "0", ":", "lc", "=", "k", ".", "lower", "(", ")", "if", "lc", "in", "known_attrs", ":", "k", "=", "lc", "if", "k", "==", "\"version\"", ":", "# This is an RFC 2109 cookie.", "v", "=", "_strip_quotes", "(", "v", ")", "version_set", "=", "True", "if", "k", "==", "\"expires\"", ":", "# convert expires date to seconds since epoch", "v", "=", "http2time", "(", "_strip_quotes", "(", "v", ")", ")", "# None if invalid", "pairs", ".", "append", "(", "(", "k", ",", "v", ")", ")", "if", "pairs", ":", "if", "not", "version_set", ":", "pairs", ".", "append", "(", "(", "\"version\"", ",", "\"0\"", ")", ")", "result", ".", "append", "(", "pairs", ")", "return", "result" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py#L444-L493
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/tools/quantization/quantize_graph.py
python
GraphRewriter.should_merge_with_fake_quant_node
(self)
return top[1] == 0 and top[0].op in ["FakeQuantWithMinMaxVars"]
Should the current node merge with self.state.output_node_stack[-1]?
Should the current node merge with self.state.output_node_stack[-1]?
[ "Should", "the", "current", "node", "merge", "with", "self", ".", "state", ".", "output_node_stack", "[", "-", "1", "]", "?" ]
def should_merge_with_fake_quant_node(self): """Should the current node merge with self.state.output_node_stack[-1]?""" if not self.state.output_node_stack: return False top = self.state.output_node_stack[-1] return top[1] == 0 and top[0].op in ["FakeQuantWithMinMaxVars"]
[ "def", "should_merge_with_fake_quant_node", "(", "self", ")", ":", "if", "not", "self", ".", "state", ".", "output_node_stack", ":", "return", "False", "top", "=", "self", ".", "state", ".", "output_node_stack", "[", "-", "1", "]", "return", "top", "[", "1", "]", "==", "0", "and", "top", "[", "0", "]", ".", "op", "in", "[", "\"FakeQuantWithMinMaxVars\"", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/tools/quantization/quantize_graph.py#L554-L559