text:
class SessionsController < ActionController::Base
  def create
    @user = User.find_or_create_from_auth_hash(auth_hash)

    session[:user_id] = @user.id

    User::UpdateStarredJob.perform_async(@user.id)

    redirect_to '/'
  end

  def destroy
    reset_session

    redirect_to '/'
  end

  def failure
    flash[:alert] = failure_message

    redirect_to '/'
  end

  protected

  def failure_message
    exception = env["omniauth.error"]
    error   = exception.error_reason if exception.respond_to?(:error_reason)
    error ||= exception.error        if exception.respond_to?(:error)
    error ||= env["omniauth.error.type"].to_s
    error.to_s.humanize if error
  end

  def auth_hash
    request.env['omniauth.auth']
  end
end


text:
/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js API               **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013-2015, LAMP/EPFL   **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-lang.org/     **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */

package scala.scalajs.macroimpls

import scala.annotation.tailrec
import scala.scalajs.js

import Compat210._

/** Macros for `js.use(x).as[T]`.
 *
 *  This implements a structural typechecker conforming to the JavaScript calling
 *  convention in Scala.js' export and facade system.
 *
 *  @author Tobias Schlatter
 */
private[scalajs] object UseAsMacros {
  // Import macros only here, otherwise we collide with Compat210._
  import scala.reflect.macros._
  import blackbox.Context

  def as_impl[A: c.WeakTypeTag, B <: js.Any: c.WeakTypeTag](
      c: Context { type PrefixType = js.Using[_] }): c.Expr[B] = {
    (new Macros[c.type](c)).as[A, B]
  }

  private class Macros[C <: Context { type PrefixType = js.Using[_] }](val c: C)
      extends JSMembers with Compat210Component {

    import c.universe._

    private val JSNameAnnotation = typeOf[js.annotation.JSName].typeSymbol
    private val JSBracketAccessAnnotation = typeOf[js.annotation.JSBracketAccess].typeSymbol
    private val JSBracketCallAnnotation = typeOf[js.annotation.JSBracketCall].typeSymbol
    private val JSExportAnnotation = typeOf[js.annotation.JSExport].typeSymbol
    private val JSExportAllAnnotation = typeOf[js.annotation.JSExportAll].typeSymbol

    /** Base classes that are allowed in a target type.
     *  These are also the classes whose methods do not need to be provided.
     */
    private val JSObjectAncestors = typeOf[js.Object].baseClasses.toSet

    def as[A: WeakTypeTag, B <: js.Any: WeakTypeTag]: Expr[B] = {
      val trgTpe = verifyTargetType(weakTypeOf[B])
      val srcTpe = weakTypeOf[A]

      val srcSym = srcTpe.typeSymbol

      // Nothing and Null have everything
      if (srcSym != definitions.NothingClass &&
          srcSym != definitions.NullClass) {
        check(srcTpe, trgTpe)
      }

      reify { c.prefix.splice.x.asInstanceOf[B] }
    }

    /** Perform the actual structural typechecking.
     *
     *  Checks if [[srcTpe]] conforms to [[trgTpe]]. Reports errors otherwise.
     */
    private def check(srcTpe: Type, trgTpe: Type): Unit = {
      val rawMembers = rawJSMembers(trgTpe)
      val exports = exportedMembers(srcTpe)

      for ((jsMemberSelection, jsMember) <- rawMembers) {
        jsMemberSelection match {
          case JSNamedMember(name) =>
            exports.get(name).fold {
              val msg = s"$srcTpe does not export a member named $name"
              c.error(c.enclosingPosition, msg)
            } { candidates =>
              if (!candidates.exists(_.conformsTo(jsMember))) {
                val msg = s"$srcTpe does not export " + jsMember.displayStr(name)
                c.error(c.enclosingPosition, msg)
              }
            }

          case JSMemberCall =>
            c.abort(c.enclosingPosition, s"$trgTpe defines an apply method. " +
                "This cannot be implemented by any Scala exported type, since " +
                "it would need to chain Function's prototype.")

          case JSMemberBracketAccess =>
            c.abort(c.enclosingPosition, s"$trgTpe defines a " +
                "@JSMemberBracketAccess method. Existence of such a method " +
                "cannot be statically checked for any Scala exported type.")

          case JSMemberBracketCall =>
            c.abort(c.enclosingPosition, s"$trgTpe defines a " +
                "@JSMemberBracketCall method. Existence of such a method " +
                "cannot be statically checked for any Scala exported type.")
        }
      }
    }

    /** Members that a facade type defines */
    private def rawJSMembers(
        tpe: Type): Iterable[(JSMemberSelection, JSMember)] = {

      def isAPIMember(member: Symbol) = {
        !JSObjectAncestors(member.owner) &&
        !member.isConstructor &&
        member.isMethod &&
        !member.asTerm.isParamWithDefault
      }

      for (member <- tpe.members if isAPIMember(member)) yield {
        val memberMethod = member.asMethod
        (jsMemberSelection(memberMethod), jsMemberFor(tpe, memberMethod))
      }
    }

    /** Returns the way a member of a raw JS type is selected in JS */
    private def jsMemberSelection(sym: MethodSymbol): JSMemberSelection = {
      val annots = memberAnnotations(sym)

      def hasAnnot(annot: Symbol) = annots.exists(annotIs(_, annot))

      if (hasAnnot(JSBracketAccessAnnotation)) {
        JSMemberBracketAccess
      } else if (hasAnnot(JSBracketCallAnnotation)) {
        JSMemberBracketCall
      } else {
        val optAnnot = annots.find(annotIs(_, JSNameAnnotation))
        val optName = optAnnot.flatMap(annotStringArg)

        optName.fold {
          val name = defaultName(sym)
          if (name == "apply") JSMemberCall
          else JSNamedMember(name)
        } { name => JSNamedMember(name) }
      }
    }

    /** Returns all exported members of a type */
    private def exportedMembers(tpe: Type): Map[String, List[JSMember]] = {
      val exports = tpe.baseClasses.flatMap(exportedDecls(tpe, _))

      // Group exports by name
      for {
        (name, elems) <- exports.groupBy(_._1)
      } yield {
        (name, elems.map(_._2).toList)
      }
    }

    /** All exported declarations of a class.
     *  (both @JSExportAll and @JSExport)
     */
    private def exportedDecls(origTpe: Type, sym: Symbol) = {
      require(sym.isClass)

      val exportAll = sym.annotations.exists(annotIs(_, JSExportAllAnnotation))

      for {
        decl <- sym.info.decls if decl.isMethod && !decl.isConstructor
        name <- exportNames(decl.asMethod, exportAll)
      } yield {
        (name, jsMemberFor(origTpe, decl.asMethod))
      }
    }

    /** Get the JS member for a method in [[origTpe]] */
    private def jsMemberFor(origTpe: Type, sym: MethodSymbol): JSMember = {
      sym.info.asSeenFrom(origTpe, sym.owner) match {
        case MethodType(List(param), resultType)
            if resultType.typeSymbol == definitions.UnitClass &&
               sym.name.decodedName.toString.endsWith("_=") =>
          JSSetter(param.info)

        case NullaryMethodType(returnType) =>
          JSGetter(returnType)

        case info: MethodType =>
          @tailrec
          def flatParams(tpe: Type, acc: List[JSMethodParam]): JSMethod = {
            tpe match {
              case MethodType(params, returnTpe) =>
                val ps = params map { p =>
                  JSMethodParam(p.info, p.asTerm.isParamWithDefault)
                }
                flatParams(returnTpe, ps reverse_::: acc)
              case tpe =>
                JSMethod(acc.reverse, tpe)
            }
          }

          flatParams(info, Nil)

        case PolyType(_, _) =>
          c.abort(c.enclosingPosition, "Polymorphic methods are currently " +
              s"not supported. Offending method: ${sym.fullName}")

        case tpe =>
          sys.error(s"Unexpected method type: $tpe for $sym. Report this as a bug.")
      }
    }

    /** Names a method is exported to */
    private def exportNames(sym: MethodSymbol, exportAll: Boolean) = {
      lazy val default = defaultName(sym)

      val explicitNames = for {
        annot <- memberAnnotations(sym)
        if annotIs(annot, JSExportAnnotation)
      } yield {
        annotStringArg(annot).getOrElse(default)
      }

      if (exportAll && sym.isPublic) default :: explicitNames
      else explicitNames
    }

    /** Default JavaScript name of a method */
    private def defaultName(sym: MethodSymbol): String =
      sym.name.decodedName.toString.stripSuffix("_=")

    /** Verifies that the given type is a class type or a refined type,
     *  has no class ancestors lower than js.Object and does only
     *  refine type members.
     *  @returns dealiased tpe
     */
    private def verifyTargetType(tpe: Type): Type = {
      tpe.dealias match {
        case tpe @ TypeRef(_, sym0, _) if sym0.isClass =>
          val sym = sym0.asClass

          if (!sym.isTrait)
            c.abort(c.enclosingPosition, "Only traits can be used with as")

          def allowedParent(sym: Symbol) =
            sym.asClass.isTrait || JSObjectAncestors(sym)

          for (base <- sym.baseClasses if !allowedParent(base)) {
            c.abort(c.enclosingPosition, s"Supertype ${base.fullName} of $sym " +
                "is a class. Cannot be used with as.")
          }

          tpe

        case tpe @ RefinedType(parents, decls) =>
          parents.foreach(verifyTargetType)

          for (decl <- decls if !decl.isType) {
            c.abort(c.enclosingPosition, s"Refinement ${decl.name} " +
                "is not a type. Only types may be refined with as.")
          }

          tpe

        case tpe =>
          c.abort(c.enclosingPosition, "Only class types can be used with as")
      }
    }

    /** Annotations of a member symbol.
     *  Looks on accessed field if this is an accessor
     */
    private def memberAnnotations(sym: MethodSymbol): List[Annotation] = {
      val trgSym = if (sym.isAccessor) sym.accessed else sym

      // Force typeSignature to calculate annotations
      trgSym.typeSignature

      trgSym.annotations
    }

    /** Retrieve first argument to the annotation as literal string */
    private def annotStringArg(annot: Annotation): Option[String] = {
      val args = annot.tree.children.tail
      args match {
        case List(Literal(Constant(s: String))) => Some(s)
        case _                                  => None
      }
    }

    /** Checks if [[annot]] is of class [[clsSym]] */
    private def annotIs(annot: Annotation, clsSym: Symbol) =
      annot.tree.tpe.typeSymbol == clsSym

  }

}

redpajama_set_name: RedPajamaGithub


text:
"""
 mbed CMSIS-DAP debugger
 Copyright (c) 2015 ARM Limited

 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.
"""

import argparse
import logging
import os
import sys
import optparse
from optparse import make_option
import traceback

import pyOCD
from pyOCD import __version__
from pyOCD.board import MbedBoard
from pyOCD.target import target_kinetis

# Make disasm optional.
try:
    import capstone
    isCapstoneAvailable = True
except ImportError:
    isCapstoneAvailable = False

LEVELS = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'critical':logging.CRITICAL
        }

CORE_STATUS_DESC = {
        pyOCD.target.cortex_m.TARGET_HALTED : "Halted",
        pyOCD.target.cortex_m.TARGET_RUNNING : "Running"
        }

## Default SWD clock in kHz.
DEFAULT_CLOCK_FREQ_KHZ = 1000

## Command info and help.
COMMAND_INFO = {
        'list' : {
            'aliases' : [],
            'args' : "",
            'help' : "Show available targets"
            },
        'erase' : {
            'aliases' : [],
            'args' : "",
            'help' : "Erase all internal flash"
            },
        'unlock' :  {
            'aliases' : [],
            'args' : "",
            'help' : "Unlock security on the target"
            },
        'info' : {
            'aliases' : ['i'],
            'args' : "",
            'help' : "Display target type and IDs"
            },
        'status' : {
            'aliases' : ['stat'],
            'args' : "",
            'help' : "Show the target's current state"
            },
        'reg' : {
            'aliases' : [],
            'args' : "[REG]",
            'help' : "Print all or one register"
            },
        'wreg' : {
            'aliases' : [],
            'args' : "REG VALUE",
            'help' : "Set the value of a register"
            },
        'reset' : {
            'aliases' : [],
            'args' : "[-h/--halt]",
            'help' : "Reset the target"
            },
        'read8' : {
            'aliases' : ['read', 'r'],
            'args' : "ADDR [LEN]",
            'help' : "Read 8-bit bytes"
            },
        'read16' : {
            'aliases' : ['r16'],
            'args' : "ADDR [LEN]",
            'help' : "Read 16-bit halfwords"
            },
        'read32' : {
            'aliases' : ['r32'],
            'args' : "ADDR [LEN]",
            'help' : "Read 32-bit words"
            },
        'write8' : {
            'aliases' : ['write', 'w'],
            'args' : "ADDR DATA...",
            'help' : "Write 8-bit bytes"
            },
        'write16' : {
            'aliases' : ['w16'],
            'args' : "ADDR DATA...",
            'help' : "Write 16-bit halfwords"
            },
        'write32' : {
            'aliases' : ['w32'],
            'args' : "ADDR DATA...",
            'help' : "Write 32-bit words"
            },
        'go' : {
            'aliases' : ['g'],
            'args' : "",
            'help' : "Resume execution of the target"
            },
        'step' : {
            'aliases' : ['s'],
            'args' : "",
            'help' : "Step one instruction"
            },
        'halt' : {
            'aliases' : ['h'],
            'args' : "",
            'help' : "Halt the target"
            },
        'help' : {
            'aliases' : ['?'],
            'args' : "[CMD]",
            'help' : "Show help for commands"
            },
        'disasm' : {
            'aliases' : ['d'],
            'args' : "[-c/--center] ADDR [LEN]",
            'help' : "Disassemble instructions at an address"
            },
        'log' : {
            'aliases' : [],
            'args' : "LEVEL",
            'help' : "Set log level to one of debug, info, warning, error, critical"
            },
        'clock' : {
            'aliases' : [],
            'args' : "KHZ",
            'help' : "Set SWD or JTAG clock frequency"
            },
        'exit' : {
            'aliases' : ['quit'],
            'args' : "",
            'help' : "Quit pyocd-tool"
            },
        }

def dumpHexData(data, startAddress=0, width=8):
    i = 0
    while i < len(data):
        print "%08x: " % (startAddress + i),

        while i < len(data):
            d = data[i]
            i += 1
            if width == 8:
                print "%02x" % d,
                if i % 4 == 0:
                    print "",
                if i % 16 == 0:
                    break
            elif width == 16:
                print "%04x" % d,
                if i % 8 == 0:
                    break
            elif width == 32:
                print "%08x" % d,
                if i % 4 == 0:
                    break
        print

class ToolError(Exception):
    pass

class ToolExitException(Exception):
    pass

def cmdoptions(opts):
    def process_opts(fn):
        parser = optparse.OptionParser(add_help_option=False)
        for opt in opts:
            parser.add_option(opt)
        def foo(inst, args):
            namespace, other_args = parser.parse_args(args)
            return fn(inst, namespace, other_args)
        return foo
    return process_opts

class PyOCDConsole(object):
    PROMPT = '>>> '

    def __init__(self, tool):
        self.tool = tool
        self.last_command = ''

    def run(self):
        try:
            while True:
                try:
                    line = raw_input(self.PROMPT)
                    line = line.strip()
                    if line:
                        self.process_command_line(line)
                        self.last_command = line
                    elif self.last_command:
                        self.process_command(self.last_command)
                except KeyboardInterrupt:
                    print
        except EOFError:
            # Print a newline when we get a Ctrl-D on a Posix system.
            # Windows exits with a Ctrl-Z+Return, so there is no need for this.
            if os.name != "nt":
                print

    def process_command_line(self, line):
        for cmd in line.split(';'):
            self.process_command(cmd)

    def process_command(self, cmd):
        try:
            args = cmd.split()
            cmd = args[0].lower()
            args = args[1:]

            # Handle help.
            if cmd in ['?', 'help']:
                self.show_help(args)
                return

            # Handle register name as command.
            if cmd in pyOCD.target.cortex_m.CORE_REGISTER:
                self.tool.handle_reg([cmd])
                return

            # Check for valid command.
            if cmd not in self.tool.command_list:
                print "Error: unrecognized command '%s'" % cmd
                return

            # Run command.
            handler = self.tool.command_list[cmd]
            handler(args)
        except ValueError:
            print "Error: invalid argument"
            traceback.print_exc()
        except pyOCD.transport.transport.TransferError:
            print "Error: transfer failed"
        except ToolError as e:
            print "Error:", e

    def show_help(self, args):
        if not args:
            self.list_commands()

    def list_commands(self):
        cmds = sorted(COMMAND_INFO.keys())
        print "Commands:\n---------"
        for cmd in cmds:
            info = COMMAND_INFO[cmd]
            print "{cmd:<25} {args:<20} {help}".format(
                cmd=', '.join(sorted([cmd] + info['aliases'])),
                **info)
        print
        print "All register names are also available as commands that print the register's value."
        print "Any ADDR or LEN argument will accept a register name."

class PyOCDTool(object):
    def __init__(self):
        self.board = None
        self.exitCode = 0
        self.command_list = {
                'list' :    self.handle_list,
                'erase' :   self.handle_erase,
                'unlock' :  self.handle_unlock,
                'info' :    self.handle_info,
                'i' :       self.handle_info,
                'status' :  self.handle_status,
                'stat' :    self.handle_status,
                'reg' :     self.handle_reg,
                'wreg' :    self.handle_write_reg,
                'reset' :   self.handle_reset,
                'read' :    self.handle_read8,
                'read8' :   self.handle_read8,
                'read16' :  self.handle_read16,
                'read32' :  self.handle_read32,
                'r' :       self.handle_read8,
                'r16' :     self.handle_read16,
                'r32' :     self.handle_read32,
                'write' :   self.handle_write8,
                'write8' :  self.handle_write8,
                'write16' : self.handle_write16,
                'write32' : self.handle_write32,
                'w' :       self.handle_write8,
                'w16' :     self.handle_write16,
                'w32' :     self.handle_write32,
                'go' :      self.handle_go,
                'g' :       self.handle_go,
                'step' :    self.handle_step,
                's' :       self.handle_step,
                'halt' :    self.handle_halt,
                'h' :       self.handle_halt,
                'disasm' :  self.handle_disasm,
                'd' :       self.handle_disasm,
                'map' :     self.handle_memory_map,
                'log' :     self.handle_log,
                'clock' :   self.handle_clock,
                'exit' :    self.handle_exit,
                'quit' :    self.handle_exit
            }

    def get_args(self):
        debug_levels = LEVELS.keys()

        epi = "Available commands:\n" + ', '.join(sorted(self.command_list.keys()))

        parser = argparse.ArgumentParser(description='Target inspection utility', epilog=epi)
        parser.add_argument('--version', action='version', version=__version__)
        parser.add_argument("-H", "--halt", action="store_true", help="Halt core upon connect.")
        parser.add_argument('-k', "--clock", metavar='KHZ', default=DEFAULT_CLOCK_FREQ_KHZ, type=int, help="Set SWD speed in kHz. (Default 1 MHz.)")
        parser.add_argument('-b', "--board", action='store', metavar='ID', help="Use the specified board. ")
        parser.add_argument('-t', "--target", action='store', metavar='TARGET', help="Override target.")
        parser.add_argument("-d", "--debug", dest="debug_level", choices=debug_levels, default='warning', help="Set the level of system logging output. Supported choices are: "+", ".join(debug_levels), metavar="LEVEL")
        parser.add_argument("cmd", nargs='?', default=None, help="Command")
        parser.add_argument("args", nargs='*', help="Arguments for the command.")
        return parser.parse_args()

    def configure_logging(self):
        level = LEVELS.get(self.args.debug_level, logging.WARNING)
        logging.basicConfig(level=level)

    def run(self):
        try:
            # Read command-line arguments.
            self.args = self.get_args()
            self.cmd = self.args.cmd
            if self.cmd:
                self.cmd = self.cmd.lower()

            # Set logging level
            self.configure_logging()

            # Check for a valid command.
            if self.cmd and self.cmd not in self.command_list:
                print "Error: unrecognized command '%s'" % self.cmd
                return 1

            # List command must be dealt with specially.
            if self.cmd == 'list':
                self.handle_list([])
                return 0

            if self.args.clock != DEFAULT_CLOCK_FREQ_KHZ:
                print "Setting SWD clock to %d kHz" % self.args.clock

            # Connect to board.
            self.board = MbedBoard.chooseBoard(board_id=self.args.board, target_override=self.args.target, init_board=False, frequency=(self.args.clock * 1000))
            self.board.target.setAutoUnlock(False)
            self.board.target.setHaltOnConnect(False)
            try:
                self.board.init()
            except Exception as e:
                print "Exception while initing board:", e

            self.target = self.board.target
            self.transport = self.board.transport
            self.flash = self.board.flash

            # Halt if requested.
            if self.args.halt:
                self.handle_halt()

            # Handle a device with flash security enabled.
            self.didErase = False
            if self.target.isLocked() and self.cmd != 'unlock':
                print "Error: Target is locked, cannot complete operation. Use unlock command to mass erase and unlock."
                if self.cmd and self.cmd not in ['reset', 'info']:
                    return 1

            # If no command, enter interactive mode.
            if not self.cmd:
                # Say what we're connected to.
                print "Connected to %s [%s]: %s" % (self.target.part_number,
                    CORE_STATUS_DESC[self.target.getState()], self.board.getUniqueID())

                # Remove list command that disrupts the connection.
                self.command_list.pop('list')
                COMMAND_INFO.pop('list')

                # Run the command line.
                console = PyOCDConsole(self)
                console.run()
            else:
                # Invoke action handler.
                result = self.command_list[self.cmd](self.args.args)
                if result is not None:
                    self.exitCode = result

        except ToolExitException:
            self.exitCode = 0
        except ValueError:
            print "Error: invalid argument"
        except pyOCD.transport.transport.TransferError:
            print "Error: transfer failed"
            self.exitCode = 2
        except ToolError as e:
            print "Error:", e
            self.exitCode = 1
        finally:
            if self.board != None:
                # Pass false to prevent target resume.
                self.board.uninit(False)

        return self.exitCode

    def handle_list(self, args):
        MbedBoard.listConnectedBoards()

    def handle_info(self, args):
        print "Target:    %s" % self.target.part_number
        print "CPU type:  %s" % pyOCD.target.cortex_m.CORE_TYPE_NAME[self.target.core_type]
        print "Unique ID: %s" % self.board.getUniqueID()
        print "Core ID:   0x%08x" % self.target.readIDCode()

    def handle_status(self, args):
        if self.target.isLocked():
            print "Security:       Locked"
        else:
            print "Security:       Unlocked"
        if isinstance(self.target, pyOCD.target.target_kinetis.Kinetis):
            print "MDM-AP Control: 0x%08x" % self.transport.readAP(target_kinetis.MDM_CTRL)
            print "MDM-AP Status:  0x%08x" % self.transport.readAP(target_kinetis.MDM_STATUS)
        print "Core status:    %s" % CORE_STATUS_DESC[self.target.getState()]

    def handle_reg(self, args):
        # If there are no args, print all register values.
        if len(args) < 1:
            self.dump_registers()
            return

        reg = args[0].lower()
        value = self.target.readCoreRegister(reg)
        if type(value) is int:
            print "%s = 0x%08x (%d)" % (reg, value, value)
        elif type(value) is float:
            print "%s = %g" % (reg, value)
        else:
            raise ToolError("Unknown register value type")

    def handle_write_reg(self, args):
        if len(args) < 1:
            raise ToolError("No register specified")
        if len(args) < 2:
            raise ToolError("No value specified")

        reg = args[0].lower()
        if reg.startswith('s'):
            value = float(args[1])
        else:
            value = self.convert_value(args[1])
        self.target.writeCoreRegister(reg, value)

    @cmdoptions([make_option('-h', "--halt", action="store_true")])
    def handle_reset(self, args, other):
        print "Resetting target"
        if args.halt:
            self.target.resetStopOnReset()

            status = self.target.getState()
            if status != pyOCD.target.cortex_m.TARGET_HALTED:
                print "Failed to halt device on reset"
            else:
                print "Successfully halted device on reset"
        else:
            self.target.reset()

    @cmdoptions([make_option('-c', "--center", action="store_true")])
    def handle_disasm(self, args, other):
        if len(other) == 0:
            print "Error: no address specified"
            return 1
        addr = self.convert_value(other[0])
        if len(other) < 2:
            count = 6
        else:
            count = self.convert_value(other[1])

        if args.center:
            addr -= count // 2

        # Since we're disassembling, make sure the Thumb bit is cleared.
        addr &= ~1

        # Print disasm of data.
        data = self.target.readBlockMemoryUnaligned8(addr, count)
        self.print_disasm(str(bytearray(data)), addr)

    def handle_read8(self, args):
        return self.do_read(args, 8)

    def handle_read16(self, args):
        return self.do_read(args, 16)

    def handle_read32(self, args):
        return self.do_read(args, 32)

    def handle_write8(self, args):
        return self.do_write(args, 8)

    def handle_write16(self, args):
        return self.do_write(args, 16)

    def handle_write32(self, args):
        return self.do_write(args, 32)

    def do_read(self, args, width):
        if len(args) == 0:
            print "Error: no address specified"
            return 1
        addr = self.convert_value(args[0])
        if len(args) < 2:
            count = 4
        else:
            count = self.convert_value(args[1])

        if width == 8:
            data = self.target.readBlockMemoryUnaligned8(addr, count)
            byteData = data
        elif width == 16:
            byteData = self.target.readBlockMemoryUnaligned8(addr, count)
            data = pyOCD.utility.conversion.byteListToU16leList(byteData)
        elif width == 32:
            byteData = self.target.readBlockMemoryUnaligned8(addr, count)
            data = pyOCD.utility.conversion.byteListToU32leList(byteData)

        # Print hex dump of output.
        dumpHexData(data, addr, width=width)

    def do_write(self, args, width):
        if len(args) == 0:
            print "Error: no address specified"
            return 1
        addr = self.convert_value(args[0])
        if len(args) <= 1:
            print "Error: no data for write"
            return 1
        else:
            data = [self.convert_value(d) for d in args[1:]]

        if width == 8:
            pass
        elif width == 16:
            data = pyOCD.utility.conversion.u16leListToByteList(data)
        elif width == 32:
            data = pyOCD.utility.conversion.u32leListToByteList(data)

        if self.isFlashWrite(addr, width, data):
            target.flash.init()
            target.flash.programPhrase(addr, data)
        else:
            self.target.writeBlockMemoryUnaligned8(addr, data)

    def handle_erase(self, args):
        self.flash.init()
        self.flash.eraseAll()

    def handle_unlock(self, args):
        # Currently the same as erase.
        if not self.didErase:
            self.target.massErase()

    def handle_go(self, args):
        self.target.resume()
        status = self.target.getState()
        if status == pyOCD.target.cortex_m.TARGET_RUNNING:
            print "Successfully resumed device"
        else:
            print "Failed to resume device"

    def handle_step(self, args):
        self.target.step()
        print "Successfully stepped device"

    def handle_halt(self, args):
        self.target.halt()

        status = self.target.getState()
        if status != pyOCD.target.cortex_m.TARGET_HALTED:
            print "Failed to halt device"
            return 1
        else:
            print "Successfully halted device"

    def handle_memory_map(self, args):
        self.print_memory_map()

    def handle_log(self, args):
        if len(args) < 1:
            print "Error: no log level provided"
            return 1
        if args[0].lower() not in LEVELS:
            print "Error: log level must be one of {%s}" % ','.join(LEVELS.keys())
            return 1
        logging.getLogger().setLevel(LEVELS[args[0].lower()])

    def handle_clock(self, args):
        if len(args) < 1:
            print "Error: no clock frequency provided"
            return 1
        try:
            freq_Hz = int(args[0]) * 1000
        except:
            print "Error: invalid frequency"
            return 1
        self.transport.setClock(freq_Hz)

        if self.transport.mode == pyOCD.transport.cmsis_dap.DAP_MODE_SWD:
            swd_jtag = 'SWD'
        else:
            swd_jtag = 'JTAG'

        if freq_Hz >= 1000000:
            nice_freq = "%.2f MHz" % (freq_Hz / 1000000)
        elif freq_Hz > 1000:
            nice_freq = "%.2f kHz" % (freq_Hz / 1000)
        else:
            nice_freq = "%d Hz" % freq_Hz

        print "Changed %s frequency to %s" % (swd_jtag, nice_freq)

    def handle_exit(self, args):
        raise ToolExitException()

    def isFlashWrite(self, addr, width, data):
        mem_map = self.board.target.getMemoryMap()
        region = mem_map.getRegionForAddress(addr)
        if (region is None) or (not region.isFlash):
            return False

        if width == 8:
            l = len(data)
        elif width == 16:
            l = len(data)*2
        elif width == 32:
            l = len(data)*4

        return region.containsRange(addr, length=l)

    ## @brief Convert an argument to a 32-bit integer.
    #
    # Handles the usual decimal, binary, and hex numbers with the appropriate prefix.
    # Also recognizes register names and address dereferencing. Dereferencing using the
    # ARM assembler syntax. To dereference, put the value in brackets, i.e. '[r0]' or
    # '[0x1040]'. You can also use put an offset in the brackets after a comma, such as
    # '[r3,8]'. The offset can be positive or negative, and any supported base.
    def convert_value(self, arg):
        arg = arg.lower()
        deref = (arg[0] == '[')
        if deref:
            arg = arg[1:-1]
            offset = 0
            if ',' in arg:
                arg, offset = arg.split(',')
                arg = arg.strip()
                offset = int(offset.strip(), base=0)

        if arg in pyOCD.target.cortex_m.CORE_REGISTER:
            value = self.target.readCoreRegister(arg)
            print "%s = 0x%08x" % (arg, value)
        else:
            value = int(arg, base=0)

        if deref:
            value = pyOCD.utility.conversion.byteListToU32leList(self.target.readBlockMemoryUnaligned8(value + offset, 4))[0]
            print "[%s,%d] = 0x%08x" % (arg, offset, value)

        return value

    def dump_registers(self):
        # Registers organized into columns for display.
        regs = ['r0', 'r6', 'r12',
                'r1', 'r7', 'sp',
                'r2', 'r8', 'lr',
                'r3', 'r9', 'pc',
                'r4', 'r10', 'xpsr',
                'r5', 'r11', 'primask']

        for i, reg in enumerate(regs):
            regValue = self.target.readCoreRegister(reg)
            print "{:>8} {:#010x} ".format(reg + ':', regValue),
            if i % 3 == 2:
                print

    def print_memory_map(self):
        print "Region          Start         End           Blocksize"
        for region in self.target.getMemoryMap():
            print "{:<15} {:#010x}    {:#010x}    {}".format(region.name, region.start, region.end, region.blocksize if region.isFlash else '-')

    def print_disasm(self, code, startAddr):
        if not isCapstoneAvailable:
            print "Warning: Disassembly is not available because the Capstone library is not installed"
            return

        pc = self.target.readCoreRegister('pc') & ~1
        md = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB)

        addrLine = 0
        text = ''
        for i in md.disasm(code, startAddr):
            hexBytes = ''
            for b in i.bytes:
                hexBytes += '%02x' % b
            pc_marker = '*' if (pc==i.address) else ' '
            text += "{addr:#010x}:{pc_marker} {bytes:<10}{mnemonic:<8}{args}\n".format(addr=i.address, pc_marker=pc_marker, bytes=hexBytes, mnemonic=i.mnemonic, args=i.op_str)

        print text

def main():
    sys.exit(PyOCDTool().run())

if __name__ == '__main__':
    main()


text:
@(loginForm: Form[forms.LoginForm])(implicit request: RequestHeader, messages: Messages, flash: Flash)

@import helper._

@main("Top") {
  @form(action = routes.UsersController.login()) {
    @CSRF.formField
    @request.session.get("user")

          @inputText(loginForm("account"), '_label -> "ID", '_showConstraints -> false, 'maxlength -> 10)

          @inputPassword(loginForm("password"), '_label -> "パスワード", '_showConstraints -> false, 'maxlength -> 20)

          <button type="submit" value="login">ログイン</button>
          <button type="reset" value="reset">リセット</button>

  }
}


text:
class LwoPolygons : public LwoChunk {
public:
  enum PolygonFlags {
    PF_continuity_1    = 0x0400,
    PF_continuity_2    = 0x0800,
    PF_numverts_mask   = 0x03f,

    // This "flag" is stored artificially when reading 5.x LWOB files,
    // and indicates that the polygon is a decal of a preceding
    // polygon.
    PF_decal           = 0x0001
  };

  class Polygon : public ReferenceCount {
  public:
    int _flags;
    vector_int _vertices;

    // This value is only filled in when reading 5.x LWOB files, and
    // indicates the surface index of the polygon within a preceding
    // SRFS (LwoTags) chunk.  For 6.x and later files, this will be
    // set to -1.
    int _surface_index;
  };

  int get_num_polygons() const;
  Polygon *get_polygon(int n) const;

  IffId _polygon_type;

public:
  virtual bool read_iff(IffInputFile *in, size_t stop_at);
  virtual void write(ostream &out, int indent_level = 0) const;

private:
  typedef pvector< PT(Polygon) > Polygons;
  Polygons _polygons;

public:
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    LwoChunk::init_type();
    register_type(_type_handle, "LwoPolygons",
                  LwoChunk::get_class_type());
  }

private:
  static TypeHandle _type_handle;
};

#endif


text:
package com.example.taxihelper.constant;

/**
 * Created by Raven on 2017/8/7.
 */

public class Constant {

    //===============================神州
    /**
     * 测试url
     */
    public static final String SHENZHOU_TEST_AUTH = "https://sandboxoauth.10101111.com";
    public static final String SHENZHOU_TEST_API = "https://sandboxapi.10101111.com";

    /**
     * 正式url
     */
    public static final String SHENZHOU_OFFICAL_AUTH = "https://oauth.10101111.com";
    public static final String SHENZHOU_OFFICAL_API = "https://openapi.10101111.com";

    /**
     * 相关
     */
    public static final String SHENZHOU_CLIENT_ID = "A73371C10000030A";
    public static final String SHENZHOU_CLIENT_PASSWORD = "0ema19eje46m8j0gxp77";
    /**
     * 重定向URL
     */
    public static final String SHENZHOUE_REDIRECT_URL = "http://nmid.cqupt.edu.cn/";

    /**
     * 电话号码
     */
    public static final String PHONE_NUM = "phone_number";
    /**
     * 字符串
     */
    public static final String ACCESS_TOKEN = "access_token";
    public static final String REFRESH_ACCESS_TOKEN ="refresh_access_token";
    public static final String EXPIRED_TIME = "expired_time";

    public static final String REFRESH_TYPE = "refresh_token";

    //
    public static final String CURRENT_CITY = "current_city";
    public static final String CURRENT_LOCATION = "location";
    public static final String TYPE = "type";
    public static final String TYPE_START = "start";
    public static final String TYPE_END = "end";
    public static final String TYPE_CAR = "car";
    public static final String SERVICE_ID = "serviceId";

    /**
     * 打车结果常亮
     */
    public static final String CAR_TYPE = "car_type";
    public static final String CAR_PRICES = "price";
    public static final String CAR_GROUP_ID ="car_group_id";

    /**
     * 订单
     */
    public static final String ORDER_ID = "order_id";

    /**
     * 测试接单司机
     */
    public static final long SHANGWU_DRIVER= 43851;
    public static final long GONGWU_DRIVER = 42393;
    public static final long HAOHUA_DRIVER = 44118;

    /**
     * 测试订单时选择的类型
     */
    public static final String SHANGWU_TYPE = "shangwu_type";
    public static final String GONGWU_TYPE = "gongwu_type";
    public static final String HAOHUA_TYPE = "haohua_type";

    /**
     * created > dispatched > arriving > arrived > serviceStarted > serviceFinished > feeSubmitted > paid > completed
     */
    public static final String ORDER_CREATED = "created";
    public static final String ORDER_DISPATCHED = "dispatched";
    public static final String ORDER_ARRIVING = "arriving";
    public static final String ORDER_ARRIVED = "arrived";
    public static final String ORDER_SERVICE_STARTED = "serviceStarted";
    public static final String ORDER_SERVICE_FINISHED = "serviceFinished";
    public static final String ORDER_FEE_SUBMITTED = "feeSubmitted";
    public static final String ORDER_PAID = "paid";
    public static final String ORRDER_COMPLEDTED = "completed";
    public static final String [] ORDER_STATUS = new String[]{"dispatched","arriving","arrived",
            "serviceStarted","serviceFinished","feeSubmitted","paid","completed"};

    public static final String ORDER_DETAIL_INFO = "orderDetailInfo";

    public static final String TAXI_PRICE = "taxi_price_data";

}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)

# arccosine : (-1.0, 1.0) --> (0, PI)
describe "Math.acos" do
  before(:each) do
    ScratchPad.clear
  end

  it "returns a float" do
    Math.acos(1).should be_kind_of(Float )
  end

  it "returns the arccosine of the argument" do
    Math.acos(1).should be_close(0.0, TOLERANCE)
    Math.acos(0).should be_close(1.5707963267949, TOLERANCE)
    Math.acos(-1).should be_close(Math::PI,TOLERANCE)
    Math.acos(0.25).should be_close(1.31811607165282, TOLERANCE)
    Math.acos(0.50).should be_close(1.0471975511966 , TOLERANCE)
    Math.acos(0.75).should be_close(0.722734247813416, TOLERANCE)
  end

  conflicts_with :Complex do
    it "raises an Errno::EDOM if the argument is greater than 1.0" do
      lambda { Math.acos(1.0001) }.should raise_error(Errno::EDOM)
    end

    it "raises an Errno::EDOM if the argument is less than -1.0" do
      lambda { Math.acos(-1.0001) }.should raise_error(Errno::EDOM)
    end
  end

  ruby_version_is ""..."1.9" do
    it "raises an ArgumentError if the string argument cannot be coerced with Float()" do
      lambda { Math.acos("test") }.should raise_error(ArgumentError)
    end

    it "raises Errno::EDOM given NaN" do
      lambda { Math.acos(nan_value) }.should raise_error(Errno::EDOM)
    end
  end

  ruby_version_is "1.9" do
    it "raises a TypeError if the string argument cannot be coerced with Float()" do
      lambda { Math.acos("test") }.should raise_error(TypeError)
    end

    it "returns NaN given NaN" do
      Math.acos(nan_value).nan?.should be_true
    end
  end

  it "raises an TypeError if the argument cannot be coerced with Float()" do
    lambda { Math.acos(MathSpecs::UserClass.new) }.should raise_error(TypeError)
  end

  it "raises a TypeError if the argument is nil" do
    lambda { Math.acos(nil) }.should raise_error(TypeError)
  end

  it "accepts any argument that can be coerced with Float()" do
    Math.acos(MathSpecs::Float.new(0.5)).should be_close(Math.acos(0.5), TOLERANCE)
  end

  ruby_version_is ""..."1.9" do
    it "coerces string argument with Float() without calling to_f" do
      s = MathSpecs::StringSubClass.new("0.5")
      s.should_not_receive(:to_f)
      Math.acos(s).should be_close(Math.acos(0.5), TOLERANCE)
    end
  end
end

describe "Math#acos" do
  it "is accessible as a private instance method" do
    IncludesMath.new.send(:acos, 0).should be_close(1.5707963267949, TOLERANCE)
  end
end


text:
#ifndef __SOCKET_ADDRESS_H__
#define __SOCKET_ADDRESS_H__

#include <iostream>

#include <string.h>

#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>

#include <Exception.hpp>
#include <Assert.hpp>

enum AddressFamily { IPv4AddressFamily = AF_INET, IPv6AddressFamily = AF_INET6 };

class SocketAddress {
public:
	SocketAddress(const struct sockaddr *socketAddress);
	SocketAddress(const SocketAddress &socketAddress);
	~SocketAddress();
	AddressFamily family() const;
	std::string toString() const;
	const struct sockaddr* sockaddr() const;
	std::string hostname() const;
protected:
	void initializeWith(const struct sockaddr *socketAddress);
protected:
	struct sockaddr *_socketAddress;
};

std::ostream& operator<<(std::ostream &ostream, const SocketAddress &socketAddress);

#define GETNAMEINFO_SUCCESS 0

#endif /* __SOCKET_ADDRESS_H__ */


text:
<!DOCTYPE HTML>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="google-site-verification" content="" />

  <title>加速计和陀螺仪</title>
  <meta name="author" content="Ray">
   <meta name="description" content="Blog">

  <meta property="og:title" content="加速计和陀螺仪"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta property="og:site_name" content="Ray"/>
 <meta property="og:image" content="undefined"/>

  <link rel="alternate" href="/atom.xml" title="Ray" type="application/atom+xml">
  <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.5.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="/css/m.min.css">
  <link rel="icon" type="image/x-icon" href="/favicon.ico">

         Ray

        加速计和陀螺仪

<time datetime="2015-10-27T16:00:00.000Z">

  2015-10-28
</time>

    iOS

对于设备方向XYZ轴判断,iOS内置的对于设备朝向的判断,还有判断设备是否摇晃了

首先在storyboard中定义这几个label

@IBOutlet weak var XLabel: UILabel!
@IBOutlet weak var YLabel: UILabel!
@IBOutlet weak var ZLabel: UILabel!
@IBOutlet weak var orientationLabel: UILabel!
@IBOutlet weak var shake: UILabel!

声明一个加速计管理者,所有的操作都会由这个motionManager接管

var motionManager = CMMotionManager()

在viewDidLoad()中,添加

//设置检测时间
motionManager.accelerometerUpdateInterval = 0.1

//判断是否可以使用加速计
if motionManager.accelerometerAvailable
{
    //如果设备支持加速计,用startAccelermeterUpdatesToQueue方法开始检测设备的加速情况
    motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler:
    { ( accelerometerData :CMAccelerometerData?, error:NSError?) -> Void in
        if error != nil
        {
            //停止使用加速计
            self.motionManager.stopAccelerometerUpdates()
        }
        else
        {
            self.XLabel.text = "X:\(accelerometerData!.acceleration.x)"
            self.YLabel.text = "Y:\(accelerometerData!.acceleration.y)"
            self.ZLabel.text = "Z:\(accelerometerData!.acceleration.z)"
        }
    })
}
else
{
    let alert = UIAlertView(title: "你的设备不支持加速计", message: nil, delegate: nil, cancelButtonTitle: "OK")
    alert.show()
}

用iOS内置的方法判断设备方向

/*通过UIDevice.currentDevice()来获取设备,可以取得设备当前的方向,我们可以添加一个通知,来监听设备的方向变化,这样在开发中可以对不同的方向定制不同的排版布局界面,实现代码如下*/

//感知设备方向,开启监听设备方向
UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()

//添加通知,监听设备方向改变
NSNotificationCenter.defaultCenter().addObserver(self, selector: "receivedRotation", name: UIDeviceOrientationDidChangeNotification, object: nil)

如果要关闭设备监听,代码如下

UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications()

实现通知监听方法触发的代码

func receivedRotation()
{
    let device = UIDevice.currentDevice()

    if device.orientation == UIDeviceOrientation.Unknown
    {
        orientationLabel.text = "方向未知"
    }
    else if device.orientation == UIDeviceOrientation.Portrait
    {
        orientationLabel.text = "面向设备保持垂直,Home键位于下部"
    }
    else if device.orientation == UIDeviceOrientation.PortraitUpsideDown
    {
        orientationLabel.text = "面向设备保持垂直,Home键位于上部"
    }
    else if device.orientation == UIDeviceOrientation.LandscapeLeft
    {
     //但是这里我测试出来方向不一样,左和右反了
        orientationLabel.text = "面向设备保持水平,Home键位于左侧"
    }
    else if device.orientation == UIDeviceOrientation.LandscapeRight
    {
        orientationLabel.text = "面向设备保持水平,Home键位于右侧"
    }
    else if device.orientation == UIDeviceOrientation.FaceUp
    {
        orientationLabel.text = "设备水平放,Home键朝上"
    }
    else if device.orientation == UIDeviceOrientation.FaceDown
    {
        orientationLabel.text = "设备水平放,Home键朝下"
    }
}

摇晃,iOS SDK中已经将摇晃shake事件很方便的融合进去,就像触发touch事件一样简单,发生shake事件后程序会自动执行

//开始摇晃
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
    shake.text = "开始摇晃"
}
//摇晃结束
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
    shake.text = "摇晃结束"
}
//摇晃被意外终止
override func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?) {
    shake.text = "摇晃被意外终止"
}

  </script>

    页阅读量:  ・
    站访问量:  ・
    站访客数:

        © Ray 2015-2016

        Theme Pln


text:
"""
:mod:`hastie`
===========

.. module:: hastie
    :platform: Unix, Windows
    :synopsis:

.. moduleauthor:: hbldh <henrik.blidh@nedomkull.com>

Created on 2015-11-10

"""

from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

import six
import numpy as np
from sklearn.datasets import make_hastie_10_2

__all__ = ['Hastie_10_2', ]

class Hastie_10_2(object):
    """Returns a Hastie et al. 2009, Example 10.2 dataset, divided into bags for MIL learning.

    See `Scikit-learn documentation
    <http://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_hastie_10_2.html>`_
    for more details on the Hastie et al. 2009, Example 10.2 dataset generating method.

    """

    def __init__(self, random_state=1, n=6):

        self.data, self.labels = make_hastie_10_2(random_state=random_state)
        i = np.argsort(self.labels)
        self.labels = self.labels[i]
        self.data = self.data[i, :]

        self.bag_labels = []
        for i, k in enumerate(six.moves.range(0, len(self.labels), n)):
            self.labels[k:k+n] *= i + 1
            self.bag_labels.append(np.sign(np.max(self.labels[k:k+n])))
        self.labels = np.array(self.labels, 'int')
        self.bag_labels = np.array(self.bag_labels, 'int')
        self.bag_partitioning = np.cumsum(np.bincount(np.abs(self.labels))[1:])[:-1]


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/local_popup_bg"
    >
<TextView
    android:id="@+id/tv_uninstall"
    android:gravity="center"
    android:drawableTop="@drawable/img1"
    android:text="@string/tv_uninstall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
    <TextView
        android:gravity="center"
        android:id="@+id/tv_start"
        android:drawableTop="@drawable/img2"
        android:text="@string/tv_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/tv_share"
        android:text="@string/tv_share"
        android:drawableTop="@drawable/img3"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


text:
import logging
class NullHandler(logging.Handler):
    def emit(self, record):
        pass


text:
{% load wagtailadmin_tags staticfiles %}

{% comment %}
    CSS declarations to be included on the 'create page' and 'edit page' views
{% endcomment %}

<link rel="stylesheet" href="{% static 'wagtailadmin/css/layouts/page-editor.css' %}" type="text/css" />
<link rel="stylesheet" href="{% static 'wagtailadmin/css/panels/rich-text.css' %}" type="text/css" />

<style>
    #id_main_color { height: 40px!important; width: 100px!important; padding: 0px!important;}
</style>

{% hook_output 'insert_editor_css' %}

{{ edit_handler.form.media.css }}


text:
package com.covata.delta.sdk.api.common;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;

@JsonPropertyOrder(alphabetic = true)
public class EncryptionDetails {

    private final String symmetricKey;

    private final String initialisationVector;

    @JsonCreator
    public EncryptionDetails(@JsonProperty("symmetricKey") String symmetricKey,
                             @JsonProperty("initialisationVector") String initialisationVector) {
        this.symmetricKey = symmetricKey;
        this.initialisationVector = initialisationVector;
    }

    public String getSymmetricKey() {
        return symmetricKey;
    }

    public String getInitialisationVector() {
        return initialisationVector;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        EncryptionDetails that = (EncryptionDetails) o;
        return Objects.equal(symmetricKey, that.symmetricKey) &&
                Objects.equal(initialisationVector, that.initialisationVector);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(symmetricKey, initialisationVector);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("symmetricKey", symmetricKey)
                .add("initialisationVector", initialisationVector)
                .toString();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
    <msapplication>
        <tile>
            <square150x150logo src="/bs-react-native/mstile-150x150.png"/>
            <TileColor>#222222</TileColor>
        </tile>
    </msapplication>
</browserconfig>


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>JSDoc: Source: app/app.js</title>

		<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
		<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: app/app.js

'use strict';

/**
 * @memberOf myApp
 * @class myApp
 * @description Contains dependencies, routing, Firebase, Auth0 and responsive set up..
 */
angular.module('myApp', [
  'ngRoute',
  'auth0',
  'angular-storage',
  'angular-jwt',
  'firebase',
  'myApp.navbar',
  'myApp.view1',
  'myApp.view2',
  'myApp.view3',
  'myApp.add',
  'myApp.version',
  'myApp.home',
  'myApp.login',
  'myApp.locations',
  'myApp.inspections',
  'myApp.data',
  'myApp.directives'
]).
config(['$routeProvider', function($routeProvider, authProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    requiresLogin: true
  })
  .when('/locations', {
    templateUrl: 'view1/locations.html',
    requiresLogin: true
  })
  .when('/data', {
    templateUrl: 'view1/data.html',
    requiresLogin: true
  })
  .when('/view2/:artist', {
    templateUrl: 'view2/view2.html',
    controller: 'View2Ctrl',
    requiresLogin: true
  })
  .when('/view3/:paintingNo', {
    templateUrl: 'view3/view3.html',
    requiresLogin: true
  })
  .when( '/login', {
    templateUrl: 'login/login.html',
    pageTitle: 'Login',
    controller: 'LoginCtrl'
  })
  .when( '/add', {
    templateUrl: 'view3/add.html',
    pageTitle: 'Add',
    requiresLogin: true
  })
  .when( '/inspections', {
    templateUrl: 'view3/inspections.html',
    requiresLogin: true
  })
  .otherwise({redirectTo: '/login'});
}])
.config(function (authProvider) {
  try {
  var envValues = document.getElementById('env-values').value;
  var response = JSON.parse(envValues);
      authProvider.init({
        domain: response.AUTH0_DOMAIN,
        clientID: response.AUTH0_CLIENT_ID,
        loginUrl: '/login'
      });
    } catch (error) {
      console.log('local environment',error);
    }
})
.run(function($http, auth, $window, $rootScope) {
  var envValues = document.getElementById('env-values').value;
  var response = null;
  $http.get('./env.json')
       .then(function(res){
          $rootScope.firebaseUri = res.data.FIREBASE_URI;
          auth.init({
            domain: res.data.AUTH0_DOMAIN,
            clientID: res.data.AUTH0_CLIENT_ID,
            loginUrl: '/login'
          });
        auth.hookEvents();
  });

  // responsive size variables
  // the first time thru we need to initialize the sceen sizes
  if ($window.innerWidth < 900) {
    $rootScope.smallWidth = true;
  }
  if ($window.innerWidth < 1200 && $window.innerWidth > 900) {
    $rootScope.mediumWidth = true;
  }

  // now we can update those sizes when the screen size changes
  angular.element($window).bind('resize', function() {
    if ($window.innerWidth < 900) {
      $rootScope.smallWidth = true;
    } else {
      $rootScope.smallWidth = false;
    }
    if ($window.innerWidth < 1200 && $window.innerWidth > 900) {
      $rootScope.mediumWidth = true;
    } else {
      $rootScope.mediumWidth = false;
    }
    // manuall $digest required as resize event
    // is outside of angular
    $rootScope.$digest();
    //console.log('width '+$window.innerWidth);
  });
});

Home

Classes

myApp

			Documentation generated by JSDoc 3.4.0 on Thu May 05 2016 02:38:18 GMT+1000 (AEST)


text:
using Reinforced.Typings.Fluent;
using Xunit;

namespace Reinforced.Typings.Tests.SpecificCases
{
    public partial class SpecificTestCases
    {
        [Fact]
        public void EnumKeyedDictionary()
        {
            const string result = @"
export enum SomeEnum {
	One = 0,
	Two = 1
}
export interface IParametrizedGenericsInterface
{
	Bag: { [key in SomeEnum]: string };
	Bag2: { [key:string]: SomeEnum }[];
	Bag3: { [key in SomeEnum]: SomeEnum }[][];
	Bag4: { [key in SomeEnum]: { [key:string]: SomeEnum[][] } };
}";
            AssertConfiguration(s =>
            {
                s.Global(a => a.DontWriteWarningComment().UseModules());
                s.ExportAsEnum<SomeEnum>();
                s.ExportAsInterfaces(
                    new[] {typeof(IParametrizedGenericsInterface<SomeEnum, string>)},
                    x => x.WithPublicProperties().WithPublicMethods());
            }, result);
        }
    }
}


text:
#ifndef ENGINE_MGR_H
#define ENGINE_MGR_H

#include <list>
#include <string>
#include "Engine.h"

class MidiIn;
class AudioOut;
class OutMgr;
/**Container/Owner of the long lived Engines*/
class EngineMgr
{
    public:
        static EngineMgr &getInstance();
        ~EngineMgr();

        /**Gets requested engine
         * @param name case unsensitive name of engine
         * @return pointer to Engine or NULL
         */
        Engine *getEng(std::string name);

        /**Start up defaults*/
        bool start();

        /**Stop all engines*/
        void stop();

        std::list<Engine *> engines;

        //return false on failure
        bool setInDefault(std::string name);
        bool setOutDefault(std::string name);

        //default I/O
        AudioOut *defaultOut;
        MidiIn   *defaultIn;
    private:
        EngineMgr();
};
#endif


text:
module DSA
  class SkipListNode
    attr_accessor :key, :value, :prev, :next, :up, :down
    def initialize(key, value = nil)
      @key = key
      @value = value
      @prev = nil
      @next = nil
      @up = nil
      @down = nil
    end

    def is_sentinel?
      @key.equal? SkipListLevel::SENTINEL
    end
  end

  class SkipListLevel
    attr_accessor :head, :tail
    SENTINEL = Object.new
    def initialize
      @head = SkipListNode.new(SENTINEL, 'Sentinel')
      @tail = SkipListNode.new(SENTINEL, 'Sentinel')
      @head.next = @tail
      @tail.prev = @head
    end
  end

  class SkipList
    attr_reader :length, :height
    include Enumerable
    def initialize
      @levels = [SkipListLevel.new]
      @length = 0
      @height = 0
    end

    def find(key)
      nodes = find_nodes key

      if block_given?
        return unless nodes
        nodes.each do |node|
          yield [node.key, node.value]
        end
      else
        Enumerator.new do |y|
          find(key) do |key, value|
            y << [key, value]
          end
        end
      end

    end

    def each
      walk = @levels.first.head
      if block_given?
        walk = walk.next
        until walk.is_sentinel?
          yield [ walk.key, walk.value ]
          walk = walk.next
        end
      else
        Enumerator.new do |y|
          each do |key, value|
            y << [key, value]
          end
        end
      end
    end

    def gt(key)
      nodes = find_nodes(key, true, false)

      if block_given?
        return unless nodes
        walk = nodes.last.next
        until walk.is_sentinel?
          yield [ walk.key, walk.value ]
          walk = walk.next
        end
      else
        Enumerator.new do |y|
          gt(key) do |key, value|
            y << [key, value]
          end
        end
      end
    end

    def ge(key)
      nodes = find_nodes(key, true, false)

      if block_given?
        return unless nodes
        if nodes.first.key == key
          walk = nodes.first
        else
          walk = nodes.first.next
        end
        until walk.is_sentinel?
          yield [ walk.key, walk.value ]
          walk = walk.next
        end
      else
        Enumerator.new do |y|
          ge(key) do |key, value|
            y << [key, value]
          end
        end
      end
    end

    def lt(key)
      nodes = find_nodes(key, false, true)

      if block_given?
        return unless nodes
        walk = nodes.first.prev
        until walk.is_sentinel?
          yield [ walk.key, walk.value ]
          walk = walk.prev
        end
      else
        Enumerator.new do |y|
          lt(key) do |key, value|
            y << [key, value]
          end
        end
      end
    end

    def le(key)
      nodes = find_nodes(key, false, true)

      if block_given?
        return unless nodes
        if nodes.first.key == key
          walk = nodes.last
        else
          walk = nodes.last.prev
        end
        until walk.is_sentinel?
          yield [ walk.key, walk.value ]
          walk = walk.prev
        end
      else
        Enumerator.new do |y|
          le(key) do |key, value|
            y << [key, value]
          end
        end
      end
    end

    # if value provided, the nodes have the same key/value pairs will be deleted,
    # otherwise, all nodes have the same key are deleted
    # return the value of last deleted node
    def delete(key, value = nil)
      nodes = find_nodes(key)
      return false unless nodes

      return_value = false
      nodes.each do |node|
        if !value || value == node.value
          return_value = remove_tower node
          @length -= 1
          remove_empty_level
        end
      end

      return_value
    end

    def add(key, value = nil)
      potential_place = []
      walk = start_node
      while 1
        if walk.next.is_sentinel? || key <= walk.next.key
          if walk.down
            potential_place.push walk
            walk = walk.down
            next
          else
            insert_node_between walk, walk.next, SkipListNode.new(key, value)
            @length += 1
            build_tower walk.next, potential_place, key, value
            break
          end
        else
          walk = walk.next
          next
        end
      end
    end

    def print_me(width = 10)
      rec = Hash.new
      walk = @levels.first.head
      i = 0
      j = 0
      walk = walk.next
      while ! walk.is_sentinel?
        rec[ [i, j] ] = "#{walk.key},#{walk.value}"
        up_walk = walk
        while up_walk.up
          up_walk = up_walk.up
          j += 1
          rec[ [i, j] ] ="#{up_walk.key},#{up_walk.value}"
        end
        walk = walk.next
        i += 1
        j = 0
      end

      # print
      puts '=' * 100
      (height+1).times.reverse_each do |j|
        printf 'Sentinel--'
        (length).times do |i|
          if rec[ [i, j] ]
            printf ">%#{width+2}s", "#{rec[ [i, j] ]}--"
          else
            printf '-' + '-' * width + '--'
          end
        end
        puts '>Sentinel'
      end
      puts '=' * 100
    end

    private
    def remove_empty_level
      return if @length < 2
      one_to_last = @levels[-2]
      if one_to_last.head.next.is_sentinel?
        @levels.pop
        @height -= 1
      end
    end

    # if not found, two more options are provided
    def find_nodes(key, return_previous = false, return_next = false )
      walk = start_node
      while 1
        if !walk.is_sentinel? && key == walk.key
          break
        elsif walk.next.is_sentinel? || key < walk.next.key
          if walk.down
            walk = walk.down
            next
          else
            if return_previous
              return [walk]
            elsif return_next
              return [walk.next]
            else
              return nil
            end
          end
        else
          walk = walk.next
          next
        end
      end

      nodes = []
      while !walk.is_sentinel? && walk.down
        walk = walk.down
      end

      nodes.push walk

      # to find the duplicates
      other_node = walk.next
      while !other_node.is_sentinel? && other_node.key == key
        nodes.push other_node
        other_node = other_node.next
      end

      other_node = walk.prev
      while !other_node.is_sentinel? && other_node.key == key
        nodes.unshift other_node
        other_node = other_node.prev
      end

      nodes
    end

    def remove_tower(base)
      remove_node base
      remove_tower base.up if base.up
      base.value
    end

    def build_tower(base, tower, key, value)
      up_stair_previous = nil
      tower.reverse_each do |node|
        return unless go_up?
        up_stair_previous = node
        new_node = SkipListNode.new(key, value)
        insert_node_between up_stair_previous, up_stair_previous.next, new_node
        vertical_link_node new_node, base
        base = new_node
      end
      # add new level
      if go_up?
        add_level
        @height += 1
      end

    end

    def add_level
      new_level = SkipListLevel.new
      vertical_link_node  new_level.head, @levels.last.head
      vertical_link_node  new_level.tail, @levels.last.tail
      @levels.push new_level
    end

    def vertical_link_node(above, below)
      above.down = below
      below.up = above
    end

    def go_up?
      [true, false].sample
    end

    def insert_node_between(a, b, new_one)
      a.next = new_one
      new_one.prev = a
      new_one.next = b
      b.prev = new_one
    end

    # remove a node
    def remove_node(node)
      before = node.prev
      after = node.next
      before.next = after
      after.prev = before
      node
    end

    def start_node
      @levels.last.head
    end

    def end_node
      @levels.first.tail
    end

  end
end


text:
<?php

/** Error reporting */
error_reporting( E_ALL );
ini_set( 'display_errors', true );
ini_set( 'display_startup_errors', true );

define( 'EOL', ( PHP_SAPI == 'cli' ) ? PHP_EOL : '<br />' );

date_default_timezone_set( 'Europe/London' );

/** Include PHPExcel */
require_once dirname( __FILE__ ).'/../Classes/PHPExcel.php';

// Create new PHPExcel object
echo date( 'H:i:s' ), " Create new PHPExcel object", EOL;
$objPHPExcel = new PHPExcel();

// Set document properties
echo date( 'H:i:s' ), " Set document properties", EOL;
$objPHPExcel->getProperties()->setCreator( "Maarten Balliauw" )
    ->setLastModifiedBy( "Maarten Balliauw" )
    ->setTitle( "Office 2007 XLSX Test Document" )
    ->setSubject( "Office 2007 XLSX Test Document" )
    ->setDescription( "Test document for Office 2007 XLSX, generated using PHP classes." )
    ->setKeywords( "office 2007 openxml php" )
    ->setCategory( "Test result file" );

// Generate an image
echo date( 'H:i:s' ), " Generate an image", EOL;
$gdImage = @imagecreatetruecolor( 120, 20 ) or die( 'Cannot Initialize new GD image stream' );
$textColor = imagecolorallocate( $gdImage, 255, 255, 255 );
imagestring( $gdImage, 1, 5, 5, 'Created with PHPExcel', $textColor );

// Add a drawing to the worksheet
echo date( 'H:i:s' ), " Add a drawing to the worksheet", EOL;
$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setName( 'Sample image' );
$objDrawing->setDescription( 'Sample image' );
$objDrawing->setImageResource( $gdImage );
$objDrawing->setRenderingFunction( PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG );
$objDrawing->setMimeType( PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT );
$objDrawing->setHeight( 36 );
$objDrawing->setWorksheet( $objPHPExcel->getActiveSheet() );

echo date( 'H:i:s' ), " Write to Excel2007 format", EOL;
$objWriter = PHPExcel_IOFactory::createWriter( $objPHPExcel, 'Excel2007' );
$objWriter->save( str_replace( '.php', '.xlsx', __FILE__ ) );
echo date( 'H:i:s' ), " File written to ", str_replace( '.php', '.xlsx', pathinfo( __FILE__, PATHINFO_BASENAME ) ), EOL;

// Echo memory peak usage
echo date( 'H:i:s' ), " Peak memory usage: ", ( memory_get_peak_usage( true ) / 1024 / 1024 ), " MB", EOL;

// Echo done
echo date( 'H:i:s' ), " Done writing file", EOL;
echo 'File has been created in ', getcwd(), EOL;


text:
/* ft-document-list-item element demo */
/* Imports */
/**

An element that renders information about a FileThis document in a parent list

@demo
 */
/*
  FIXME(polymer-modulizer): the above comments were extracted
  from HTML and may be out of place here. Review them and
  then delete this comment!
*/

import '@polymer/iron-flex-layout/iron-flex-layout-classes.js';
import '@polymer/polymer/polymer-legacy.js';
import '../ft-document-list-item.js';
import { Polymer } from '@polymer/polymer/lib/legacy/polymer-fn.js';
import { html } from '@polymer/polymer/lib/utils/html-tag.js';

Polymer
({
  _template: html`

                <ft-document-list-item id="normal" style="width:600px;"></ft-document-list-item>

                <ft-document-list-item id="selected" style="width:600px;"></ft-document-list-item>

`,

  is: 'demo-fixture',

  properties:
  {
  },

  ready: function()
  {
      this._loadFakeDocument();
  },

  _loadFakeDocument: function()
  {
      var path = "fake-document.json";

      var xmlHttpRequest = new XMLHttpRequest();
      xmlHttpRequest.overrideMimeType("application/json");
      xmlHttpRequest.open('GET', path, true);
      xmlHttpRequest.onreadystatechange = function()
      {
          if (xmlHttpRequest.readyState === 4 &&
              xmlHttpRequest.status === 200)
          {
              var document = JSON.parse(xmlHttpRequest.responseText);

              // Normal
              var documentNormal = Object.assign({}, document);
              this.$.normal.document = documentNormal;

              // Selected
              var documentSelected = Object.assign({}, document);
              this.$.selected.document = documentSelected;
              this.$.selected.selected = true;
          }
      }.bind(this);
      xmlHttpRequest.send();
  }
});


text:
package alraune;

import pieces100.*;

public class AlDB_Params_betty_BuilderStep1  {
    private AlDB.Params_betty shitBeingBuilt;
    AlDB_Params_betty_BuilderStep1(AlDB.Params_betty x) {shitBeingBuilt = x;}

    AlDB_Params_betty_BuilderStep2 counting(java.lang.Boolean x) {
        shitBeingBuilt.counting = x;
        return new AlDB_Params_betty_BuilderStep2(shitBeingBuilt);
    }

}

/*
 */


text:
// Copyright (c) 2008-2022, Hazelcast, Inc. All Rights Reserved.
//
// 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.

using System;
using Hazelcast.Core;
using Hazelcast.Models;
using Hazelcast.Serialization;
using Hazelcast.Serialization.Compact;
using Moq;
using NUnit.Framework;

namespace Hazelcast.Tests.Serialization.Compact
{
    [TestFixture]
    public class CompactWriterTests
    {
        [Test]
        public void CannotWriteOnceCompleted()
        {
            var orw = Mock.Of<IReadWriteObjectsFromIObjectDataInputOutput>();
            var output = new ObjectDataOutput(0, orw, Endianness.BigEndian);
            var schema = new Schema();
            var writer = new CompactWriter(orw, output, schema);

            writer.Complete();
            Assert.Throws<InvalidOperationException>(() => writer.WriteInt8("name", 0));
        }

        [Test]
        public void OkToCompleteMultipleTimes()
        {
            var orw = Mock.Of<IReadWriteObjectsFromIObjectDataInputOutput>();
            var output = new ObjectDataOutput(0, orw, Endianness.BigEndian);
            var schema = new Schema();
            var writer = new CompactWriter(orw, output, schema);

            writer.Complete();
            writer.Complete();
            writer.Complete();
            Assert.Throws<InvalidOperationException>(() => writer.WriteInt8("name", 0));
        }

        [Test]
        public void TimeStampWithTimeZonePrecision()
        {
            var orw = Mock.Of<IReadWriteObjectsFromIObjectDataInputOutput>();
            var output = new ObjectDataOutput(0, orw, Endianness.BigEndian);
            var schema = SchemaBuilder.For("type").WithField("name", FieldKind.TimeStampWithTimeZone).Build();
            var writer = new CompactWriter(orw, output, schema);

            // sub-second precision for offset throws
            Assert.Throws<SerializationException>(() =>
                writer.WriteTimeStampWithTimeZone("name", new HOffsetDateTime(DateTime.Now, TimeSpan.FromMilliseconds(500))));
        }

        [Test]
        public void Exceptions()
        {
            var orw = Mock.Of<IReadWriteObjectsFromIObjectDataInputOutput>();
            var output = new ObjectDataOutput(0, orw, Endianness.BigEndian);
            var schema = SchemaBuilder.For("type").WithField("name", FieldKind.String).Build();
            var writer = new CompactWriter(orw, output, schema);

            Assert.Throws<SerializationException>(() => writer.WriteInt8("name", 0));
        }

        [Test]
        public void CanWriteArrayOfCompactOfSameType()
        {
            var orw = Mock.Of<IReadWriteObjectsFromIObjectDataInputOutput>();
            var output = new ObjectDataOutput(0, orw, Endianness.BigEndian);
            var schema = SchemaBuilder.For("array").WithField("array", FieldKind.ArrayOfCompact).Build();
            var writer = new CompactWriter(orw, output, schema);

            // only one type and the right one
            var value = new Thing[] { new(), new() };
            writer.WriteArrayOfCompact("array", value);
        }

        [Test]
        public void CannotWriteArrayOfCompactOfDifferentTypes()
        {
            var orw = Mock.Of<IReadWriteObjectsFromIObjectDataInputOutput>();
            var output = new ObjectDataOutput(0, orw, Endianness.BigEndian);
            var schema = SchemaBuilder.For("array").WithField("array", FieldKind.ArrayOfCompact).Build();
            var writer = new CompactWriter(orw, output, schema);

            // two different types
            var value = new Thing[] { new(), new ThingExtend() };
            Assert.Throws<SerializationException>(() => writer.WriteArrayOfCompact("array", value));
        }

        [Test]
        public void CannotWriteArrayOfCompactOfDerivedTypes()
        {
            var orw = Mock.Of<IReadWriteObjectsFromIObjectDataInputOutput>();
            var output = new ObjectDataOutput(0, orw, Endianness.BigEndian);
            var schema = SchemaBuilder.For("array").WithField("array", FieldKind.ArrayOfCompact).Build();
            var writer = new CompactWriter(orw, output, schema);

            // only one type but not the right one
            var value = new Thing[] { new ThingExtend() };
            Assert.Throws<SerializationException>(() => writer.WriteArrayOfCompact("array", value));
        }
    }
}


text:
package org.apache.usergrid.chop.stack;

public class BasicInstance implements Instance {

    private String id;
    private InstanceSpec spec;
    private InstanceState state;
    private String privateDnsName;
    private String publicDnsName;
    private String privateIpAddress;
    private String publicIpAddress;

    private BasicInstance() {

    }

    public BasicInstance( final String id, final InstanceSpec spec, final InstanceState state,
                           final String privateDnsName, final String publicDnsName, final String privateIpAddress,
                           final String publicIpAddress ) {
        this.id = id;
        this.spec = spec;
        this.state = state;
        this.privateDnsName = privateDnsName;
        this.publicDnsName = publicDnsName;
        this.privateIpAddress = privateIpAddress;
        this.publicIpAddress = publicIpAddress;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public InstanceSpec getSpec() {
        return spec;
    }

    /**
     * @return Returns the last checked state of the instance
     */
    @Override
    public InstanceState getState() {
        return state;
    }

    @Override
    public String getPrivateDnsName() {
        return privateDnsName;
    }

    @Override
    public String getPublicDnsName() {
        return publicDnsName;
    }

    @Override
    public String getPrivateIpAddress() {
        return privateIpAddress;
    }

    @Override
    public String getPublicIpAddress() {
        return publicIpAddress;
    }

    public void setId( final String id ) {
        this.id = id;
    }

    public void setSpec( final InstanceSpec spec ) {
        this.spec = spec;
    }

    public void setState( final InstanceState state ) {
        this.state = state;
    }

    public void setPrivateDnsName( final String privateDnsName ) {
        this.privateDnsName = privateDnsName;
    }

    public void setPublicDnsName( final String publicDnsName ) {
        this.publicDnsName = publicDnsName;
    }

    public void setPrivateIpAddress( final String privateIpAddress ) {
        this.privateIpAddress = privateIpAddress;
    }

    public void setPublicIpAddress( final String publicIpAddress ) {
        this.publicIpAddress = publicIpAddress;
    }

    @Override
    public boolean equals( final Object o ) {
        if ( this == o ) {
            return true;
        }
        if ( !( o instanceof BasicInstance ) ) {
            return false;
        }

        final BasicInstance that = ( BasicInstance ) o;

        if ( id != null ? !id.equals( that.id ) : that.id != null ) {
            return false;
        }
        if ( privateDnsName != null ? ! privateDnsName.equals( that.privateDnsName ) : that.privateDnsName != null ) {
            return false;
        }
        if ( privateIpAddress != null ? ! privateIpAddress.equals( that.privateIpAddress ) :
             that.privateIpAddress != null ) {
            return false;
        }
        if ( publicDnsName != null ? ! publicDnsName.equals( that.publicDnsName ) : that.publicDnsName != null ) {
            return false;
        }
        if ( publicIpAddress != null ? ! publicIpAddress.equals( that.publicIpAddress ) :
             that.publicIpAddress != null ) {
            return false;
        }
        if ( spec != null ? !spec.equals( that.spec ) : that.spec != null ) {
            return false;
        }
        if ( state != that.state ) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + ( spec != null ? spec.hashCode() : 0 );
        result = 31 * result + ( state != null ? state.hashCode() : 0 );
        result = 31 * result + ( privateDnsName != null ? privateDnsName.hashCode() : 0 );
        result = 31 * result + ( publicDnsName != null ? publicDnsName.hashCode() : 0 );
        result = 31 * result + ( privateIpAddress != null ? privateIpAddress.hashCode() : 0 );
        result = 31 * result + ( publicIpAddress != null ? publicIpAddress.hashCode() : 0 );
        return Math.abs( result );
    }
}


text:
from support.gen import *
from support.util import *

class CSupportElektra(CSupport):
	def funcname(self, key):
		if key.startswith('/'):
			return self.funcpretty(key[1:])
		elif key.startswith('user:/'):
			return self.funcpretty(key[5:])
		elif key.startswith('system:/'):
			return self.funcpretty(key[7:])
		else:
			raise Exception("invalid keyname " + key)

	def getfuncname(self, key):
		return "elektraGet"+self.funcname(key)

	def setfuncname(self, key):
		return "elektraSet"+self.funcname(key)

	def funcpretty(self, key):
		return ''.join(x for x in key.title() if not x == '/' and not x == '_')

if __name__ == "__main__":
	import doctest
	doctest.testmod()