text:
using namespace llvm;

namespace {

/// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
/// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
/// directed by the GCStrategy. It also performs automatic root initialization
/// and custom intrinsic lowering.
class LowerIntrinsics : public FunctionPass {
  bool DoLowering(Function &F, GCStrategy &S);

public:
  static char ID;

  LowerIntrinsics();
  StringRef getPassName() const override;
  void getAnalysisUsage(AnalysisUsage &AU) const override;

  bool doInitialization(Module &M) override;
  bool runOnFunction(Function &F) override;
};

/// GCMachineCodeAnalysis - This is a target-independent pass over the machine
/// function representation to identify safe points for the garbage collector
/// in the machine code. It inserts labels at safe points and populates a
/// GCMetadata record for each function.
class GCMachineCodeAnalysis : public MachineFunctionPass {
  GCFunctionInfo *FI;
  MachineModuleInfo *MMI;
  const TargetInstrInfo *TII;

  void FindSafePoints(MachineFunction &MF);
  void VisitCallPoint(MachineBasicBlock::iterator CI);
  MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
                        const DebugLoc &DL) const;

  void FindStackOffsets(MachineFunction &MF);

public:
  static char ID;

  GCMachineCodeAnalysis();
  void getAnalysisUsage(AnalysisUsage &AU) const override;

  bool runOnMachineFunction(MachineFunction &MF) override;
};
}

// -----------------------------------------------------------------------------

INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
                      false)
INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)

FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }

char LowerIntrinsics::ID = 0;

LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
  initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
}

StringRef LowerIntrinsics::getPassName() const {
  return "Lower Garbage Collection Instructions";
}

void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
  FunctionPass::getAnalysisUsage(AU);
  AU.addRequired<GCModuleInfo>();
  AU.addPreserved<DominatorTreeWrapperPass>();
}

/// doInitialization - If this module uses the GC intrinsics, find them now.
bool LowerIntrinsics::doInitialization(Module &M) {
  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    if (!I->isDeclaration() && I->hasGC())
      MI->getFunctionInfo(*I); // Instantiate the GC strategy.

  return false;
}

/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
/// instruction could introduce a safe point.
static bool CouldBecomeSafePoint(Instruction *I) {
  // The natural definition of instructions which could introduce safe points
  // are:
  //
  //   - call, invoke (AfterCall, BeforeCall)
  //   - phis (Loops)
  //   - invoke, ret, unwind (Exit)
  //
  // However, instructions as seemingly inoccuous as arithmetic can become
  // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
  // it is necessary to take a conservative approach.

  if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
      isa<LoadInst>(I))
    return false;

  // llvm.gcroot is safe because it doesn't do anything at runtime.
  if (CallInst *CI = dyn_cast<CallInst>(I))
    if (Function *F = CI->getCalledFunction())
      if (Intrinsic::ID IID = F->getIntrinsicID())
        if (IID == Intrinsic::gcroot)
          return false;

  return true;
}

static bool InsertRootInitializers(Function &F, ArrayRef<AllocaInst *> Roots) {
  // Scroll past alloca instructions.
  BasicBlock::iterator IP = F.getEntryBlock().begin();
  while (isa<AllocaInst>(IP))
    ++IP;

  // Search for initializers in the initial BB.
  SmallPtrSet<AllocaInst *, 16> InitedRoots;
  for (; !CouldBecomeSafePoint(&*IP); ++IP)
    if (StoreInst *SI = dyn_cast<StoreInst>(IP))
      if (AllocaInst *AI =
              dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
        InitedRoots.insert(AI);

  // Add root initializers.
  bool MadeChange = false;

  for (AllocaInst *Root : Roots)
    if (!InitedRoots.count(Root)) {
      StoreInst *SI = new StoreInst(
          ConstantPointerNull::get(cast<PointerType>(Root->getAllocatedType())),
          Root);
      SI->insertAfter(Root);
      MadeChange = true;
    }

  return MadeChange;
}

/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
/// Leave gcroot intrinsics; the code generator needs to see those.
bool LowerIntrinsics::runOnFunction(Function &F) {
  // Quick exit for functions that do not use GC.
  if (!F.hasGC())
    return false;

  GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
  GCStrategy &S = FI.getStrategy();

  return DoLowering(F, S);
}

/// Lower barriers out of existance (if the associated GCStrategy hasn't
/// already done so...), and insert initializing stores to roots as a defensive
/// measure.  Given we're going to report all roots live at all safepoints, we
/// need to be able to ensure each root has been initialized by the point the
/// first safepoint is reached.  This really should have been done by the
/// frontend, but the old API made this non-obvious, so we do a potentially
/// redundant store just in case.
bool LowerIntrinsics::DoLowering(Function &F, GCStrategy &S) {
  SmallVector<AllocaInst *, 32> Roots;

  bool MadeChange = false;
  for (BasicBlock &BB : F)
    for (BasicBlock::iterator II = BB.begin(), E = BB.end(); II != E;) {
      IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++);
      if (!CI)
        continue;

      Function *F = CI->getCalledFunction();
      switch (F->getIntrinsicID()) {
      default: break;
      case Intrinsic::gcwrite: {
        // Replace a write barrier with a simple store.
        Value *St = new StoreInst(CI->getArgOperand(0),
                                  CI->getArgOperand(2), CI);
        CI->replaceAllUsesWith(St);
        CI->eraseFromParent();
        MadeChange = true;
        break;
      }
      case Intrinsic::gcread: {
        // Replace a read barrier with a simple load.
        Value *Ld = new LoadInst(CI->getType(), CI->getArgOperand(1), "", CI);
        Ld->takeName(CI);
        CI->replaceAllUsesWith(Ld);
        CI->eraseFromParent();
        MadeChange = true;
        break;
      }
      case Intrinsic::gcroot: {
        // Initialize the GC root, but do not delete the intrinsic. The
        // backend needs the intrinsic to flag the stack slot.
        Roots.push_back(
            cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
        break;
      }
      }
    }

  if (Roots.size())
    MadeChange |= InsertRootInitializers(F, Roots);

  return MadeChange;
}

// -----------------------------------------------------------------------------

char GCMachineCodeAnalysis::ID = 0;
char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;

INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
                "Analyze Machine Code For Garbage Collection", false, false)

GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}

void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  MachineFunctionPass::getAnalysisUsage(AU);
  AU.setPreservesAll();
  AU.addRequired<MachineModuleInfo>();
  AU.addRequired<GCModuleInfo>();
}

MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
                                             MachineBasicBlock::iterator MI,
                                             const DebugLoc &DL) const {
  MCSymbol *Label = MBB.getParent()->getContext().createTempSymbol();
  BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
  return Label;
}

void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
  // Find the return address (next instruction), since that's what will be on
  // the stack when the call is suspended and we need to inspect the stack.
  MachineBasicBlock::iterator RAI = CI;
  ++RAI;

  MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
  FI->addSafePoint(Label, CI->getDebugLoc());
}

void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
  for (MachineBasicBlock &MBB : MF)
    for (MachineBasicBlock::iterator MI = MBB.begin(), ME = MBB.end();
         MI != ME; ++MI)
      if (MI->isCall()) {
        // Do not treat tail or sibling call sites as safe points.  This is
        // legal since any arguments passed to the callee which live in the
        // remnants of the callers frame will be owned and updated by the
        // callee if required.
        if (MI->isTerminator())
          continue;
        VisitCallPoint(MI);
      }
}

void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
  const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
  assert(TFI && "TargetRegisterInfo not available!");

  for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
       RI != FI->roots_end();) {
    // If the root references a dead object, no need to keep it.
    if (MF.getFrameInfo().isDeadObjectIndex(RI->Num)) {
      RI = FI->removeStackRoot(RI);
    } else {
      unsigned FrameReg; // FIXME: surely GCRoot ought to store the
                         // register that the offset is from?
      RI->StackOffset = TFI->getFrameIndexReference(MF, RI->Num, FrameReg);
      ++RI;
    }
  }
}

bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
  // Quick exit for functions that do not use GC.
  if (!MF.getFunction().hasGC())
    return false;

  FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(MF.getFunction());
  MMI = &getAnalysis<MachineModuleInfo>();
  TII = MF.getSubtarget().getInstrInfo();

  // Find the size of the stack frame.  There may be no correct static frame
  // size, we use UINT64_MAX to represent this.
  const MachineFrameInfo &MFI = MF.getFrameInfo();
  const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
  const bool DynamicFrameSize = MFI.hasVarSizedObjects() ||
    RegInfo->needsStackRealignment(MF);
  FI->setFrameSize(DynamicFrameSize ? UINT64_MAX : MFI.getStackSize());

  // Find all safe points.
  if (FI->getStrategy().needsSafePoints())
    FindSafePoints(MF);

  // Find the concrete stack offsets for all roots (stack slots)
  FindStackOffsets(MF);

  return false;
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using SuperXML;

namespace Test
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            Compiler.Filters.Add("helloFilter", input =>
            {
                return "Hello " + input;
            });
        }

        private int[] _generateInts(int times)
        {
            var l = new List<int>();
            for (var i = 0; i < times; i++)
            {
                l.Add(i);
            }
            return l.ToArray();
        }

        private void CompileClick(object sender, RoutedEventArgs e)
        {

            var compiler = new Compiler()
                .AddKey("m", new ViewModel
                {
                    Name = "Excel",
                    Date = DateTime.Now,
                    Width = 100,
                    Height = 300,
                    Bounds = new List<int>
                    {
                        1,
                        2,
                        3,
                        4,
                        5
                    },
                    Users = new List<User>
                    {
                        new User {Name = "John", Age = 13},
                        new User {Name = "Maria", Age = 57},
                        new User {Name = "Mark", Age = 23},
                        new User {Name = "Edit", Age = 82},
                        new User {Name = "Susan", Age = 37}
                    },
                    NullUser = new User
                    {
                        Name = null,
                        Age = 10,
                        Date = new DateTime?()
                    }
                });

            Compiler.OnNullOrNotFound = "";

            var startedTime = DateTime.Now;
            var compiledAsString = compiler.CompileString(SourceBox.Text);
            ResultBlock.Text = "Compilation total time " + (DateTime.Now - startedTime).TotalMilliseconds + "ms";

            CompiledBox.Text = compiledAsString;
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            //Xml Example
            //using (var sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "testFile.xml"))
            //{
            //    SourceBox.Text = sr.ReadToEnd();
            //}

            //String Exmaple
            using (var sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "testfile.xml"))
            {
                SourceBox.Text = sr.ReadToEnd();
            }
        }

        public class User
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public DateTime? Date { get; set; }
        }

        public class ViewModel
        {
            public string Name { get; set; }
            public DateTime? Date { get; set; }
            public int Width { get; set; }
            public int Height { get; set; }
            public List<int> Bounds { get; set; }
            public List<User> Users { get; set; }
            public User NullUser { get; set; }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function() {
  var DocPad, action, docpadConfig, getArgument;

  DocPad = require('../lib/docpad');

  getArgument = function(name, value, defaultValue) {
    var argumentIndex, result;
    if (value == null) {
      value = null;
    }
    if (defaultValue == null) {
      defaultValue = null;
    }
    result = defaultValue;
    argumentIndex = process.argv.indexOf("--" + name);
    if (argumentIndex !== -1) {
      result = value != null ? value : process.argv[argumentIndex + 1];
    }
    return result;
  };

  action = getArgument('action', null, 'server generate');

  docpadConfig = {};

  docpadConfig.port = (function() {
    var port;
    port = getArgument('port');
    if (port && isNaN(port) === false) {
      port = parseInt(port, 10);
    }
    return port;
  })();

  DocPad.createInstance(docpadConfig, function(err, docpad) {
    if (err) {
      return console.log(err.stack);
    }
    return docpad.action(action, function(err) {
      if (err) {
        return console.log(err.stack);
      }
      return console.log('OK');
    });
  });

}).call(this);


text:
class UpdateCertificates < ActiveRecord::Migration[5.0]
  def change
    Procedure.where(procedure_id: nil).delete_all
    certificate = Procedure.find_by(procedure_id: 1856)
    certificate.active_in_totem = true
    certificate.info = "El trámite se puede realizar durante todo el año."
    certificate.description = "Permite acreditar que la situación militar del interesado está en conformidad con la ley.

En Chile, el certificado se puede solicitar en línea o en las oficinas del cantón de reclutamiento; en el extranjero, en cualquier consulado chileno.

Si no tiene la situación militar al día diríjase al cantón de reclutamiento más cercano."
    certificate.save
  end
end


text:
#ifndef __ALD_CONF_H__
#define __ALD_CONF_H__

#define ALD_DMA
#define ALD_GPIO
#define ALD_UART
#define ALD_LPUART
#define ALD_USART
#define ALD_SMARTCARD   /* The ALD_SMARTCARD depend on ALD_USART */
#define ALD_I2C
#define ALD_CMU
#define ALD_RMU
#define ALD_PMU
#define ALD_WDT
#define ALD_LCD
#define ALD_RTC
#define ALD_CAN
#define ALD_FLASH
#define ALD_ADC
#define ALD_CRC
#define ALD_CRYPT
#define ALD_TIMER
#define ALD_LPTIM
#define ALD_PIS
#define ALD_SPI
#define ALD_CALC
#define ALD_ACMP
#define ALD_OPAMP
#define ALD_TRNG
#define ALD_TEMP
#define ALD_BKPC
#define ALD_DAC
#define ALD_IAP

#define TICK_INT_PRIORITY   3

#endif


text:
namespace Brainary.Commons.Extensions
{
    using System;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;

    public static partial class Extensions
    {
        /// <summary>
        /// Get byte array from string
        /// </summary>
        /// <param name="str">String</param>
        /// <returns>Byte array</returns>
        public static byte[] GetBytes(this string str)
        {
            var bytes = new byte[str.Length * sizeof(char)];
            Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        /// <summary>
        /// Get MD5 hash from string
        /// </summary>
        /// <param name="str">String</param>
        /// <returns>String</returns>
        public static string GetMd5Hash(this string str)
        {
            using (var md5Hash = MD5.Create())
            {
                var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(str));
                var builder = new StringBuilder();

                foreach (var t in data)
                    builder.Append(t.ToString("x2"));

                return builder.ToString();
            }
        }

        public static string CleanRut(this string str)
        {
            return new string(str.Where(char.IsLetterOrDigit).ToArray());
        }

        public static string FormatRut(this string str)
        {
            var value = str.CleanRut();
            return string.Format("{0}-{1}", int.Parse(value.Substring(0, value.Length - 1)).ToString("N0"), value.Last());
        }
    }
}


text:
from collections import defaultdict
import telnetlib
import os,sys,commands,multiprocessing
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

import sys
if not "/root/labroom" in sys.path:
    sys.path.append("/root/labroom")
import messageMode
#-------config--dir----------------
devicefile = '/root/alllogscan/alllogscan.ini'              #Attention use full path
logfile_path = '/root/log/'
alllogscan_path = '/root/alllogscan/'
pythonlog =  '/root/mylog.txt'

#-------parameter-------
sms_off = 0    #if you want trun off sms ,please set to 1
mail_off = 0    #if you want trun off sms ,please set to 1
linecount = 0
MAX_process = 100         #mutiprocessing
once_line = 300           #every exec will read 300 line logs

#---init paramater------
device_idct = defaultdict(lambda:defaultdict(dict))
begintime =  time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

#---read file into idct-----------
file = open(devicefile)
for line in file.readlines():
    if (line.split()[0].find('#') >= 0)|(len(line) < 5): #jump the comments,jump short than 1.1.1.1
        #os.system("echo "+begintime+' '+" init device file error ! >> "+pythonlog)  # log to mylog.txt
        #print 'init device file error'
        continue
    else:
        device_idct[linecount]['ip'] = line.split()[0]
        device_idct[linecount]['name']= line.split()[1]
        device_idct[linecount]['muti_grep']= line.split()[2]
        device_idct[linecount]['muti_mail']= line.split()[3]
        device_idct[linecount]['muti_phone']= line.split()[4]
        linecount += 1    #line counter
file.close()
#print "linecount:",linecount
#print device_idct

def alllogscan(_fuc_ip,_fuc_name,_fuc_muti_grep,_fuc_muti_mail,_fuc_muti_phone):
    '''log scan
    '''
    successful_flag = 'ok'
    mail_tmp_list = []
    newlogfile = ''
    newlogfile_bak = ''

    #print _fuc_ip,_fuc_name,_fuc_muti_grep,_fuc_muti_mail,_fuc_muti_phone

    log_path = logfile_path+_fuc_ip
    log_temp_path = alllogscan_path+_fuc_ip+'.logtmp'
    sendmail_temp_path = alllogscan_path+_fuc_ip+'.lasttmp'

    #--------read last mail to mail_tmp_list--------------
    if os.path.exists(sendmail_temp_path):
        last_mail = open(sendmail_temp_path)
        for lastmailline in last_mail.readlines():
            mail_tmp_list.append(lastmailline)
        last_mail.close()
    print 'last mail line',len(mail_tmp_list)

    #-------creat new grep log to ip.logtmp------------
    for grep_index in range(0, len(_fuc_muti_grep.split(';'))):
        every_grep =  _fuc_muti_grep.split(';')[grep_index]
        every_grep = every_grep.replace('_',' ')
        commandstr_os = 'tail -n '+str(once_line)+' '+log_path+' |egrep '+every_grep+ ' >> ' +log_temp_path
        print commandstr_os
        os.system(commandstr_os)

    #-----read the file ip.logtmp to MEM------
    Tmp_log_mem = open(log_temp_path)
    for line in Tmp_log_mem.readlines():
        newlogfile += line
    Tmp_log_mem.close()
    newlogfile_bak =  newlogfile
    print 'newlog lines:',newlogfile_bak.count('\n')

    #----delete every line of last mail in this newlogfile--find different content--
    for index_last in range(0,len(mail_tmp_list)):
        #print index_last
        #print newlogfile_bak.find(every_line)
        newlogfile_bak = newlogfile_bak.replace(mail_tmp_list[index_last],'')

    print 'diff lines:',newlogfile_bak.count('\n')
    print 'diff content will be send:',newlogfile_bak

    #-----write to lastlogtmp ------
    thistime_mail = open(sendmail_temp_path,'w')
    thistime_mail.write(newlogfile)
    thistime_mail.close()

    if newlogfile_bak != '':
        #print 'mail send ----------'
        #print _fuc_ip,_fuc_name,_fuc_muti_grep,_fuc_muti_mail,_fuc_muti_phone
        #-------send mail to receivers----------------

        messageMode.send_muti_sms(_fuc_muti_phone,sms_off,'Alllogscan '+_fuc_name,'log:' + _fuc_name+' '+newlogfile_bak)
        messageMode.sendtxtmail(_fuc_name +' '+' log scan',mail_off,newlogfile_bak,_fuc_muti_mail,begintime)

    return successful_flag

def func(_index):
    new_idct = device_idct
    fuc_index = _index
    fuc_ip = new_idct[_index]['ip']
    fuc_name = new_idct[_index]['name']
    fuc_muti_grep = new_idct[_index]['muti_grep']
    fuc_muti_mail = new_idct[_index]['muti_mail']
    fuc_muti_phone = new_idct[_index]['muti_phone']

    print '---',fuc_index,'/',linecount,'--',fuc_ip,'----',fuc_name,'----[',fuc_muti_grep,']-----'
    logscan_ret =  alllogscan(fuc_ip,fuc_name,fuc_muti_grep,fuc_muti_mail,fuc_muti_phone)
    if (logscan_ret != 'ok'):
        os.system("echo "+begintime+' '+fuc_ip+':'+"  logscan fail ! Code:"+logscan_ret+" >> "+pythonlog)
        print fuc_name +' '+fuc_ip+'  logscan   error...'
        return 'error'
    return 'not find this menu...'

def main(_linecount):
    os.system("echo "+begintime+"   all log Scan begin !  >> "+pythonlog)  # log to mylog.txt
    pool = multiprocessing.Pool(processes=MAX_process)
    result = []
    for index in xrange(_linecount):
        result.append(pool.apply_async(func, (index, )))
        #time.sleep(1)
    pool.close()
    pool.join()

    for res in result:
        #print 'Mutiprocess ret:',res.get(),res.successful()
        if (res.successful() != True):
            print "Mutiprocess fail !"

    endtime =  time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    os.system("echo "+endtime+"  all log Scanned over !  >> "+pythonlog)  # log to mylog.txt

if __name__ == "__main__":
   logtmpfilepath_cmd = "rm -f "+alllogscan_path + "*.logtmp"
   #print logtmpfilepath_cmd
   os.system(logtmpfilepath_cmd)
   #time.sleep(2)
   main(linecount)


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

<TITLE>
PropertyString (EarthquakeService: version 0.9)
</TITLE>

<META NAME="date" CONTENT="2013-07-31">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      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

realtimeweb.earthquakeservice.util

Class PropertyString

Object
  realtimeweb.earthquakeservice.util.PropertyString

public class PropertyString
extends Object

This is a convenient class for converting a list of key-value pairs into a
 nicely-formatted string.

Author:

acbart

Constructor Summary

PropertyString(String name)

          Create a new PropertyString with the given name.

Method Summary

 PropertyString
add(String property,
       String value)

          Add a new key-value property pair to the list of properties.

 String
toString()

          Return a nicely-formatted string representation of this PropertyString.

Methods inherited from class Object

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

Constructor Detail

PropertyString

public PropertyString(String name)

Create a new PropertyString with the given name.

Parameters:
name -

Method Detail

add

public PropertyString add(String property,
                          String value)

Add a new key-value property pair to the list of properties.

Parameters:
property -
value -

Returns:

toString

public String toString()

Return a nicely-formatted string representation of this PropertyString.

Overrides:
toString in class Object

      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


text:
/**
 * Please note, this plugin requires the jQuery cookie plugin, which comes bundled with the bp-default theme and many BuddyPress themes.
 * If you theme does not include it it, please copy it from bp-default/_inc/global.js and paste in your js file
 **/
jQuery( document ).ready( function() {
    var jq = jQuery;
    var is_activity_loading = false;//We'll use this variable to make sure we don't send the request again and again.

    //Check the window scroll event.
    jq( window ).scroll( function() {
       //Find the visible "load more" button.
       //since BP does not remove the "load more" button, we need to find the last one that is visible.
        var load_more_btn = jq( '.load-more:visible' );
        //If there is no visible "load more" button, we've reached the last page of the activity stream.
        if( ! load_more_btn.get(0))
            return;

        //Find the offset of the button.
         var pos = load_more_btn.offset();

       //If the window height+scrollTop is greater than the top offset of the "load more" button, we have scrolled to the button's position. Let us load more activity.

       if( jq( window ).scrollTop() + jq( window ).height() > pos.top ) {

            load_more_activity();
       }

    });

    /**
     * This routine loads more activity.
     * We call it whenever we reach the bottom of the activity listing.
     *
     */
    function load_more_activity() {
        //Check if activity is loading, which means another request is already doing this.
        //If yes, just return and let the other request handle it.
            if( is_activity_loading ) {
                    return false;
			}
           //So, it is a new request, let us set the var to true.
            is_activity_loading = true;

			var $parent = jq('#content');
			if( ! $parent.get(0) ) {
				$parent = jq( '#buddypress' );
			}

			if( ! $parent ) {
				return ;
			}
            //Add loading class to "load more" button.
            //Theme authors may need to change the selector if their theme uses a different id for the content container.
            //This is designed to work with the structure of bp-default/derivative themes.
            //Change #content to whatever you have named the content container in your theme.
            $parent.find( 'li.load-more' ).addClass( 'loading' );

            if ( null == jq.cookie( 'bp-activity-oldestpage' ) ) {
                    jq.cookie( 'bp-activity-oldestpage', 1, {
                            path: '/'
                    } );
			}

            var oldest_page = ( jq.cookie( 'bp-activity-oldestpage' ) * 1 ) + 1;

            //Send the ajax request.
            jq.post( ajaxurl, {
                    action: 'activity_get_older_updates',
                    cookie: encodeURIComponent(document.cookie),
                    page: oldest_page
            },
            function( response )
            {
                    $parent.find( '.load-more' ).hide();//Hide any "load more" button.
                    $parent.find( 'li.load-more' ).removeClass( 'loading' );//Theme authors, you may need to change #content to the id of your container here, too.

                    //Update cookie...

                    //and append the response.

                    // Inicio Cambios
                    // $parent.find( 'ul.activity-list' ).append( response.contents );
                    $parent.find('#activity-stream').css('visibility', 'hidden').fadeOut(150 , function() {
                        // He puesto un fadeIn en la siguiente línea para hacer uso de la función nada más, de momento eso
                        // porque no soy un mago de js y no sé como va el lío
                        $parent.find('ul.activity-list').append( response.contents ).fadeIn(150 , function(){
                            var container = document.querySelector('#activity-stream');
                            var msnry = new Masonry( container, {
                                itemSelector: '.activity-item',
                                columnWidth: '.activity-sizer',
                                percentPosition: true
                            });

                            $parent.find('#activity-stream').css('visibility', 'visible').hide().fadeIn(150);

                        });
                    });
                    // Fin cambios

					jq.cookie( 'bp-activity-oldestpage', oldest_page, {
                            path: '/'
                    } );
                    //Since the request is complete, let us reset is_activity_loading to false, so we'll be ready to run the routine again.

                    is_activity_loading = false;

            }, 'json' );

            return false;
    }

} );//end of dom ready


text:
<?php

defined('_JEXEC') or die;

/**
 * Client controller class.
 *
 * @since  1.6
 */
class BannersControllerClient extends JControllerForm
{
	/**
	 * The prefix to use with controller messages.
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $text_prefix = 'COM_BANNERS_CLIENT';
}


text:
import express from 'express';
import request from 'supertest';
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { GraphQLSchema } from 'graphql';

import { graphqlHTTP } from '../index';

describe('Useful errors when incorrectly used', () => {
  it('requires an option factory function', () => {
    expect(() => {
      // @ts-expect-error
      graphqlHTTP();
    }).to.throw('GraphQL middleware requires options.');
  });

  it('requires option factory function to return object', async () => {
    const app = express();

    app.use(
      '/graphql',
      // @ts-expect-error
      graphqlHTTP(() => null),
    );

    const response = await request(app).get('/graphql?query={test}');

    expect(response.status).to.equal(500);
    expect(JSON.parse(response.text)).to.deep.equal({
      errors: [
        {
          message:
            'GraphQL middleware option function must return an options object or a promise which will be resolved to an options object.',
        },
      ],
    });
  });

  it('requires option factory function to return object or promise of object', async () => {
    const app = express();

    app.use(
      '/graphql',
      // @ts-expect-error
      graphqlHTTP(() => Promise.resolve(null)),
    );

    const response = await request(app).get('/graphql?query={test}');

    expect(response.status).to.equal(500);
    expect(JSON.parse(response.text)).to.deep.equal({
      errors: [
        {
          message:
            'GraphQL middleware option function must return an options object or a promise which will be resolved to an options object.',
        },
      ],
    });
  });

  it('requires option factory function to return object with schema', async () => {
    const app = express();

    app.use(
      '/graphql',
      // @ts-expect-error
      graphqlHTTP(() => ({})),
    );

    const response = await request(app).get('/graphql?query={test}');

    expect(response.status).to.equal(500);
    expect(JSON.parse(response.text)).to.deep.equal({
      errors: [
        { message: 'GraphQL middleware options must contain a schema.' },
      ],
    });
  });

  it('requires option factory function to return object or promise of object with schema', async () => {
    const app = express();

    app.use(
      '/graphql',
      // @ts-expect-error
      graphqlHTTP(() => Promise.resolve({})),
    );

    const response = await request(app).get('/graphql?query={test}');

    expect(response.status).to.equal(500);
    expect(JSON.parse(response.text)).to.deep.equal({
      errors: [
        { message: 'GraphQL middleware options must contain a schema.' },
      ],
    });
  });

  it('validates schema before executing request', async () => {
    // @ts-expect-error
    const schema = new GraphQLSchema({ directives: [null] });

    const app = express();

    app.use(
      '/graphql',
      graphqlHTTP(() => Promise.resolve({ schema })),
    );

    const response = await request(app).get('/graphql?query={test}');

    expect(response.status).to.equal(500);
    expect(JSON.parse(response.text)).to.deep.equal({
      errors: [
        { message: 'Query root type must be provided.' },
        { message: 'Expected directive but got: null.' },
      ],
    });
  });
});


text:
var telInput = $("#phone"),
  errorMsg = $("#error-msg"),
  validMsg = $("#valid-msg");

// initialise plugin
telInput.intlTelInput({
  utilsScript: "../../build/js/utils.js"
});

var reset = function() {
  telInput.removeClass("error");
  errorMsg.addClass("hide");
  validMsg.addClass("hide");
};

// on blur: validate
telInput.blur(function() {
  reset();
  if ($.trim(telInput.val())) {
    if (telInput.intlTelInput("isValidNumber")) {
      validMsg.removeClass("hide");
    } else {
      telInput.addClass("error");
      errorMsg.removeClass("hide");
    }
  }
});

// on keyup / change flag: reset
telInput.on("keyup change", reset);


text:
module.exports = {
  baidu: require('./baidu_translator'),
  youdao: require('./youdao_translator'),
};


text:
'''
Created on May 1, 2012

@author: Charlie
'''
import unittest
import os
from files.core import SimpleFile

class Test(unittest.TestCase):

    def get_file_name(self):
        fileName = "bar.txt"
        return fileName

    def get_file_text(self):
        textToWrite = "This line"
        return textToWrite

    def create_file(self):
        simple_file = SimpleFile(self.get_file_name())
        simple_file.write_new_text_file(self.get_file_text())

    def delete_file(self, simple_file):
        simple_file.delete_file()
        self.assertFalse(os.path.isfile(self.get_file_name()), "Could not delete file")

    def test_write_file(self):
        simple_file = SimpleFile(self.get_file_name())
        simple_file.write_new_text_file(self.get_file_text())
        self.assertTrue(os.path.isfile(self.get_file_name()))
        self.delete_file(simple_file)

    def test_read_file(self):
        self.create_file()
        simple_file = SimpleFile(self.get_file_name())
        read_text = simple_file.read_text()
        self.assertEqual(read_text,self.get_file_text())
        self.delete_file(simple_file)

    def test_append_file(self):
        self.create_file()
        simple_file = SimpleFile(self.get_file_name())
        simple_file.append_text(self.get_file_text())
        read_text = simple_file.read_text()
        self.assertEqual(read_text,self.get_file_text()+self.get_file_text())
        self.delete_file(simple_file)

    def test_create_csv(self):
        simple_file = SimpleFile(self.get_file_name())
        simple_file.write_csv("One", "Two", "Three")
        simple_file.write_csv("Four", "Five", "Six")
        self.delete_file(simple_file)

    def test_csv_row(self):
        simple_file = SimpleFile(self.get_file_name())
        simple_file.write_csv_row(["one","two","three"])
        simple_file.write_csv_row(["four","five","six"])
        self.delete_file(simple_file)

    def test_csv_read(self):
        simple_file = SimpleFile(self.get_file_name())
        simple_file.write_csv_row(["one","two","three"])
        simple_file.write_csv_row(["four","five","six"])
        row = simple_file.read_csv_row()
        self.assertEqual(row, ["one", "two", "three", "four", "five", "six"])

    def test_csv_read_item(self):
        simple_file = SimpleFile(self.get_file_name())
        simple_file.write_csv_row(["one","two","three"])
        simple_file.write_csv_row(["four","five","six"])
        item = simple_file.read_csv_get_item(1, 1)
        self.assertEqual(item, "five")

# suite = unittest.TestLoader().loadTestsFromTestCase(Test)
# unittest.TextTestRunner(verbosity=2).run(suite)


text:
struct PLUGIN_API IPluginObject1;

typedef IPluginObject1 IPluginObject;
typedef IPluginObject1* PIPluginObject;

// A plugin object type
typedef long long PL_TYPE;

// A result returned by the plugin framework's interface.
typedef int PL_RES;

// A loaded plugin ID. Useful if we want to manually close any opened plugins
typedef unsigned int PL_LIBID;

// An error code delivered by the plugin framework
typedef int PL_ERRCODE;

// Symbolizes an unsigned long in the plugin framework
typedef unsigned long PL_UINT64;

#define PL_OK 1
#define PL_ERR 0

//
// Define a plugin object type ID (ID for this specific interface).
//
// @param Type
//			The interface type
// @param UID
//			A unique ID number. It's up to your project to select which ones you want.
//			Numbers below 10 are restricted.
#define DEFINE_PLTYPE(Type, UID) static const PL_TYPE Type##_ID = UID##LL

//
// Retrieves a plugin object type ID unique to the supplied Type. You are also free to manually type in <Type>_ID if you want.
//
// @param Type
//			The type
#define PL_TYPEOF(Type) Type##_ID

//
// Declare a new interface useful for the plugin framework.
//
// @param Name
//			The interface name
// @param Inherits
//			The class that the new interface inherits from. If nothing then specify IPluginObject
#define DECLARE_INTERFACE(Name, Inherits) struct PLUGIN_API Name : public Inherits

#ifndef SAFE_RELEASE
#define SAFE_RELEASE(Obj) if(Obj != nullptr) Obj->Release()
#endif

#ifndef FAILURE
#define FAILURE(X) ((X) == PL_ERR)
#endif

#ifndef SUCCESS
#define SUCCESS(X) ((X) == PL_OK)
#endif

//
// Error codes
//

// No error has occured
#define PL_ERRCODE_NOERROR 0

// The library was not found
#define PL_ERRCODE_LIBRARYNOTFOUND 1

// The entry point is missing inside the plugin
#define PL_ERRCODE_MISSINGENTRYPOINT 2

// Entry point returned failure
#define PL_ERRCODE_ENTRYPOINTFAILURE 3

// The object you are looking for is not found
#define PL_ERRCODE_OBJECTNOTFOUND 4

// The supplied PL_LIBID doesn't exist
#define PL_ERRCODE_NONEXISTENTLIBID 5

// You are trying to perform an action without an active plugin available
#define PL_ERRCODE_NOACTIVEPLUGIN 6

// You are trying to register a non-global object as a plugin, which is not allowed.
#define PL_ERRCODE_NOTHOSTERROR 7

// The plugin framework is not initialized
#define PL_ERRCODE_NOTINITIALIZED 8

// This error code happens if the host application tries to unload
// a library that's currently in use (has object's with reference counter > 0).
#define PL_ERRCODE_LIBRARYINUSE 9

// Error code occures if retrieval of get objects fails by some reason
#define PL_ERRCODE_GETOBJECTSFAILED 10

// A supplied argument is invalid
#define PL_ERRCODE_INVALIDARGUMENT 11

#endif


text:
require.config({
	paths: {
		jquery: 'libs/jquery/jquery',
		underscore: 'libs/underscore/underscore',
		handlebars: 'libs/handlebars/handlebars',
		backbone: 'libs/backbone/backbone',
		viewcache: 'libs/backbone.viewcache/backbone.viewcache',
		bootstrap: 'libs/bootstrap/bootstrap',
		three: 'libs/three/three',
		gsvpano: 'libs/gsvpano/gsvpano',
		hyperlapse: 'libs/hyperlapse/hyperlapse'
	},
	shim: {
		'bootstrap': {
			deps: ['jquery'],
			exports: 'Bootstrap'
		},
		'three': {
			deps: [],
			exports: 'THREE'
		},
		'gsvpano': {
			deps: [],
			exports: 'GSVPANO'
		},
		'hyperlapse': {
			deps: ['three', 'gsvpano'],
			exports: 'Hyperlapse'
		}
	}
});

require([
	'app',
], function(App) {
	console.log('start: initialize App');
	App.initialize();
	console.log('end: initialize App');
});


text:
/**
 * @file GroupGrid component
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

// Components
import Grid from '../Grid';
import Tip from '../Tip';

// Statics
import Theme from '../Theme';
import SelectMode from '../_statics/SelectMode';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';
import Calculation from '../_vendors/Calculation';
import ComponentUtil from '../_vendors/ComponentUtil';

class GroupGrid extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            value: Calculation.getInitValue({
                value: ComponentUtil.getDerivedState(props, state, 'value'),
                selectMode: props.selectMode
            })
        };
    }

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: Calculation.getInitValue(props)
        };

    }

    render() {

        const {children, className, style, data, disabled, ...restProps} = this.props,
            {value} = this.state;

        return (

                {
                    data && data.map((item, index) =>

{item.name}

                            <Grid {...restProps}
                                  data={item.children}
                                  value={value}/>

                    )
                }

                {children}

        );

    }
}

GroupGrid.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme of the list item select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * Children passed into the ListItem.
     */
    data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

        // group name
        name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        children: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

            /**
             * The CSS class name of the list button.
             */
            className: PropTypes.string,

            /**
             * Override the styles of the list button.
             */
            style: PropTypes.object,

            /**
             * The theme of the list button.
             */
            theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

            /**
             * The text value of the list button.Type can be string or number.
             */
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The list item's display text. Type can be string, number or bool.
             */
            text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The desc value of the list button. Type can be string or number.
             */
            desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * If true,the list item will be disabled.
             */
            disabled: PropTypes.bool,

            /**
             * If true,the button will be have loading effect.
             */
            isLoading: PropTypes.bool,

            /**
             * If true,the element's ripple effect will be disabled.
             */
            disableTouchRipple: PropTypes.bool,

            /**
             * Use this property to display an icon. It will display on the left.
             */
            iconCls: PropTypes.string,

            /**
             * Use this property to display an icon. It will display on the right.
             */
            rightIconCls: PropTypes.string,

            /**
             * The message of tip.
             */
            tip: PropTypes.string,

            /**
             * The position of tip.
             */
            tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)),

            /**
             * If true,the item will have center displayed ripple effect.
             */
            rippleDisplayCenter: PropTypes.bool,

            /**
             * You can create a complicated renderer callback instead of value and desc prop.
             */
            itemRenderer: PropTypes.func,

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onClick: PropTypes.func

        }), PropTypes.string, PropTypes.number]))

    }), PropTypes.symbol])).isRequired,

    /**
     * The id field name in data. (default: "id")
     */
    idField: PropTypes.string,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the list will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * If true, the list will be at loading status.
     */
    isLoading: PropTypes.bool,

    /**
     * The mode of listItem.Can be normal,checkbox.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the list-item select.
     */
    onItemClick: PropTypes.func,

    /**
     * Callback function fired when the list changed.
     */
    onChange: PropTypes.func

};

GroupGrid.defaultProps = {

    theme: Theme.DEFAULT,
    selectTheme: Theme.DEFAULT,

    data: [],

    idField: 'id',
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    disabled: false,
    selectMode: SelectMode.SINGLE_SELECT,

    radioUncheckedIconCls: 'fas fa-check',
    radioCheckedIconCls: 'fas fa-check',
    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square'

};

export default GroupGrid;


text:
/*jslint node: true */
var async = require('async');
var optimist = require('optimist');
var underscore = require('underscore');


text:
using System;
using System.Collections.ObjectModel;
using System.Linq;
using Prism.Mvvm;
using Sautom.Client.Comunication.Commands;
using Sautom.Client.Comunication.QueriesService;
using Sautom.Client.Modules.Client.Models;

namespace Sautom.Client.Modules.Client.Controls.ViewModels
{
    public class OrderViewerViewModel : BindableBase
    {
	    public OrderViewerViewModel(CommandBase<Guid> printOrderDetails)
        {
            PrintOrderDetails = printOrderDetails;
        }

	    #region Commands

	    public CommandBase<Guid> PrintOrderDetails { get; }

	    #endregion

	    #region View properties

	    public bool IsShowAirlineTicket
        {
            get { return Order != null && Order.AirlineTicket != null && Order.AirlineTicket.Id != Guid.Empty; }
        }

	    private ObservableCollection<GuidStringSelected> _embasyDocs;

	    public ObservableCollection<GuidStringSelected> EmbasyDocs
        {
            get { return _embasyDocs; }
            set
            {
                _embasyDocs = value;
                OnPropertyChanged(() => EmbasyDocs);
            }
        }

	    private OrderItemDtoOutput _order;

	    public OrderItemDtoOutput Order
        {
            get { return _order; }
            set
            {
                PreSelectionAction(Order);
                _order = value;
                OnPropertyChanged(() => Order);
                InitializeDependencies(value);
            }
        }

	    private void InitializeDependencies(OrderItemDtoOutput value)
        {
            if (value != null)
            {
                EmbasyDocs = new ObservableCollection<GuidStringSelected>(value.FullDocsList.Select(
                    rec =>
                    new GuidStringSelected { Id = rec.Id, Value = rec.Element, IsSelected = value.Docs.Contains(rec.Id) }));

                OnPropertyChanged(() => IsShowAirlineTicket);
                PrintOrderDetails.RaiseCanExecuteChanged();
            }
        }

	    private void PreSelectionAction(OrderItemDtoOutput value)
        {
            if (value != null)
            {
                value.Docs = EmbasyDocs.Where(rec => rec.IsSelected).Select(rec => rec.Id).ToArray();
            }
        }

	    #endregion
    }
}


text:
Describe "Failing test used to test CI Scripts" -Tags 'CI' {
    It "Should fail" {
        1 | should be 2
    }
}


text:
define(['getMember', 'getCell', 'createCube', 'cubeIndex', 'thesaurus', 'hierarchy', 'mergeHierarchies', 'mergeCubes', 'slice'],
    function (getMember, getCell, createCube, CubeIndex, Thesaurus, Hierarchy, mergeHierarchies, mergeCubes, slice) {
  return {
    getMember: getMember,
    getCell: getCell,
    createCube: createCube,
    createCubeIndex: CubeIndex,
    createThesaurus: Thesaurus,
    mergeCubes: mergeCubes,
    slice: slice,

    Hierarchy: Hierarchy,
    mergeHierarchies: mergeHierarchies,
  };
});


text:
package com.beanu.l3_login.model.bean;

/**
 * 短信验证码
 * Created by Beanu on 2017/2/13.
 */

public class SMSCode {

    private String code;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}


text:
package com.beegman.webbee.block;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.MemoryCacheImageOutputStream;

import org.aldan3.util.BarCode2D;

import com.beegman.webbee.model.AppModel;

public class Barcode2d<A extends AppModel> extends Stream<A> {
	static final String IMAGE_FORMAT = "gif";

	static final int masks[] = { 1, 2, 4, 8, 16, 32, 64, 128 };

	@Override
	protected void fillStream(OutputStream os) throws IOException {
		BarCode2D bc = new BarCode2D();
		BarCodeAttributes bca = getBarcodeAttributes();
		try {
			bc.setText(bca.code);
			bc.setOptions(bca.format);
			//bc.setYHeight(1);
			bc.paintCode();
			int bitsw = bc.getBitColumns();
			int bitsh = bc.getCodeRows();
			byte bits[] = bc.getOutBits();
			int dotW = bca.dotWidth;
			int dotH = bca.dotHeight;
			//log("bar %dx%d = %d for %s", null, bitsw, bitsh, bits.length, bca.code);
			int[] barcode = new int[bitsw * bitsh * dotW * dotH];
			BufferedImage bi = new BufferedImage(bitsw * dotW, bitsh * dotH, BufferedImage.TYPE_INT_RGB);
			int byteW = (bitsw + 7) / 8;
			for (int r = 0; r < bitsh; r++) {
				for (int c = 0; c < bitsw; c++) {
					int bm = 7 - c % 8;
					int bp = c / 8;
					putDot(barcode, bitsw * dotW, c, r, dotW, dotH,
							(bits[r * byteW + bp] & masks[bm]) != 0 ? 0xffffff : 0);
				}
			}
			bi.setRGB(0, 0, bitsw * dotW, bitsh * dotH, barcode, 0, bitsw * dotW);
			Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(IMAGE_FORMAT);
			if (writers != null && writers.hasNext()) {
				ImageWriter wr = (ImageWriter) writers.next();
				// TODO analyze on freeing resources
				MemoryCacheImageOutputStream mms;
				wr.setOutput(mms = new MemoryCacheImageOutputStream(os));
				wr.write(bi);
				mms.flush();
				wr.dispose();
			} else
				log("No image writer found for %s", null, IMAGE_FORMAT);
		} catch (UnsupportedEncodingException e) {
			log("Error in barcode gen", e);
		} catch (IOException e) {
			log("Error in barcode out", e);
		}
	}

	protected void putDot(int[] barcode, int ss, int c, int r, int dw, int dh, int rgb) {
		int cornX = c * dw;
		int cornY = r * ss * dh;
		for (int y = 0; y < dh; y++) {
			for (int x = 0; x < dw; x++) {
				barcode[cornY + (y * ss) + cornX + x] = rgb;
			}
		}
	}

	@Override
	protected void setHeaders() {
		super.setHeaders();
		resp.setContentType("image/" + IMAGE_FORMAT);
	}

	protected BarCodeAttributes getBarcodeAttributes() {
		BarCodeAttributes res = new BarCodeAttributes();
		res.code = getStringParameterValue("code", "", 0);
		return res;
	}

	public static class BarCodeAttributes {
		public String code;
		public int dotWidth = 2;
		public int dotHeight =  dotWidth*3;
		public int format = BarCode2D.PDF417_INVERT_BITMAP;
	}

}


text:
/**
 * modified by badqiu (badqiu(a)gmail.com)
 * blog: http://badqiu.javaeye.com
 * Project Home: http://code.google.com/p/rapid-validation/
 * Rapid Framework Project Home: http://code.google.com/p/rapid-framework/
 * Version 1.5.1
 */

/*
 * Really easy field validation with Prototype
 * http://tetlaw.id.au/view/blog/really-easy-field-validation-with-prototype
 * Andrew Tetlaw
 * Version 1.5.3 (2006-07-15)
 *
 * Copyright (c) 2006 Andrew Tetlaw
 * http://www.opensource.org/licenses/mit-license.php
 */

var ValidationDefaultOptions = function(){};
ValidationDefaultOptions.prototype = {
	onSubmit : true, //ÊÇ·ñ¼àÌýformµÄsubmit'þ
	onReset : true, //ÊÇ·ñ¼àÌýformµÄreset'þ
	stopOnFirst : false, //±íµ¥Ñé֤ʱͣÁôÔÚµÚÒ»¸öÑéÖ¤µÄµØ·½,²»¼ÌÐøÑéÖ¤ÏÂÈ¥
	immediate : false, //ÊÇ·ñʵʱ¼ì²éÊý¾ÝµÄºÏ·¨ÐÔ
	focusOnError : true, //ÊÇ·ñ³ö´íʱ½«¹â±êÖ¸ÕëÒƵ½³ö´íµÄÊäÈë¿òÉÏ
	useTitles : false, //ÊÇ·ñʹÓÃinputµÄtitleÊôÐÔ×÷Ϊ³ö´íʱµÄÌáʾÐÅÏ¢
	onFormValidate : function(result, form) {return result;},//FormÑé֤ʱµÄ»Øµ÷º¯Êý,¿ÉÒÔÐÞ¸Ä×îÖյķµ»Ø½á¹û
	onElementValidate : function(result, elm) {} //ij¸öinputÑé֤ʱµÄ»Øµ÷º¯Êý
}

var ValidatorDefaultOptions = function(){}
ValidatorDefaultOptions.prototype = {
	ignoreEmptyValue : true, //ÊÇ·ñºöÂÔ¿ÕÖµ
	depends : [] //Ïà¹ØÒÀÀµÏî
}

//compatible with prototype
if(typeof Prototype != 'undefined' && (typeof $ != 'undefined')) {
	$prototype = $;
}

Validator = Class.create();

Validator.messageSource = {};
Validator.messageSource['en-us'] = [
	['validation-failed' , 'Validation failed.'],
	['required' , 'This is a required field.'],
	['validate-number' , 'Please enter a valid number in this field.'],
	['validate-digits' , 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.'],
	['validate-alpha' , 'Please use letters only (a-z) in this field.'],
	['validate-alphanum' , 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.'],
	['validate-email' , 'Please enter a valid email address. For example fred@domain.com .'],
	['validate-url' , 'Please enter a valid URL.'],
	['validate-currency-dollar' , 'Please enter a valid $ amount. For example $100.00 .'],
	['validate-one-required' , 'Please select one of the above options.'],
	['validate-integer' , 'Please enter a valid integer in this field'],
	['validate-pattern' , 'Validation failed.'],
	['validate-ip','Please enter a valid IP address'],
	['min-value' , 'min value is %s.'],
	['max-value' , 'max value is %s.'],
	['min-length' , 'min length is %s,current length is %s.'],
	['max-length' , 'max length is %s,current length is %s.'],
	['int-range' , 'Please enter integer value between %s and %s'],
	['float-range' , 'Please enter number between %s and %s'],
	['length-range' , 'Please enter value length between %s and %s,current length is %s'],
	['equals','Conflicting with above value.'],
	['less-than','Input value must be less than above value.'],
	['less-than-equal','Input value must be less than or equal above value.'],
	['great-than','Input value must be great than above value.'],
	['great-than-equal','Input value must be great than or equal above value.'],
	['validate-date' , 'Please use this date format: %s. For example %s.'],
	['validate-selection' , 'Please make a selection.'],
	['validate-file' , function(v,elm,args,metadata) {
		return ValidationUtils.format("Please enter file type in [%s]",[args.join(',')]);
	}],
	//ÖйúÌØÓеÄÏà¹ØÑéÖ¤ÌáʾÐÅÏ¢
	['validate-id-number','Please enter a valid id number.'],
	['validate-chinese','Please enter chinese'],
	['validate-phone','Please enter a valid phone number,current length is %s.'],
	['validate-mobile-phone','Please enter a valid mobile phone,For example 13910001000.current length is %s.'],
	['validate-zip','Please enter a valid zip code.'],
	['validate-qq','Please enter a valid qq number']
]

Validator.messageSource['en'] = Validator.messageSource['en-us']

Validator.messageSource['zh-cn'] = [
	['validation-failed' , 'Ñé֤ʧ°Ü.'],
	['required' , 'ÇëÊäÈëÖµ.'],
	['validate-number' , 'ÇëÊäÈëÓÐЧµÄÊý×Ö.'],
	['validate-digits' , 'ÇëÊäÈëÊý×Ö.'],
	['validate-alpha' , 'ÇëÊäÈëÓ¢ÎÄ×Öĸ.'],
	['validate-alphanum' , 'ÇëÊäÈëÓ¢ÎÄ×Öĸ»òÊÇÊý×Ö,ÆäËü×Ö·ûÊDz»ÔÊÐíµÄ.'],
	['validate-email' , 'ÇëÊäÈëÓÐЧµÄÓ'þµØÖ·,Èç username@example.com.'],
	['validate-url' , 'ÇëÊäÈëÓÐЧµÄURLµØÖ·.'],
	['validate-currency-dollar' , 'Please enter a valid $ amount. For example $100.00 .'],
	['validate-one-required' , 'ÔÚÇ°ÃæÑ¡ÏîÖÁÉÙÑ¡ÔñÒ»¸ö.'],
	['validate-integer' , 'ÇëÊäÈëÕýÈ·µÄÕûÊý'],
	['validate-pattern' , 'ÊäÈëµÄÖµ²»Æ¥Åä'],
	['validate-ip','ÇëÊäÈëÕýÈ·µÄIPµØÖ·'],
	['min-value' , '×îСֵΪ%s'],
	['max-value' , '×î´óֵΪ%s'],
	['min-length' , '×îС³¤¶ÈΪ%s,µ±Ç°³¤¶ÈΪ%s.'],
	['max-length', '×î´ó³¤¶ÈΪ%s,µ±Ç°³¤¶ÈΪ%s.'],
	['int-range' , 'ÊäÈëÖµÓ¦¸ÃΪ %s ÖÁ %s µÄÕûÊý'],
	['float-range' , 'ÊäÈëÖµÓ¦¸ÃΪ %s ÖÁ %s µÄÊý×Ö'],
	['length-range' , 'ÊäÈëÖµµÄ³¤¶ÈÓ¦¸ÃÔÚ %s ÖÁ %s Ö®¼ä,µ±Ç°³¤¶ÈΪ%s'],
	['equals','Á½´ÎÊäÈë²»Ò»ÖÂ,ÇëÖØÐÂÊäÈë'],
	['less-than','ÇëÊäÈëСÓÚÇ°ÃæµÄÖµ'],
	['less-than-equal','ÇëÊäÈëСÓÚ»òµÈÓÚÇ°ÃæµÄÖµ'],
	['great-than','ÇëÊäÈë´óÓÚÇ°ÃæµÄÖµ'],
	['great-than-equal','ÇëÊäÈë´óÓÚ»òµÈÓÚÇ°ÃæµÄÖµ'],
	['validate-date' , 'ÇëÊäÈëÓÐЧµÄÈÕÆÚ,¸ñʽΪ %s. ÀýÈç:%s.'],
	['validate-selection' , 'ÇëÑ¡Ôñ.'],
	['validate-file' , function(v,elm,args,metadata) {
		return ValidationUtils.format("ÎļþÀàÐÍÓ¦¸ÃΪ[%s]ÆäÖÐÖ®Ò»",[args.join(',')]);
	}],
	//ÖйúÌØÓеÄÏà¹ØÑéÖ¤ÌáʾÐÅÏ¢
	['validate-id-number','ÇëÊäÈëºÏ·¨µÄÉí·ÝÖ¤ºÅÂë'],
	['validate-chinese','ÇëÊäÈëÖÐÎÄ'],
	['validate-phone','ÇëÊäÈëÕýÈ·µÄµç»°ºÅÂë,Èç:010-29392929,µ±Ç°³¤¶ÈΪ%s.'],
	['validate-mobile-phone','ÇëÊäÈëÕýÈ·µÄÊÖ»úºÅÂë,µ±Ç°³¤¶ÈΪ%s.'],
	['validate-zip','ÇëÊäÈëÓÐЧµÄÓÊÕþ±àÂë'],
	['validate-qq','ÇëÊäÈëÓÐЧµÄQQºÅÂë.']
]

ValidationUtils = {
	isVisible : function(elm) {
		while(elm && elm.tagName != 'BODY') {
			if(!$prototype(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getReferenceForm : function(elm) {
		while(elm && elm.tagName != 'BODY') {
			if(elm.tagName == 'FORM') return elm;
			elm = elm.parentNode;
		}
		return null;
	},
	getInputValue : function(elm) {
		var elm = $prototype(elm);
		if(elm.type.toLowerCase() == 'file') {
			return elm.value;
		}else {
			return $F(elm);
		}
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	format : function(str,args) {
		args = args || [];
		ValidationUtils.assert(args.constructor == Array,"ValidationUtils.format() arguement 'args' must is Array");
		var result = str
		for (var i = 0; i < args.length; i++){
			result = result.replace(/%s/, args[i]);
		}
		return result;
	},
	// ͨ¹ýclassname´«µÝµÄ²ÎÊý±ØÐëͨ¹ý'-'·Ö¸ô¸÷¸ö²ÎÊý
	// ·µ»ØÖµ°üº¬Ò»¸ö²ÎÊýsingleArgument,Àý:validate-pattern-/[a-c]/gi,singleArgumentֵΪ/[a-c]/gi
	getArgumentsByClassName : function(prefix,className) {
		if(!className || !prefix)
			return [];
		var pattern = new RegExp(prefix+'-(\\S+)');
		var matchs = className.match(pattern);
		if(!matchs)
			return [];
		var results = [];
		results.singleArgument = matchs[1];
		var args =  matchs[1].split('-');
		for(var i = 0; i < args.length; i++) {
			if(args[i] == '') {
				if(i+1 < args.length) args[i+1] = '-'+args[i+1];
			}else{
				results.push(args[i]);
			}
		}
		return results;
	},
	assert : function(condition,message) {
		var errorMessage = message || ("assert failed error,condition="+condition);
		if (!condition) {
			alert(errorMessage);
			throw new Error(errorMessage);
		}else {
			return condition;
		}
	},
	isDate : function(v,dateFormat) {
		var MONTH = "MM";
	   	var DAY = "dd";
	   	var YEAR = "yyyy";
		var regex = '^'+dateFormat.replace(YEAR,'\\d{4}').replace(MONTH,'\\d{2}').replace(DAY,'\\d{2}')+'$';
		if(!new RegExp(regex).test(v)) return false;

		var year = v.substr(dateFormat.indexOf(YEAR),4);
		var month = v.substr(dateFormat.indexOf(MONTH),2);
		var day = v.substr(dateFormat.indexOf(DAY),2);

		var d = new Date(ValidationUtils.format('%s/%s/%s',[year,month,day]));
		return ( parseInt(month, 10) == (1+d.getMonth()) ) &&
					(parseInt(day, 10) == d.getDate()) &&
					(parseInt(year, 10) == d.getFullYear() );
	},
	//document: http://ajaxcn.org/space/start/2006-05-15/2
	fireSubmit: function(form) {
	    var form = $prototype(form);
	    if (form.fireEvent) { //for ie
	    	if(form.fireEvent('onsubmit'))
	    		form.submit();
	    } else if (document.createEvent) { // for dom level 2
			var evt = document.createEvent("HTMLEvents");
	      	//true for can bubble, true for cancelable
	      	evt.initEvent('submit', false, true);
	      	form.dispatchEvent(evt);
	    }
 	},
 	getLanguage : function() {
 		var lang = null;
		if (typeof navigator.userLanguage == 'undefined')
			lang = navigator.language.toLowerCase();
		else
			lang = navigator.userLanguage.toLowerCase();
 		return lang;
 	},
 	getMessageSource : function() {
 		var lang = ValidationUtils.getLanguage();
 		var messageSource = Validator.messageSource['zh-cn'];
		if(Validator.messageSource[lang]) {
			messageSource = Validator.messageSource[lang];
		}

		var results = {};
		for(var i = 0; i < messageSource.length; i++) {
			results[messageSource[i][0]] = messageSource[i][1];
		}
		return results;
 	},
 	getI18nMsg : function(key) {
 		return ValidationUtils.getMessageSource()[key];
 	}
}

Validator.prototype = {
	initialize : function(className, test, options) {
		this.options = Object.extend(new ValidatorDefaultOptions(), options || {});
		this._test = test ? test : function(v,elm){ return true };
		this._error = ValidationUtils.getI18nMsg(className) ? ValidationUtils.getI18nMsg(className) : ValidationUtils.getI18nMsg('validation-failed');
		this.className = className;
		this._dependsTest = this._dependsTest.bind(this);
		this.testAndGetError = this.testAndGetError.bind(this);
		this.testAndGetDependsError = this.testAndGetDependsError.bind(this);
	},
	_dependsTest : function(v,elm) {
		if(this.options.depends && this.options.depends.length > 0) {
			var dependsResult = $A(this.options.depends).all(function(depend){
				return Validation.get(depend).test(v,elm);
			});
			return dependsResult;
		}
		return true;
	},
	test : function(v, elm) {
		if(!this._dependsTest(v,elm))
			return false;
		if(!elm) elm = {}
		var isEmpty = (this.options.ignoreEmptyValue && ((v == null) || (v.length == 0)));
		return  isEmpty || this._test(v,elm,ValidationUtils.getArgumentsByClassName(this.className,elm.className),this);
	},
	testAndGetDependsError : function(v,elm) {
		var depends = this.options.depends;
		if(depends && depends.length > 0) {
			var dependsError = null;
			for(var i = 0; i < depends.length; i++) {
				var dependsError = Validation.get(depends[i]).testAndGetError(v,elm);
				if(dependsError) return dependsError;
			}
		}
		return null;
	},
	testAndGetError : function(v, elm,useTitle) {
		var dependsError = this.testAndGetDependsError(v,elm);
		if(dependsError) return dependsError;

		if(!elm) elm = {}
		var isEmpty = (this.options.ignoreEmptyValue && ((v == null) || (v.length == 0)));
		var result = isEmpty || this._test(v,elm,ValidationUtils.getArgumentsByClassName(this.className,elm.className),this);
		if(!result) return this.error(v,elm,useTitle);
		return null;
	},
	error : function(v,elm,useTitle) {
		var args  = ValidationUtils.getArgumentsByClassName(this.className,elm.className);
		var error = this._error;
		if(typeof error == 'string') {
			if(v) args.push(v.length);
			error = ValidationUtils.format(this._error,args);
		}else if(typeof error == 'function') {
			error = error(v,elm,args,this);
		}else {
			alert('property "_error" must type of string or function,current type:'+typeof error+" current className:"+this.className);
		}
		if(!useTitle) useTitle = elm.className.indexOf('useTitle') >= 0;
		return useTitle ? ((elm && elm.title) ? elm.title : error) : error;
	}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend(new ValidationDefaultOptions(), options || {});
		this.form = $prototype(form);
		var formId =  ValidationUtils.getElmID($prototype(form));
		Validation.validations[formId] = this;
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.onReset) Event.observe(this.form,'reset',this.reset.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			var elements = $A(Form.getElements(this.form));
			for(var i = 0; i < elements.length; i++) {
				var input = elements[i];
				Event.observe(input, 'blur', function(ev) { Validation.validateElement(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			}
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = true;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			var elements = $A(Form.getElements(this.form));
			for(var i = 0; i < elements.length; i++) {
				var elm = elements[i];
				result = Validation.validateElement(elm,{useTitle : useTitles, onElementValidate : callback});
				if(!result) break;
			}
		} else {
			var elements = $A(Form.getElements(this.form));
			for(var i = 0; i < elements.length; i++) {
				var elm = elements[i];
				if(!Validation.validateElement(elm,{useTitle : useTitles, onElementValidate : callback})) {
					result = false;
				}
			}
		}

		if(!result && this.options.focusOnError) {
			var first = Form.getElements(this.form).findAll(function(elm){return $prototype(elm).hasClassName('validation-failed')})[0];
			if(first.select) first.select();
			first.focus();
		}
		return this.options.onFormValidate(result, this.form);
	},
	reset : function() {
		var elements = $A(Form.getElements(this.form))
		for(var i = 0; i < elements.length; i++)
			Validation.reset(elements[i]);
	}
}

Object.extend(Validation, {
	validateElement : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $prototype(elm);
		var cn = $A(elm.classNames());
		for(var i = 0; i < cn.length; i++) {
			var value = cn[i];
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			if(!test) return false;
		}
		return true;
	},
	newErrorMsgAdvice : function(name,elm,errorMsg) {
		var advice = '
' + errorMsg + '
'
		switch (elm.type.toLowerCase()) {
			case 'checkbox':
			case 'radio':
				var p = elm.parentNode;
				if(p) {
					new Insertion.Bottom(p, advice);
				} else {
					new Insertion.After(elm, advice);
				}
				break;
			default:
				new Insertion.After(elm, advice);
	    }
		advice = $prototype('advice-' + name + '-' + ValidationUtils.getElmID(elm));
		return advice;
	},
	showErrorMsg : function(name,elm,errorMsg) {
		var elm = $prototype(elm);
		if(typeof Tooltip != 'undefined') {
			if (!elm.tooltip) {
				elm.tooltip = new Tooltip(elm, {backgroundColor:"#FC9", borderColor:"#C96", textColor:"#000", textShadowColor:"#FFF"});
			}
			elm.tooltip.content = errorMsg;
		}else {
			var prop = Validation._getAdviceProp(name);
			var advice = Validation.getAdvice(name, elm);
			if(!elm[prop]) {
				if(!advice) {
					advice = Validation.newErrorMsgAdvice(name,elm,errorMsg);
				}
			}
			if(advice && !advice.visible()) {
				if(typeof Effect == 'undefined') {
					advice.style.display = '';
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			advice.innerHTML = errorMsg;
			elm[prop] = true;
		}

		elm.removeClassName('validation-passed');
		elm.addClassName('validation-failed');
	},
	hideErrorMsg : function(name,elm) {
		var elm = $prototype(elm);
		if(typeof Tooltip != 'undefined') {
			if (elm.tooltip) {
				elm.tooltip.stop();
				elm.tooltip = false;
			}
		}else {
			var prop = Validation._getAdviceProp(name);
			var advice = Validation.getAdvice(name, elm);
			if(advice && elm[prop]) {
				if(typeof Effect == 'undefined')
					advice.hide()
				else
					new Effect.Fade(advice, {duration : 1 });
			}
			elm[prop] = false;
		}

		elm.removeClassName('validation-failed');
		elm.addClassName('validation-passed');
	},
	_getAdviceProp : function(validatorName) {
		return '__advice'+validatorName;
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var errorMsg = null;
		if(ValidationUtils.isVisible(elm))
			errorMsg = v.testAndGetError(ValidationUtils.getInputValue(elm),elm,useTitle);
		if(errorMsg) {
			Validation.showErrorMsg(name,elm,errorMsg);
			return false;
		} else {
			Validation.hideErrorMsg(name,elm);
			return true;
		}
	},
	getAdvice : function(name, elm) {
		return $prototype('advice-' + name + '-' + ValidationUtils.getElmID(elm)) || $prototype('advice-' + ValidationUtils.getElmID(elm));
	},
	reset : function(elm) {
		elm = $prototype(elm);
		var cn = $A(elm.classNames());
		for(var i = 0; i < cn.length; i++) {
			var value = cn[i];
			var prop = Validation._getAdviceProp(value);
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		}
	},
	add : function(className, test, options) {
		var nv = {};
		var testFun = test;
		if(test instanceof RegExp)
			testFun = function(v,elm,args,metadata){ return test.test(v); }
		nv[className] = new Validator(className, testFun, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var validators = $A(validators);
		for(var i = 0; i < validators.length; i++) {
			var value = validators[i];
			Validation.add(value[0], value[1], (value.length > 2 ? value[2] : {}));
		}
	},
	get : function(name) {
		var resultMethodName;
		for(var methodName in Validation.methods) {
			if(name == methodName) {
				resultMethodName = methodName;
				break;
			}
			if(name.indexOf(methodName) >= 0) {
				resultMethodName = methodName;
			}
		}
		return Validation.methods[resultMethodName] ? Validation.methods[resultMethodName] : new Validator();
	},
	$ : function(formId) {
		return Validation.validations[formId];
	},
	methods : {},
	validations : {}
});

Validation.addAllThese([
	['required', function(v) {
				return !((v == null) || (v.length == 0) || /^[\s|\u3000]+$/.test(v));
			},{ignoreEmptyValue:false}],
	['validate-number', function(v) {
				return (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', function(v) {
				return !/[^\d]/.test(v);
			}],
	['validate-alphanum', function(v) {
				return !/\W/.test(v)
			}],
	['validate-one-required', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			},{ignoreEmptyValue : false}],

	['validate-digits',/^[\d]+$/],
	['validate-alphanum',/^[a-zA-Z0-9]+$/],
	['validate-alpha',/^[a-zA-Z]+$/],
	['validate-email',/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/],
	['validate-url',/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i],
	// [$]1[##][,###]+[.##]
	// [$]1###+[.##]
	// [$]0.##
	// [$].##
	['validate-currency-dollar',/^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/]
]);

//custom validate start

Validation.addAllThese([
	/**
	 * Usage : equals-$otherInputId
	 * Example : equals-username or equals-email etc..
	 */
	['equals', function(v,elm,args,metadata) {
				return $F(args[0]) == v;
			},{ignoreEmptyValue:false}],
	/**
	 * Usage : less-than-$otherInputId
	 */
	['less-than', function(v,elm,args,metadata) {
				if(Validation.get('validate-number').test(v) && Validation.get('validate-number').test($F(args[0])))
					return parseFloat(v) < parseFloat($F(args[0]));
				return v < $F(args[0]);
			}],
	/**
	 * Usage : less-than-equal-$otherInputId
	 */
	['less-than-equal', function(v,elm,args,metadata) {
				if(Validation.get('validate-number').test(v) && Validation.get('validate-number').test($F(args[0])))
					return parseFloat(v) <= parseFloat($F(args[0]));
				return v < $F(args[0]) || v == $F(args[0]);
			}],
	/**
	 * Usage : great-than-$otherInputId
	 */
	['great-than', function(v,elm,args,metadata) {
				if(Validation.get('validate-number').test(v) && Validation.get('validate-number').test($F(args[0])))
					return parseFloat(v) > parseFloat($F(args[0]));
				return v > $F(args[0]);
			}],
	/**
	 * Usage : great-than-equal-$otherInputId
	 */
	['great-than-equal', function(v,elm,args,metadata) {
				if(Validation.get('validate-number').test(v) && Validation.get('validate-number').test($F(args[0])))
					return parseFloat(v) >= parseFloat($F(args[0]));
				return v > $F(args[0]) || v == $F(args[0]);
			}],
	/*
	 * Usage: min-length-$number
	 * Example: min-length-10
	 */
	['min-length',function(v,elm,args,metadata) {
		return v.length >= parseInt(args[0]);
	}],
	/*
	 * Usage: max-length-$number
	 * Example: max-length-10
	 */
	['max-length',function(v,elm,args,metadata) {
		return v.length <= parseInt(args[0]);
	}],
	/*
	 * Usage: validate-file-$type1-$type2-$typeX
	 * Example: validate-file-png-jpg-jpeg
	 */
	['validate-file',function(v,elm,args,metadata) {
		return $A(args).any(function(extentionName) {
			return new RegExp('\\.'+extentionName+'$','i').test(v);
		});
	}],
	/*
	 * Usage: float-range-$minValue-$maxValue
	 * Example: -2.1 to 3 = float-range--2.1-3
	 */
	['float-range',function(v,elm,args,metadata) {
		return (parseFloat(v) >= parseFloat(args[0]) && parseFloat(v) <= parseFloat(args[1]))
	},{depends : ['validate-number']}],
	/*
	 * Usage: int-range-$minValue-$maxValue
	 * Example: -10 to 20 = int-range--10-20
	 */
	['int-range',function(v,elm,args,metadata) {
		return (parseInt(v) >= parseInt(args[0]) && parseInt(v) <= parseInt(args[1]))
	},{depends : ['validate-integer']}],
	/*
	 * Usage: length-range-$minLength-$maxLength
	 * Example: 10 to 20 = length-range-10-20
	 */
	['length-range',function(v,elm,args,metadata) {
		return (v.length >= parseInt(args[0]) && v.length <= parseInt(args[1]))
	}],
	/*
	 * Usage: max-value-$number
	 * Example: max-value-10
	 */
	['max-value',function(v,elm,args,metadata) {
		return parseFloat(v) <= parseFloat(args[0]);
	},{depends : ['validate-number']}],
	/*
	 * Usage: min-value-$number
	 * Example: min-value-10
	 */
	['min-value',function(v,elm,args,metadata) {
		return parseFloat(v) >= parseFloat(args[0]);
	},{depends : ['validate-number']}],
	/*
	 * Usage: validate-pattern-$RegExp
	 * Example: <input id='sex' class='validate-pattern-/^[fm]$/i'>
	 */
	['validate-pattern',function(v,elm,args,metadata) {
		return eval('('+args.singleArgument+'.test(v))');
	}],
	/*
	 * Usage: validate-ajax-$url
	 * Example: <input id='email' class='validate-ajax-http://localhost:8080/validate-email.jsp'>
	 */
	['validate-ajax',function(v,elm,args,metadata) {
		var form = ValidationUtils.getReferenceForm(elm);
		var params = (form ? Form.serialize(form) : Form.Element.serialize(elm));
		params += ValidationUtils.format("&what=%s&value=%s",[elm.name,encodeURIComponent(v)]);
		var request = new Ajax.Request(args.singleArgument,{
			parameters : params,
			asynchronous : false,
			method : "get"
		});

		var responseText = request.transport.responseText;
		if("" == responseText.strip()) return true;
		metadata._error = responseText;
		return false;
	}],
	/*
	 * Usage: validate-dwr-${service}.${method}
	 * Example: <input id='email' class='validate-dwr-service.method'>
	 */
	['validate-dwr',function(v,elm,args,metadata) {
		var result = false;
		var callback = function(methodResult) {
			if(methodResult)
				metadata._error = methodResult;
			else
				result = true;
		}
		var call = args.singleArgument+"('"+v+"',callback)";
		DWREngine.setAsync(false);
		eval(call);
		DWREngine.setAsync(true);
		return result;
	}],
	/*
	 * Usage: validate-buffalo-${service}.${method}
	 * Example: <input id='email' class='validate-buffalo-service.method'>
	 */
	['validate-buffalo',function(v,elm,args,metadata) {
		var result = false;
		var callback = function(reply) {
			if(replay.getResult())
				metadata._error = replay.getResult();
			else
				result = true;
		}
		if(!BUFFALO_END_POINT) alert('not found "BUFFALO_END_POINT" variable');
		var buffalo = new Buffalo(BUFFALO_END_POINT,false);
		buffalo.remoteCall(args.singleArgument,v,callback);
		return result;
	}],
	/*
	 * Usage: validate-date-$dateFormat or validate-date($dateFormat default is yyyy-MM-dd)
	 * Example: validate-date-yyyy/MM/dd
	 */
	['validate-date', function(v,elm,args,metadata) {
			var dateFormat = args.singleArgument || 'yyyy-MM-dd';
			metadata._error = ValidationUtils.format(ValidationUtils.getI18nMsg(metadata.className),[dateFormat,dateFormat.replace('yyyy','2006').replace('MM','03').replace('dd','12')]);
			return ValidationUtils.isDate(v,dateFormat);
		}],
	['validate-selection', function(v,elm,args,metadata) {
			return elm.options ? elm.selectedIndex > 0 : !((v == null) || (v.length == 0));
		}],
	['validate-integer',/^[-+]?[1-9]\d*$|^0$/],
	['validate-ip',/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/],

	//ÖйúÏà¹ØÑéÖ¤¿ªÊ¼
	['validate-id-number',function(v,elm,args,metadata) {
		if(!(/^\d{17}(\d|x)$/i.test(v) || /^\d{15}$/i.test(v))) return false;
		var provinceCode = parseInt(v.substr(0,2));
		if((provinceCode < 11) || (provinceCode > 91)) return false;
		var forTestDate = v.length == 18 ? v : v.substr(0,6)+"19"+v.substr(6,15);
		var birthday = forTestDate.substr(6,8);
		if(!ValidationUtils.isDate(birthday,'yyyyMMdd')) return false;
		if(v.length == 18) {
			v = v.replace(/x$/i,"a");
			var verifyCode = 0;
			for(var i = 17;i >= 0;i--)
            	verifyCode += (Math.pow(2,i) % 11) * parseInt(v.charAt(17 - i),11);
            if(verifyCode % 11 != 1) return false;
		}
		return true;
	}],
	['validate-chinese',/^[\u4e00-\u9fa5]+$/],
	['validate-phone',/^((0[1-9]{3})?(0[12][0-9])?[-])?\d{6,8}$/],
	['validate-mobile-phone',/(^0?[1][358][0-9]{9}$)/],
	['validate-zip',/^[1-9]\d{5}$/],
	['validate-qq',/^[1-9]\d{4,8}$/]
]);

Validation.autoBind = function() {
	 var forms = $A(document.getElementsByClassName('required-validate'));
	 for(var i = 0; i < forms.length; i++) {
	 	var form = forms[i];
	 	var validation = new Validation(form,{immediate:true,useTitles:true,stopOnFirst:true});
		Event.observe(form,'reset',function() {validation.reset();},false);
	 }
};

Event.observe(window,'load',Validation.autoBind,false);


text:
package org.ovirt.engine.core.config.entity.helper;

import java.util.Arrays;
import java.util.Collection;

import org.apache.commons.collections.CollectionUtils;
import org.ovirt.engine.core.config.EngineConfigCLIParser;
import org.ovirt.engine.core.config.entity.ConfigKey;

/**
 * This helper validates multiple values from the allowed
 * values list. Given Values should be comma separated.
 *
 */
public class StringMultipleValueHelper extends BaseValueHelper {

    @Override
    public String getValue(String value) {
        return value;
    }

    @Override
    public String setValue(String value) {
        return value;
    }

    @Override
    public ValidationResult validate(ConfigKey key, String value) {

        Collection<String> validValues = key.getValidValues();

        boolean isValid = false;
        if (validValues.isEmpty() || value.equals("")) {
            isValid = true;
        } else {
            isValid = CollectionUtils.isSubCollection(Arrays.asList(value.split(",")), validValues);
        }
        return new ValidationResult(isValid);
    }

    @Override
    public void setParser(EngineConfigCLIParser parser) {
        // NOP
    }

    @Override
    public String getHelpNote(ConfigKey key) {
        return getHelpNoteByType(key, "a comma delimited subset of any of the possible values");
    }

}


text:
class Cafe < Formula
  desc "Computational Analysis of gene Family Evolution"
  homepage "https://hahnlab.github.io/CAFE/"
  url "https://github.com/hahnlab/CAFE/archive/v4.2.1.tar.gz"
  sha256 "c9f0bdb9071105c1d23162f355632cab1a017e5798b95042b86c04bae86ff4aa"
  version "4.2.1"

  depends_on "gcc"
  depends_on "autoconf" => :build
  depends_on "automake" => :build

  def install
    inreplace "cafe/cafe_commands.cpp",
      "std::abs",
      "fabs"
    system "autoreconf -i configure.ac"
    system "./configure", "--disable-debug",
                          "--disable-dependency-tracking",
                          "--disable-silent-rules",
                          "--prefix=#{prefix}"
    system "make"
    bin.install "release/cafe"
  end
  test do
      system "#{bin}/cafe"
  end
end


text:
class Features::Passenger < Feature
  DEFAULT_GEM_VERSION = "3.0.4"

  attr_accessor :gem_version, :max_pool_size

  def initialize(options={})
    super(options)
    self.gem_version ||= DEFAULT_GEM_VERSION

    self.max_pool_size ||= default_max_pool_size
  end

  def create_dependencies
    depends_on :packages => {
                 :names => %w[apache2-prefork-dev libapr1-dev libaprutil1-dev
                              libcurl4-openssl-dev],
               }
    depends_on :ruby_gem => {
                 :name => :passenger,
                 :version => gem_version
               }
    depends_on :file => {
                 :name => '/etc/apache2/mods-enabled/passenger.conf',
                 :owner => :root, :group => :root, :mode => 0644,
                 :source => "passenger/passenger.conf.erb",
                 :erb => { :passenger_version => gem_version,
                           :passenger_ruby_version => default_ruby_version,
                           :max_pool_size => max_pool_size,
                          }
               },
               :do_after => self
  end

  def done?
    File.exist? "#{gem_path}/ext/apache2/mod_passenger.so"
  end

  def apply
    execute("rvm #{default_ruby_version} --passenger", :context => rvm)

    execute("/usr/local/rvm/gems/#{default_ruby_version}" +
            "/gems/passenger-#{gem_version}/bin" +
            "/passenger-install-apache2-module --auto",
            :context => rvm)
  end

  def gem_path
    "/usr/local/rvm/gems/#{default_ruby_version}" +
      "/gems/passenger-#{gem_version}"
  end

  def default_ruby_version
    @default_ruby ||= rvm.default_ruby_version
  end

  def default_max_pool_size
    @default_max_pool_size ||= begin
      # How many instances should Passenger run, max?
      # ((total_mem in MB) - (mem for Mysql) - (mem for Redis)) / (60MB/instance)
      # eg (768 - 100 - 50) / 60 = 5
      mysql_present = !find_feature(:mysql_server, :anything).nil?
      redis_present = !find_feature(:redis, :anything).nil?
      memory = /(\d+)/.match(execute("grep MemTotal /proc/meminfo").output)[1].to_i / 1024
      memory -= 100 if mysql_present
      memory -= 50 if redis_present
      instances = memory / 60 # assume each Rails instance costs 100MB
      instances = 2 if instances < 2
      log(:info, "Using calculated max_pool_size = #{instances} (redis=#{redis_present.inspect}, mysql=#{mysql_present.inspect}")
      instances
    end
  end

  def rvm
    @rvm ||= find_feature(:rvm, :anything)
  end
end


text:
Hazmat
======

About
-----
Hazmat is a namespace injection tool for Microsoft library (.lib) files. It also has an obfuscation mode that can change
symbol names without destroying the functionality of the library.

It's primary purpose is to resolve name conflicts between static libraries that share a common base that may change over time.
It also can be used to hide sensitive IP that may be revealed by symbol names.

For every internally defined symbol it can obfuscate the symbol or "nest" it into a namespace. Hazmat also has a method for excluding functions which will be accessed externally.
This can be used to obfuscate a libraries symbol names but still expose a public interface.

Compiling
---------
A Visual Studio 2010 sln file "hazmat.sln" is included for building the executable. It has been tested in Debug and Release
builds for Win32.

Usage
-----
To nest all symbols in original.lib into the namespace ABC
`hazmat /IN:original.lib /OUT:output.lib /NEST:ABC /X:none`

To nest all symbols into ABC, but exclude two symbols by manged name
`hazmat /IN:original.lib /OUT:output.lib /NEST:ABC /XM:?mangledcplus@name@@abcdefg,?anothermangled@name@@abcdefg`

To nest all symbols into ABC, but exclude two based on substring match
`hazmat /IN:original.lib /OUT:output.lib /NEST:ABC /X:MyEngineClass,MyPublicAllocatorNamespace`

To obfuscate all the symbols in original lib
`hazmat /IN:original.lib /OUT:output.lib /OBFS`

To obfuscate all the symbols, and nest the obfuscated symbols into a namespace but still expose public namespaces or classes
`hazmat /IN:original.lib /OUT:output.lib /OBFS /NEST:ABC /X:PublicInterfaceClass,PublicFactoryNamespace`

Notes
-----
Hazmat may not work properly on libraries built with whole program optimization enabled. There are no guarantees that
even the Microsoft library tools will work on libs built with /GL. For more information on this limitation and how
/GL effects static libraries visit [MSDN /GL (Whole Program Optimization)][1]

License
-------
Hazmat is distributed under the BSD License. See the file LICENSE.md for full license information.
Copyright (c) 2012 iZotope Inc.

[1]: http://msdn.microsoft.com/en-us/library/0zza0de8(v=VS.100).aspx


text:
defaults write com.apple.screencapture location ~/Documents/Screenshots/     # change scresnshot dir
defaults write com.apple.Terminal AppleShowScrollBars -string WhenScrolling  # no scrollbar in mac terminal
defaults write -g ApplePressAndHoldEnabled -bool false                       # enable key repeat
sudo nvram SystemAudioVolume="%00"                                           # no boot bell
defaults write com.apple.universalaccess reduceTransparency -bool true       # disable transparency
defaults write NSGlobalDomain NSTableViewDefaultSizeMode -int 2              # medium sidebar icon size
defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false  # save to disk instead of iCloud by default
defaults write com.apple.print.PrintingPrefs "Quit When Finished" -bool true # quit printer app after print
# defaults write com.apple.LaunchServices LSQuarantine -bool false  # disable "Are you sure you want to open this app" thing
defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking -int 1 # use tap instead of click on trackpad
defaults -currentHost write NSGlobalDomain com.apple.mouse.tapBehavior -int 1     # use tap instead of click on trackpad
defaults write NSGlobalDomain com.apple.mouse.tapBehavior -int 1                  # use tap instead of click on trackpad
defaults write NSGlobalDomain KeyRepeat -int 1                                    # key repeat speed
defaults write NSGlobalDomain InitialKeyRepeat -int 15                            # initial key repeat delay
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true      # no .DS_Store on network devices
defaults write com.apple.desktopservices DSDontWriteUSBStores -bool true          # no .DS_Store on USB storage
defaults write com.apple.finder FXDefaultSearchScope -string "SCcf"               # search current dir in finder by default
defaults write com.apple.finder FXPreferredViewStyle -string "Nlsv"               # set listview as preferred view in finder
defaults write com.apple.dock tilesize -int 20                                    # smaller dock icons
defaults write com.apple.dock mouse-over-hilite-stack -bool false                 # no highlight effect on docker grid view
defaults write com.apple.dock minimize-to-application -bool false                 # minimise to individual app spots
defaults write com.apple.dashboard mcx-disabled -bool true                        # disable dashboard
defaults write com.apple.dock dashboard-in-overlay -bool true                     # do not show dashboard as a space
defaults write com.apple.dock mru-spaces -bool false                              # do not rearrange spaces based on recently used
defaults write com.apple.dock autohide -bool true                                 # automatically show and hide dock
defaults write com.apple.dock showhidden -bool true                               # made hidden app icons translucent in dock
defaults write com.apple.dock show-recents -bool false                            # do not show recent apps in dock
defaults write com.apple.ActivityMonitor IconType -int 5                          # show cpu usage in activity monitor icon

# Setup macOS hot corners
# 0:no-op 2:Mission Control 3:Show application windows 4:Desktop
# 5:Start screen saver 6:Disable screen saver 7:Dashboard
# 10:Sleep display 11:Launchpad 12:Notification Center 13:Lock Screen
defaults write com.apple.dock wvous-tl-corner -int 2 # top-left
defaults write com.apple.dock wvous-tl-modifier -int 0
defaults write com.apple.dock wvous-tr-corner -int 2 # top-right
defaults write com.apple.dock wvous-tr-modifier -int 0

if test ! "$(which brew)"; then
	echo "Installing homebrew"
	ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi
prepare-list() {sed 's/\s*#.*//g; /^$/d' "$1"}
prepare-list ./brew.packages | xargs -n1 brew install
prepare-list ./brew-cask.packages | xargs -n1 brew install --cask
prepare-list ./node.packages | xargs -n1 npm i -g
prepare-list ./python3.packages | xargs -n1 pip3 install
prepare-list ./go.packages | xargs -n go get -vu
prepare-list ./tlmgr.packages | xargs -n1 sudo tlmgr install
prepare-list ./dasht.packages | xargs -n1 dasht-docsets-install -f

# Setup rust using rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup component add rust-src
prepare-list ./cargo.packages | xargs -n1 cargo install

# install vim-plug
curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs \
	https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

# Setup hammerspoon init file to be under .config dir
defaults write org.hammerspoon.Hammerspoon MJConfigFile "$HOME/.config/hammerspoon/init.lua"

# enable `at` (https://superuser.com/questions/43678/mac-os-x-at-command-not-working)
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.atrun.plist


text:
package net.tridb.core

case class Athlete(uid : String, name : String)


text:
using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Query;
using UltimateWorkflowToolkit.Common;

namespace UltimateWorkflowToolkit.CoreOperations.Security
{
    public class IsUserMemberOfTeam: CrmWorkflowBase
    {
        #region Input/Output Parameters

        [Input("User")]
        [RequiredArgument]
        [ReferenceTarget("systemuser")]
        public InArgument<EntityReference> User { get; set; }

        [Input("Team")]
        [RequiredArgument]
        [ReferenceTarget("team")]
        public InArgument<EntityReference> Team { get; set; }

        [Output("Is Member")]
        public OutArgument<bool> IsMember { get; set; }

        #endregion Input/Output Parameters

        protected override void ExecuteWorkflowLogic()
        {
            var userQuery = new QueryExpression("systemuser")
            {
                ColumnSet = new ColumnSet(false)
            };
            userQuery.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, User.Get(Context.ExecutionContext).Id);

            var teamLink = userQuery.AddLink("teammembership", "systemuserid", "systemuserid");
            teamLink.LinkCriteria.AddCondition("teamid", ConditionOperator.Equal, Team.Get(Context.ExecutionContext).Id);

            var isMember = Context.SystemService.RetrieveMultiple(userQuery).Entities.Count != 0;

            IsMember.Set(Context.ExecutionContext, isMember);
        }
    }
}


text:
var GINK = GINK || {};

GINK.EditorScreen = function ($) {
    var that = this,
        level,
        currentTool,
        currentAction,
        editObj,
        ctx = $.canvasContext;

    this.setLevel = function (l) {
        level = l;
    };

    this.draw = function () {
        var i,
            levelObjects;

        ctx.fillStyle = '#000000';
        ctx.fillRect(0, 0, $.SCREEN_WIDTH, $.SCREEN_HEIGHT);

        levelObjects = level.getObjects();
        for (i = 0; i < levelObjects.length; i++) {
            levelObjects[i].draw(ctx);
        }
        if (editObj !== null && editObj !== undefined && editObj.draw !== undefined) {
            editObj.draw(ctx, "#00a9a9");
        }
    };

    this.toolBoxChange = function (obj) {
        currentTool = obj.tool;
        if (currentTool === 'player') {
            editObj = level.getPlayer();
        } else if (currentTool === 'platform') {
            editObj = level.getNextPlatform();
        }
        that.draw();
    };

    this.actionBarChange = function (obj) {
        currentAction = obj.action;
        if (currentAction === 'new') {
            if (currentTool === 'platform') {
                editObj = new $.Platform($);
                level.addPlatform(editObj);
            }
        }
        that.draw();
    };

    this.keyEventListener = function () {
        var CTRL = 17,
            LEFT = 37,
            UP = 38,
            RIGHT = 39,
            DOWN = 40,
            DELETE = 46;

        if (isPressed(CTRL) && isPressed(RIGHT) && currentAction === 'edit') {
            editObj.incSize();
            that.draw();
            return;
        }

        if (isPressed(CTRL) && isPressed(LEFT) && currentAction === 'edit') {
            editObj.decSize();
            that.draw();
            return;
        }

        if (isPressed(RIGHT) && currentAction === 'edit') {
            editObj.incX();
            that.draw();
            return;
        }

        if (isPressed(LEFT) && currentAction === 'edit') {
            editObj.decX();
            that.draw();
            return;
        }

        if (isPressed(UP) && currentAction === 'edit') {
            editObj.decY();
            that.draw();
            return;
        }

        if (isPressed(DOWN) && currentAction === 'edit') {
            editObj.incY();
            that.draw();
            return;
        }

        if (isPressed(DELETE) && currentAction === 'edit') {
            level.removePlatform(editObj);
            editObj = level.getFirstPlatform();
            that.draw();
            $.actionBar.resetAction();
            return;
        }

        if (isPressed(RIGHT) && currentAction === 'select') {
            editObj = level.getNextPlatform(editObj);
            that.draw();
            return;
        }

        if (isPressed(LEFT) && currentAction === 'select') {
            editObj = level.getPreviousPlatform(editObj);
            that.draw();
            return;
        }

    };

    var isPressed = function (key) {
        return ($.keypressList.indexOf(key) !== -1);
    };

};