text:
"""Texture Atlas and Map File Generation Utility Classes"""

DESCRIPTION = """Packs many smaller images into one larger image, a Texture
Atlas. A companion file (.map), is created that defines where each texture is
mapped in the atlas."""

import PIL.Image as Image
import argparse
import os.path
import re
import shlex
import struct

class Packable(object):
    """A two-dimensional object with position information."""

    def __init__(self, width, height):
        self._x      = 0
        self._y      = 0
        self._width  = width
        self._height = height

    @property
    def x(self):
        return self._x
    @x.setter
    def x(self, value):
        self._x = value

    @property
    def y(self):
        return self._y
    @y.setter
    def y(self, value):
        self._y = value

    @property
    def width(self):
        return self._width

    @property
    def height(self):
        return self._height

    @property
    def perimeter(self):
        return 2*self._width + 2*self._height

class PackRegion(object):
    """A region that two-dimensional Packable objects can be packed into."""

    def __init__(self, x, y, width, height):
        """Constructor."""
        self._x        = x
        self._y        = y
        self._width    = width
        self._height   = height
        self._sub1     = None
        self._sub2     = None
        self._packable = None

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

    @property
    def width(self):
        return self._width

    @property
    def height(self):
        return self._height

    @property
    def packable(self):
        return self._packable

    def get_all_packables(self):
        """Returns a list of all Packables in this region and sub-regions."""
        if self._packable:
            return [self._packable] + self._sub1.get_all_packables() + \
                                      self._sub2.get_all_packables()
        return []

    def pack(self, packable):
        """Pack 2D packable into this region."""
        if not self._packable:
            # Is there room to pack this?
            if (packable.width  > self._width) or \
               (packable.height > self._height):
                return False

            # Pack
            self._packable = packable

            # Set x, y on Packable
            self._packable.x = self._x
            self._packable.y = self._y

            # Create sub-regions
            self._sub1 = PackRegion(self._x,
                                    self._y+self._packable.height,
                                    self._packable.width,
                                    self._height-self._packable.height)
            self._sub2 = PackRegion(self._x+self._packable.width,
                                    self._y,
                                    self._width-self._packable.width,
                                    self._height)
            return True

        # Pack into sub-region
        return self._sub1.pack(packable) or self._sub2.pack(packable)

class Frame(Packable):
    """An image file that can be packed into a PackRegion."""

    def __init__(self, filename):
        self._filename = filename

        # Determine frame dimensions
        image = Image.open(filename)
        width, height = image.size
        del image

        super(Frame, self).__init__(width, height)

    @property
    def filename(self):
        return self._filename

    def draw(self, image):
        """Draw this frame into another Image."""
        i = Image.open(self._filename)
        image.paste(i, (self.x, self.y))
        del i

class Texture(object):
    """A collection of one or more frames."""

    def __init__(self, name, frames):
        self._name   = name
        self._frames = frames

    @property
    def name(self):
        return self._name

    @property
    def frames(self):
        return self._frames

class TextureAtlas(PackRegion):
    """Texture Atlas generator."""

    def __init__(self, width, height):
        super(TextureAtlas, self).__init__(0, 0, width, height)
        self._textures = []

    @property
    def textures(self):
        return self._textures

    def pack(self, texture):
        """Pack a Texture into this atlas."""
        self._textures.append(texture)
        for frame in texture.frames:
            if not super(TextureAtlas, self).pack(frame):
                raise Exception('Failed to pack frame %s' % frame.filename)

    def write(self, filename, mode):
        """Generates the final texture atlas."""
        out = Image.new(mode, (self.width, self.height))
        for t in self._textures:
            for f in t.frames:
                f.draw(out)
        out.save(filename)

class TextureAtlasMap(object):
    """Texture Atlas Map file generator."""

    def __init__(self, atlas):
        self._atlas = atlas

    def write(self, fd):
        """Writes the texture atlas map file into file object fd."""
        raise Exception('Not Implemented')

class BinaryTextureAtlasMap(TextureAtlasMap):
    """Binary Texture Atlas Map file generator.

    The binary atlas map is composed of four sections. The first section is the
    header. The second section contains the details of each texture (name,
    number of frames, etc.). The third section contains all null-terminated
    strings referenced by other sections. The fourth section contains the
    coordinates and dimensions of all texture frames.

    HEADER FORMAT

    Offset Size Description
    ------ ---- -----------
    0      4    Magic ('TEXA' = 0x41584554)
    4      4    Texture Atlas Width
    8      4    Texture Atlas Height
    12     4    Number of Textures
    16     4    Texture Section Offset
    20     4    Texture Section Size
    24     4    String Section Offset
    28     4    String Section Size
    32     4    Frame Section Offset
    36     4    Frame Section Size

    TEXTURE FORMAT

    Offset Size Description
    ------ ---- -----------
    0      4    Offset to Texture Name in String Section
    4      4    Number of Frames
    8      4    Offset to first Frame

    FRAME FORMAT

    Offset Size Description
    ------ ---- -----------
    0      4    X-Coordinate of Frame
    4      4    Y-Coordinate of Frame
    8      4    Frame Width
    12     4    Frame Height
    """

    def __init__(self, atlas):
        super(BinaryTextureAtlasMap, self).__init__(atlas)

    def write(self, fd):
        """Writes the binary texture atlas map file into file object fd."""
        # Calculate offset and size of each section
        hdr_fmt = 'IIIIIIIII'
        hdr_fmt_len = struct.calcsize(hdr_fmt)
        hdr_section_len = hdr_fmt_len+4 # Header + Magic

        tex_fmt = 'III'
        tex_fmt_len = struct.calcsize(tex_fmt)
        tex_section_off = hdr_section_len
        tex_section_len = len(self._atlas.textures)*tex_fmt_len

        str_section_off = tex_section_off+tex_section_len
        str_section_len = sum(map(lambda t:len(t.name)+1, self._atlas.textures))

        frm_fmt = 'IIII'
        frm_fmt_len = struct.calcsize(frm_fmt)
        frm_section_off = str_section_off + str_section_len
        frm_section_len = sum(map(lambda t:len(t.frames), self._atlas.textures))
        frm_section_len *= frm_fmt_len

        # Write Header
        fd.write('TEXA')
        fd.write(struct.pack(hdr_fmt, self._atlas.width,
                                      self._atlas.height,
                                      len(self._atlas.textures),
                                      tex_section_off, tex_section_len,
                                      str_section_off, str_section_len,
                                      frm_section_off, frm_section_len))

        # Write Texture Section
        str_offset = 0
        frm_offset = 0
        for t in self._atlas.textures:
            fd.write(struct.pack(tex_fmt, str_offset,
                                          len(t.frames),
                                          frm_offset))
            str_offset += len(t.name)+1 # +1 for sentinel byte
            frm_offset += len(t.frames)*frm_fmt_len

        # Write String Section
        for t in self._atlas.textures:
            fd.write(t.name + '\x00')

        # Write Frame Section
        for t in self._atlas.textures:
            for f in t.frames:
                fd.write(struct.pack(frm_fmt, f.x,
                                              f.y,
                                              f.width,
                                              f.height))

def main():
    # Parse arguments
    arg_parser = argparse.ArgumentParser(description=DESCRIPTION,
                                         formatter_class=argparse.RawDescriptionHelpFormatter)
    arg_parser.add_argument('-o',
                            dest='outfile',
                            metavar='output-file',
                            type=str,
                            default='atlas.png',
                            help='output filename (atlas.png)')
    arg_parser.add_argument('-m', '--mode',
                            metavar='mode',
                            type=str,
                            default='RGBA',
                            help='output file mode (RGBA)')
    arg_parser.add_argument('-s', '--size',
                            metavar='size',
                            type=int,
                            default=512,
                            help='size of atlas (n x n)')
    arg_parser.add_argument('textures',
                            metavar='texture',
                            type=str,
                            nargs='+',
                            help='filename of texture')

    args = arg_parser.parse_args()
    filename, ext = os.path.splitext(args.outfile)

    if ext == '':
        print 'Error: Specify an image extension for outfile (e.g. atlas.png).'
        exit(1)

    # Parse texture names
    textures = []
    for texture in args.textures:
        # Look for a texture name
        matches = re.match('^((\w+)=)?(.+)', texture)
        name, frames = matches.group(2), shlex.split(matches.group(3))

        # If no name was specified, use the first frame's filename
        name = name or os.path.splitext(os.path.basename(frames[0]))[0]

        # Build frame objects
        frames = [Frame(f) for f in frames]

        # Add frames to texture object list
        textures.append(Texture(name, frames))

    # Sort textures by perimeter size in non-increasing order
    textures = sorted(textures, key=lambda i:i.frames[0].perimeter, reverse=True)

    # Create the atlas and pack textures in
    atlas = TextureAtlas(args.size, args.size)

    for texture in textures:
        atlas.pack(texture)

    # Write atlas and map file
    atlas.write(args.outfile, args.mode)
    f = open(filename+'.map', 'wb')
    BinaryTextureAtlasMap(atlas).write(f)
    f.close()

if __name__ == '__main__':
    main()


text:
package test.quote.soap.config;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import test.quote.common.rpc.RemoteProxyConfigurer;

/**
 * Created by Daniil Molchanov on 19.02.17.
 */
@Configuration
public class RabbitConfig {

    @Bean("connectionFactory")
    ConnectionFactory connectionFactory(
            @Value("${rabbit.host}") String host,
            @Value("${rabbit.port}") int port) {
        return new CachingConnectionFactory(host, port);
    }

    @Bean
    public RemoteProxyConfigurer proxy(@Value("${rabbit.rpc.exchange}") String rpcExchange) {
        return new RemoteProxyConfigurer("test.quote.soap", rpcExchange);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Colours.App;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Colours
{
    static class Program
    {
        [DllImport("shcore.dll")]
        static extern int SetProcessDpiAwareness(int value);

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            var state = AppArgParser.ParseArgs(args,
                Properties.Settings.Default.LastColor.ToRgbColor().ToHsv(),
                Properties.Settings.Default.SchemeType);
            if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
                Environment.OSVersion.Version >= new Version(6, 3))
            {
                SetProcessDpiAwareness(1);
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm(state));
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.security;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.airlift.log.Logger;
import io.airlift.units.Duration;
import io.prestosql.plugin.base.security.ForwardingSystemAccessControl;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.connector.CatalogSchemaName;
import io.prestosql.spi.connector.CatalogSchemaTableName;
import io.prestosql.spi.connector.SchemaTableName;
import io.prestosql.spi.security.Identity;
import io.prestosql.spi.security.Privilege;
import io.prestosql.spi.security.SystemAccessControl;
import io.prestosql.spi.security.SystemAccessControlFactory;

import java.nio.file.Paths;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Suppliers.memoizeWithExpiration;
import static io.prestosql.plugin.base.JsonUtils.parseJson;
import static io.prestosql.plugin.base.security.FileBasedAccessControlConfig.SECURITY_CONFIG_FILE;
import static io.prestosql.plugin.base.security.FileBasedAccessControlConfig.SECURITY_REFRESH_PERIOD;
import static io.prestosql.spi.StandardErrorCode.CONFIGURATION_INVALID;
import static io.prestosql.spi.security.AccessDeniedException.denyCatalogAccess;
import static io.prestosql.spi.security.AccessDeniedException.denySetUser;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class FileBasedSystemAccessControl
        implements SystemAccessControl
{
    private static final Logger log = Logger.get(FileBasedSystemAccessControl.class);

    public static final String NAME = "file";

    private final List<CatalogAccessControlRule> catalogRules;
    private final Optional<List<PrincipalUserMatchRule>> principalUserMatchRules;

    private FileBasedSystemAccessControl(List<CatalogAccessControlRule> catalogRules, Optional<List<PrincipalUserMatchRule>> principalUserMatchRules)
    {
        this.catalogRules = catalogRules;
        this.principalUserMatchRules = principalUserMatchRules;
    }

    public static class Factory
            implements SystemAccessControlFactory
    {
        @Override
        public String getName()
        {
            return NAME;
        }

        @Override
        public SystemAccessControl create(Map<String, String> config)
        {
            requireNonNull(config, "config is null");

            String configFileName = config.get(SECURITY_CONFIG_FILE);
            checkState(configFileName != null, "Security configuration must contain the '%s' property", SECURITY_CONFIG_FILE);

            if (config.containsKey(SECURITY_REFRESH_PERIOD)) {
                Duration refreshPeriod;
                try {
                    refreshPeriod = Duration.valueOf(config.get(SECURITY_REFRESH_PERIOD));
                }
                catch (IllegalArgumentException e) {
                    throw invalidRefreshPeriodException(config, configFileName);
                }
                if (refreshPeriod.toMillis() == 0) {
                    throw invalidRefreshPeriodException(config, configFileName);
                }
                return ForwardingSystemAccessControl.of(memoizeWithExpiration(
                        () -> {
                            log.info("Refreshing system access control from %s", configFileName);
                            return create(configFileName);
                        },
                        refreshPeriod.toMillis(),
                        MILLISECONDS));
            }
            return create(configFileName);
        }

        private PrestoException invalidRefreshPeriodException(Map<String, String> config, String configFileName)
        {
            return new PrestoException(
                    CONFIGURATION_INVALID,
                    format("Invalid duration value '%s' for property '%s' in '%s'", config.get(SECURITY_REFRESH_PERIOD), SECURITY_REFRESH_PERIOD, configFileName));
        }

        private SystemAccessControl create(String configFileName)
        {
            FileBasedSystemAccessControlRules rules = parseJson(Paths.get(configFileName), FileBasedSystemAccessControlRules.class);

            ImmutableList.Builder<CatalogAccessControlRule> catalogRulesBuilder = ImmutableList.builder();
            catalogRulesBuilder.addAll(rules.getCatalogRules());

            // Hack to allow Presto Admin to access the "system" catalog for retrieving server status.
            // todo Change userRegex from ".*" to one particular user that Presto Admin will be restricted to run as
            catalogRulesBuilder.add(new CatalogAccessControlRule(
                    true,
                    Optional.of(Pattern.compile(".*")),
                    Optional.of(Pattern.compile("system"))));

            return new FileBasedSystemAccessControl(catalogRulesBuilder.build(), rules.getPrincipalUserMatchRules());
        }
    }

    @Override
    public void checkCanSetUser(Optional<Principal> principal, String userName)
    {
        requireNonNull(principal, "principal is null");
        requireNonNull(userName, "userName is null");

        if (!principalUserMatchRules.isPresent()) {
            return;
        }

        if (!principal.isPresent()) {
            denySetUser(principal, userName);
        }

        String principalName = principal.get().getName();

        for (PrincipalUserMatchRule rule : principalUserMatchRules.get()) {
            Optional<Boolean> allowed = rule.match(principalName, userName);
            if (allowed.isPresent()) {
                if (allowed.get()) {
                    return;
                }
                denySetUser(principal, userName);
            }
        }

        denySetUser(principal, userName);
    }

    @Override
    public void checkCanSetSystemSessionProperty(Identity identity, String propertyName)
    {
    }

    @Override
    public void checkCanAccessCatalog(Identity identity, String catalogName)
    {
        if (!canAccessCatalog(identity, catalogName)) {
            denyCatalogAccess(catalogName);
        }
    }

    @Override
    public Set<String> filterCatalogs(Identity identity, Set<String> catalogs)
    {
        ImmutableSet.Builder<String> filteredCatalogs = ImmutableSet.builder();
        for (String catalog : catalogs) {
            if (canAccessCatalog(identity, catalog)) {
                filteredCatalogs.add(catalog);
            }
        }
        return filteredCatalogs.build();
    }

    private boolean canAccessCatalog(Identity identity, String catalogName)
    {
        for (CatalogAccessControlRule rule : catalogRules) {
            Optional<Boolean> allowed = rule.match(identity.getUser(), catalogName);
            if (allowed.isPresent()) {
                return allowed.get();
            }
        }
        return false;
    }

    @Override
    public void checkCanCreateSchema(Identity identity, CatalogSchemaName schema)
    {
    }

    @Override
    public void checkCanDropSchema(Identity identity, CatalogSchemaName schema)
    {
    }

    @Override
    public void checkCanRenameSchema(Identity identity, CatalogSchemaName schema, String newSchemaName)
    {
    }

    @Override
    public void checkCanShowSchemas(Identity identity, String catalogName)
    {
    }

    @Override
    public Set<String> filterSchemas(Identity identity, String catalogName, Set<String> schemaNames)
    {
        if (!canAccessCatalog(identity, catalogName)) {
            return ImmutableSet.of();
        }

        return schemaNames;
    }

    @Override
    public void checkCanCreateTable(Identity identity, CatalogSchemaTableName table)
    {
    }

    @Override
    public void checkCanDropTable(Identity identity, CatalogSchemaTableName table)
    {
    }

    @Override
    public void checkCanRenameTable(Identity identity, CatalogSchemaTableName table, CatalogSchemaTableName newTable)
    {
    }

    @Override
    public void checkCanShowTablesMetadata(Identity identity, CatalogSchemaName schema)
    {
    }

    @Override
    public Set<SchemaTableName> filterTables(Identity identity, String catalogName, Set<SchemaTableName> tableNames)
    {
        if (!canAccessCatalog(identity, catalogName)) {
            return ImmutableSet.of();
        }

        return tableNames;
    }

    @Override
    public void checkCanAddColumn(Identity identity, CatalogSchemaTableName table)
    {
    }

    @Override
    public void checkCanDropColumn(Identity identity, CatalogSchemaTableName table)
    {
    }

    @Override
    public void checkCanRenameColumn(Identity identity, CatalogSchemaTableName table)
    {
    }

    @Override
    public void checkCanSelectFromColumns(Identity identity, CatalogSchemaTableName table, Set<String> columns)
    {
    }

    @Override
    public void checkCanInsertIntoTable(Identity identity, CatalogSchemaTableName table)
    {
    }

    @Override
    public void checkCanDeleteFromTable(Identity identity, CatalogSchemaTableName table)
    {
    }

    @Override
    public void checkCanCreateView(Identity identity, CatalogSchemaTableName view)
    {
    }

    @Override
    public void checkCanDropView(Identity identity, CatalogSchemaTableName view)
    {
    }

    @Override
    public void checkCanCreateViewWithSelectFromColumns(Identity identity, CatalogSchemaTableName table, Set<String> columns)
    {
    }

    @Override
    public void checkCanSetCatalogSessionProperty(Identity identity, String catalogName, String propertyName)
    {
    }

    @Override
    public void checkCanGrantTablePrivilege(Identity identity, Privilege privilege, CatalogSchemaTableName table, String grantee, boolean withGrantOption)
    {
    }

    @Override
    public void checkCanRevokeTablePrivilege(Identity identity, Privilege privilege, CatalogSchemaTableName table, String revokee, boolean grantOptionFor)
    {
    }
}


text:
#ifndef _BOOTSTRAP_H_
#define	_BOOTSTRAP_H_

#include <sys/types.h>
#include <sys/queue.h>
#include <sys/linker_set.h>

/*
 * Generic device specifier; architecture-dependant
 * versions may be larger, but should be allowed to
 * overlap.
 */
struct devdesc
{
    struct devsw	*d_dev;
    int			d_type;
#define DEVT_NONE	0
#define DEVT_DISK	1
#define DEVT_NET	2
#define	DEVT_CD		3
#define DEVT_ZFS	4
    int			d_unit;
    void		*d_opendata;
};

/* Commands and return values; nonzero return sets command_errmsg != NULL */
typedef int	(bootblk_cmd_t)(int argc, char *argv[]);
extern char	*command_errmsg;
extern char	command_errbuf[];	/* XXX blah, length */
#define CMD_OK		0
#define CMD_ERROR	1

/* interp.c */
void	interact(void);
int	include(const char *filename);

/* interp_backslash.c */
char	*backslash(char *str);

/* interp_parse.c */
int	parse(int *argc, char ***argv, char *str);

/* interp_forth.c */
void	bf_init(void);
int	bf_run(char *line);

/* boot.c */
int	autoboot(int timeout, char *prompt);
void	autoboot_maybe(void);
int	getrootmount(char *rootdev);

/* misc.c */
char	*unargv(int argc, char *argv[]);
void	hexdump(caddr_t region, size_t len);
size_t	strlenout(vm_offset_t str);
char	*strdupout(vm_offset_t str);
void	kern_bzero(vm_offset_t dest, size_t len);
int	kern_pread(int fd, vm_offset_t dest, size_t len, off_t off);
void	*alloc_pread(int fd, off_t off, size_t len);

/* bcache.c */
int	bcache_init(u_int nblks, size_t bsize);
void	bcache_flush(void);
int	bcache_strategy(void *devdata, int unit, int rw, daddr_t blk,
			size_t size, char *buf, size_t *rsize);

/*
 * Disk block cache
 */
struct bcache_devdata
{
    int         (*dv_strategy)(void *devdata, int rw, daddr_t blk, size_t size, char *buf, size_t *rsize);
    void	*dv_devdata;
};

/*
 * Modular console support.
 */
struct console
{
    const char	*c_name;
    const char	*c_desc;
    int		c_flags;
#define C_PRESENTIN	(1<<0)	    /* console can provide input */
#define C_PRESENTOUT	(1<<1)	    /* console can provide output */
#define C_ACTIVEIN	(1<<2)	    /* user wants input from console */
#define C_ACTIVEOUT	(1<<3)	    /* user wants output to console */
    void	(* c_probe)(struct console *cp);	/* set c_flags to match hardware */
    int		(* c_init)(int arg);			/* reinit XXX may need more args */
    void	(* c_out)(int c);			/* emit c */
    int		(* c_in)(void);				/* wait for and return input */
    int		(* c_ready)(void);			/* return nonzer if input waiting */
};
extern struct console	*consoles[];
void		cons_probe(void);

/*
 * Plug-and-play enumerator/configurator interface.
 */
struct pnphandler
{
    const char	*pp_name;		/* handler/bus name */
    void	(* pp_enumerate)(void);	/* enumerate PnP devices, add to chain */
};

struct pnpident
{
    char			*id_ident;	/* ASCII identifier, actual format varies with bus/handler */
    STAILQ_ENTRY(pnpident)	id_link;
};

struct pnpinfo
{
    char			*pi_desc;	/* ASCII description, optional */
    int				pi_revision;	/* optional revision (or -1) if not supported */
    char			*pi_module;	/* module/args nominated to handle device */
    int				pi_argc;	/* module arguments */
    char			**pi_argv;
    struct pnphandler		*pi_handler;	/* handler which detected this device */
    STAILQ_HEAD(,pnpident)	pi_ident;	/* list of identifiers */
    STAILQ_ENTRY(pnpinfo)	pi_link;
};

STAILQ_HEAD(pnpinfo_stql, pnpinfo);

extern struct pnpinfo_stql pnp_devices;

extern struct pnphandler	*pnphandlers[];		/* provided by MD code */

void			pnp_addident(struct pnpinfo *pi, char *ident);
struct pnpinfo		*pnp_allocinfo(void);
void			pnp_freeinfo(struct pnpinfo *pi);
void			pnp_addinfo(struct pnpinfo *pi);
char			*pnp_eisaformat(u_int8_t *data);

/*
 *  < 0	- No ISA in system
 * == 0	- Maybe ISA, search for read data port
 *  > 0	- ISA in system, value is read data port address
 */
extern int			isapnp_readport;

/*
 * Preloaded file metadata header.
 *
 * Metadata are allocated on our heap, and copied into kernel space
 * before executing the kernel.
 */
struct file_metadata
{
    size_t			md_size;
    u_int16_t			md_type;
    struct file_metadata	*md_next;
    char			md_data[1];	/* data are immediately appended */
};

struct preloaded_file;
struct mod_depend;

struct kernel_module
{
    char			*m_name;	/* module name */
    int				m_version;	/* module version */
/*    char			*m_args;*/	/* arguments for the module */
    struct preloaded_file	*m_fp;
    struct kernel_module	*m_next;
};

/*
 * Preloaded file information. Depending on type, file can contain
 * additional units called 'modules'.
 *
 * At least one file (the kernel) must be loaded in order to boot.
 * The kernel is always loaded first.
 *
 * String fields (m_name, m_type) should be dynamically allocated.
 */
struct preloaded_file
{
    char			*f_name;	/* file name */
    char			*f_type;	/* verbose file type, eg 'ELF kernel', 'pnptable', etc. */
    char			*f_args;	/* arguments for the file */
    struct file_metadata	*f_metadata;	/* metadata that will be placed in the module directory */
    int				f_loader;	/* index of the loader that read the file */
    vm_offset_t			f_addr;		/* load address */
    size_t			f_size;		/* file size */
    struct kernel_module	*f_modules;	/* list of modules if any */
    struct preloaded_file	*f_next;	/* next file */
};

struct file_format
{
    /* Load function must return EFTYPE if it can't handle the module supplied */
    int		(* l_load)(char *filename, u_int64_t dest, struct preloaded_file **result);
    /* Only a loader that will load a kernel (first module) should have an exec handler */
    int		(* l_exec)(struct preloaded_file *mp);
};

extern struct file_format	*file_formats[];	/* supplied by consumer */
extern struct preloaded_file	*preloaded_files;

int			mod_load(char *name, struct mod_depend *verinfo, int argc, char *argv[]);
int			mod_loadkld(const char *name, int argc, char *argv[]);

struct preloaded_file *file_alloc(void);
struct preloaded_file *file_findfile(char *name, char *type);
struct file_metadata *file_findmetadata(struct preloaded_file *fp, int type);
void file_discard(struct preloaded_file *fp);
void file_addmetadata(struct preloaded_file *fp, int type, size_t size, void *p);
int  file_addmodule(struct preloaded_file *fp, char *modname, int version,
	struct kernel_module **newmp);

/* MI module loaders */
#ifdef __elfN
/* Relocation types. */
#define ELF_RELOC_REL	1
#define ELF_RELOC_RELA	2

/* Relocation offset for some architectures */
extern u_int64_t __elfN(relocation_offset);

struct elf_file;
typedef Elf_Addr (symaddr_fn)(struct elf_file *ef, Elf_Size symidx);

int	__elfN(loadfile)(char *filename, u_int64_t dest, struct preloaded_file **result);
int	__elfN(obj_loadfile)(char *filename, u_int64_t dest,
	    struct preloaded_file **result);
int	__elfN(reloc)(struct elf_file *ef, symaddr_fn *symaddr,
	    const void *reldata, int reltype, Elf_Addr relbase,
	    Elf_Addr dataaddr, void *data, size_t len);
#endif

/*
 * Support for commands
 */
struct bootblk_command
{
    const char		*c_name;
    const char		*c_desc;
    bootblk_cmd_t	*c_fn;
};

#define COMMAND_SET(tag, key, desc, func)				\
    static bootblk_cmd_t func;						\
    static struct bootblk_command _cmd_ ## tag = { key, desc, func };	\
    DATA_SET(Xcommand_set, _cmd_ ## tag)

SET_DECLARE(Xcommand_set, struct bootblk_command);

/*
 * The intention of the architecture switch is to provide a convenient
 * encapsulation of the interface between the bootstrap MI and MD code.
 * MD code may selectively populate the switch at runtime based on the
 * actual configuration of the target system.
 */
struct arch_switch
{
    /* Automatically load modules as required by detected hardware */
    int		(*arch_autoload)(void);
    /* Locate the device for (name), return pointer to tail in (*path) */
    int		(*arch_getdev)(void **dev, const char *name, const char **path);
    /* Copy from local address space to module address space, similar to bcopy() */
    ssize_t	(*arch_copyin)(const void *src, vm_offset_t dest,
			       const size_t len);
    /* Copy to local address space from module address space, similar to bcopy() */
    ssize_t	(*arch_copyout)(const vm_offset_t src, void *dest,
				const size_t len);
    /* Read from file to module address space, same semantics as read() */
    ssize_t	(*arch_readin)(const int fd, vm_offset_t dest,
			       const size_t len);
    /* Perform ISA byte port I/O (only for systems with ISA) */
    int		(*arch_isainb)(int port);
    void	(*arch_isaoutb)(int port, int value);

    /*
     * Interface to adjust the load address according to the "object"
     * being loaded.
     */
    uint64_t	(*arch_loadaddr)(u_int type, void *data, uint64_t addr);
#define	LOAD_ELF	1	/* data points to the ELF header. */
#define	LOAD_RAW	2	/* data points to the file name. */

    /*
     * Interface to inform MD code about a loaded (ELF) segment. This
     * can be used to flush caches and/or set up translations.
     */
#ifdef __elfN
    void	(*arch_loadseg)(Elf_Ehdr *eh, Elf_Phdr *ph, uint64_t delta);
#else
    void	(*arch_loadseg)(void *eh, void *ph, uint64_t delta);
#endif

    /* Probe ZFS pool(s), if needed. */
    void	(*arch_zfs_probe)(void);
};
extern struct arch_switch archsw;

/* This must be provided by the MD code, but should it be in the archsw? */
void	delay(int delay);

void	dev_cleanup(void);

time_t	time(time_t *tloc);

#ifndef CTASSERT                /* Allow lint to override */
#define CTASSERT(x)             _CTASSERT(x, __LINE__)
#define _CTASSERT(x, y)         __CTASSERT(x, y)
#define __CTASSERT(x, y)        typedef char __assert ## y[(x) ? 1 : -1]
#endif

#endif /* !_BOOTSTRAP_H_ */


text:
file(GLOB_RECURSE ALL_SOURCE_FILES
     RELATIVE ${CMAKE_CURRENT_BINARY_DIR}
     ${CMAKE_SOURCE_DIR}/src/*.cpp ${CMAKE_SOURCE_DIR}/src/*.h ${CMAKE_SOURCE_DIR}/src/*.hpp
     ${CMAKE_SOURCE_DIR}/tests/*.cpp ${CMAKE_SOURCE_DIR}/tests/*.h ${CMAKE_SOURCE_DIR}/tests/*.hpp
     ${CMAKE_SOURCE_DIR}/perf/*.cpp ${CMAKE_SOURCE_DIR}/perf/*.h ${CMAKE_SOURCE_DIR}/perf/*.hpp
     ${CMAKE_SOURCE_DIR}/tools/*.cpp ${CMAKE_SOURCE_DIR}/tools/*.h ${CMAKE_SOURCE_DIR}/tools/*.hpp
     ${CMAKE_SOURCE_DIR}/include/*.h
    )

if("${CLANG_FORMAT}" STREQUAL "")
  set(CLANG_FORMAT "clang-format")
endif()

add_custom_target(
        clang-format
        COMMAND ${CLANG_FORMAT} -style=file -i ${ALL_SOURCE_FILES}
)

function(JOIN VALUES GLUE OUTPUT)
  string (REPLACE ";" "${GLUE}" _TMP_STR "${VALUES}")
  set (${OUTPUT} "${_TMP_STR}" PARENT_SCOPE)
endfunction()

configure_file(builds/cmake/clang-format-check.sh.in clang-format-check.sh @ONLY)

add_custom_target(
        clang-format-check
        COMMAND chmod +x clang-format-check.sh
        COMMAND ./clang-format-check.sh
        COMMENT "Checking correct formatting according to .clang-format file using ${CLANG_FORMAT}"
)

add_custom_target(
        clang-format-diff
        COMMAND ${CLANG_FORMAT} -style=file -i ${ALL_SOURCE_FILES}
        COMMAND git diff ${ALL_SOURCE_FILES}
        COMMENT "Formatting with clang-format (using ${CLANG_FORMAT}) and showing differences with latest commit"
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/general-authorities-and-area-representatives/larsen-dean-l" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/general-authorities-and-area-representatives/larsen-dean-l</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Larsen, Dean L.</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/general-authorities-and-area-representatives/larsen-dean-l</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/general-authorities-and-area-representatives/larsen-dean-l</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
package mariculture.magic.enchantments;

import mariculture.core.config.Enchantments;
import mariculture.core.helpers.KeyHelper;
import mariculture.core.network.PacketHandler;
import mariculture.core.network.PacketTeleport;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.MovingObjectPosition.MovingObjectType;

public class EnchantmentBlink extends EnchantmentJewelry {
    public static long LAST_BLINK = 0L;

    public EnchantmentBlink(int i, int weight, EnumEnchantmentType type) {
        super(i, weight, type);
        setName("blink");
        minLevel = 25;
        maxLevel = 40;
    }

    @Override
    public int getMaxLevel() {
        return 3;
    }

    public static void sendPacket(EntityClientPlayerMP player) {
        long currentTime = System.currentTimeMillis();
        long msSinceLastBlink = currentTime - LAST_BLINK;

        if (msSinceLastBlink < Enchantments.BLINK_MILLISECONDS) {
            return;
        }

        MovingObjectPosition lookAt = player.rayTrace(Enchantments.RAY_TRACE_DISTANCE, 1);
        if (lookAt != null && lookAt.typeOfHit == MovingObjectType.BLOCK && KeyHelper.isActivateKeyPressed()) {
            PacketHandler.sendToServer(new PacketTeleport(lookAt.blockX, lookAt.blockY + 1, lookAt.blockZ));
            LAST_BLINK = System.currentTimeMillis();
        }
    }
}


text:
from twisted.plugin import IPlugin
from zope.interface import implementer

from desertbot.message import IRCMessage
from desertbot.moduleinterface import IModule
from desertbot.modules.commandinterface import BotCommand
from desertbot.response import IRCResponse

@implementer(IPlugin, IModule)
class Shorten(BotCommand):
    def triggers(self):
        return ['shorten']

    def help(self, query):
        return "shorten <url> - Gives you a shortened version of a url, via https://dbco.link"

    def execute(self, message: IRCMessage):
        if len(message.parameterList) == 0:
            return IRCResponse("You didn't give a URL to shorten!", message.replyTo)

        url = self.bot.moduleHandler.runActionUntilValue('shorten-url',
                                                         message.parameters)

        if not url:
            return IRCResponse("No url returned from dbco.link, "
                               "are both pb and mongodb running?", message.replyTo)

        return IRCResponse(url, message.replyTo)

shorten = Shorten()


text:
#include <glbinding/glbinding_api.h>

#include <glbinding/gl/nogl.h>

#include <glbinding/gl/extension.h>

#include <glbinding/gl/types.h>

#include <glbinding/gl/boolean.h>

#include <glbinding/gl/bitfield14.h>
#include <glbinding/gl/bitfield14ext.h>
#include <glbinding/gl/enum14.h>
#include <glbinding/gl/enum14ext.h>
#include <glbinding/gl/functions14.h>
#include <glbinding/gl/functions14ext.h>


text:
package db

import anorm._
import io.flow.common.v0.models.UserReference
import io.flow.delta.v0.models.{GithubUser, GithubUserForm}
import io.flow.postgresql.{OrderBy, Query}
import io.flow.util.IdGenerator
import play.api.db._

@javax.inject.Singleton
class GithubUsersDao @javax.inject.Inject() (
  db: Database,
  usersDao: UsersDao
) {

  private[this] val BaseQuery = Query(s"""
    select github_users.id,
           github_users.user_id,
           github_users.github_user_id,
           github_users.login
      from github_users
  """)

  private[this] val InsertQuery = """
    insert into github_users
    (id, user_id, github_user_id, login, updated_by_user_id)
    values
    ({id}, {user_id}, {github_user_id}, {login}, {updated_by_user_id})
  """

  def upsertById(createdBy: Option[UserReference], form: GithubUserForm): GithubUser = {
    db.withConnection { implicit c =>
      upsertByIdWithConnection(createdBy, form)
    }
  }

  def upsertByIdWithConnection(createdBy: Option[UserReference], form: GithubUserForm)(implicit c: java.sql.Connection): GithubUser = {
    findByGithubUserId(form.githubUserId).getOrElse {
      createWithConnection(createdBy, form)
    }
  }

  def create(createdBy: Option[UserReference], form: GithubUserForm): GithubUser = {
    db.withConnection { implicit c =>
      createWithConnection(createdBy, form)
    }
  }

  private[db] def createWithConnection(createdBy: Option[UserReference], form: GithubUserForm)(implicit c: java.sql.Connection): GithubUser = {
    val id = IdGenerator("ghu").randomId()
    SQL(InsertQuery).on(
      Symbol("id") ->id,
      Symbol("user_id") ->form.userId,
      Symbol("github_user_id") ->form.githubUserId,
      Symbol("login") ->form.login.trim,
      Symbol("updated_by_user_id") ->createdBy.getOrElse(usersDao.anonymousUser).id
    ).execute()

    findById(id).getOrElse {
      sys.error("Failed to create github user")
    }
  }

  def findByGithubUserId(githubUserId: Long): Option[GithubUser] = {
    findAll(githubUserId = Some(githubUserId), limit = Some(1)).headOption
  }

  def findById(id: String): Option[GithubUser] = {
    findAll(id = Some(Seq(id)), limit = Some(1)).headOption
  }

  def findAll(
    id: Option[Seq[String]] = None,
    userId: Option[String] = None,
    login: Option[String] = None,
    githubUserId: Option[Long] = None,
    orderBy: OrderBy = OrderBy("github_users.created_at"),
    limit: Option[Long],
    offset: Long = 0
  ): Seq[GithubUser] = {
    db.withConnection { implicit c =>
      BaseQuery.
        optionalIn("github_users.id", id).
        equals("github_users.user_id", userId).
        optionalText("github_users.login", login).
        equals("github_users.github_user_id", githubUserId).
        orderBy(orderBy.sql).
        optionalLimit(limit).
        offset(offset).
        as(
          io.flow.delta.v0.anorm.parsers.GithubUser.parser().*
        )
    }
  }

}


text:
"""
Files views.
"""
from flask import request

from osf import features

from website.util import rubeus
from website.project.decorators import must_be_contributor_or_public, must_not_be_retracted_registration
from website.project.views.node import _view_project
from website.ember_osf_web.decorators import ember_flag_is_active

@must_not_be_retracted_registration
@must_be_contributor_or_public
@ember_flag_is_active(features.EMBER_PROJECT_FILES)
def collect_file_trees(auth, node, **kwargs):
    """Collect file trees for all add-ons implementing HGrid views, then
    format data as appropriate.
    """
    serialized = _view_project(node, auth, primary=True)
    # Add addon static assets
    serialized.update(rubeus.collect_addon_assets(node))
    return serialized

@must_be_contributor_or_public
def grid_data(auth, node, **kwargs):
    """View that returns the formatted data for rubeus.js/hgrid
    """
    data = request.args.to_dict()
    return {'data': rubeus.to_hgrid(node, auth, **data)}


text:
package org.telegram.api.messages.stickers;

import org.telegram.api.document.TLDocument;
import org.telegram.tl.StreamingUtils;
import org.telegram.tl.TLContext;
import org.telegram.tl.TLVector;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * The type TL stickers.
 * @author Ruben Bermudez
 * @version 2.0
 * @brief TLStickers
 * @date 9 /01/15
 */
public class TLStickers extends TLAbsStickers {
    /**
     * The constant CLASS_ID.
     */
    public static final int CLASS_ID = 0x8a8ecd32;

    private String hash;
    private TLVector<TLDocument> documents;

    /**
     * Instantiates a new TL stickers.
     */
    public TLStickers() {
        super();
    }

    @Override
    public int getClassId() {
        return CLASS_ID;
    }

    /**
     * Gets hash.
     *
     * @return the hash
     */
    public String getHash() {
        return this.hash;
    }

    /**
     * Sets hash.
     *
     * @param hash the hash
     */
    public void setHash(String hash) {
        this.hash = hash;
    }

    /**
     * Gets documents.
     *
     * @return the documents
     */
    public TLVector<TLDocument> getDocuments() {
        return this.documents;
    }

    /**
     * Sets documents.
     *
     * @param documents the documents
     */
    public void setDocuments(TLVector<TLDocument> documents) {
        this.documents = documents;
    }

    @Override
    public void serializeBody(OutputStream stream)
            throws IOException {
        StreamingUtils.writeTLString(this.hash, stream);
        StreamingUtils.writeTLVector(this.documents, stream);
    }

    @Override
    public void deserializeBody(InputStream stream, TLContext context)
            throws IOException {
        this.hash = StreamingUtils.readTLString(stream);
        this.documents = StreamingUtils.readTLVector(stream, context, TLDocument.class);
    }

    @Override
    public String toString() {
        return "stickers#8a8ecd32";
    }
}


text:
import React, { Component, PropTypes } from 'react'
import Command from '../Shared/Command'
import Colors from '../Theme/Colors'

const COMMAND_TITLE = 'IMAGE'

const Styles = {
  imageContainer: {
  },
  image: {
    maxWidth: '100%',
    maxHeight: '100%'
  },
  caption: {
    paddingTop: 10,
    paddingBottom: 10,
    fontSize: 'larger'
  },
  dimensions: {
    color: Colors.constant
  },
  filename: {
    color: Colors.highlight
  }
}

class DisplayCommand extends Component {
  static propTypes = {
    command: PropTypes.object.isRequired
  }

  shouldComponentUpdate (nextProps) {
    return this.props.command.id !== nextProps.command.id
  }

  render () {
    const { command } = this.props
    const { payload, important } = command

    const { uri, preview, caption, width, height, filename } = payload
    const dimensions = width && height && `${width} x ${height}`

    return (
      <Command command={command} title={COMMAND_TITLE} important={important} preview={preview}>

          {caption &&
{caption}
}
          {dimensions &&
{dimensions}
}
          {filename &&
{filename}
}

      </Command>
    )
  }
}

export default DisplayCommand


text:
package com.bakoproductions.pokemoncleanexample.data.entities.mappers;

import com.bakoproductions.pokemoncleanexample.domain.models.errors.Error;

import retrofit2.Response;

/**
 * Created by Michael on 15/4/2017.
 */

public class ErrorMapper {
    /**
     * Transforms the response to an Error
     *
     * @param error The error to be sent back to the data layer
     * @param response The retrofit response
     * @param <T> The class of the response
     * @param <E> The error class
     * @return The error object with its data filled
     */
    public <T, E extends Error> E transform(E error, Response<T> response) {
        error.setStatus(response.code());
        error.setMessage(response.message());

        return error;
    }

    /**
     * Transforms the exception to an Error
     * @param error The error to be sent back to the data layer
     * @param throwable The exception from Retrofit
     * @param <E> The error class
     * @return
     */
    public <E extends Error> E transform(E error, Throwable throwable) {
        error.setStatus(Error.NETWORK_ERROR_CODE);
        error.setMessage(throwable.getMessage());

        return error;
    }
}


text:
layout: post
title: "How to configure Postman API tests in Azure DevOps"
subtitle: "This post is configuring Postman API tests in Azure DevOps. Postman makes API development easy. Postman platform offers the tools to simplify each step of the API building process and streamlines collaboration so you can create better APIs faster."
date: 2020-12-19 00:00:00
categories: [Azure,Postman,API Testing]
tags: [Azure,Postman,API Testing]
author: "Anuraj"
image: /assets/images/2020/12/testplans_runs.png
---
This post is configuring Postman API tests in Azure DevOps. Postman makes API development easy. Postman platform offers the tools to simplify each step of the API building process and streamlines collaboration so you can create better APIs faster. In this post I am discussing about configuring Postman API testing in Azure DevOps and GitHub actions.

First I created a collection in Postman, then I am using some API endpoint for this post. Along with that, I am adding few test cases. Here is one request with test.

![Postman Request]({{ site.url }}/assets/images/2020/12/postman_request.png)

Once it is executed and working as expected, click on the collection and export it.

![Postman Export Collection]({{ site.url }}/assets/images/2020/12/postman_export.png)

From the Export collection dialog, choose the `Collection v2.1 (recommended)`, and save the JSON file. For demo purposes I am not using any environment variables. If you're using any tokens or variables, you can using Postman environments, and you need to export that as well.

To run the Postman collection in DevOps pipelines you need to use `newman` CLI tool - which is from postman helps you to run the Postman collection files, this can be installed using npm command - `npm install -g newman`. And you can run the tests using the command - `newman run TestAPICollection.json` - this command will execute the test cases and print the output in the console.

![Postman Running Console]({{ site.url }}/assets/images/2020/12/postman_running.png)

Next I committed the JSON file to source control, I am using GitHub. Once you commit the JSON file we can start creating the Azure DevOps pipeline. I am creating a Azure DevOps Build pipeline, I am using Class Editor option, not YAML option. Next I am adding few build steps - first build step in a `npm task` will be installing the `newman`. Next step is a command line script - which will be running the newman with the file. And final step is `Publish Test Results` - this step will publish the test results from the previous step. We may need to provide one more parameter which will export the results in JUnit XML.

Here is the YAML file.

{% highlight Javascript %}
resources:
  repositories:
  - repository: self
    type: git
    ref: master
jobs:
- job: Job_1
  displayName: Agent job 1
  pool:
    vmImage: vs2017-win2016
  steps:
  - checkout: self
  - task: Npm@1
    displayName: npm custom
    inputs:
      command: custom
      verbose: false
      customCommand: install -g newman
  - task: CmdLine@2
    displayName: Command Line Script
    inputs:
      script: newman run $(Build.SourcesDirectory)\Testing.postman_collection.json -x -r junit --reporter-junit-export $(build.artifactstagingdirectory)\Results\JunitResults.xml
  - task: PublishTestResults@2
    displayName: Publish Test Results
    inputs:
      testResultsFiles: '**\*.xml'
      searchFolder: $(build.artifactstagingdirectory)

{% endhighlight %}

And here is the Build pipeline.

![Postman Running Console]({{ site.url }}/assets/images/2020/12/azure_devops_pipeline.png)

If you notice the `newman run` command comes with few more parameters which helps to publish the results as JUnit XML file. The `-x` flag will ignore the exit code and continue the build steps, if you want to stop the build execution if any of the tests fails, you need to remove it. In this post I build a pipeline only specific for monitoring purposes, that is why I added an ignore exit code parameter. Here is the results after running the pipeline.

![DevOps Pipeline Tests]({{ site.url }}/assets/images/2020/12/devops_pipeline_tests.png)

You can find more details about the test run in the Test Plans > Runs. You can find more details like Test Runs and details about Tests.

![DevOps Pipeline Tests]({{ site.url }}/assets/images/2020/12/testplans_runs.png)

You can configure the it to be run it with scheduled trigger or as a continuous delivery option, so that this API tests can validate your app and show the results. You can use similar script and execute the same test cases in GitHub actions as well.

Happy Programming :)


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="cq:ClientLibraryFolder"
          jsProcessor="[default:none,min:gcc]"
          categories="acs-commons.version-compare"
    dependencies="[coralui2,jquery,acs-commons.vendor.jsplumb,acs-commons.coralui2.angularjs,acs-commons.angularjs]"/>


text:
<title>script.aculo.us Drag and drop functional test file</title>

script.aculo.us Drag and drop functional test file

w/o hoverclass

### DROP HERE ###

 <-- drag this!

w/ hoverclass

### DROP HERE ###


text:
About the educational institution

Netaji Subhash Engineering College

University

Maulana Abdul Kalam Azad University Of Technology

Website

         www.nsec.ac.in


text:
package uk.co.jezuk.mango;

/**
  * A Generator describes a function which takes no arguments
 * fn(). It returns some object of type R, and
 * may return the same object or different objects for each invocation.
 * It can refer to local state, perform disk reads or writes, or whatever.
 * @see Generators
 * @author Jez Higgins, jez@jezuk.co.uk
 */
public interface Generator<R>
{
  public R fn();
} // Generator


text:
using System.Collections.Generic;
using Newtonsoft.Json;

namespace AutomaticSharp.Models
{
    public class AutomaticCollection<T>
    {
        /// <summary>
        /// Metadata
        /// </summary>
        [JsonProperty("_metadata")]
        public MetaData Metadata { get; set; }

        /// <summary>
        /// Results
        /// </summary>
        public List<T> Results { get; set; }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
Apache Struts API Documentation: Class  RequestUtils
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.apache.struts.util

Class  RequestUtils

java.lang.Object
  |
  +--org.apache.struts.util.RequestUtils

public class RequestUtils
extends java.lang.Object

General purpose utility methods related to processing a servlet request
 in the Struts controller framework.

Version:
$Revision: 1.1 $ $Date: 2001-09-18 05:13:30 +0900 (火, 18  9月 2001) $

Author:
Craig R. McClanahan

Field Summary

private static java.util.Locale
defaultLocale

          The default Locale for our server.

private static MessageResources
messages

          The message resources for this package.

Constructor Summary

RequestUtils()

Method Summary

static java.net.URL
absoluteURL(javax.servlet.http.HttpServletRequest request,
            java.lang.String path)

          Create and return an absolute URL for the specified context-relative
 path, based on the server and context information in the specified
 request.

static java.util.Map
computeParameters(javax.servlet.jsp.PageContext pageContext,
                  java.lang.String paramId,
                  java.lang.String paramName,
                  java.lang.String paramProperty,
                  java.lang.String paramScope,
                  java.lang.String name,
                  java.lang.String property,
                  java.lang.String scope,
                  boolean transaction)

          Compute a set of query parameters that will be dynamically added to
 a generated URL.

static java.lang.String
computeURL(javax.servlet.jsp.PageContext pageContext,
           java.lang.String forward,
           java.lang.String href,
           java.lang.String page,
           java.util.Map params,
           java.lang.String anchor,
           boolean redirect)

          Compute a hyperlink URL based on the forward,
 href, or page parameter that is not null.

static java.lang.Object
lookup(javax.servlet.jsp.PageContext pageContext,
       java.lang.String name,
       java.lang.String scope)

          Locate and return the specified bean, from an optionally specified
 scope, in the specified page context.

static java.lang.Object
lookup(javax.servlet.jsp.PageContext pageContext,
       java.lang.String name,
       java.lang.String property,
       java.lang.String scope)

          Locate and return the specified property of the specified bean, from
 an optionally specified scope, in the specified page context.

static java.lang.String
message(javax.servlet.jsp.PageContext pageContext,
        java.lang.String bundle,
        java.lang.String locale,
        java.lang.String key)

          Look up and return a message string, based on the specified parameters.

static java.lang.String
message(javax.servlet.jsp.PageContext pageContext,
        java.lang.String bundle,
        java.lang.String locale,
        java.lang.String key,
        java.lang.Object[] args)

          Look up and return a message string, based on the specified parameters.

static void
populate(java.lang.Object bean,
         javax.servlet.http.HttpServletRequest request)

          Populate the properties of the specified JavaBean from the specified
 HTTP request, based on matching each parameter name against the
 corresponding JavaBeans "property setter" methods in the bean's class.

static void
populate(java.lang.Object bean,
         java.lang.String prefix,
         java.lang.String suffix,
         javax.servlet.http.HttpServletRequest request)

          Populate the properties of the specified JavaBean from the specified
 HTTP request, based on matching each parameter name (plus an optional
 prefix and/or suffix) against the corresponding JavaBeans "property
 setter" methods in the bean's class.

static boolean
present(javax.servlet.jsp.PageContext pageContext,
        java.lang.String bundle,
        java.lang.String locale,
        java.lang.String key)

          Return true if a message string for the specified message key
 is present for the specified Locale.

static java.lang.String
printableURL(java.net.URL url)

          Compute the printable representation of a URL, leaving off the
 scheme/host/port part if no host is specified.

static java.net.URL
requestURL(javax.servlet.http.HttpServletRequest request)

          Return the URL representing the current request.

static void
saveException(javax.servlet.jsp.PageContext pageContext,
              java.lang.Throwable exception)

          Save the specified exception as a request attribute for later use.

static java.net.URL
serverURL(javax.servlet.http.HttpServletRequest request)

          Return the URL representing the scheme, server, and port number of
 the current request.

Methods inherited from class java.lang.Object

<clinit>, clone, equals, finalize, getClass, hashCode, notify, notifyAll, registerNatives, toString, wait, wait, wait

Field Detail

defaultLocale

private static final java.util.Locale defaultLocale

The default Locale for our server.

messages

private static MessageResources messages

The message resources for this package.

Constructor Detail

RequestUtils

public RequestUtils()

Method Detail

absoluteURL

public static java.net.URL absoluteURL(javax.servlet.http.HttpServletRequest request,
                                       java.lang.String path)
                                throws java.net.MalformedURLException

Create and return an absolute URL for the specified context-relative
 path, based on the server and context information in the specified
 request.

Parameters:
request - The servlet request we are processing
path - The context-relative path (must start with '/')
Throws:
java.net.MalformedURLException - if we cannot create an absolute URL

computeParameters

public static java.util.Map computeParameters(javax.servlet.jsp.PageContext pageContext,
                                              java.lang.String paramId,
                                              java.lang.String paramName,
                                              java.lang.String paramProperty,
                                              java.lang.String paramScope,
                                              java.lang.String name,
                                              java.lang.String property,
                                              java.lang.String scope,
                                              boolean transaction)
                                       throws javax.servlet.jsp.JspException

Compute a set of query parameters that will be dynamically added to
 a generated URL.  The returned Map is keyed by parameter name, and the
 values are either null (no value specified), a String (single value
 specified), or a String[] array (multiple values specified).  Parameter
 names correspond to the corresponding attributes of the
 <html:link> tag.  If no query parameters are
 identified, return null.

Parameters:
pageContext - PageContext we are operating in
paramId - Single-value request parameter name (if any)
paramName - Bean containing single-value parameter value
paramProperty - Property (of bean named by paramName
  containing single-value parameter value
paramScope - Scope containing bean named by
  paramScope
name - Bean containing multi-value parameters Map (if any)
property - Property (of bean named by name
  containing multi-value parameters Map
scope - Scope containing bean named by
  name
transaction - Should we add our transaction control token?
Throws:
javax.servlet.jsp.JspException - if we cannot look up the required beans
javax.servlet.jsp.JspException - if a class cast exception occurs on a
  looked-up bean or property

computeURL

public static java.lang.String computeURL(javax.servlet.jsp.PageContext pageContext,
                                          java.lang.String forward,
                                          java.lang.String href,
                                          java.lang.String page,
                                          java.util.Map params,
                                          java.lang.String anchor,
                                          boolean redirect)
                                   throws java.net.MalformedURLException

Compute a hyperlink URL based on the forward,
 href, or page parameter that is not null.
 The returned URL will have already been passed to
 response.encodeURL() for adding a session identifier.

Parameters:
pageContext - PageContext for the tag making this call
forward - Logical forward name for which to look up
  the context-relative URI (if specified)
href - URL to be utilized unmodified (if specified)
page - Context-relative page for which a URL should
  be created (if specified)
params - Map of parameters to be dynamically included (if any)
anchor - Anchor to be dynamically included (if any)
redirect - Is this URL for a response.sendRedirect()?
Throws:
java.net.MalformedURLException - if a URL cannot be created
  for the specified parameters

lookup

public static java.lang.Object lookup(javax.servlet.jsp.PageContext pageContext,
                                      java.lang.String name,
                                      java.lang.String scope)
                               throws javax.servlet.jsp.JspException

Locate and return the specified bean, from an optionally specified
 scope, in the specified page context.  If no such bean is found,
 return null instead.  If an exception is thrown, it will
 have already been saved via a call to saveException().

Parameters:
pageContext - Page context to be searched
name - Name of the bean to be retrieved
scope - Scope to be searched (page, request, session, application)
  or null to use findAttribute() instead
Throws:
javax.servlet.jsp.JspException - if an invalid scope name
  is requested

lookup

public static java.lang.Object lookup(javax.servlet.jsp.PageContext pageContext,
                                      java.lang.String name,
                                      java.lang.String property,
                                      java.lang.String scope)
                               throws javax.servlet.jsp.JspException

Locate and return the specified property of the specified bean, from
 an optionally specified scope, in the specified page context.  If an
 exception is thrown, it will have already been saved via a call to
 saveException().

Parameters:
pageContext - Page context to be searched
name - Name of the bean to be retrieved
property - Name of the property to be retrieved, or
  null to retrieve the bean itself
scope - Scope to be searched (page, request, session, application)
  or null to use findAttribute() instead
Throws:
javax.servlet.jsp.JspException - if an invalid scope name
  is requested
javax.servlet.jsp.JspException - if the specified bean is not found
javax.servlet.jsp.JspException - if accessing this property causes an
  IllegalAccessException, IllegalArgumentException,
  InvocationTargetException, or NoSuchMethodException

message

public static java.lang.String message(javax.servlet.jsp.PageContext pageContext,
                                       java.lang.String bundle,
                                       java.lang.String locale,
                                       java.lang.String key)
                                throws javax.servlet.jsp.JspException

Look up and return a message string, based on the specified parameters.

Parameters:
pageContext - The PageContext associated with this request
bundle - Name of the servlet context attribute for our
  message resources bundle
locale - Name of the session attribute for our user's Locale
key - Message key to be looked up and returned
Throws:
javax.servlet.jsp.JspException - if a lookup error occurs (will have been
  saved in the request already)

message

public static java.lang.String message(javax.servlet.jsp.PageContext pageContext,
                                       java.lang.String bundle,
                                       java.lang.String locale,
                                       java.lang.String key,
                                       java.lang.Object[] args)
                                throws javax.servlet.jsp.JspException

Look up and return a message string, based on the specified parameters.

Parameters:
pageContext - The PageContext associated with this request
bundle - Name of the servlet context attribute for our
  message resources bundle
locale - Name of the session attribute for our user's Locale
key - Message key to be looked up and returned
args - Replacement parameters for this message
Throws:
javax.servlet.jsp.JspException - if a lookup error occurs (will have been
  saved in the request already)

populate

public static void populate(java.lang.Object bean,
                            javax.servlet.http.HttpServletRequest request)
                     throws javax.servlet.ServletException

Populate the properties of the specified JavaBean from the specified
 HTTP request, based on matching each parameter name against the
 corresponding JavaBeans "property setter" methods in the bean's class.
 Suitable conversion is done for argument types as described under
 convert().

Parameters:
bean - The JavaBean whose properties are to be set
request - The HTTP request whose parameters are to be used
                to populate bean properties
Throws:
javax.servlet.ServletException - if an exception is thrown while setting
            property values

populate

public static void populate(java.lang.Object bean,
                            java.lang.String prefix,
                            java.lang.String suffix,
                            javax.servlet.http.HttpServletRequest request)
                     throws javax.servlet.ServletException

Populate the properties of the specified JavaBean from the specified
 HTTP request, based on matching each parameter name (plus an optional
 prefix and/or suffix) against the corresponding JavaBeans "property
 setter" methods in the bean's class.  Suitable conversion is done for
 argument types as described under setProperties().

 If you specify a non-null prefix and a non-null
 suffix, the parameter name must match both
 conditions for its value(s) to be used in populating bean properties.
 If the request's content type is "multipart/form-data" and the
 method is "POST", the HttpServletRequest object will be wrapped in
 a MultipartRequestWrapper object.

Parameters:
bean - The JavaBean whose properties are to be set
prefix - The prefix (if any) to be prepend to bean property
               names when looking for matching parameters
suffix - The suffix (if any) to be appended to bean property
               names when looking for matching parameters
request - The HTTP request whose parameters are to be used
                to populate bean properties
Throws:
javax.servlet.ServletException - if an exception is thrown while setting
            property values

present

public static boolean present(javax.servlet.jsp.PageContext pageContext,
                              java.lang.String bundle,
                              java.lang.String locale,
                              java.lang.String key)
                       throws javax.servlet.jsp.JspException

Return true if a message string for the specified message key
 is present for the specified Locale.

Parameters:
pageContext - The PageContext associated with this request
bundle - Name of the servlet context attribute for our
  message resources bundle
locale - Name of the session attribute for our user's Locale
key - Message key to be looked up and returned
Throws:
javax.servlet.jsp.JspException - if a lookup error occurs (will have been
  saved in the request already)

printableURL

public static java.lang.String printableURL(java.net.URL url)

Compute the printable representation of a URL, leaving off the
 scheme/host/port part if no host is specified.  This will typically
 be the case for URLs that were originally created from relative
 or context-relative URIs.

Parameters:
url - URL to render in a printable representation

requestURL

public static java.net.URL requestURL(javax.servlet.http.HttpServletRequest request)
                               throws java.net.MalformedURLException

Return the URL representing the current request.  This is equivalent
 to HttpServletRequest.getRequestURL() in Servlet 2.3.

Parameters:
request - The servlet request we are processing
Throws:
java.net.MalformedURLException - if a URL cannot be created

serverURL

public static java.net.URL serverURL(javax.servlet.http.HttpServletRequest request)
                              throws java.net.MalformedURLException

Return the URL representing the scheme, server, and port number of
 the current request.  Server-relative URLs can be created by simply
 appending the server-relative path (starting with '/') to this.

Parameters:
request - The servlet request we are processing
Throws:
java.net.MalformedURLException - if a URL cannot be created

saveException

public static void saveException(javax.servlet.jsp.PageContext pageContext,
                                 java.lang.Throwable exception)

Save the specified exception as a request attribute for later use.

Parameters:
pageContext - The PageContext for the current page
exception - The exception to be saved

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 2000-2001 - Apache Software Foundation


text:
package coursier.cli.fetch

import java.io.{File, PrintStream}
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.util.concurrent.ExecutorService

import caseapp._
import cats.data.Validated
import coursier.cli.CoursierCommand
import coursier.cli.resolve.{Output, Resolve, ResolveException}
import coursier.core.Resolution
import coursier.install.Channels
import coursier.util.{Artifact, Sync, Task}

import scala.concurrent.ExecutionContext

object Fetch extends CoursierCommand[FetchOptions] {

  def task(
    params: FetchParams,
    pool: ExecutorService,
    args: Seq[String],
    stdout: PrintStream = System.out,
    stderr: PrintStream = System.err
  ): Task[(Resolution, Option[String], Option[String], Seq[(Artifact, File)])] = {

    val resolveTask = coursier.cli.resolve.Resolve.task(
      params.resolve,
      pool,
      System.out,
      System.err,
      args,
      force = params.artifact.force
    )

    val logger = params.resolve.output.logger()

    val cache = params.resolve.cache.cache(pool, logger)

    for {
      t <- resolveTask
      (res, scalaVersionOpt, platformOpt, _) = t
      artifacts = coursier.Artifacts.artifacts(
        res,
        params.artifact.classifiers,
        Some(params.artifact.mainArtifacts), // allow to be null?
        Some(params.artifact.artifactTypes), // allow to be null?
        params.resolve.classpathOrder.getOrElse(true)
      )

      artifactFiles <- coursier.Artifacts.fetchArtifacts(
        artifacts.map(_._3).distinct,
        cache
        // FIXME Allow to adjust retryCount via CLI args?
      )

      _ <- {
        params.jsonOutputOpt match {
          case Some(output) =>
            Task.delay {
              val report = JsonOutput.report(
                res,
                artifacts,
                artifactFiles.collect { case (a, Some(f)) => a -> f },
                params.artifact.classifiers,
                printExclusions = false
              )

              Files.write(output, report.getBytes(StandardCharsets.UTF_8))
            }
          case None =>
            Task.point(())
        }
      }
    } yield (
      res,
      scalaVersionOpt,
      platformOpt,
      artifactFiles.collect { case (a, Some(f)) => a -> f }
    )
  }

  def run(options: FetchOptions, args: RemainingArgs): Unit = {

    var pool: ExecutorService = null

    // get options and dependencies from apps if any
    val (options0, deps) =
      FetchParams(options).toEither.toOption.fold((options, args.all)) { initialParams =>
        val initialRepositories = initialParams.resolve.repositories.repositories
        val channels            = initialParams.channel.channels
        pool = Sync.fixedThreadPool(initialParams.resolve.cache.parallel)
        val cache = initialParams.resolve.cache.cache(pool, initialParams.resolve.output.logger())
        val channels0 = Channels(channels, initialRepositories, cache)
        val res       = Resolve.handleApps(options, args.all, channels0)(_.addApp(_))
        res
      }

    val params = FetchParams(options0) match {
      case Validated.Invalid(errors) =>
        for (err <- errors.toList)
          Output.errPrintln(err)
        sys.exit(1)
      case Validated.Valid(p) => p
    }

    if (pool == null)
      pool = Sync.fixedThreadPool(params.resolve.cache.parallel)
    val ec = ExecutionContext.fromExecutorService(pool)

    val t = task(params, pool, deps)

    val (_, _, _, files) = t.attempt.unsafeRun()(ec) match {
      case Left(e: ResolveException) if params.resolve.output.verbosity <= 1 =>
        Output.errPrintln(e.message)
        sys.exit(1)
      case Left(e: coursier.error.FetchError) if params.resolve.output.verbosity <= 1 =>
        Output.errPrintln(e.getMessage)
        sys.exit(1)
      case Left(e)  => throw e
      case Right(t) => t
    }

    // Some progress lines seem to be scraped without this.
    Console.out.flush()

    val out =
      if (files.isEmpty) ""
      else if (options.classpath)
        files
          .map(_._2.toString)
          .mkString(File.pathSeparator) + System.lineSeparator()
      else
        files
          .map(_._2.toString + System.lineSeparator())
          .mkString

    print(out)
  }

}


text:
public class FilmRentalArrayTest {

  public static void main (String args[]) {

    FilmRentalArray myFilmRentalArray = new FilmRentalArray();

    myFilmRentalArray.setFilmRentalArray();

    myFilmRentalArray.displayFilmRentalArray();

  }
}


text:
package org.ojalgo.matrix.decomposition;

import java.math.BigDecimal;

import org.ojalgo.TestUtils;
import org.ojalgo.matrix.BigMatrix;
import org.ojalgo.matrix.MatrixUtils;
import org.ojalgo.matrix.P20030422Case;
import org.ojalgo.matrix.store.ComplexDenseStore;
import org.ojalgo.matrix.store.MatrixStore;
import org.ojalgo.matrix.store.PhysicalStore;
import org.ojalgo.matrix.store.PrimitiveDenseStore;
import org.ojalgo.matrix.transformation.Householder;
import org.ojalgo.netio.BasicLogger;
import org.ojalgo.scalar.ComplexNumber;
import org.ojalgo.type.context.NumberContext;

/**
 * @author apete
 */
public class QRTest extends MatrixDecompositionTests {

    private static final int DIMENSION = 4;

    /**
     * An Hermitian matrix (or self-adjoint matrix) is a square matrix with complex entries that is equal to
     * its own conjugate transpose.
     */
    private static MatrixStore<ComplexNumber> makeHermitianMatrix() {
        final PhysicalStore<ComplexNumber> tmpBase = MatrixUtils.makeRandomComplexStore(DIMENSION, DIMENSION);
        return tmpBase.multiply(tmpBase.conjugate());
    }

    public QRTest() {
        super();
    }

    public QRTest(final String arg0) {
        super(arg0);
    }

    public void testDiagonalCase() {

        final PhysicalStore<Double> tmpOriginalMatrix = PrimitiveDenseStore.FACTORY
                .rows(new double[][] { { 4.0, 3.0, 2.0, 1.0 }, { 0.0, 3.0, 2.0, 1.0 }, { 0.0, 0.0, 2.0, 1.0 }, { 0.0, 0.0, 0.0, 1.0 } });

        final QR<Double> tmpDecomp = QR.makePrimitive();
        tmpDecomp.decompose(tmpOriginalMatrix);

        if (MatrixDecompositionTests.DEBUG) {
            BasicLogger.debug("Should be I", tmpDecomp.getQ());
            BasicLogger.debug("Should be A", tmpDecomp.getR());
        }

        TestUtils.assertEquals(tmpOriginalMatrix, tmpDecomp, new NumberContext(7, 6));
        TestUtils.assertEquals(PrimitiveDenseStore.FACTORY.makeEye(4, 4), tmpDecomp.getQ(), new NumberContext(7, 6));
        TestUtils.assertEquals(tmpOriginalMatrix, tmpDecomp.getR(), new NumberContext(7, 6));
    }

    public void testHermitian() {

        final int tmpLim = DIMENSION - 1;
        final MatrixStore<ComplexNumber> tmpOriginal = QRTest.makeHermitianMatrix();

        if (MatrixDecompositionTests.DEBUG) {
            BasicLogger.debug("Original", tmpOriginal);
        }

        final QR<ComplexNumber> tmpDecomposition = QR.makeComplex();
        tmpDecomposition.decompose(tmpOriginal);
        final MatrixStore<ComplexNumber> tmpDecompQ = tmpDecomposition.getQ();
        final MatrixStore<ComplexNumber> tmpDecompR = tmpDecomposition.getR();

        final DecompositionStore<ComplexNumber> tmpInPlace = ComplexDenseStore.FACTORY.copy(tmpOriginal);

        final DecompositionStore<ComplexNumber> tmpNowQ = ComplexDenseStore.FACTORY.makeEye(DIMENSION, DIMENSION);
        final DecompositionStore<ComplexNumber> tmpNowR = ComplexDenseStore.FACTORY.copy(tmpOriginal);

        final DecompositionStore<ComplexNumber> tmpForwardQ = ComplexDenseStore.FACTORY.makeEye(DIMENSION, DIMENSION);
        final DecompositionStore<ComplexNumber> tmpForwardR = ComplexDenseStore.FACTORY.copy(tmpOriginal);

        final DecompositionStore<ComplexNumber> tmpReverseQ = ComplexDenseStore.FACTORY.makeEye(DIMENSION, DIMENSION);

        final Householder.Complex[] tmpHouseholders = new Householder.Complex[tmpLim];

        for (int ij = 0; ij < tmpLim; ij++) {

            final Householder.Complex tmpVector = new Householder.Complex(DIMENSION);

            if (tmpInPlace.generateApplyAndCopyHouseholderColumn(ij, ij, tmpVector)) {
                tmpInPlace.transformLeft(tmpVector, ij + 1);
                tmpNowQ.transformRight(tmpVector, 0);
                tmpNowR.transformLeft(tmpVector, ij);
            }

            tmpHouseholders[ij] = tmpVector;
        }

        for (int h = 0; h < tmpHouseholders.length; h++) {

            final Householder.Complex tmpVector = tmpHouseholders[h];

            tmpForwardQ.transformRight(tmpVector, 0);
            tmpForwardR.transformLeft(tmpVector, h);
        }

        for (int h = tmpHouseholders.length - 1; h >= 0; h--) {

            final Householder.Complex tmpVector = tmpHouseholders[h];

            tmpReverseQ.transformLeft(tmpVector, 0);
        }

        if (MatrixDecompositionTests.DEBUG) {
            BasicLogger.debug();
            BasicLogger.debug("Decomp Q", tmpDecompQ);
            BasicLogger.debug("Now Q", tmpNowQ);
            BasicLogger.debug("Forward Q", tmpForwardQ);
            BasicLogger.debug("Reverse Q", tmpReverseQ);
            BasicLogger.debug();
            BasicLogger.debug("Decomp R", tmpDecompR);
            BasicLogger.debug("Now R", tmpNowR);
            BasicLogger.debug("Forward R", tmpForwardR);
        }

        TestUtils.assertEquals(tmpOriginal, tmpDecomposition, new NumberContext(7, 6));

        TestUtils.assertEquals(tmpDecompQ, tmpNowQ, new NumberContext(7, 6));
        TestUtils.assertEquals(tmpDecompQ, tmpForwardQ, new NumberContext(7, 6));
        TestUtils.assertEquals(tmpDecompQ, tmpReverseQ, new NumberContext(7, 6));

        TestUtils.assertEquals(tmpDecompR, tmpNowR, new NumberContext(7, 6));
        TestUtils.assertEquals(tmpDecompR, tmpForwardR, new NumberContext(7, 6));
    }

    public void testP20030422Case() {

        final BigMatrix tmpOriginal = P20030422Case.getProblematic();

        final QR<BigDecimal> tmpBigDecomp = QR.makeBig();
        final QR<ComplexNumber> tmpComplexDecomp = QR.makeComplex();
        final QR<Double> tmpPrimitiveDecomp = QR.makePrimitive();

        tmpBigDecomp.decompose(tmpOriginal);
        tmpComplexDecomp.decompose(tmpOriginal);
        tmpPrimitiveDecomp.decompose(tmpOriginal);

        final MatrixStore<BigDecimal> tmpBigQ = tmpBigDecomp.getQ();
        final MatrixStore<ComplexNumber> tmpComplexQ = tmpComplexDecomp.getQ();
        final MatrixStore<Double> tmpPrimitiveQ = tmpPrimitiveDecomp.getQ();

        if (MatrixDecompositionTests.DEBUG) {
            BasicLogger.debug("Big Q", tmpBigQ);
            BasicLogger.debug("Complex Q", tmpComplexQ);
            BasicLogger.debug("Primitive Q", tmpPrimitiveQ);
        }

        final MatrixStore<BigDecimal> tmpBigR = tmpBigDecomp.getR();
        final MatrixStore<ComplexNumber> tmpComplexR = tmpComplexDecomp.getR();
        final MatrixStore<Double> tmpPrimitiveR = tmpPrimitiveDecomp.getR();

        if (MatrixDecompositionTests.DEBUG) {
            BasicLogger.debug("Big R", tmpBigR);
            BasicLogger.debug("Complex R", tmpComplexR);
            BasicLogger.debug("Primitive R", tmpPrimitiveR);
        }

        TestUtils.assertEquals(tmpOriginal.toBigStore(), tmpBigDecomp, new NumberContext(7, 14));
        ;
        TestUtils.assertEquals(tmpOriginal.toComplexStore(), tmpComplexDecomp, new NumberContext(7, 14));
        ;
        TestUtils.assertEquals(tmpOriginal.toPrimitiveStore(), tmpPrimitiveDecomp, new NumberContext(7, 14));
        ;

    }

    public void testLeastSquaresInvert() {

        MatrixUtils.setThresholdsMinValue(100000);

        final int tmpDim = 3;
        final MatrixStore<Double> tmpA = MatrixUtils.makeSPD(tmpDim).builder().below(MatrixStore.PRIMITIVE.makeIdentity(tmpDim).get()).build();

        final QR<Double> tmpDenseQR = new QRDecomposition.Primitive();
        final QR<Double> tmpRawQR = new RawQR();

        final DecompositionStore<Double> tmpDenseAlloc = tmpDenseQR.preallocate(tmpA);
        final DecompositionStore<Double> tmpRawAlloc = tmpRawQR.preallocate(tmpA);

        final MatrixStore<Double> tmpDenseInv = tmpDenseQR.invert(tmpA, tmpDenseAlloc);
        final MatrixStore<Double> tmpRawInv = tmpRawQR.invert(tmpA, tmpRawAlloc);

        TestUtils.assertEquals(tmpDenseInv, tmpRawInv);

        final MatrixStore<Double> tmpIdentity = MatrixStore.PRIMITIVE.makeIdentity(tmpDim).get();
        TestUtils.assertEquals(tmpIdentity, tmpDenseInv.multiply(tmpA));
        TestUtils.assertEquals(tmpIdentity, tmpRawInv.multiply(tmpA));
    }

}


text:
package com.fasterxml.jackson.core.io.doubleparser;

import static com.fasterxml.jackson.core.io.doubleparser.FastDoubleMath.*;
import static com.fasterxml.jackson.core.io.doubleparser.FastIntegerMath.fullMultiplication;

/**
 * This class complements {@link FastDoubleMath} with methods for
 * converting {@code FloatingPointLiteral} productions to floats.
 *

 * See {@link JavaDoubleParser} for a description of
 * {@code FloatingPointLiteral}.
 */
class FastFloatMath {
    /**
     * Bias used in the exponent of a float.
     */
    private static final int FLOAT_EXPONENT_BIAS = 127;
    /**
     * The number of bits in the significand, including the implicit bit.
     */
    private static final int FLOAT_SIGNIFICAND_WIDTH = 24;
    private final static int FLOAT_MIN_EXPONENT_POWER_OF_TEN = -45;
    private final static int FLOAT_MAX_EXPONENT_POWER_OF_TEN = 38;
    private final static int FLOAT_MIN_EXPONENT_POWER_OF_TWO = Float.MIN_EXPONENT;
    private final static int FLOAT_MAX_EXPONENT_POWER_OF_TWO = Float.MAX_EXPONENT;
    /**
     * Precomputed powers of ten from 10^0 to 10^10. These
     * can be represented exactly using the float type.
     */
    private static final float[] FLOAT_POWER_OF_TEN = {
            1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f, 1e7f, 1e8f, 1e9f, 1e10f};

    /**
     * Don't let anyone instantiate this class.
     */
    private FastFloatMath() {

    }

    static float decFloatLiteralToFloat(boolean isNegative, long significand, int exponent,
                                        boolean isSignificandTruncated,
                                        int exponentOfTruncatedSignificand) {
        if (significand == 0) {
            return isNegative ? -0.0f : 0.0f;
        }

        final float result;
        if (isSignificandTruncated) {

            // We have too many digits. We may have to round up.
            // To know whether rounding up is needed, we may have to examine up to 768 digits.

            // There are cases, in which rounding has no effect.
            if (FLOAT_MIN_EXPONENT_POWER_OF_TEN <= exponentOfTruncatedSignificand
                    && exponentOfTruncatedSignificand <= FLOAT_MAX_EXPONENT_POWER_OF_TEN) {
                float withoutRounding = tryDecToFloatWithFastAlgorithm(isNegative, significand, exponentOfTruncatedSignificand);
                float roundedUp = tryDecToFloatWithFastAlgorithm(isNegative, significand + 1, exponentOfTruncatedSignificand);
                if (!Float.isNaN(withoutRounding) && roundedUp == withoutRounding) {
                    return withoutRounding;
                }
            }

            // We have to take a slow path.
            //return Double.parseDouble(str.toString());
            result = Float.NaN;

        } else if (FLOAT_MIN_EXPONENT_POWER_OF_TEN <= exponent && exponent <= FLOAT_MAX_EXPONENT_POWER_OF_TEN) {
            result = tryDecToFloatWithFastAlgorithm(isNegative, significand, exponent);
        } else {
            result = Float.NaN;
        }
        return result;
    }

    static float hexFloatLiteralToFloat(boolean isNegative, long significand, int exponent,
                                        boolean isSignificandTruncated,
                                        int exponentOfTruncatedSignificand) {
        if (significand == 0) {
            return isNegative ? -0.0f : 0.0f;
        }
        final float result;
        if (isSignificandTruncated) {

            // We have too many digits. We may have to round up.
            // To know whether rounding up is needed, we may have to examine up to 768 digits.

            // There are cases, in which rounding has no effect.
            if (FLOAT_MIN_EXPONENT_POWER_OF_TWO <= exponentOfTruncatedSignificand && exponentOfTruncatedSignificand <= FLOAT_MAX_EXPONENT_POWER_OF_TWO) {
                float withoutRounding = tryHexToFloatWithFastAlgorithm(isNegative, significand, exponentOfTruncatedSignificand);
                float roundedUp = tryHexToFloatWithFastAlgorithm(isNegative, significand + 1, exponentOfTruncatedSignificand);
                if (!Double.isNaN(withoutRounding) && roundedUp == withoutRounding) {
                    return withoutRounding;
                }
            }

            // We have to take a slow path.
            result = Float.NaN;

        } else if (FLOAT_MIN_EXPONENT_POWER_OF_TWO <= exponent && exponent <= FLOAT_MAX_EXPONENT_POWER_OF_TWO) {
            result = tryHexToFloatWithFastAlgorithm(isNegative, significand, exponent);
        } else {
            result = Float.NaN;
        }
        return result;
    }

    /**
     * Attempts to compute {@literal digits * 10^(power)} exactly;
     * and if "negative" is true, negate the result.
     *

     * This function will only work in some cases, when it does not work it
     * returns null. This should work *most of the time* (like 99% of the time).
     * We assume that power is in the
     * [{@value FastDoubleMath#DOUBLE_MIN_EXPONENT_POWER_OF_TEN},
     * {@value FastDoubleMath#DOUBLE_MAX_EXPONENT_POWER_OF_TEN}]
     * interval: the caller is responsible for this check.
     *
     * @param isNegative whether the number is negative
     * @param digits     uint64 the digits of the number
     * @param power      int32 the exponent of the number
     * @return the computed double on success, {@link Double#NaN} on failure
     */
    static float tryDecToFloatWithFastAlgorithm(boolean isNegative, long digits, int power) {

        // we start with a fast path
        if (-10 <= power && power <= 10 && Long.compareUnsigned(digits, (1L << FLOAT_SIGNIFICAND_WIDTH) - 1L) <= 0) {
            // convert the integer into a float. This is lossless since
            // 0 <= i <= 2^24 - 1.
            float d = (float) digits;
            //
            // The general idea is as follows.
            // If 0 <= s < 2^24 and if 10^0 <= p <= 10^10 then
            // 1) Both s and p can be represented exactly as 32-bit floating-point values
            // 2) Because s and p can be represented exactly as floating-point values,
            // then s * p and s / p will produce correctly rounded values.
            //
            if (power < 0) {
                d = d / FLOAT_POWER_OF_TEN[-power];
            } else {
                d = d * FLOAT_POWER_OF_TEN[power];
            }
            return (isNegative) ? -d : d;
        }

        // The fast path has now failed, so we are falling back on the slower path.

        // We are going to need to do some 64-bit arithmetic to get a more precise product.
        // We use a table lookup approach.
        // It is safe because
        // power >= DOUBLE_MIN_EXPONENT_POWER_OF_TEN
        // and power <= DOUBLE_MAX_EXPONENT_POWER_OF_TEN
        // We recover the mantissa of the power, it has a leading 1. It is always
        // rounded down.
        long factorMantissa = MANTISSA_64[power - DOUBLE_MIN_EXPONENT_POWER_OF_TEN];

        // The exponent is 127 + 64 + power
        //     + floor(log(5**power)/log(2)).
        // The 127 is the exponent bias.
        // The 64 comes from the fact that we use a 64-bit word.
        //
        // Computing floor(log(5**power)/log(2)) could be
        // slow. Instead ,we use a fast function.
        //
        // For power in (-400,350), we have that
        // (((152170 + 65536) * power ) >> 16);
        // is equal to
        //  floor(log(5**power)/log(2)) + power when power >= 0
        // and it is equal to
        //  ceil(log(5**-power)/log(2)) + power when power < 0
        //
        //
        // The 65536 is (1<<16) and corresponds to
        // (65536 * power) >> 16 ---> power
        //
        // ((152170 * power ) >> 16) is equal to
        // floor(log(5**power)/log(2))
        //
        // Note that this is not magic: 152170/(1<<16) is
        // approximately equal to log(5)/log(2).
        // The 1<<16 value is a power of two; we could use a
        // larger power of 2 if we wanted to.
        //
        long exponent = (((152170L + 65536L) * power) >> 16) + FLOAT_EXPONENT_BIAS + 64;
        // We want the most significant bit of digits to be 1. Shift if needed.
        int lz = Long.numberOfLeadingZeros(digits);
        digits <<= lz;
        // We want the most significant 64 bits of the product. We know
        // this will be non-zero because the most significant bit of i is
        // 1.
        FastIntegerMath.UInt128 product = fullMultiplication(digits, factorMantissa);
        long lower = product.low;
        long upper = product.high;
        // We know that upper has at most one leading zero because
        // both i and factor_mantissa have a leading one. This means
        // that the result is at least as large as ((1<<63)*(1<<63))/(1<<64).

        // As long as the first 39 bits of "upper" are not "1", then we
        // know that we have an exact computed value for the leading
        // 25 bits because any imprecision would play out as a +1, in
        // the worst case.
        // Having 25 bits is necessary because
        // we need 24 bits for the mantissa, but we have to have one rounding bit, and
        // we can waste a bit if the most significant bit of the product is zero.
        // We expect this next branch to be rarely taken (say 1% of the time).
        // When (upper &0x3FFFFFFFFF) == 0x3FFFFFFFFF, it can be common for
        // lower + i < lower to be true (proba. much higher than 1%).
        if ((upper & 0x3_FFFFF_FFFFL) == 0x3_FFFFF_FFFFL && Long.compareUnsigned(lower + digits, lower) < 0) {
            long factor_mantissa_low =
                    MANTISSA_128[power - DOUBLE_MIN_EXPONENT_POWER_OF_TEN];
            // next, we compute the 64-bit x 128-bit multiplication, getting a 192-bit
            // result (three 64-bit values)
            product = fullMultiplication(digits, factor_mantissa_low);
            long product_low = product.low;
            long product_middle2 = product.high;
            long product_middle1 = lower;
            long product_high = upper;
            long product_middle = product_middle1 + product_middle2;
            if (Long.compareUnsigned(product_middle, product_middle1) < 0) {
                product_high++; // overflow carry
            }

            // we want to check whether mantissa *i + i would affect our result
            // This does happen, e.g. with 7.3177701707893310e+15 ????
            if (((product_middle + 1 == 0) && ((product_high & 0x7_FFFFF_FFFFL) == 0x7_FFFFF_FFFFL) &&
                    (product_low + Long.compareUnsigned(digits, product_low) < 0))) { // let us be prudent and bail out.
                return Float.NaN;
            }
            upper = product_high;
            //lower = product_middle;
        }

        // The final mantissa should be 24 bits with a leading 1.
        // We shift it so that it occupies 25 bits with a leading 1.
        long upperbit = upper >>> 63;
        long mantissa = upper >>> (upperbit + 38);
        lz += (int) (1 ^ upperbit);
        // Here we have mantissa < (1<<25).
        //assert mantissa < (1<<25);

        // We have to round to even. The "to even" part
        // is only a problem when we are right in between two floating-point values
        // which we guard against.
        // If we have lots of trailing zeros, we may fall right between two
        // floating-point values.
        if (((upper & 0x3_FFFFF_FFFFL) == 0x3_FFFFF_FFFFL)
                || ((upper & 0x3_FFFFF_FFFFL) == 0) && (mantissa & 3) == 1) {
            // if mantissa & 1 == 1 we might need to round up.
            //
            // Scenarios:
            // 1. We are not in the middle. Then we should round up.
            //
            // 2. We are right in the middle. Whether we round up depends
            // on the last significant bit: if it is "one" then we round
            // up (round to even) otherwise, we do not.
            //
            // So if the last significant bit is 1, we can safely round up.
            // Hence, we only need to bail out if (mantissa & 3) == 1.
            // Otherwise, we may need more accuracy or analysis to determine whether
            // we are exactly between two floating-point numbers.
            // It can be triggered with 1e23. ??
            // Note: because the factor_mantissa and factor_mantissa_low are
            // almost always rounded down (except for small positive powers),
            // almost always should round up.
            return Float.NaN;
        }

        mantissa += 1;
        mantissa >>>= 1;

        // Here we have mantissa < (1<<24), unless there was an overflow
        if (mantissa >= (1L << FLOAT_SIGNIFICAND_WIDTH)) {
            // This will happen when parsing values such as 7.2057594037927933e+16 ??
            mantissa = (1L << (FLOAT_SIGNIFICAND_WIDTH - 1));
            lz--; // undo previous addition
        }

        mantissa &= ~(1L << (FLOAT_SIGNIFICAND_WIDTH - 1));

        long real_exponent = exponent - lz;
        // we have to check that real_exponent is in range, otherwise we bail out
        if ((real_exponent < 1) || (real_exponent > FLOAT_MAX_EXPONENT_POWER_OF_TWO + FLOAT_EXPONENT_BIAS)) {
            return Float.NaN;
        }

        int bits = (int) (mantissa | real_exponent << (FLOAT_SIGNIFICAND_WIDTH - 1)
                | (isNegative ? 1L << 31 : 0));
        return Float.intBitsToFloat(bits);
    }

    static float tryHexToFloatWithFastAlgorithm(boolean isNegative, long digits, int power) {
        if (digits == 0 || power < Float.MIN_EXPONENT - 54) {
            return isNegative ? -0.0f : 0.0f;
        }
        if (power > Float.MAX_EXPONENT) {
            return isNegative ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
        }

        // we start with a fast path
        // We try to mimic the fast described by Clinger WD for decimal
        // float number literals. How to read floating point numbers accurately.
        // ACM SIGPLAN Notices. 1990
        if (Long.compareUnsigned(digits, 0x1fffffffffffffL) <= 0) {
            // convert the integer into a double. This is lossless since
            // 0 <= i <= 2^53 - 1.
            float d = (float) digits;
            //
            // The general idea is as follows.
            // If 0 <= s < 2^53  then
            // 1) Both s and p can be represented exactly as 64-bit floating-point
            // values (binary64).
            // 2) Because s and p can be represented exactly as floating-point values,
            // then s * p will produce correctly rounded values.
            //
            d = d * Math.scalb(1f, power);
            if (isNegative) {
                d = -d;
            }
            return d;
        }

        // The fast path has failed
        return Float.NaN;
    }

}