Create an Output class from a pseudo terminal.
        (This will take the dimensions by reading the pseudo
        terminal attributes.)
558720
def from_pty(cls, stdout, true_color=False, ansi_colors_only=None, term=None):
        
        assert stdout.isatty()
        def get_size():
            rows, columns = _get_size(stdout.fileno())
            # If terminal (incorrectly) reports its size as 0, pick a reasonable default.
            # See https://github.com/ipython/ipython/issues/10071
            return Size(rows=(rows or 24), columns=(columns or 80))

        return cls(stdout, get_size, true_color=true_color,
                   ansi_colors_only=ansi_colors_only, term=term)
1244626
def _gen_indicator_class(self):
        """"""

        for entry in self.tcex.indicator_types_data.values():
            name = entry.get('name')
            class_name = name.replace(' ', '')
            # temp fix for API issue where boolean are returned as strings
            entry['custom'] = self.tcex.utils.to_bool(entry.get('custom'))

            if class_name in globals():
                # skip Indicator Type if a class already exists
                continue

            # Custom Indicator can have 3 values. Only add the value if it is set.
            value_fields = []
            if entry.get('value1Label'):
                value_fields.append(entry['value1Label'])
            if entry.get('value2Label'):
                value_fields.append(entry['value2Label'])
            if entry.get('value3Label'):
                value_fields.append(entry['value3Label'])
            value_count = len(value_fields)

            class_data = {}
            # Add Class for each Custom Indicator type to this module
            custom_class = custom_indicator_class_factory(name, Indicator, class_data, value_fields)
            setattr(module, class_name, custom_class)

            # Add Custom Indicator Method
            self._gen_indicator_method(name, custom_class, value_count)
959038
def classifySPoutput(targetOutputColumns, outputColumns):
  
  numTargets, numDims = targetOutputColumns.shape
  overlap = np.zeros((numTargets,))
  for i in range(numTargets):
    overlap[i] = percentOverlap(outputColumns, targetOutputColumns[i, :])
  classLabel = np.argmax(overlap)
  return classLabel
1089546
def convert(self):
        
        cname = str(self.config["wrapper"])
        self._output = classes.from_commandline(self._input, classname=cname)
        return None
676849
def create(cls, class_name: str, monoid_type=Union[Monoid, str]):
        

        def unit(cls, value):
            if hasattr(monoid_type, "empty"):
                log = monoid_type.empty()
            else:
                log = monoid_type()

            return cls(value, log)

        return type(class_name, (Writer, ), dict(unit=classmethod(unit)))
19266
def get_terminal_size(default_rows=25, default_cols=80):
    
    # Collect a list of viable input channels that may tell us something
    # about the terminal dimensions.
    fileno_list = []
    try:
        fileno_list.append(sys.stdout.fileno())
    except AttributeError:
        # Channel was redirected to an object that has no fileno()
        pass
    except ValueError:
        # Channel was closed while attemting to read it
        pass
    try:
        fileno_list.append(sys.stdin.fileno())
    except AttributeError:
        pass
    except ValueError:
        # Channel was closed while attemting to read it
        pass
    try:
        fileno_list.append(sys.stderr.fileno())
    except AttributeError:
        pass
    except ValueError:
        # Channel was closed while attemting to read it
        pass

    # Ask each channel for the terminal window size.
    for fd in fileno_list:
        try:
            rows, cols = _get_terminal_size(fd)
        except TypeError:
            # _get_terminal_size() returned None.
            pass
        else:
            return rows, cols

    # Try os.ctermid()
    try:
        fd = os.open(os.ctermid(), os.O_RDONLY)
    except AttributeError:
        # os.ctermid does not exist on Windows.
        pass
    except OSError:
        # The device pointed to by os.ctermid() does not exist.
        pass
    else:
        try:
            rows, cols = _get_terminal_size(fd)
        except TypeError:
            # _get_terminal_size() returned None.
            pass
        else:
            return rows, cols
        finally:
            os.close(fd)

    # Try `stty size`
    with open(os.devnull, 'w') as devnull:
        try:
            process = Popen(['stty', 'size'], stderr=devnull, stdout=PIPE,
                            close_fds=True)
        except (OSError, ValueError):
            pass
        else:
            errcode = process.wait()
            output = process.stdout.read()
            try:
                rows, cols = output.split()
                return int(rows), int(cols)
            except (ValueError, TypeError):
                pass

    # Try environment variables.
    try:
        return tuple(int(os.getenv(var)) for var in ('LINES', 'COLUMNS'))
    except (ValueError, TypeError):
        pass

    # Give up.
    return default_rows, default_cols
1125920
def _class_factory(base):
    
    class ClsPyPy(base):
        def __repr__(self):
            return repr(base(super(ClsPyPy, self).value))

        @classmethod
        def from_buffer(cls, ba):
            try:
                integer = struct.unpack_from(getattr(cls, '_type_'), ba)[0]
            except struct.error:
                len_ = len(ba)
                size = struct.calcsize(getattr(cls, '_type_'))
                if len_ < size:
                    raise ValueError('Buffer size too small ({0} instead of at least {1} bytes)'.format(len_, size))
                raise
            return cls(integer)

    class ClsPy26(base):
        def __repr__(self):
            return repr(base(super(ClsPy26, self).value))

        def __iter__(self):
            return iter(struct.pack(getattr(super(ClsPy26, self), '_type_'), super(ClsPy26, self).value))

    try:
        base.from_buffer(bytearray(base()))
    except TypeError:
        # Python2.6, ctypes cannot be converted to bytearrays.
        return ClsPy26
    except AttributeError:
        # PyPy on my Raspberry Pi, ctypes don't have from_buffer attribute.
        return ClsPyPy
    except ValueError:
        # PyPy on Travis CI, from_buffer cannot handle non-buffer() bytearrays.
        return ClsPyPy
    return base
392031
def create(input_width, input_height, input_channels=1, output_dim=512):
    
    def instantiate(**_):
        return NatureCnn(
            input_width=input_width, input_height=input_height, input_channels=input_channels,
            output_dim=output_dim
        )

    return ModelFactory.generic(instantiate)
102630
def from_size(cls, data, width, height):
        # type: (bytearray, int, int) -> ScreenShot
        

        monitor = {"left": 0, "top": 0, "width": width, "height": height}
        return cls(data, monitor)
1033371
def output_sizes(self):
    """"""
    return tuple([l() if callable(l) else l for l in self._output_sizes])
466233
def write(source_mapping, output_stream=sys.stdout):
        
        # a set of classes, modules and/or functions that are values in
        # configman options.  These values will have to be imported in the
        # module that this method is writing.
        set_of_classes_needing_imports = set()
        # once symbols are imported, they are in the namespace of the module,
        # but that's not where we want them.  We only want them to be values
        # in configman Options.  This set will be used to make a list of
        # these symbols, to forewarn a future configman that reads this
        # module, that it can ignore these symbols. This will prevent that
        # future configman from issuing a "mismatced symbols" warinng.
        symbols_to_ignore = set()

        # look ahead to see what sort of imports we're going to have to do
        for key in source_mapping.keys_breadth_first():
            value = source_mapping[key]

            if isinstance(value, Aggregation):
                # Aggregations don't get included, skip on
                continue

            if '.' in key:
                # this indicates that there are things in nested namespaces,
                # we will use the DotDict class to represent namespaces
                set_of_classes_needing_imports.add(DotDict)

            option = None
            if isinstance(value, Option):
                # it's the value inside the option, not the option itself
                # that is of interest to us
                option = value
                value = option.value

            if value is None:
                # we don't need in import anything having to do with None
                continue

            if isclass(value) or ismodule(value) or isfunction(value):
                # we know we need to import any of these types
                set_of_classes_needing_imports.add(value)
            else:
                try:
                    # perhaps the value is an instance of a class?  If so,
                    # we'll likely need to import that class, but only if
                    # we don't have a way to convert a string to that class
                    set_of_classes_needing_imports.add(value.__class__)
                except AttributeError:
                    # it's not a class instance, we can skip on
                    pass

        # for everyone of the imports that we're going to have to create
        # we need to know the dotted module pathname and the name of the
        # of the class/module/function.  This routine make a list of 3-tuples
        # class, dotted_module_path, class_name
        class_and_module_path_and_class_name = []
        for a_class in set_of_classes_needing_imports:
            module_path, class_name = get_import_for_type(a_class)
            if (not module_path) and (not class_name):
                continue
            class_and_module_path_and_class_name.append(
                (a_class, module_path, class_name)
            )

        # using the collection of 3-tuples, create a lookup mapping where a
        # class is the key to a 2-tuple of the dotted_module_path & class_name.
        # This is also the appropriate time to detect any name collisions
        # and create a mapping of aliases, so we can resolve name collisions.
        class_name_by_module_path_list = defaultdict(list)
        alias_by_class = {}
        previously_used_names = set()
        for (
            a_class,
            a_module_path,
            class_name
        ) in class_and_module_path_and_class_name:
            if class_name:
                if class_name in previously_used_names:
                    new_class_name_alias = "%s_%s" % (
                        a_module_path.replace('.', '_'),
                        class_name
                    )
                    alias_by_class[a_class] = new_class_name_alias
                    previously_used_names.add(new_class_name_alias)
                else:
                    previously_used_names.add(class_name)
                class_name_by_module_path_list[a_module_path].append(
                    (a_class, class_name)
                )

        # start writing the output module
        print("# generated Python configman file\n", file=output_stream)

        # the first section that we're going to write is imports of the form:
        #     from X import Y
        # and
        #     from X import (
        #         A,
        #         B,
        #     )
        sorted_list = [x.value for x in sorted([OrderableObj(x) for x in
                       class_name_by_module_path_list.keys()])]
        for a_module_path in sorted_list:
            print(a_module_path)
            # if there is no module path, then it is something that we don't
            # need to import.  If the module path begins with underscore then
            # it is private and we ought not step into that mire.  If that
            # causes the output module to fail, it is up to the implementer
            # of the configman option to have created an approprate
            # "from_string" & "to_string" configman Option function references.
            if a_module_path is None or a_module_path.startswith('_'):
                continue
            list_of_class_names = \
                class_name_by_module_path_list[a_module_path]
            if len(list_of_class_names) > 1:
                output_line = "from %s import (\n" % a_module_path
                sorted_list = [x.value for x in sorted([OrderableTuple(x)
                               for x in list_of_class_names])]
                for a_class, a_class_name in sorted_list:
                    if a_class in alias_by_class:
                        output_line = "%s\n    %s as %s," % (
                            output_line,
                            a_class_name,
                            alias_by_class[a_class]
                        )
                        symbols_to_ignore.add(alias_by_class[a_class])
                    else:
                        output_line = "%s    %s,\n" % (
                            output_line,
                            a_class_name
                        )
                        symbols_to_ignore.add(a_class_name)

                output_line = output_line + ')'
                print(output_line.strip(), file=output_stream)
            else:
                a_class, a_class_name = list_of_class_names[0]
                output_line = "from %s import %s" % (
                    a_module_path,
                    a_class_name
                )
                if a_class in alias_by_class:
                    output_line = "%s as %s" % (
                        output_line,
                        alias_by_class[a_class]
                    )
                    symbols_to_ignore.add(alias_by_class[a_class])
                else:
                    symbols_to_ignore.add(a_class_name)
                print(output_line.strip(), file=output_stream)
        print('', file=output_stream)

        # The next section to write will be the imports of the form:
        #     import X
        sorted_list = [x.value for x in sorted([OrderableObj(x) for x in
                       class_name_by_module_path_list.keys()])]
        for a_module_path in sorted_list:
            list_of_class_names = \
                class_name_by_module_path_list[a_module_path]
            a_class, a_class_name = list_of_class_names[0]
            if a_module_path:
                continue
            import_str = ("import %s" % a_class_name).strip()
            symbols_to_ignore.add(a_class_name)
            print(import_str, file=output_stream)

        # See the explanation of 'symbols_to_ignore' above
        if symbols_to_ignore:
            print(
                "\n" \
                "# the following symbols will be ignored by configman when\n" \
                "# this module is used as a value source.  This will\n" \
                "# suppress the mismatch warning since these symbols are\n" \
                "# values for options, not option names themselves.",
                file=output_stream
            )
            print("ignore_symbol_list = [", file=output_stream)
            for a_symbol in sorted(symbols_to_ignore):
                print('    "%s",' % a_symbol, file=output_stream)
            print(']\n', file=output_stream)

        # finally, as the last step, we need to write out the keys and values
        # will be used by a future configman as Options and values.
        sorted_keys = sorted(
            source_mapping.keys_breadth_first(include_dicts=True)
        )
        for key in sorted_keys:
            value = source_mapping[key]
            if isinstance(value, Namespace):
                ValueSource.write_namespace(key, value, output_stream)
            elif isinstance(value, Option):
                ValueSource.write_option(
                    key,
                    value,
                    alias_by_class,
                    output_stream
                )
            elif isinstance(value, Aggregation):
                # skip Aggregations
                continue
            else:
                ValueSource.write_bare_value(key, value, output_stream)
184066
@SuppressWarnings("unchecked")
  public Class<? extends OutputFormat<?,?>> getOutputFormatClass() 
     throws ClassNotFoundException {
    return (Class<? extends OutputFormat<?,?>>) 
      conf.getClass(OUTPUT_FORMAT_CLASS_ATTR, TextOutputFormat.class);
  }
1306002
def new_from_memory(cls, data):
        """"""

        size = len(data)
        copy = g_memdup(data, size)
        ptr = cast(copy, POINTER(guint8))
        try:
            with gerror(GIError) as error:
                return GITypelib._new_from_memory(ptr, size, error)
        except GIError:
            free(copy)
            raise
1008559
def get_unix_tput_terminal_size():
    
    import subprocess
    try:
        proc = subprocess.Popen(["tput", "cols"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        output = proc.communicate(input=None)
        cols = int(output[0])
        proc = subprocess.Popen(["tput", "lines"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        output = proc.communicate(input=None)
        rows = int(output[0])
        return cols, rows
    except (IOError, OSError):
        return None
25128
def _init_ugly_crap():
    
    import ctypes
    from types import TracebackType

    # figure out side of _Py_ssize_t
    if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
        _Py_ssize_t = ctypes.c_int64
    else:
        _Py_ssize_t = ctypes.c_int

    # regular python
    class _PyObject(ctypes.Structure):
        pass
    _PyObject._fields_ = [
        ('ob_refcnt', _Py_ssize_t),
        ('ob_type', ctypes.POINTER(_PyObject))
    ]

    # python with trace
    if object.__basicsize__ != ctypes.sizeof(_PyObject):
        class _PyObject(ctypes.Structure):
            pass
        _PyObject._fields_ = [
            ('_ob_next', ctypes.POINTER(_PyObject)),
            ('_ob_prev', ctypes.POINTER(_PyObject)),
            ('ob_refcnt', _Py_ssize_t),
            ('ob_type', ctypes.POINTER(_PyObject))
        ]

    class _Traceback(_PyObject):
        pass
    _Traceback._fields_ = [
        ('tb_next', ctypes.POINTER(_Traceback)),
        ('tb_frame', ctypes.POINTER(_PyObject)),
        ('tb_lasti', ctypes.c_int),
        ('tb_lineno', ctypes.c_int)
    ]

    def tb_set_next(tb, next):
        """Set the tb_next attribute of a traceback object."""
        if not (isinstance(tb, TracebackType) and
                (next is None or isinstance(next, TracebackType))):
            raise TypeError('tb_set_next arguments must be traceback objects')
        obj = _Traceback.from_address(id(tb))
        if tb.tb_next is not None:
            old = _Traceback.from_address(id(tb.tb_next))
            old.ob_refcnt -= 1
        if next is None:
            obj.tb_next = ctypes.POINTER(_Traceback)()
        else:
            next = _Traceback.from_address(id(next))
            next.ob_refcnt += 1
            obj.tb_next = ctypes.pointer(next)

    return tb_set_next
924234
private void generateUMLClass(PackageDoc[] pkgs) throws IOException {
        for (int i=0; i < pkgs.length; i++) {
            // generate statistics
            generateUMLClass(pkgs[i].ordinaryClasses(), pkgs[i].name());
        }
    }
677863
def create_class(self):
        
        if self.target_language in ['java', 'go']:
            n_indents = 1 if self.target_language == 'java' else 0
            class_head_temp = self.temp('separated.{}.class'.format(
                self.prefix), n_indents=n_indents, skipping=True)
            self.class_head = class_head_temp.format(**self.__dict__)

        return self.temp('separated.class').format(**self.__dict__)