text:
"""
Kenshoto's Elf parser

This package will let you use programatic ninja-fu
when trying to parse Elf binaries.  The API is based
around several objects representing constructs in the
Elf binary format.  The Elf object itself contains
parsed metadata and lists of things like section headers
and relocation entries.  Additionally, most of the
objects implement repr() in some form or another which
allows you a bunch of readelf-like functionality.

*Eventually* this API will allow you to modify Elf binaries
and spit them back out in working order (not complete, you
may notice some of the initial code).

Send bug reports to Invisigoth or Metr0.

"""
# Copyright (C) 2007 Invisigoth - See LICENSE file for details
import os
import sys
import struct
import traceback
import zlib

from stat import *
from Elf.elf_lookup import *
import vstruct
import vstruct.defs.elf as vs_elf

verbose = False

class ElfReloc:
    """
    Elf relocation entries consist mostly of "fixup" address which
    are taken care of by the loader at runtime.  Things like
    GOT entries, PLT jmp codes etc all have an Elf relocation
    entry.
    """

    def __init__(self):
        self.name = ""

    def __repr__(self):
        return "reloc: @%s %d %s" % (hex(self.r_offset),self.getType(),self.getName())

    def setName(self, name):
        self.name = name

    def getName(self):
        return self.name

    def getType(self):
        return self.r_info & 0xff

class Elf32Reloc(ElfReloc, vs_elf.Elf32Reloc):
    def __init__(self):
        vs_elf.Elf32Reloc.__init__(self)
        ElfReloc.__init__(self)

    def getSymTabIndex(self):
        return self.r_info >> 8

class Elf32Reloca(ElfReloc, vs_elf.Elf32Reloca):
    def __init__(self):
        vs_elf.Elf32Reloca.__init__(self)
        ElfReloc.__init__(self)

    def getSymTabIndex(self):
        return self.r_info >> 8

class Elf64Reloc(ElfReloc, vs_elf.Elf64Reloc):
    def __init__(self):
        vs_elf.Elf64Reloc.__init__(self)
        ElfReloc.__init__(self)

    def getSymTabIndex(self):
        return self.r_info >> 32

class Elf64Reloca(ElfReloc, vs_elf.Elf64Reloca):
    def __init__(self):
        vs_elf.Elf64Reloca.__init__(self)
        ElfReloc.__init__(self)

    def getSymTabIndex(self):
        return self.r_info >> 32

class ElfDynamic:
    has_string = [DT_NEEDED,DT_SONAME]
    """
    An object to represent an Elf dynamic entry.
    (linker/loader directives)
    """

    def __init__(self, bytes=None):
        self.name = ""

    def __repr__(self):
        name = self.getName()
        if not name:
            name = hex(self.d_value)
        return "%s %s" % (name,self.getTypeName())

    def getName(self):
        return self.name

    def setName(self, name):
        self.name = name

    def getTypeName(self):
        return dt_types.get(self.d_tag,"Unknown: %s"%hex(self.d_tag))

class Elf32Dynamic(ElfDynamic, vs_elf.Elf32Dynamic):
    def __init__(self):
        vs_elf.Elf32Dynamic.__init__(self)
        ElfDynamic.__init__(self)

class Elf64Dynamic(ElfDynamic, vs_elf.Elf64Dynamic):
    def __init__(self):
        vs_elf.Elf64Dynamic.__init__(self)
        ElfDynamic.__init__(self)

class ElfSymbol:
    def __init__(self):
        self.name = ""

    def getInfoType(self):
        return self.st_info & 0xf

    def getInfoBind(self):
        return self.st_info >> 4

    def __cmp__(self, other):
        if self.st_value > other.st_value:
            return 1
        return -1

    def setName(self,name):
        self.name = name

    def getName(self):
        return self.name

    def __repr__(self):
        return "0x%.8x %d %s" % (self.st_value, self.st_size, self.name)

class Elf32Symbol(ElfSymbol, vs_elf.Elf32Symbol):
    def __init__(self):
        vs_elf.Elf32Symbol.__init__(self)
        ElfSymbol.__init__(self)

class Elf64Symbol(ElfSymbol, vs_elf.Elf64Symbol):
    def __init__(self):
        vs_elf.Elf64Symbol.__init__(self)
        ElfSymbol.__init__(self)

class ElfPheader:

    def __init__(self):
        pass

    def getTypeName(self):
        return ph_types.get(self.p_type, "Unknown")

    def __repr__(self):
        return '[%35s] VMA: 0x%.8x  offset: %8d  memsize: %8d  align: %8d  (filesz: %8d)  flags: %x' % (
            self.getTypeName(),
            self.p_vaddr,
            self.p_offset,
            self.p_memsz,
            self.p_align,
            self.p_filesz,
            self.p_flags)

class Elf32Pheader(ElfPheader, vs_elf.Elf32Pheader):
    def __init__(self):
        vs_elf.Elf32Pheader.__init__(self)
        ElfPheader.__init__(self)

class Elf64Pheader(ElfPheader, vs_elf.Elf64Pheader):
    def __init__(self):
        vs_elf.Elf64Pheader.__init__(self)
        ElfPheader.__init__(self)

class ElfSection:
    def __init__(self):
        self.name = ''

    def setName(self, name):
        self.name = name

    def getName(self):
        return self.name

    def __repr__(self):
        return 'Elf Sec: [%20s] @0x%.8x (%8d)  ent/size: %8d/%8d  align: %8d' % (
                self.name,
                self.sh_addr,
                self.sh_offset,
                self.sh_entsize,
                self.sh_size,
                self.sh_addralign)

class Elf32Section(ElfSection, vs_elf.Elf32Section):
    def __init__(self):
        vs_elf.Elf32Section.__init__(self)
        ElfSection.__init__(self)

class Elf64Section(ElfSection, vs_elf.Elf64Section):
    def __init__(self):
        vs_elf.Elf64Section.__init__(self)
        ElfSection.__init__(self)

class Elf(vs_elf.Elf32, vs_elf.Elf64):

    def __init__(self, fd, inmem=False):

        # Grab a 32bit header to use to check for other
        # machine types...
        e = vs_elf.Elf32()
        fd.seek(0)
        bytes = fd.read(len(e))
        e.vsParse(bytes)
        if e.e_machine in e_machine_32:
            vs_elf.Elf32.__init__(self)
            self.bits = 32
            self.psize = 4

            self._cls_reloc  = Elf32Reloc
            self._cls_reloca = Elf32Reloca
            self._cls_symbol = Elf32Symbol
            self._cls_section = Elf32Section

        elif e.e_machine in e_machine_64:
            vs_elf.Elf64.__init__(self)
            self.bits = 64
            self.psize = 8

            self._cls_reloc  = Elf64Reloc
            self._cls_reloca = Elf64Reloca
            self._cls_symbol = Elf64Symbol
            self._cls_section = Elf64Section

        else:
            raise Exception('Unrecognized e_machine: %d' % e.e_machine)

        self.fd = fd

        bytes = self.readAtOffset(0, len(self))
        self.vsParse(bytes)

        if self.e_machine == EM_386:
            self.r_types = r_types_386
        elif self.e_machine == EM_X86_64:
            self.r_types = r_types_amd64
        else:
            self.r_types = {}

        self.pheaders = []
        self.sections = []
        self.secnames = {}
        self.symbols  = []
        self.relocs   = []
        self.symbols_by_name = {}
        self.symbols_by_addr = {}
        self.dynamics = []
        self.dynamic_symbols = []

        self._parsePheaders()
        self._parseSections()
        self._parseSymbols()
        self._parseDynamic()
        self._parseRelocs()

    def getRelocTypeName(self, rtype):
        '''
        Because relocation type names are decided based on the
        arch, only the Elf knows for sure...
        '''
        return self.r_types.get(rtype)

    def _parsePheaders(self):
        # Load up any program headers we find
        if self.e_phoff:
            pbase = self.e_phoff
            plen = self.e_phentsize
            for i in range(self.e_phnum):
                if self.bits == 32:
                    pgm = Elf32Pheader()
                elif self.bits == 64:
                    pgm = Elf64Pheader()
                else:
                    raise Exception('Platform not supported: %d' % (self.bits))

                bytes = self.readAtOffset(pbase, plen)
                pgm.vsParse(bytes)

                self.pheaders.append(pgm)
                pbase += plen

    def _parseSections(self):
        # Load up all the section headers
        if self.e_shoff:
            # Load up the sections
            sbase = self.e_shoff
            sec = self._cls_section()
            slen = self.e_shentsize
            if len(sec) != slen:
                raise Exception('Invalid Section Header Size: %d' % slen)

            secbytes = self.readAtOffset(sbase, self.e_shnum * slen)

            secs = sec * self.e_shnum
            vstruct.VArray(elems=secs).vsParse(secbytes,fast=True)

            self.sections.extend(secs)

            # Populate the section names
            strsec = self.sections[self.e_shstrndx]
            names = self.readAtOffset(strsec.sh_offset,strsec.sh_size)
            for sec in self.sections:
                name = names[sec.sh_name:].split("\x00")[0]
                if len(name) > 0:
                    sec.setName(name)
                    self.secnames[name] = sec

    def _parseSymbols(self):
        """
        Parse out the symbols that this elf binary has for us.
        """
        for sec in self.sections:
            if sec.sh_type == SHT_SYMTAB:
                sym = self._cls_symbol()
                symtab = self.readAtOffset(sec.sh_offset, sec.sh_size)

                count,remain = divmod(sec.sh_size,len(sym))
                syms = sym * count

                vstruct.VArray(elems=syms).vsParse(symtab,fast=True)

                for sym in syms:
                    if sym.st_name:
                        name = self.getStrtabString(sym.st_name, ".strtab")
                        sym.setName(name)

                    self.addSymbol(sym)

    def _parseDynamic(self):
        symtab = self.getSectionBytes('.dynsym')
        if symtab == None:
            return

        sym = self._cls_symbol()
        syms = sym * (len(symtab) / len(sym))
        vstruct.VArray(elems=syms).vsParse(symtab,fast=True)

        for sym in syms:
            if not sym.st_name:
                continue
            name = self.getStrtabString(sym.st_name,".dynstr")
            sym.setName(name)

        self.dynamic_symbols.extend(syms)

        dynbytes = self.getSectionBytes('.dynamic')
        while dynbytes:
            if self.bits == 32:
                dyn = Elf32Dynamic()
            elif self.bits == 64:
                dyn = Elf64Dynamic()
            else:
                raise Exception('Platform not supported: %d' % (self.bits))
            dyn.vsParse(dynbytes)
            if dyn.d_tag in Elf32Dynamic.has_string:
                name = self.getStrtabString(dyn.d_value, ".dynstr")
                dyn.setName(name)

            self.dynamics.append(dyn)
            if dyn.d_tag == DT_NULL: # Represents the end
                break
            dynbytes = dynbytes[len(dyn):]

    def _parseRelocs(self):
        """
        Parse all the relocation entries out of any sections with
        sh_type == SHT_REL
        """
        for sec in self.sections:
            if sec.sh_type not in (SHT_REL,SHT_RELA):
                continue

            reloccls = self._cls_reloc
            if sec.sh_type == SHT_RELA:
                reloccls = self._cls_reloca

            secbytes = self.readAtOffset(sec.sh_offset, sec.sh_size)
            reloc = reloccls()
            count, remain = divmod(len(secbytes),len(reloc))

            relocs = reloc * count
            vstruct.VArray(elems=relocs).vsParse(secbytes,fast=True)

            for reloc in relocs:
                index = reloc.getSymTabIndex()
                if index < len(self.dynamic_symbols):
                    sym = self.dynamic_symbols[index]
                    reloc.setName( sym.getName() )
                self.relocs.append(reloc)

    def getBaseAddress(self):
        """
        For prelinked and main-exe elf binaries, return the
        value for the loaded base address...
        """
        shrd = self.isSharedObject()
        plnk = self.isPreLinked()

        # If it's a shared object and *not* prelinked,
        # we need to select a base address for it
        # FIXME find non-coliding addr in workspace
        if shrd and not plnk:
            return 0x02000000

        # Find the best base address from the list of
        # section addresses...
        base = None
        for pgm in self.getPheaders():

            if pgm.p_vaddr == 0:
                continue

            if base == None:
                base = pgm.p_vaddr
                continue

            if pgm.p_vaddr < base:
                base = pgm.p_vaddr

        if base == None:
            base = 0x20000000

        base &= 0xfffff000
        return base

    def readAtRva(self, rva, size):
        '''
        Calculate the file offset for the given RVA and
        read from it...
        '''
        return self.readAtOffset(self.rvaToOffset(rva), size)

    def rvaToOffset(self, rva):
        '''
        Convert an RVA for this ELF binary to a file offset.
        '''
        baseaddr = 0
        #if self.isPreLinked() or not self.isSharedObject():
        #if not self.isSharedObject():
            #print 'SUBTRACTING CALCULATED BASE'
            #baseaddr = self.getBaseAddress()

        for pgm in self.pheaders:
            if pgm.p_type != PT_LOAD:
                continue
            phrva = pgm.p_vaddr - baseaddr
            if rva < phrva:
                continue
            if rva >= phrva+pgm.p_memsz:
                continue
            # We are inside this pgrm header!
            rvaoff = rva - phrva
            return pgm.p_offset + rvaoff

        raise 'omg',hex(rva)
        return None

    def readAtOffset(self, off, size):
        '''
        Read from the given file offset.
        '''
        self.fd.seek(off)
        return self.fd.read(size)

    def getSection(self, secname):
        return self.secnames.get(secname,None)

    def getSections(self):
        """
        Return the array of sections for this Elf
        """
        return list(self.sections)

    def getSectionBytes(self, secname):
        sec = self.getSection(secname)
        if sec == None:
            return None
        return self.readAtOffset(sec.sh_offset, sec.sh_size)

    def getStrtabString(self, offset, section=".strtab"):
        sec = self.getSection(section)
        bytes = self.readAtOffset(sec.sh_offset, sec.sh_size)
        index = bytes.find("\x00", offset)
        return bytes[offset:index]

    def getNotes(self):
        '''
        Retrieve a list of the ElfNote vstructs from any
        sections of type SHT_NOTE.

        Example:
            for note in e.getNotes():
                print('%s : %d' % (e.name,e.ntype))
        '''
        for sec in self.getSections():
            if sec.sh_type != SHT_NOTE:
                continue

            notebytes =  self.readAtOffset(sec.sh_offset, sec.sh_size)

            offset = 0
            while offset < len(notebytes):
                note = vs_elf.ElfNote()
                offset = note.vsParse(notebytes,offset=offset)
                yield note

    def getPlatform(self):
        '''
        Return a "best effort" platform guess (envi platform name).
        ( and platform specific details if any )

        Example:
            plat = e.getPlatform()
        '''
        for note in self.getNotes():
            if note.name == 'GNU\x00' and note.ntype == 1:
                desc0 = int(note.desc[0])
                return osnotes.get(desc0,'unknown')

        return 'unknown'

    def getDynamics(self):
        '''
        Return a list of the dynamics.
        '''
        return list(self.dynamics)

    def getDynSyms(self):
        '''
        Return a list of dynamic symbol objects.
        '''
        return self.dynamic_symbols

    def getRelocs(self):
        '''
        Get the list of relocations.
        '''
        return list(self.relocs)

    def isPreLinked(self):
        '''
        Returns True if the Elf binary is prelinked.
        '''
        for dyn in self.dynamics:
            if dyn.d_tag == DT_GNU_PRELINKED:
                return True
            if dyn.d_tag == DT_GNU_CONFLICTSZ:
                return True
        return False

    def isSharedObject(self):
        '''
        Returns true if the given Elf binary is a dynamically shared
        object.
        '''
        if self.e_type == ET_DYN:
            return True
        return False

    def isExecutable(self):
        '''
        Returns true if the given Elf binary is an executable file type.
        '''
        return self.e_type == ET_EXEC

    def __repr__(self, verbose=False):
        """  Returns a string summary of this ELF.  If (verbose) the summary will include Symbols, Relocs, Dynamics and Dynamic Symbol tables"""
        mystr = 'Elf Binary:'
        mystr+= "\n= Intimate Details:"
        mystr+= "\n==Magic:\t\t\t\t"       + self.e_ident
        mystr+= "\n==Type:\t\t\t\t\t"        + e_types.get(self.e_type)
        mystr+= "\n==Machine Arch:\t\t\t\t"  + e_machine_types.get(self.e_machine)
        mystr+= "\n==Version:\t\t\t\t%d"     % (self.e_version)
        mystr+= "\n==Entry:\t\t\t\t0x%.8x"      % (self.e_entry)
        mystr+= "\n==Program Headers(offset):\t\t%d (0x%x) bytes" % (self.e_phoff, self.e_phoff)
        mystr+= "\n==Section Headers(offset):\t\t%d (0x%x) bytes" % (self.e_shoff, self.e_shoff)
        mystr+= "\n==Flags:\t\t\t\t" + repr(self.e_flags) + " "
        mystr+= "\n==Elf Header Size:\t\t\t" + repr(self.e_ehsize) + " (" + hex(self.e_ehsize) + " bytes)"
        mystr+= "\n==Program Header Size:\t\t\t" + repr(self.e_phentsize) + " (" + hex(self.e_phentsize) + " bytes)"
        mystr+= "\n==Program Header Count:\t\t\t" + repr(self.e_phnum) + " (" + hex(self.e_phnum)+ ")"
        mystr+= "\n==Section Header Size:\t\t\t" + repr(self.e_shentsize) + " (" + hex(self.e_shentsize) + " bytes)"
        mystr+= "\n==Section Header Count:\t\t\t" + repr(self.e_shnum) + " (" + hex(self.e_shnum) + ")"
        mystr+= "\n==Section Header String Index\t\t" + repr(self.e_shstrndx) + " (" + hex(self.e_shstrndx) + " bytes)"

        mystr+= "\n\n= Sections:"
        for sec in self.sections:
            mystr+= "\n"+repr(sec)

        mystr+= "\n\n= Program Headers:"
        for ph in self.pheaders:
            mystr+= "\n"+repr(ph)

        return mystr

    def verbrepr(self):
        mystr = repr(self)

        mystr+= "\n\n= Symbols table:"
        for sym in self.symbols:
            mystr+= "\n"+repr(sym)

        mystr+= "\n\n= Relocation table:"
        for reloc in self.relocs:
            mystr+= "\n"+repr(reloc)

        mystr+= "\n\n= Dynamics table:"
        for dyn in self.dynamics:
            mystr+= "\n"+repr(dyn)

        mystr+= "\n\n= Dynamic Symbols table:"
        for dyn in self.dynamic_symbols:
            mystr+= "\n"+repr(dyn)

        return mystr

    def lookupSymbolName(self, name):
        """
        Lookup symbol entries in this elf binary by name.  The result is
        a long representing the address for the given symbol. Or None if
        it's not found.
        """
        return self.symbols_by_name.get(name, None)

    def lookupSymbolAddr(self, address):
        """
        lookup symbols from this elf binary by address.
        This returns the name for the given symbol or None for not found
        """
        return self.symbols_by_addr.get(address, None)

    def getPheaders(self):
        """
        Return a list of the program headers for this elf
        """
        return list(self.pheaders)

    def addSymbol(self, symbol):
        self.symbols.append(symbol)
        self.symbols_by_name[symbol.getName()] = symbol
        self.symbols_by_addr[symbol.st_value] = symbol

    def getSymbols(self):
        return self.symbols

def getRelocType(val):
    return val & 0xff

def getRelocSymTabIndex(val):
    return val >> 8


text:
package pl.newicom.dddd.view.sql

import pl.newicom.dddd.messaging.event.DomainEventMessage

import scala.slick.jdbc.JdbcBackend

trait Projection {

  def consume(event: DomainEventMessage)(implicit session: JdbcBackend.Session)

}

redpajama_set_name: RedPajamaGithub


text:
from . import megatron

class TFIDF:
    def __init__(self, megatron):
            self.megatron = megatron

    def compute_idf(self):
            print('creating index')
            self.megatron.word_book_controller.add_indices()
            print('created index')
            self.megatron.tf_idf_controller.drop_tables()
            self.megatron.tf_idf_controller.create_tables()
            print('precomputing top book word count')
            self.megatron.tf_idf_controller.compute_top_book_word_count()
            print('precomputing idf')
            self.megatron.tf_idf_controller.compute_idf()

    def compute_tfidf(self):
            print('creating index')
            self.megatron.tf_idf_controller.add_idf_indices()
            print('created index')
            self.megatron.tf_idf_controller.compute_tfidf()
            print('creating index')
            self.megatron.tf_idf_controller.add_tfidf_indices()
            print('created index')

    def compute_top_words(self):
            self.megatron.tf_idf_controller.compute_top_words()


text:
import { useState, useEffect } from 'react';
import API from '../../services/API';
import useYearMonth from '../common/UseYearMonth';

const useUsageByUser = () => {
    const { years, year, setYear, months, month, setMonth } = useYearMonth();
    const [filter, setFilter] = useState('');
    const [data, setData] = useState();
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        async function fetch() {
            const usageByUser = await API.getUsageByUser(year, month, filter);
            setData(usageByUser);
            setLoading(false);
        }
        if (year && month) {
            fetch();
        }
    }, [year, month, filter]);

    return { years, year, setYear, months, month, setMonth, filter, setFilter, data, loading };
};

export default useUsageByUser;


text:
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.deserializer;

import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_EXPRESSION;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_VALUE;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_ARGUMENT__EVALUATOR;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_ARGUMENT__LITERAL;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_MEDIATOR__ARGS;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_MEDIATOR__PAYLOAD;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_MEDIATOR__PAYLOAD_FORMAT;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.PAYLOAD_FACTORY_MEDIATOR__PAYLOAD_KEY;

import org.apache.synapse.config.xml.SynapsePath;
import org.apache.synapse.mediators.AbstractMediator;
import org.apache.synapse.mediators.transform.Argument;
import org.eclipse.core.runtime.Assert;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.MediaType;
import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFactoryArgument;
import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFactoryArgumentType;
import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFactoryEvaluatorType;
import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFactoryMediator;
import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFormatType;
import org.wso2.developerstudio.eclipse.gmf.esb.RegistryKeyProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes;

public class PayloadFactoryMediatorDeserializer
        extends AbstractEsbNodeDeserializer<AbstractMediator, PayloadFactoryMediator> {
    private static String XML_LITERAL = "xml";
    private static String JSON_LITERAL = "json";
    private static String TEXT_LITERAL = "text";

    public PayloadFactoryMediator createNode(IGraphicalEditPart part, AbstractMediator mediator) {
        Assert.isTrue(mediator instanceof org.apache.synapse.mediators.transform.PayloadFactoryMediator,
                "Unsupported mediator passed in for deserialization at " + this.getClass());

        org.apache.synapse.mediators.transform.PayloadFactoryMediator payloadFactoryMediator = (org.apache.synapse.mediators.transform.PayloadFactoryMediator) mediator;

        PayloadFactoryMediator visualPayloadFactoryMediator = (PayloadFactoryMediator) DeserializerUtils
                .createNode(part, EsbElementTypes.PayloadFactoryMediator_3597);
        setElementToEdit(visualPayloadFactoryMediator);
        setCommonProperties(payloadFactoryMediator, visualPayloadFactoryMediator);

        if (payloadFactoryMediator.getType() != null) {
            if (payloadFactoryMediator.getType().equals(XML_LITERAL)) {
                executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.XML);
            } else if (payloadFactoryMediator.getType().equals(JSON_LITERAL)) {
                executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.JSON);
            } else if (payloadFactoryMediator.getType().equals(TEXT_LITERAL)) {
                executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.TEXT);
            }
        }

        if (payloadFactoryMediator.getFormatKey() != null) {
            executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__PAYLOAD_FORMAT, PayloadFormatType.REGISTRY_REFERENCE);
            RegistryKeyProperty payloadFormatKey = EsbFactory.eINSTANCE.createRegistryKeyProperty();
            payloadFormatKey.setKeyValue(payloadFactoryMediator.getFormatKey().getKeyValue());

            executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__PAYLOAD_KEY, payloadFormatKey);

        } else {
            executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__PAYLOAD_FORMAT, PayloadFormatType.INLINE);
            executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__PAYLOAD, payloadFactoryMediator.getFormat());
        }

        EList<PayloadFactoryArgument> arguments = new BasicEList<PayloadFactoryArgument>();
        for (Argument argument : payloadFactoryMediator.getPathArgumentList()) {
            PayloadFactoryArgument payloadFactoryArgument = EsbFactory.eINSTANCE.createPayloadFactoryArgument();
            if (argument.getExpression() != null) {
                executeSetValueCommand(payloadFactoryArgument, PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_EXPRESSION,
                        createNamespacedProperty(argument.getExpression()));
                executeSetValueCommand(payloadFactoryArgument, PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE,
                        PayloadFactoryArgumentType.EXPRESSION);
                if (argument.getExpression().getPathType() == SynapsePath.X_PATH) {
                    executeSetValueCommand(payloadFactoryArgument, PAYLOAD_FACTORY_ARGUMENT__EVALUATOR, PayloadFactoryEvaluatorType.XML);
                } else if (argument.getExpression().getPathType() == SynapsePath.JSON_PATH) {
                    executeSetValueCommand(payloadFactoryArgument, PAYLOAD_FACTORY_ARGUMENT__EVALUATOR, PayloadFactoryEvaluatorType.JSON);
                }

            } else {
                executeSetValueCommand(payloadFactoryArgument, PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_VALUE,
                        argument.getValue());
                executeSetValueCommand(payloadFactoryArgument, PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE,
                        PayloadFactoryArgumentType.VALUE);
            }

            // adding deserialization support for literal attribute
            if (argument.isLiteral()) {
                executeSetValueCommand(payloadFactoryArgument, PAYLOAD_FACTORY_ARGUMENT__LITERAL, true);
            } else {
                executeSetValueCommand(payloadFactoryArgument, PAYLOAD_FACTORY_ARGUMENT__LITERAL, false);
            }
            arguments.add(payloadFactoryArgument);
        }

        /*
         * for(Argument argument: payloadFactoryMediator.getJsonPathArgumentList()){
         * PayloadFactoryArgument payloadFactoryArgument= EsbFactory.eINSTANCE.createPayloadFactoryArgument();
         * if(argument.getJsonPath()!=null){
         * try {
         * SynapseXPath xpath = new SynapseXPath(argument.getJsonPath().getJsonPathExpression());
         * executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_EXPRESSION,
         * createNamespacedProperty(xpath));
         * executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE,
         * PayloadFactoryArgumentType.EXPRESSION);
         * executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__EVALUATOR, MediaType.JSON);
         * arguments.add(payloadFactoryArgument);
         * } catch (Exception e) {
         * e.printStackTrace();
         * }
         * }
         * }
         */

        executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__ARGS, arguments);

        return visualPayloadFactoryMediator;
    }

}


text:
package de.codecentric.boot.admin.discovery;

import static org.apache.commons.lang.StringUtils.defaultIfEmpty;
import static org.apache.commons.lang.StringUtils.stripStart;

import java.net.URI;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.util.UriComponentsBuilder;

import de.codecentric.boot.admin.model.Application;

/**
 * Converts any {@link ServiceInstance}s to {@link Application}s. To customize the health- or
 * management-url for all applications you can set healthEndpointPath or managementContextPath
 * respectively. If you want to influence the url per service you can add
 * management.context-path or management.port or health.path
 * to the instances metadata.
 *
 * @author Johannes Edmeier
 */
public class DefaultServiceInstanceConverter implements ServiceInstanceConverter {
	private static final String KEY_MANAGEMENT_PORT = "management.port";
	private static final String KEY_MANAGEMENT_PATH = "management.context-path";
	private static final String KEY_HEALTH_PATH = "health.path";
	private String managementContextPath = "";
	private String healthEndpointPath = "health";

	@Override
	public Application convert(ServiceInstance instance) {
		Application.Builder builder = Application.create(instance.getServiceId());
		URI healthUrl = getHealthUrl(instance);
		if (healthUrl != null) {
			builder.withHealthUrl(healthUrl.toString());
		}

		URI managementUrl = getManagementUrl(instance);
		if (managementUrl != null) {
			builder.withManagementUrl(managementUrl.toString());
		}

		URI serviceUrl = getServiceUrl(instance);
		if (serviceUrl != null) {
			builder.withServiceUrl(serviceUrl.toString());
		}

		return builder.build();
	}

	protected URI getHealthUrl(ServiceInstance instance) {
		String healthPath = defaultIfEmpty(instance.getMetadata().get(KEY_HEALTH_PATH),
				healthEndpointPath);
		healthPath = stripStart(healthPath, "/");

		return UriComponentsBuilder.fromUri(getManagementUrl(instance)).pathSegment(healthPath)
				.build().toUri();
	}

	protected URI getManagementUrl(ServiceInstance instance) {
		String managamentPath = defaultIfEmpty(instance.getMetadata().get(KEY_MANAGEMENT_PATH),
				managementContextPath);
		managamentPath = stripStart(managamentPath, "/");

		URI serviceUrl = getServiceUrl(instance);
		String managamentPort = defaultIfEmpty(instance.getMetadata().get(KEY_MANAGEMENT_PORT),
				String.valueOf(serviceUrl.getPort()));

		return UriComponentsBuilder.fromUri(serviceUrl).port(managamentPort)
				.pathSegment(managamentPath).build().toUri();
	}

	protected URI getServiceUrl(ServiceInstance instance) {
		return instance.getUri();
	}

	/**
	 * Default management.context-path to be appended to the url of the discovered
	 * service for the managment-url.
	 *
	 * @param managementContextPath the management context-path.
	 */
	public void setManagementContextPath(String managementContextPath) {
		this.managementContextPath = managementContextPath;
	}

	/**
	 * Default path of the health-endpoint to be used for the health-url of the discovered service.
	 *
	 * @param healthEndpointPath the path for the health-endpoint.
	 */
	public void setHealthEndpointPath(String healthEndpointPath) {
		this.healthEndpointPath = healthEndpointPath;
	}
}


text:
@interface ZXBlockPair : NSObject

@property (nonatomic, assign, readonly) int8_t *dataBytes;
@property (nonatomic, assign, readonly) int8_t *errorCorrectionBytes;
@property (nonatomic, assign, readonly) int errorCorrectionLength;
@property (nonatomic, assign, readonly) int length;

- (id)initWithData:(int8_t *)data length:(unsigned int)length errorCorrection:(int8_t *)errorCorrection errorCorrectionLength:(unsigned int)errorCorrectionLength;

@end


text:
![build status](https://travis-ci.org/exercism/xelixir.svg?branch=master)

Exercism Exercises in Elixir

## Setup

The exercises currently target Elixir 1.3.2 and Erlang/OTP 19. Detailed installation instructions can be found at [http://elixir-lang.org/install.html](http://elixir-lang.org/install.html).

##Contributing

Thank you so much for contributing! :tada:

We welcome pull requests that provide fixes and improvements to existing exercises. If you're unsure, then go ahead and open a GitHub issue, and we'll discuss the change.

Please keep the following in mind:

- Please start by reading the general Exercism [contributing guide](https://github.com/exercism/x-api/blob/master/CONTRIBUTING.md#the-exercise-data).

- Pull requests should be focused on a single exercise, issue, or change.

- We welcome changes to code style, and wording. Please open a separate PR for these changes if possible.

- Please open an issue before creating a PR that makes significant (breaking) changes to an existing exercise or makes changes across many exercises. It is best to discuss these changes before doing the work.

- Follow the coding standards found in [The Elixir Style Guide](https://github.com/niftyn8/elixir_style_guide).

- Watch out for trailing spaces, extra blank lines, and spaces in blank lines.

- Each exercise must stand on its own. Do not reference files outside the exercise directory. They will not be included when the user fetches the exercise.

- Please do not add a README or README.md file to the exercise directory. The READMEs are constructed using shared metadata, which lives in the
[exercism/x-common](https://github.com/exercism/x-common) repository.

- Each problem should have a test suite, an example solution, and a template file for the real implementation.
The example solution should be named `example.exs`.

- Use typespecs in the example and template files as described [here](http://elixir-lang.org/getting-started/typespecs-and-behaviours.html).

- Each test file should have code like the following at the top of the file. This allows the tests to be run on CI and configures tests to be skipped with the `:pending` flag.

```elixir
if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("bob.exs", __DIR__)
end

ExUnit.start
ExUnit.configure exclude: :pending, trace: true
```

- All but the initial test for each exercise should be tagged `:pending`.

```elixir
@tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end
```

All the tests for xElixir exercises can be run from the top level of the repo with `$ mix test`. Please run this command before submitting your PR. Watch out for and correct any compiler warnings you may have introduced.

## License

The MIT License (MIT)

Copyright (c) 2016 Katrina Owen, _@kytrinyx.com


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.jkauflin.johnbot.MainActivity">

    <Button
        android:id="@+id/stopButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="STOP"
        android:layout_marginEnd="18dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:id="@+id/armButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ARM"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/eyesButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="EYES"
        android:layout_marginStart="18dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:text="Text here..."
        android:id="@+id/textViewWithScroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"
        android:layout_below="@+id/stopButton"
        android:layout_alignParentStart="true" />

</RelativeLayout>


text:
require 'json'
require 'oauth2'
require 'rest-client'
require 'resolv'
require 'public_suffix'
#======== End of Loadable modules

#======== Functions
def api_live(api_host,timeout,open_timeout,token)
  zones_response_json = api_get("https://#{api_host}/v1/firewall_zones/",timeout,open_timeout,token)

  if zones_response_json['firewall_zones'].length == 0
    $stderr.puts "Unable to make API calls; firewall zone array empty"
    return false
  else
    zones_response_json['firewall_zones'].each do |one_zone|
      if (one_zone['ip_address'] == '0.0.0.0/0') and (one_zone['name'] == 'any')
        return true
      end
    end
  end

  $stderr.puts "Unable to make API calls; cannot locate zone named 'any'."
  return false
end

def get_group_names(api_host,timeout,open_timeout,token)
  group_names = { }
  groups_response_json = api_get("https://#{api_host}/v1/groups",timeout,open_timeout,token)

  groups_response_json['groups'].each do |one_group|
    group_names[one_group['id']] = one_group['name']
  end
  return group_names
end

def api_delete (url,timeout,open_timeout,token)
  json_return = ''

  rest_handle = RestClient::Resource.new url, :timeout => timeout, :open_timeout => open_timeout, :headers => { 'Authorization' => "Bearer #{token}" }
  begin
    result = rest_handle.delete
  rescue RestClient::RequestFailed => e
    $stderr.puts "While DELETE'ing #{url}"
    $stderr.puts "The request failed with HTTP status code #{e.response.code}"
    $stderr.puts "The body was:"
    $stderr.puts e.response.body
  end
  #error_string = process_return_code(result.code,result.body.to_str)
  #if error_string.length > 0
  #  $stderr.puts error_string
  #  exit 1
  #end
  if (result == nil) or (result.body == "")
    json_return = JSON '{ }'
  else
    json_return = JSON result.body
  end

  return json_return
end

def api_get (url,timeout,open_timeout,token)
  json_return = ''

  rest_handle = RestClient::Resource.new url, :timeout => timeout, :open_timeout => open_timeout, :headers => { 'Authorization' => "Bearer #{token}" }
  begin
    result = rest_handle.get
  #rescue RestClient::RequestFailed => e
  rescue => e
    $stderr.puts "While GET'ing #{url}"
    $stderr.puts "The request failed with HTTP status code #{e.response.code}"
    $stderr.puts "The body was:"
    $stderr.puts e.response.body
  end

  #error_string = process_return_code(result.code,result.body.to_str)
  #if error_string.length > 0
  #  $stderr.puts error_string
  #  exit 1
  #end

  #Debug - the following prints out the entire issues json block in pretty_printed format.
  #puts JSON.pretty_generate(JSON[result.body]);

  if (result == nil) or (result.body == "")
    json_return = JSON '{ }'
  else
    json_return = JSON result.body
  end
  return json_return
end

def api_put (url,timeout,open_timeout,token,payload)
  json_return = ''

  rest_handle = RestClient::Resource.new url, :timeout => timeout, :open_timeout => open_timeout, :headers => { 'Authorization' => "Bearer #{token}", 'Content-Type' => 'application/json' }
  begin
    result = rest_handle.put(payload)
  rescue RestClient::RequestFailed => e
    $stderr.puts "While PUT'ing #{url}"
    $stderr.puts "The request failed with HTTP status code #{e.response.code}"
    $stderr.puts "The body was:"
    $stderr.puts e.response.body
  end
  #if result.code == 403
  #  #Sadly, restclient aborts on a 403 so we never get to give this.
  #  $stderr.puts "403 Forbidden returned; any chance that this is a read-only key?"
  #end
  #error_string = process_return_code(result.code,result.body.to_str)
  #if error_string.length > 0
  #  $stderr.puts error_string
  #  exit 1
  #end
  if (result == nil) or (result.body == "")
    json_return = JSON '{ }'
  else
    json_return = JSON result.body
  end
  return json_return
end

def api_post (url,timeout,open_timeout,token,payload)
  json_return = ''

  #$stderr.puts "URL: #{url}"
  #$stderr.puts "Payload: #{payload.inspect}"
  rest_handle = RestClient::Resource.new url, :timeout => timeout, :open_timeout => open_timeout, :headers => { 'Authorization' => "Bearer #{token}", 'Content-Type' => 'application/json' }
  begin
    result = rest_handle.post(payload)
  rescue RestClient::RequestFailed => e
    $stderr.puts "While POST'ing #{url}"
    $stderr.puts "The request failed with HTTP status code #{e.response.code}"
    $stderr.puts "The body was:"
    $stderr.puts e.response.body
  end
  #if result.code == 403
  #  #Sadly, restclient aborts on a 403 so we never get to give this.
  #  $stderr.puts "403 Forbidden returned; any chance that this is a read-only key?"
  #end
  #error_string = process_return_code(result.code,result.body.to_str)
  #if error_string.length > 0
  #  $stderr.puts error_string
  #  exit 1
  #end
  if (result == nil) or (result.body == "")
    json_return = JSON '{ }'
  else
    json_return = JSON result.body
  end
  return json_return
end

def cached_api_get (url,timeout,open_timeout,token,api_client_id,api_cache_dir)
  json_return = ''
  dirty_filename = api_client_id + "-" + url
  clean_filename = api_cache_dir + "/" + dirty_filename.gsub(/[^a-z0-9\-]+/i, '_') + ".cache"

  #Check that url contains "/v1/events" before doing anything with cache.  Expand if other cacheable api responses found.
  if url.to_s.match('/v1/events') and File.exists?(clean_filename)
    begin
      json_return = JSON.parse(File.read(clean_filename))
    rescue
      $stderr.puts "Warning; unable to read #{clean_filename}."
    end
  end

  #If we don't have a cached answer for any reason, get one from the grid.
  if json_return.to_s.length == 0
    json_return = api_get(url,timeout,open_timeout,token)

    #If this is a /events call, Save a copy if we don't already have one on disk
    if url.to_s.match('/v1/events') and ! File.exists?(clean_filename) and json_return['pagination'] != nil
      #We only want to cache complete (therefore non-terminal) pages.
      if json_return['pagination']['next'].to_s.length > 0
        begin
          File.open(clean_filename, 'w') { |fo| fo.puts json_return.to_json }
        rescue
          $stderr.puts "Warning; unable to save to #{clean_filename}."
        end
      #else
      #  print "Not caching last page."
      end
    end

  end
  return json_return
end

def get_parent_domain(ip_address,parent_domain)
  #Lookup in cache, if not there, perform a reverse lookup for parent domain
  domain_return = ''
  if parent_domain.has_key?(ip_address)
    domain_return = parent_domain[ip_address]
  else
    #Doesn't appear to be a working parser for Arin.  Punt and use reverse dns.
    #result = Whois.query(ip_address)
    #property = result.parser
    #p property.domain

    one_host = ''
    begin
      one_host = Resolv.getname(ip_address)
    rescue
      #Ignore, reverse dns failed
    end

    if one_host.to_s.length == 0
      domain_return = 'unknown'
    else
      domain_return = cleanup_parent_domain(PublicSuffix.parse(one_host).domain)
      parent_domain[ip_address] = domain_return
      #Debug
      #$stderr.puts ip_address, one_host, domain_return
    end
  end

  return domain_return
end

def cleanup_parent_domain(dirty_domain)
  #If one has domain(s) that should be replaced with a parent organization domain (like "gstatic.com" should be "google.com") do so here.
  case dirty_domain
  when 'cloud-ips.com'          then 'rackspace.com'
  when 'myvzw.com'              then 'verizonwireless.com'
                                else dirty_domain
  end
end

def load_api_keys(api_key_file,api_secrets,api_hosts,default_host)
  #Note: api_secrets and api_hosts are modified and passed back as params
  #Remember the first ID; we'll use that if the user does not specify an ID
  first_id = ""
  begin
    File.open(api_key_file, "r") { |key_file_handle|
      key_file_line = key_file_handle.gets
      while (key_file_line != nil) do
        key_file_line.chomp!
        match_record = key_file_line.match(/^([0-9a-fA-F]{8}) *\| *([0-9a-fA-F]{32}) *\|? *([^# ]*)/)
        if match_record
          line_id = match_record[1]
          line_secret = match_record[2]
          line_host = match_record[3]
          api_secrets[line_id] = line_secret
          if line_host.to_s.length == 0
            api_hosts[line_id] = default_host
          else
            api_hosts[line_id] = line_host
          end
          first_id = line_id if first_id == ""
        end
        key_file_line = key_file_handle.gets
      end

      key_file_handle.close
    }
  rescue
    $stderr.puts "IOError caught - #{api_key_file} doesn't exist or unreadable?  Exiting."
    exit 1
  end
  return first_id
end

def get_auth_token(api_client_id,api_client_secret,my_proxy,api_host)
  #Acquire a session key from the Halo Portal for use by the rest of this script
  client = OAuth2::Client.new(api_client_id, api_client_secret,
        :connection_opts => { :proxy => my_proxy },
        :site => "https://#{api_host}",
        :token_url => '/oauth/access_token'
  )
  #FIXME - check return code
  begin
    token = client.client_credentials.get_token.token
  rescue
    $stderr.puts "Unable to retrieve a token.  Perhaps #{api_host} is inaccessible?"
    return ''
  end
  return token
end

def id_of_server(requested_name,requested_ip_address,api_host,token,timeout,open_timeout)
  if (requested_name.to_s.length == 0) and (requested_ip_address.to_s.length == 0)
      $stderr.puts "Neither requested_name nor requested_ip_address in id_of_server, exiting."
      exit 1
  end

  servers_response_json = api_get("https://#{api_host}/v1/servers",timeout,open_timeout,token)

  servers_response_json['servers'].each do |one_server|
    if (requested_name.to_s.length > 0)
      if (one_server['hostname'] == requested_name)
        return one_server['id']
      end
    elsif (requested_ip_address.to_s.length > 0)
      if (one_server['connecting_ip_address'] == requested_ip_address)
        return one_server['id']
      end

      #Also loop through interface IP addresses and match on those.
      one_server['interfaces'].each do |one_interface|
        if (one_interface['ip_address'] == requested_ip_address)
          return one_server['id']
        end
      end
    end
  end

  return nil
end

#FIXME - will need to update this to handle other types of api calls
def process_return_code(retcode,details)
  case retcode
  when 200      then ""
  when 201      then ""
  when 204      then ""
  when 401      then "Unable to retrieve events; Unauthorized/#{retcode}, exiting."
  when 403      then "Unable to retrieve events; Forbidden/#{retcode}, exiting."
  when 404      then "Unable to retrieve events; Not found/#{retcode}, exiting.  Details: #{details}"
  when 422      then "Unable to retrieve events; Validation failed/#{retcode}, exiting.  Details: #{details}"
  when 500      then "Unable to retrieve events; Internal server error/#{retcode}, exiting.  Details: #{details}"
                else "Unrecognized API return code: #{retcode}, exiting.  Details: #{details}"
  end
end

def append_to_file(one_object,out_file,warnings)
  begin
    #create, or append existing file for write
    File.open(out_file, "a") { |jsonout_handle|
      jsonout_handle.puts one_object.inspect
      jsonout_handle.close
    }
  rescue
    warnings['no_json_write'] = "Unable to write json out to #{file} ; permissions?"
  end
end
#======== End of functions


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Scope.RouteArgs (Play! API)</title>
<meta name="date" content="2015-12-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

play.mvc

Class Scope.RouteArgs

java.lang.Object

play.mvc.Scope.RouteArgs

Enclosing class:

Scope

public static class Scope.RouteArgs
extends java.lang.Object

Routes args (used in reserve routing)

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.ThreadLocal<Scope.RouteArgs>
current

java.util.Map<java.lang.String,java.lang.Object>
data

Constructor Summary

Constructors

Constructor and Description

RouteArgs()

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

static Scope.RouteArgs
current()

java.lang.Object
get(java.lang.String key)

void
put(java.lang.String key,
   java.lang.Object arg)

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

data

public java.util.Map<java.lang.String,java.lang.Object> data

current

public static java.lang.ThreadLocal<Scope.RouteArgs> current

Constructor Detail

RouteArgs

public RouteArgs()

Method Detail

current

public static Scope.RouteArgs current()

put

public void put(java.lang.String key,
                java.lang.Object arg)

get

public java.lang.Object get(java.lang.String key)

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Guillaume Bort & zenexity - Distributed under Apache 2 licence, without any warrantly


text:
#ifndef UDP_CONNECTION_H
#define UDP_CONNECTION_H

/*
 * UdpConnection is not real a socket connection
 * this is just to safe the context of a session
 */
#include <simcode/net/UdpConnector.h>
#include <simcode/thread/thread_safe_queue.h>
#include <simcode/base/noncopyable.h>
namespace simcode
{
namespace net
{

class UdpConnection : noncopyable,
    public simex::enable_shared_from_this<UdpConnection>

{
public:
    typedef SimFunction<void (uint64_t id)> CloseCallback;
    UdpConnection(const UdpConnector& c):
        connector_(c)
    {
    }
    int errcode() const;
    int send(const char* buf, size_t len);
    int sendString(const std::string& data);
    void close();
    const SockAddr& peerAddr() const;
    uint64_t id() const;

    void setCloseCallback(const CloseCallback& c);

    void setContext(const simex::any& c);
    const simex::any& getContext() const;
    simex::any* getMutableContext();

private:
private:
    UdpConnector connector_;
    simex::any context_;
    CloseCallback closeCallback_;
};

typedef SharedPtr<UdpConnection> UdpConnectionPtr;

inline int UdpConnection::send(const char* buf, size_t len)
{
    return connector_.send(buf, len);
}

inline int UdpConnection::sendString(const std::string& data)
{
    return connector_.sendString(data);
}

inline void UdpConnection::close()
{
    //connector_.Close();
    if (closeCallback_) closeCallback_(id());
}

inline const SockAddr& UdpConnection::peerAddr() const
{
    return connector_.peerAddr();
}

inline uint64_t UdpConnection::id () const
{
    return peerAddr().id();
}

inline void UdpConnection::setCloseCallback(const CloseCallback& c)
{
    closeCallback_ = c;
}

inline void UdpConnection::setContext(const simex::any& c)
{
    context_ = c;
}

inline const simex::any& UdpConnection::getContext() const
{
    return context_;
}

inline simex::any* UdpConnection::getMutableContext()
{
    return &context_;
}

}
}
#endif


text:
package org.arsenal.framework.engine.mapping;

import org.arsenal.framework.core.UnWrapIOException;
import org.arsenal.framework.engine.IMapping;
import org.arsenal.framework.engine.UnWrapper;
import org.arsenal.framework.engine.cs.CharsetSupport;
import org.arsenal.framework.lang.XString;

public class UnWrapperMappingByte  implements MappingObjectUnWrapper<MappingByte>{

	static UnWrapper unwrapper = UnWrapper.getInstance();

	private UnWrapperMappingByte(){

	}

	public static UnWrapperMappingByte getInstance(){
		return new UnWrapperMappingByte();
	}

	@Override
	public  MappingByte toBytes(byte bytes[]) throws UnWrapIOException{
		if(bytes.length<2){
			throw new UnWrapIOException("bytes.length<2");
		}
		byte type = bytes[0];
		if(type != IMapping.one ) {
			throw new UnWrapIOException(" error format one ");
		}
	    byte value = bytes[1];
		MappingByte ms = new MappingByte( value);
		ms.setType(type);
		return ms;
	}

}


text:
package ecologylab.bigsemantics.generated.library.creativeWork.artwork;

import ecologylab.bigsemantics.metadata.Metadata;
import ecologylab.bigsemantics.metadata.builtins.MetadataBuiltinsTypesScope;
import ecologylab.bigsemantics.metadata.scalar.MetadataString;
import ecologylab.bigsemantics.metametadata.MetaMetadataCompositeField;
import ecologylab.bigsemantics.namesandnums.SemanticsNames;
import ecologylab.serialization.annotations.simpl_inherit;
import ecologylab.serialization.annotations.simpl_scalar;
import java.lang.String;
import java.util.List;
import java.util.Map;

@simpl_inherit
public class TempFieldValueHolder extends Metadata
{
	@simpl_scalar
	private MetadataString tempMedium;

	@simpl_scalar
	private MetadataString tempDimensions;

	@simpl_scalar
	private MetadataString tempYear;

	public TempFieldValueHolder()
	{ super(); }

	public TempFieldValueHolder(MetaMetadataCompositeField mmd) {
		super(mmd);
	}

	public MetadataString	tempMedium()
	{
		MetadataString	result = this.tempMedium;
		if (result == null)
		{
			result = new MetadataString();
			this.tempMedium = result;
		}
		return result;
	}

	public String getTempMedium()
	{
		return this.tempMedium == null ? null : tempMedium().getValue();
	}

	public MetadataString getTempMediumMetadata()
	{
		return tempMedium;
	}

	public void setTempMedium(String tempMedium)
	{
		if (tempMedium != null)
			this.tempMedium().setValue(tempMedium);
	}

	public void setTempMediumMetadata(MetadataString tempMedium)
	{
		this.tempMedium = tempMedium;
	}

	public MetadataString	tempDimensions()
	{
		MetadataString	result = this.tempDimensions;
		if (result == null)
		{
			result = new MetadataString();
			this.tempDimensions = result;
		}
		return result;
	}

	public String getTempDimensions()
	{
		return this.tempDimensions == null ? null : tempDimensions().getValue();
	}

	public MetadataString getTempDimensionsMetadata()
	{
		return tempDimensions;
	}

	public void setTempDimensions(String tempDimensions)
	{
		if (tempDimensions != null)
			this.tempDimensions().setValue(tempDimensions);
	}

	public void setTempDimensionsMetadata(MetadataString tempDimensions)
	{
		this.tempDimensions = tempDimensions;
	}

	public MetadataString	tempYear()
	{
		MetadataString	result = this.tempYear;
		if (result == null)
		{
			result = new MetadataString();
			this.tempYear = result;
		}
		return result;
	}

	public String getTempYear()
	{
		return this.tempYear == null ? null : tempYear().getValue();
	}

	public MetadataString getTempYearMetadata()
	{
		return tempYear;
	}

	public void setTempYear(String tempYear)
	{
		if (tempYear != null)
			this.tempYear().setValue(tempYear);
	}

	public void setTempYearMetadata(MetadataString tempYear)
	{
		this.tempYear = tempYear;
	}
}


text:
import { CoreApp } from '@grafana/data';
import store from 'app/core/store';

import { LegendFormatMode, PromQuery } from '../types';

import { QueryEditorMode } from './shared/types';

const queryEditorModeDefaultLocalStorageKey = 'PrometheusQueryEditorModeDefault';

export function changeEditorMode(query: PromQuery, editorMode: QueryEditorMode, onChange: (query: PromQuery) => void) {
  // If empty query store new mode as default
  if (query.expr === '') {
    store.set(queryEditorModeDefaultLocalStorageKey, editorMode);
  }

  onChange({ ...query, editorMode });
}

function getDefaultEditorMode(expr: string) {
  // If we already have an expression default to code view
  if (expr != null && expr !== '') {
    return QueryEditorMode.Code;
  }

  const value = store.get(queryEditorModeDefaultLocalStorageKey) as QueryEditorMode;
  switch (value) {
    case QueryEditorMode.Builder:
    case QueryEditorMode.Code:
      return value;
    default:
      return QueryEditorMode.Builder;
  }
}

/**
 * Returns query with defaults, and boolean true/false depending on change was required
 */
export function getQueryWithDefaults(query: PromQuery, app: CoreApp | undefined): PromQuery {
  let result = query;

  if (!query.editorMode) {
    result = { ...query, editorMode: getDefaultEditorMode(query.expr) };
  }

  if (query.expr == null) {
    result = { ...result, expr: '', legendFormat: LegendFormatMode.Auto };
  }

  if (query.range == null && query.instant == null) {
    // Default to range query
    result = { ...result, range: true };

    // In explore we default to both instant & range
    if (app === CoreApp.Explore) {
      result.instant = true;
    }
  }

  return result;
}


text:
"""Tests for the knowledge base."""

import unittest

from plaso.containers import artifacts
from plaso.engine import knowledge_base

from tests import test_lib as shared_test_lib

class KnowledgeBaseTest(shared_test_lib.BaseTestCase):
  """Tests for the knowledge base."""

  _MACOSX_PATHS = [
      u'/Users/dude/Library/Application Data/Google/Chrome/Default/Extensions',
      (u'/Users/dude/Library/Application Data/Google/Chrome/Default/Extensions/'
       u'apdfllckaahabafndbhieahigkjlhalf'),
      u'/private/var/log/system.log',
      u'/Users/frank/Library/Application Data/Google/Chrome/Default',
      u'/Users/hans/Library/Application Data/Google/Chrome/Default',
      (u'/Users/frank/Library/Application Data/Google/Chrome/Default/'
       u'Extensions/pjkljhegncpnkpknbcohdijeoejaedia'),
      u'/Users/frank/Library/Application Data/Google/Chrome/Default/Extensions']

  _MACOSX_USERS = [
      {u'name': u'root', u'path': u'/var/root', u'sid': u'0'},
      {u'name': u'frank', u'path': u'/Users/frank', u'sid': u'4052'},
      {u'name': u'hans', u'path': u'/Users/hans', u'sid': u'4352'},
      {u'name': u'dude', u'path': u'/Users/dude', u'sid': u'1123'}]

  _WINDOWS_PATHS = [
      u'C:\\Users\\Dude\\SomeFolder\\Chrome\\Default\\Extensions',
      (u'C:\\Users\\Dude\\SomeNoneStandardFolder\\Chrome\\Default\\Extensions\\'
       u'hmjkmjkepdijhoojdojkdfohbdgmmhki'),
      (u'C:\\Users\\frank\\AppData\\Local\\Google\\Chrome\\Extensions\\'
       u'blpcfgokakmgnkcojhhkbfbldkacnbeo'),
      u'C:\\Users\\frank\\AppData\\Local\\Google\\Chrome\\Extensions',
      (u'C:\\Users\\frank\\AppData\\Local\\Google\\Chrome\\Extensions\\'
       u'icppfcnhkcmnfdhfhphakoifcfokfdhg'),
      u'C:\\Windows\\System32',
      u'C:\\Stuff/with path separator\\Folder']

  _WINDOWS_USERS = [
      {u'name': u'dude', u'path': u'C:\\Users\\dude', u'sid': u'S-1'},
      {u'name': u'frank', u'path': u'C:\\Users\\frank', u'sid': u'S-2'}]

  def _SetUserAccounts(self, knowledge_base_object, users):
    """Sets the user accounts in the knowledge base.

    Args:
      knowledge_base_object (KnowledgeBase): knowledge base.
      users (list[dict[str,str])): users.
    """
    for user in users:
      identifier = user.get(u'sid', user.get(u'uid', None))
      if not identifier:
        continue

      user_account_artifact = artifacts.UserAccountArtifact(
          identifier=identifier, user_directory=user.get(u'path', None),
          username=user.get(u'name', None))

      # TODO: refactor the use of store number.
      user_account_artifact.store_number = 0
      knowledge_base_object.SetUserAccount(user_account_artifact)

  def testGetSetEnvironmentVariable(self):
    """Tests the Get and SetEnvironmentVariable functions."""
    knowledge_base_object = knowledge_base.KnowledgeBase()

    environment_variable = artifacts.EnvironmentVariableArtifact(
        case_sensitive=False, name=u'SystemRoot', value=u'C:\\Windows')
    knowledge_base_object.SetEnvironmentVariable(environment_variable)

    test_environment_variable = knowledge_base_object.GetEnvironmentVariable(
        u'SystemRoot')
    self.assertIsNotNone(test_environment_variable)

    test_environment_variable = knowledge_base_object.GetEnvironmentVariable(
        u'sYsTeMrOoT')
    self.assertIsNotNone(test_environment_variable)

    test_environment_variable = knowledge_base_object.GetEnvironmentVariable(
        u'Bogus')
    self.assertIsNone(test_environment_variable)

  def testGetUsernameForPath(self):
    """Tests the GetUsernameForPath function."""
    knowledge_base_object = knowledge_base.KnowledgeBase()
    self._SetUserAccounts(knowledge_base_object, self._MACOSX_USERS)

    username = knowledge_base_object.GetUsernameForPath(
        self._MACOSX_PATHS[0])
    self.assertEqual(username, u'dude')

    username = knowledge_base_object.GetUsernameForPath(
        self._MACOSX_PATHS[4])
    self.assertEqual(username, u'hans')

    username = knowledge_base_object.GetUsernameForPath(
        self._WINDOWS_PATHS[0])
    self.assertIsNone(username)

    knowledge_base_object = knowledge_base.KnowledgeBase()
    self._SetUserAccounts(knowledge_base_object, self._WINDOWS_USERS)

    username = knowledge_base_object.GetUsernameForPath(
        self._WINDOWS_PATHS[0])
    self.assertEqual(username, u'dude')

    username = knowledge_base_object.GetUsernameForPath(
        self._WINDOWS_PATHS[2])
    self.assertEqual(username, u'frank')

    username = knowledge_base_object.GetUsernameForPath(
        self._MACOSX_PATHS[2])
    self.assertIsNone(username)

  def testGetSetValue(self):
    """Tests the Get and SetValue functions."""
    knowledge_base_object = knowledge_base.KnowledgeBase()

    expected_value = u'test value'
    knowledge_base_object.SetValue(u'Test', expected_value)

    value = knowledge_base_object.GetValue(u'Test')
    self.assertEqual(value, expected_value)

    value = knowledge_base_object.GetValue(u'tEsT')
    self.assertEqual(value, expected_value)

    value = knowledge_base_object.GetValue(u'Bogus')
    self.assertIsNone(value)

if __name__ == '__main__':
  unittest.main()


text:
namespace Toolkit.Docking
{
    partial class HistoryDockForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.listView1 = new System.Windows.Forms.ListView();
            this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.SuspendLayout();
            //
            // listView1
            //
            this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.columnHeader1,
            this.columnHeader2});
            this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.listView1.Location = new System.Drawing.Point(0, 0);
            this.listView1.Name = "listView1";
            this.listView1.Size = new System.Drawing.Size(284, 261);
            this.listView1.TabIndex = 0;
            this.listView1.UseCompatibleStateImageBehavior = false;
            this.listView1.View = System.Windows.Forms.View.Details;
            //
            // columnHeader1
            //
            this.columnHeader1.Text = "";
            this.columnHeader1.Width = 26;
            //
            // columnHeader2
            //
            this.columnHeader2.Text = "Action";
            this.columnHeader2.Width = 225;
            //
            // HistoryDockForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.listView1);
            this.Name = "HistoryDockForm";
            this.Text = "HistoryDockForm";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.ListView listView1;
        private System.Windows.Forms.ColumnHeader columnHeader1;
        private System.Windows.Forms.ColumnHeader columnHeader2;
    }
}


text:
#include "pixel_desc.h"
#include "std.h"
#include "image.h"
#include "hog.h"
#include "conv.h"

/* convert a float image to a consecutive array
   a bit stupid but well
*/
UBYTE_image* image_to_arraytype( image_t* img ) {
  UBYTE_image* res = NEW(UBYTE_image);
  *res = empty_image(UBYTE,img->width,img->height);

  for(int j=0; j<img->height; j++)
    for(int i=0; i<img->width; i++)
      res->pixels[i+j*res->tx] = (UBYTE)img->data[i+j*img->stride];

  return res;
}

// set default params
void set_default_desc_params( desc_params_t* params )
{
  // default = jpg settings,
  // better in almost all cases
  params->presmooth_sigma = 1.0;
  params->mid_smoothing = 1.0;
  params->post_smoothing = 1.0;
  params->hog_sigmoid = 0.2;
  params->ninth_dim = 0.3;
  params->norm_pixels = false;
}

/* extract pixel descriptors (pixel-wise HOG)
*/
float_layers* extract_desc( image_t* _img, const desc_params_t* params, int nt )
{
  // verify parameters
  assert(between(0,params->presmooth_sigma,3));
  assert(between(0,params->mid_smoothing,3));
  assert(between(0,params->post_smoothing,3));
  assert(between(0.05,params->hog_sigmoid,0.8));
  assert(between(0,params->ninth_dim,1));
  assert(between(0,params->norm_pixels,1));

  UBYTE_image* img = image_to_arraytype(_img);  // could be optimized but well
  const int npix = img->tx*img->ty;
  //hash_image(img)D(img->tx)D(img->ty)

  // pre-smooth image
  assert( params->presmooth_sigma>=0 );
  if( params->presmooth_sigma>0 )
    _smooth_gaussian( img, params->presmooth_sigma, img, nt );
  //hash_image(img)

  // extract HOG
  float_layers grad = {NEWA(float,npix*2),img->tx,img->ty,2};
  _compute_grad_101( img, 0, &grad, nt );
  //hash_cube(&grad)
  float_layers* hog = NEW(float_layers);
  *hog = {NEWA(float,9*npix),img->tx,img->ty,8};
  _compute_hog( &grad, 1, hog, nt );
  free(grad.pixels);
  free_image(img);
  //hash_layers(hog)

  // mid smoothing
  assert( params->mid_smoothing>=0 );
  if( params->mid_smoothing )
    smooth_hog_gaussian( hog, params->mid_smoothing, nt );
  //hash_layers(hog)

  // apply non-linearity
  assert( params->hog_sigmoid>=0 );
  if( params->hog_sigmoid ) {
    float_array hog_ravel = {hog->pixels,npix*hog->tz};
    sigmoid_array( &hog_ravel, params->hog_sigmoid, 0, nt);
  }
  //hash_layers(hog)

  // final smoothing
  assert( params->post_smoothing>=0 );
  if( params->post_smoothing )
    smooth_hog_gaussian( hog, params->post_smoothing, nt );
  //hash_layers(hog)

  // add ninth dimension and normalize per-pixel
  float* ninth_layer = hog->pixels + hog->tz*npix;
  for(int i=0; i<npix; i++)
    ninth_layer[i] = params->ninth_dim;
  hog->tz++;
  //hash_layers(hog)
  if( params->norm_pixels )
    norm_layers( hog, 1, nt );
  //hash_layers(hog);D(0)getchar();

  return hog;
}


text:
namespace Camel {

  export class ConditionalBreakpoint {
    public nodeId: string;
    public language: string;
    public predicate: string;
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>LCOV - coverage.info - src/core/AppConfigResolver.cpp</title>
  <link rel="stylesheet" type="text/css" href="../../gcov.css">

LCOV - code coverage report

            Current view:
            top level - src/core - AppConfigResolver.cpp (source / functions)

            Hit
            Total
            Coverage

            Test:
            coverage.info

            Lines:
            14
            14
            100.0 %

            Date:
            2016-11-16 18:44:36

            Functions:
            4
            4
            100.0 %

          Line data    Source code

       1             : #include <theoria/core/AppConfigResolver.h>
       2             : #include <theoria/core/Registry.h>
       3             : #include <theoria/config/Config.h>
       4             : #include <theoria/util/strings.h>
       5             :
       6             : using namespace theoria ;
       7             : using namespace core ;
       8             :
       9             : /////////////////////////
      10             : //ConfigResolver
      11             :
      12             : using Result = config::ConfigVariableResolver::Result ;
      13             : using Config = config::Config ;
      14             :
      15           1 : std::string AppConfigResolver::name() const
      16             : {
      17           1 :     return "AppConfigResolver" ;
      18             : }
      19             :
      20           3 : Result AppConfigResolver::lookup(const std::string& name) const
      21             : {
      22             :
      23           3 :     const Config * config = &core::Registry::instance().appConfig() ;
      24           3 :     auto names = util::string_split(name, '.') ;
      25           3 :     int i = 0 ;
      26           4 :     for (;i<(int)names.size()-1 && config; i++) {
      27           1 :         config = config->getChild(names[i]) ;
      28             :     }
      29           3 :     if (config) {
      30           3 :         auto val = config->getAttrAsStr(names[i], "\1\1");
      31           3 :         if (val != "\1\1")
      32           2 :             return Result(this, val) ;
      33             :     }
      34           1 :     return Result(nullptr, "") ;
      35           3 : }
      36             :
      37             :

Generated by: LCOV version 1.11