text:
import h2o, h2o_cmd, re, os
import h2o_print as h2p
import getpass, time

#****************************************************************************************
# hdfs/maprfs/s3/s3n paths should be absolute from the bucket (top level)
# so only walk around for local
# using this standalone, we probably want 'put' decision making by default (can always pass schema='local')
def find_folder_and_filename(bucket, pathWithRegex, schema='put', returnFullPath=False):
    checkPath = True
    # strip the common mistake of leading "/" in path, if bucket is specified too
    giveUpAndSearchLocally = False
    if bucket is not None and re.match("/", pathWithRegex):
        h2o.verboseprint("You said bucket:", bucket, "so stripping incorrect leading '/' from", pathWithRegex)
        pathWithRegex = pathWithRegex.lstrip('/')

    if bucket is None:  # good for absolute path name
        bucketPath = ""

    elif bucket == ".":
        bucketPath = os.getcwd()

    # only use if the build_cloud was for remote H2O
    # Never use the var for remote, if you're doing a put! (which always sources local)
    elif h2o.nodes[0].remoteH2O and schema!='put' and \
        (os.environ.get('H2O_REMOTE_BUCKETS_ROOT') or h2o.nodes[0].h2o_remote_buckets_root):
        if (bucket=='smalldata' or bucket=='datasets') and schema=='local':
            msg1 = "\nWARNING: you're using remote nodes, and 'smalldata' or 'datasets' git buckets, with schema!=put"
            msg2 = "\nThose aren't git pull'ed by the test. Since they are user-maintained, not globally-maintained-by-0xdata,"
            msg3 = "\nthey may be out of date at those remote nodes?"
            msg4 = "\nGoing to assume we find a path to them locally, and remote path will be the same"
            h2p.red_print(msg1, msg2, msg3, msg4)
            giveUpAndSearchLocally = True
        else:
            if os.environ.get('H2O_REMOTE_BUCKETS_ROOT'):
                rootPath = os.environ.get('H2O_REMOTE_BUCKETS_ROOT')
                print "Found H2O_REMOTE_BUCKETS_ROOT:", rootPath
            else:
                rootPath = h2o.nodes[0].h2o_remote_buckets_root
                print "Found h2o_nodes[0].h2o_remote_buckets_root:", rootPath

            bucketPath = os.path.join(rootPath, bucket)
            checkPath = False

    # does it work to use bucket "." to get current directory
    # this covers reote with put too
    elif os.environ.get('H2O_BUCKETS_ROOT'):
        rootPath = os.environ.get('H2O_BUCKETS_ROOT')
        print "Using H2O_BUCKETS_ROOT environment variable:", rootPath

        if not (os.path.exists(rootPath)):
            raise Exception("H2O_BUCKETS_ROOT in env but %s doesn't exist." % rootPath)

        bucketPath = os.path.join(rootPath, bucket)
        if not (os.path.exists(bucketPath)):
            raise Exception("H2O_BUCKETS_ROOT and path used to form %s which doesn't exist." % bucketPath)

    else:
        giveUpAndSearchLocally = True

    #******************************************************************************************
    if giveUpAndSearchLocally:
        # if we run remotely, we're assuming the import folder path on the remote machine
        # matches what we find on our local machine. But maybe the local user doesn't exist remotely
        # so using his path won't work.
        # Resolve by looking for special state in the config. If user = 0xdiag, just force the bucket location
        # This is a lot like knowing about fixed paths with s3 and hdfs
        # Otherwise the remote path needs to match the local discovered path.

        # want to check the username being used remotely first. should exist here too if going to use
        username = getpass.getuser()
        h2oUsername = h2o.nodes[0].username
        h2o.verboseprint("username:", username, "h2oUsername:", h2oUsername)

        # bucket named "datasets" is special. Don't want to find it in /home/0xdiag/datasets
        # needs to be the git clone 'datasets'. Find it by walking upwards below
        # disable it from this looking in home dir. Could change priority order?
        # resolved in order, looking for bucket (ln -s will work) in these home dirs.

        if bucket=='datasets': # special case
            possibleUsers = []
        elif h2oUsername != username:
            possibleUsers = [username, h2oUsername, "0xdiag"]
        else:
            possibleUsers = [username, "0xdiag"]

        for u in possibleUsers:
            rootPath = os.path.expanduser("~" + u)
            bucketPath = os.path.join(rootPath, bucket)
            h2o.verboseprint("Checking bucketPath:", bucketPath, 'assuming home is', rootPath)
            if os.path.exists(bucketPath):
                h2o.verboseprint("search A did find", bucket, "at", rootPath)
                break
        else:
            # last chance to find it by snooping around
            rootPath = os.getcwd()
            h2o.verboseprint("find_bucket looking upwards from", rootPath, "for", bucket)
            # don't spin forever
            levels = 0
            while not (os.path.exists(os.path.join(rootPath, bucket))):
                h2o.verboseprint("Didn't find", bucket, "at", rootPath)
                rootPath = os.path.split(rootPath)[0]
                levels += 1
                if (levels==6):
                    raise Exception("unable to find bucket: %s. Maybe missing link in /home/0xdiag or /home/0xcustomer or jenkins ~? or whatever user is running the python or the h2o?" % bucket)

            h2o.verboseprint("search B did find", bucket, "at", rootPath)
            bucketPath = os.path.join(rootPath, bucket)

    #******************************************************************************************
    # if there's no path, just return the bucketPath
    # but what about cases with a header in the folder too? (not putfile)
    if pathWithRegex is None:
        if returnFullPath:
            return bucketPath
        else:
            return (bucketPath, None)

    # if there is a "/" in the path, that means it's not just a pattern
    # split it
    # otherwise it is a pattern. use it to search for files in python first?
    # FIX! do that later
    elif "/" in pathWithRegex:
        (head, tail) = os.path.split(pathWithRegex)
        folderPath = os.path.abspath(os.path.join(bucketPath, head))

        # accept all 0xcustomer-datasets without checking..since the current python user
        # may not have permission, but h2o will
        # try a couple times with os.stat in between, in case it's not automounting
        if '/mnt/0xcustomer-datasets' in folderPath:
            pass
        else:
            retry = 0
            while checkPath and (not os.path.exists(folderPath)) and retry<5:
                # we can't stat an actual file, because we could have a regex at the end of the pathname
                print "Retrying", folderPath, "in case there's a autofs mount problem"
                os.stat(folderPath)
                retry += 1
                time.sleep(1)

            if checkPath and not os.path.exists(folderPath):
                raise Exception("%s doesn't exist. %s under %s may be wrong?" % (folderPath, head, bucketPath))
    else:
        folderPath = bucketPath
        tail = pathWithRegex

    h2o.verboseprint("folderPath:", folderPath, "tail:", tail)

    if returnFullPath:
        return os.path.join(folderPath, tail)
    else:
        return (folderPath, tail)

#***************************************************************************yy
# passes additional params thru kwargs for parse
# use_header_file=
# header=
# exclude=
# src_key= only used if for put file key name (optional)
# path should point to a file or regex of files. (maybe folder works? but unnecessary
def import_only(node=None, schema='local', bucket=None, path=None,
    timeoutSecs=30, retryDelaySecs=0.5, initialDelaySecs=0.5, pollTimeoutSecs=180, noise=None,
    benchmarkLogging=None, noPoll=False, doSummary=True, src_key=None, noPrint=False,
    importParentDir=True, **kwargs):

    if src_key and schema!='put':
        raise Exception("can only specify a 'src_key' param for schema='put'. You have %s %s" % (schema, src_key))

    # no bucket is sometimes legal (fixed path)
    if not node: node = h2o.nodes[0]

    if path is None:
        raise Exception("import_only: path parameter needs to be specified")

    if "/" in path:
        (head, pattern) = os.path.split(path)
    else:
        (head, pattern)  = ("", path)

    h2o.verboseprint("head:", head)
    h2o.verboseprint("pattern:", pattern)

    # to train users / okay here
    # normally we import the folder above, but if we import exactly, the path can't have regex
    # the folder can't have regex in any case
    if importParentDir:
        if re.search(r"[\*<>{}[\]~`]", head):
           raise Exception("h2o folder path %s can't be regex. path= was %s" % (head, path))
    else:
        if re.search(r"[\*<>{}[\]~`]", path):
           raise Exception("h2o path %s can't be regex. path= was %s" % (head, path))

    if schema=='put':
        # to train users
        if re.search(r"[/\*<>{}[\]~`]", pattern):
           raise Exception("h2o putfile basename %s can't be regex. path= was %s" % (pattern, path))

        if not path:
            raise Exception("path= didn't say what file to put")

        (folderPath, filename) = find_folder_and_filename(bucket, path, schema)
        filePath = os.path.join(folderPath, filename)
        h2o.verboseprint("put filename:", filename, "folderPath:", folderPath, "filePath:", filePath)

        if not noPrint:
            h2p.green_print("\nimport_only:", h2o.python_test_name, "uses put:/%s" % filePath)
            h2p.green_print("Local path to file that will be uploaded: %s" % filePath)
            h2p.blue_print("That path resolves as:", os.path.realpath(filePath))

        if h2o.abort_after_import:
            raise Exception("Aborting due to abort_after_import (-aai) argument's effect in import_only()")

        key = node.put_file(filePath, key=src_key, timeoutSecs=timeoutSecs)
        return (None, key)

    if schema=='local' and not \
            (node.redirect_import_folder_to_s3_path or node.redirect_import_folder_to_s3n_path):
        (folderPath, pattern) = find_folder_and_filename(bucket, path, schema)
        filePath = os.path.join(folderPath, pattern)
        h2p.green_print("\nimport_only:", h2o.python_test_name, "uses local:/%s" % filePath)
        h2p.green_print("Path h2o will be told to use: %s" % filePath)
        h2p.blue_print("If local jvms, path resolves locally as:", os.path.realpath(filePath))
        if h2o.abort_after_import:
            raise Exception("Aborting due to abort_after_import (-aai) argument's effect in import_only()")

        folderURI = 'nfs:/' + folderPath
        if importParentDir:
            importResult = node.import_files(folderPath, timeoutSecs=timeoutSecs)
        else:
            importResult = node.import_files(folderPath + "/" + pattern, timeoutSecs=timeoutSecs)

    else:
        if bucket is not None and re.match("/", head):
            h2o.verboseprint("You said bucket:", bucket, "so stripping incorrect leading '/' from", head)
            head = head.lstrip('/')

        # strip leading / in head if present
        if bucket and head!="":
            folderOffset = bucket + "/" + head
        elif bucket:
            folderOffset = bucket
        else:
            folderOffset = head

        print "\nimport_only:", h2o.python_test_name, schema, "uses", schema + "://" + folderOffset + "/" + pattern
        if h2o.abort_after_import:
            raise Exception("Aborting due to abort_after_import (-aai) argument's effect in import_only()")

        n = h2o.nodes[0]
        if schema=='s3' or node.redirect_import_folder_to_s3_path:
            folderURI = "s3://" + folderOffset
            if not n.aws_credentials:
                print "aws_credentials: %s" % n.aws_credentials
                # raise Exception("Something was missing for s3 on the java -jar cmd line when the cloud was built")
                print "ERROR: Something was missing for s3 on the java -jar cmd line when the cloud was built"

            # FIX. using the import_hdfs method here but since it's beta_features it's the common import2?
            if h2o.beta_features:
                if importParentDir:
                    importResult = node.import_hdfs(folderURI, timeoutSecs=timeoutSecs)
                else:
                    importResult = node.import_hdfs(folderURI + "/" + pattern, timeoutSecs=timeoutSecs)
            else:
                importResult = node.import_s3(bucket, timeoutSecs=timeoutSecs)

        elif schema=='s3n' or node.redirect_import_folder_to_s3n_path:
            if not (n.use_hdfs and ((n.hdfs_version and n.hdfs_name_node) or n.hdfs_config)):
                print "use_hdfs: %s hdfs_version: %s hdfs_name_node: %s hdfs_config: %s" % \
                    (n.use_hdfs, n.hdfs_version, n.hdfs_name_node, n.hdfs_config)
                # raise Exception("Something was missing for s3n on the java -jar cmd line when the cloud was built")
                print "ERROR: Something was missing for s3n on the java -jar cmd line when the cloud was built"
            folderURI = "s3n://" + folderOffset
            if importParentDir:
                importResult = node.import_hdfs(folderURI, timeoutSecs=timeoutSecs)
            else:
                importResult = node.import_hdfs(folderURI + "/" + pattern, timeoutSecs=timeoutSecs)

        elif schema=='maprfs':
            if not n.use_maprfs:
                print "use_maprfs: %s" % n.use_maprfs
                # raise Exception("Something was missing for maprfs on the java -jar cmd line when the cloud was built")
                print "ERROR: Something was missing for maprfs on the java -jar cmd line when the cloud was built"
            # if I use the /// and default, the key names that get created by h2o only have 1 slash
            # so the parse doesn't find the key name
            if n.hdfs_name_node:
                folderURI = "maprfs://" + n.hdfs_name_node + "/" + folderOffset
            else:
                # this is different than maprfs? normally we specify the name though
                # folderURI = "maprfs:///" + folderOffset
                folderURI = "maprfs:/" + folderOffset
            if importParentDir:
                importResult = node.import_hdfs(folderURI, timeoutSecs=timeoutSecs)
            else:
                importResult = node.import_hdfs(folderURI + "/" + pattern, timeoutSecs=timeoutSecs)

        elif schema=='hdfs':
            # check that some state from the cloud building time was right
            # the requirements for this may change and require updating
            if not (n.use_hdfs and ((n.hdfs_version and n.hdfs_name_node) or n.hdfs_config)):
                print "use_hdfs: %s hdfs_version: %s hdfs_name_node: %s hdfs_config: %s" % \
                    (n.use_hdfs, n.hdfs_version, n.hdfs_name_node, n.hdfs_config)
                # raise Exception("Something was missing for hdfs on the java -jar cmd line when the cloud was built")
                print "ERROR: Something was missing for hdfs on the java -jar cmd line when the cloud was built"

            if n.hdfs_name_node:
                folderURI = "hdfs://" + n.hdfs_name_node + "/" + folderOffset
            else:
                # this is different than maprfs? normally we specify the name though
                folderURI = "hdfs://" + folderOffset
            if importParentDir:
                importResult = node.import_hdfs(folderURI, timeoutSecs=timeoutSecs)
            else:
                importResult = node.import_hdfs(folderURI + "/" + pattern, timeoutSecs=timeoutSecs)

        else:
            raise Exception("schema not understood: %s" % schema)

    importPattern = folderURI + "/" + pattern
    return (importResult, importPattern)

#****************************************************************************************
# can take header, header_from_file, exclude params
def parse_only(node=None, pattern=None, hex_key=None,
    timeoutSecs=30, retryDelaySecs=0.5, initialDelaySecs=0.5, pollTimeoutSecs=180, noise=None,
    benchmarkLogging=None, noPoll=False, **kwargs):

    if not node: node = h2o.nodes[0]

    parseResult = node.parse(key=pattern, key2=hex_key,
        timeoutSecs=timeoutSecs, retryDelaySecs=retryDelaySecs,
        initialDelaySecs=initialDelaySecs, pollTimeoutSecs=pollTimeoutSecs, noise=noise,
        benchmarkLogging=benchmarkLogging, noPoll=noPoll, **kwargs)

    parseResult['python_source'] = pattern
    return parseResult

#****************************************************************************************
def import_parse(node=None, schema='local', bucket=None, path=None,
    src_key=None, hex_key=None,
    timeoutSecs=30, retryDelaySecs=0.5, initialDelaySecs=0.5, pollTimeoutSecs=180, noise=None,
    benchmarkLogging=None, noPoll=False, doSummary=True, noPrint=True,
    importParentDir=True, **kwargs):

    ## if h2o.beta_features:
    ##     print "HACK: temporarily disabling Summary always in v2 import_parse"
    ##     doSummary = False

    if not node: node = h2o.nodes[0]

    (importResult, importPattern) = import_only(node, schema, bucket, path,
        timeoutSecs, retryDelaySecs, initialDelaySecs, pollTimeoutSecs, noise,
        benchmarkLogging, noPoll, doSummary, src_key, noPrint, importParentDir, **kwargs)

    h2o.verboseprint("importPattern:", importPattern)
    h2o.verboseprint("importResult", h2o.dump_json(importResult))

    parseResult = parse_only(node, importPattern, hex_key,
        timeoutSecs, retryDelaySecs, initialDelaySecs, pollTimeoutSecs, noise,
        benchmarkLogging, noPoll, **kwargs)
    h2o.verboseprint("parseResult:", h2o.dump_json(parseResult))

    # do SummaryPage here too, just to get some coverage
    # only if not noPoll. otherwise parse isn't done
    if doSummary and not noPoll:
        # if parse blows up, we want error isolation ..i.e. find stack traces here, rather than the next guy blowing up
        h2o.check_sandbox_for_errors()
        inspect = node.inspect(parseResult['destination_key'], timeoutSecs=timeoutSecs)
        if h2o.beta_features:
            numRows = inspect['numRows']
            numCols = inspect['numCols']
        else:
            numRows = inspect['num_rows']
            numCols = inspect['num_cols']

        # we pass numCols, for detecting whether the na cnt means a col is all NAs, (for ignoring min/max/mean/sigma)
        node.summary_page(parseResult['destination_key'], timeoutSecs=timeoutSecs, noPrint=noPrint, numRows=numRows, numCols=numCols)
        # for now, don't worry about error isolating summary
    else:
        # isolate a parse from the next thing
        h2o.check_sandbox_for_errors()

    return parseResult

# returns full key name, from current store view
def find_key(pattern=None):
    found = None
    kwargs = {'filter': pattern}
    storeViewResult = h2o.nodes[0].store_view(**kwargs)
    keys = storeViewResult['keys']
    if len(keys) == 0:
        return None

    if len(keys) > 1:
        h2o.verboseprint("Warning: multiple imported keys match the key pattern given, Using: %s" % keys[0]['key'])

    return keys[0]['key']

#****************************************************************************************
# the storeViewResult for every node may or may not be the same
# supposed to be the same? In any case
# pattern can't be regex to h2o?
# None should be same as no pattern
def delete_keys(node=None, pattern=None, timeoutSecs=120):
    if not node: node = h2o.nodes[0]
    kwargs = {'filter': pattern}
    deletedCnt = 0
    triedKeys = []
    while True:

        # FIX! h2o is getting a bad store_view NPE stack trace if I grabe all the
        # keys at the end of a test, prior to removing. Just grab 20 at a time like h2o
        # used to do for me. Maybe the keys are changing state, and going slower will eliminate the race
        # against prior work (but note that R might see the same problem
        storeViewResult = h2o_cmd.runStoreView(node, timeoutSecs=timeoutSecs, view=20, **kwargs)
        # we get 20 at a time with default storeView
        keys = storeViewResult['keys']
        if not keys:
            break

        # look for keys we already sent a remove on. Maybe those are locked.
        # give up on those
        deletedThisTime = 0
        for k in keys:
            if k in triedKeys:
                print "Already tried to delete %s. Must have failed. Not trying again" % k
            # don't delete the DRF __Tree__ keys. deleting the model does that. causes race conditions
            elif '__Tree__' in k['key']:
                print "Not deleting a tree key from DRF: %s" % k
            elif 'DRF_' in k['key']:
                print "Not deleting DRF key..they may be problematic in flight: %s" % k
            elif '__RFModel__' in k['key']:
                print "Not deleting __RFModel__ key..seeing NPE's if I try to delete them: %s" % k
            else:
                print "Deleting", k['key'], "at", node
                node.remove_key(k['key'], timeoutSecs=timeoutSecs)
                deletedCnt += 1
                deletedThisTime += 1
            triedKeys.append(k)
        # print "Deleted", deletedCnt, "keys at %s:%s" % (node.http_addr, node.port)
        if deletedThisTime==0:
            break
    # this is really the count that we attempted. Some could have failed.
    return deletedCnt

# if pattern is used, don't use the heavy h2o method
def delete_keys_at_all_nodes(node=None, pattern=None, timeoutSecs=120):
    time.sleep(5)
    # TEMP: change this to remove_all_keys which ignores locking and removes keys?
    # getting problems when tests fail in multi-test-on-one-h2o-cluster runner*sh tests
    if not node: node = h2o.nodes[0]
    totalDeletedCnt = 0
    # do it in reverse order, since we always talk to 0 for other stuff
    # this will be interesting if the others don't have a complete set
    # theoretically, the deletes should be 0 after the first node
    # since the deletes should be global
    for node in reversed(h2o.nodes):
        deletedCnt = delete_keys(node, pattern=pattern, timeoutSecs=timeoutSecs)
        totalDeletedCnt += deletedCnt

    if pattern:
        print "Total: Deleted", totalDeletedCnt, "keys with filter=", pattern, "at", len(h2o.nodes), "nodes"
    else:
        print "Total: Deleted", totalDeletedCnt, "keys at", len(h2o.nodes), "nodes"
        # do a remove_all_keys to clean out any locked keys also (locked keys will complain above)
        # doesn't work if you remove job keys first, since it looks at the job list and gets confused
        ### node.remove_all_keys(timeoutSecs=timeoutSecs)

    return totalDeletedCnt

def count_keys(node=None, pattern=None, timeoutSecs=90):
    if not node: node = h2o.nodes[0]
    kwargs = {'filter': pattern}
    nodeCnt = 0
    offset = 0
    while True:
        # we get 20 at a time with default storeView
        # if we get < 20, we're done
        storeViewResult = h2o_cmd.runStoreView(node, timeoutSecs=timeoutSecs, offset=offset, view=20, **kwargs)
        keys = storeViewResult['keys']
        if not keys:
            break
        nodeCnt += len(storeViewResult['keys'])
        if len(keys) < 20:
            break
        offset += 20

    print nodeCnt, "keys at %s:%s" % (node.http_addr, node.port)
    return nodeCnt

def count_keys_at_all_nodes(node=None, pattern=None, timeoutSecs=90):
    if not node: node = h2o.nodes[0]
    totalCnt = 0
    # do it in reverse order, since we always talk to 0 for other stuff
    # this will be interesting if the others don't have a complete set
    # theoretically, the deletes should be 0 after the first node
    # since the deletes should be global
    for node in reversed(h2o.nodes):
        nodeCnt = count_keys(node, pattern=pattern, timeoutSecs=timeoutSecs)
        totalCnt += nodeCnt
    if pattern:
        print "Total: ", totalCnt, "keys with filter=", pattern, "at", len(h2o.nodes), "nodes"
    else:
        print "Total: ", totalCnt, "keys at", len(h2o.nodes), "nodes"
    return totalCnt

#****************************************************************************************
# Since we can't trust a single node storeview list, this will get keys that match text
# for deleting, from a list saved from an import
def delete_keys_from_import_result(node=None, pattern=None, importResult=None, timeoutSecs=30):
    if not node: node = h2o.nodes[0]
    # the list could be from hdfs/s3 or local. They have to different list structures
    deletedCnt = 0
    if 'succeeded' in importResult:
        kDict = importResult['succeeded']
        for k in kDict:
            key = k['key']
            if (pattern in key) or pattern is None:
                print "Removing", key
                removeKeyResult = node.remove_key(key=key)
                deletedCnt += 1
    elif 'keys' in importResult:
        kDict = importResult['keys']
        for k in kDict:
            key = k
            if (pattern in key) or pattern is None:
                print "Removing", key
                removeKeyResult = node.remove_key(key=key)
                deletedCnt += 1
    else:
        raise Exception ("Can't find 'files' or 'succeeded' in your file dict. why? not from hdfs/s3 or local?")
    print "Deleted", deletedCnt, "keys at", node
    return deletedCnt


text:
"use babel";

fs    = require('fs')
path  = require('path')
rp    = null;

/**
 * This provides hyperclick support for Perl 6 using hyperclick
 * Please see https://atom.io/packages/hyperclick
 */
module.exports =
class Perl6HyperclickProvider {

  constructor()  {
    this.keywords = {}

    // Find path of data/perl6-help.index.json
    myPackageFolder = atom.packages.getLoadedPackage("atom-perl6-editor-tools").path
    filename = path.join(myPackageFolder, "data", "perl6-help-index.json")

    // Read data/perl6-help.index.json async and extract its keywords
    fs.readFile(filename, 'utf8', (err, data) => {
      // Did we fail?
      if (err) {
        throw err
      }

      // Keep keywords hash for later usage
      this.keywords = JSON.parse(data)
    }
    )
  }

  providerName = 'perl6-hyperclick'

  // This is called by hyperclick plugin when the user holds Ctrl and then clicks
  // the underlined word
  getSuggestionForWord(editor, word, range) {
    // Editor must be defined
    if (!editor) {
      return
    }

    // Editor must be a Perl 6 editor
    grammar = editor.getGrammar()
    if( !( grammar && grammar.scopeName && grammar.scopeName.startsWith("source.perl6") ) ) {
      return
    }

    // Keywords should be defined
    if( !this.keywords ) {
      return
    }

    helpRecs = this.keywords[word]

    // Return help callback and ranges to suggestion provider (hyperclick)
    return {
      range: range,
      callback: () => {
        if (!helpRecs || helpRecs && helpRecs.length == 0) {
          atom.notifications.addWarning(`Help not found for ${word}`)
          return
        }

        // TODO display more than one help result?
        o = helpRecs[0]

        url = `https://doc.perl6.org${o.url}.html`
        onResolve = (content ) => {
          regex = /
((.|\s)+?)<\/div>\s*/
          match = regex.exec(content)
          if(match) {
            helpText = `Category:<\/strong>  ${o.category}

URL:<\/strong>  ${url}
${match[1]}`
            atom.notifications.addInfo(helpText, { dismissable: true })
          } else {
            atom.notifications.addWarning(`Failed to match ${url}`)
          }
          return
        }
        onReject  = (code) => {
          atom.notifications.addWarning(`Failed to fetch ${url}`)
          return
        }

        // Return a promise
        if (rp == null) {
          // Lazily load since it is somehow slow on startup
          rp = require('request-promise')
        }
        return rp(url).then(onResolve, onReject)
      }
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
from typing import (
    Any,
    AsyncIterator,
    Awaitable,
    Callable,
    Sequence,
    Tuple,
    Optional,
    Iterator,
)

from google.cloud.aiplatform_v1.types import study
from google.cloud.aiplatform_v1.types import vizier_service

class ListStudiesPager:
    """A pager for iterating through ``list_studies`` requests.

    This class thinly wraps an initial
    :class:`google.cloud.aiplatform_v1.types.ListStudiesResponse` object, and
    provides an ``__iter__`` method to iterate through its
    ``studies`` field.

    If there are more pages, the ``__iter__`` method will make additional
    ``ListStudies`` requests and continue to iterate
    through the ``studies`` field on the
    corresponding responses.

    All the usual :class:`google.cloud.aiplatform_v1.types.ListStudiesResponse`
    attributes are available on the pager. If multiple requests are made, only
    the most recent response is retained, and thus used for attribute lookup.
    """

    def __init__(
        self,
        method: Callable[..., vizier_service.ListStudiesResponse],
        request: vizier_service.ListStudiesRequest,
        response: vizier_service.ListStudiesResponse,
        *,
        metadata: Sequence[Tuple[str, str]] = ()
    ):
        """Instantiate the pager.

        Args:
            method (Callable): The method that was originally called, and
                which instantiated this pager.
            request (google.cloud.aiplatform_v1.types.ListStudiesRequest):
                The initial request object.
            response (google.cloud.aiplatform_v1.types.ListStudiesResponse):
                The initial response object.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.
        """
        self._method = method
        self._request = vizier_service.ListStudiesRequest(request)
        self._response = response
        self._metadata = metadata

    def __getattr__(self, name: str) -> Any:
        return getattr(self._response, name)

    @property
    def pages(self) -> Iterator[vizier_service.ListStudiesResponse]:
        yield self._response
        while self._response.next_page_token:
            self._request.page_token = self._response.next_page_token
            self._response = self._method(self._request, metadata=self._metadata)
            yield self._response

    def __iter__(self) -> Iterator[study.Study]:
        for page in self.pages:
            yield from page.studies

    def __repr__(self) -> str:
        return "{0}<{1!r}>".format(self.__class__.__name__, self._response)

class ListStudiesAsyncPager:
    """A pager for iterating through ``list_studies`` requests.

    This class thinly wraps an initial
    :class:`google.cloud.aiplatform_v1.types.ListStudiesResponse` object, and
    provides an ``__aiter__`` method to iterate through its
    ``studies`` field.

    If there are more pages, the ``__aiter__`` method will make additional
    ``ListStudies`` requests and continue to iterate
    through the ``studies`` field on the
    corresponding responses.

    All the usual :class:`google.cloud.aiplatform_v1.types.ListStudiesResponse`
    attributes are available on the pager. If multiple requests are made, only
    the most recent response is retained, and thus used for attribute lookup.
    """

    def __init__(
        self,
        method: Callable[..., Awaitable[vizier_service.ListStudiesResponse]],
        request: vizier_service.ListStudiesRequest,
        response: vizier_service.ListStudiesResponse,
        *,
        metadata: Sequence[Tuple[str, str]] = ()
    ):
        """Instantiates the pager.

        Args:
            method (Callable): The method that was originally called, and
                which instantiated this pager.
            request (google.cloud.aiplatform_v1.types.ListStudiesRequest):
                The initial request object.
            response (google.cloud.aiplatform_v1.types.ListStudiesResponse):
                The initial response object.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.
        """
        self._method = method
        self._request = vizier_service.ListStudiesRequest(request)
        self._response = response
        self._metadata = metadata

    def __getattr__(self, name: str) -> Any:
        return getattr(self._response, name)

    @property
    async def pages(self) -> AsyncIterator[vizier_service.ListStudiesResponse]:
        yield self._response
        while self._response.next_page_token:
            self._request.page_token = self._response.next_page_token
            self._response = await self._method(self._request, metadata=self._metadata)
            yield self._response

    def __aiter__(self) -> AsyncIterator[study.Study]:
        async def async_generator():
            async for page in self.pages:
                for response in page.studies:
                    yield response

        return async_generator()

    def __repr__(self) -> str:
        return "{0}<{1!r}>".format(self.__class__.__name__, self._response)

class ListTrialsPager:
    """A pager for iterating through ``list_trials`` requests.

    This class thinly wraps an initial
    :class:`google.cloud.aiplatform_v1.types.ListTrialsResponse` object, and
    provides an ``__iter__`` method to iterate through its
    ``trials`` field.

    If there are more pages, the ``__iter__`` method will make additional
    ``ListTrials`` requests and continue to iterate
    through the ``trials`` field on the
    corresponding responses.

    All the usual :class:`google.cloud.aiplatform_v1.types.ListTrialsResponse`
    attributes are available on the pager. If multiple requests are made, only
    the most recent response is retained, and thus used for attribute lookup.
    """

    def __init__(
        self,
        method: Callable[..., vizier_service.ListTrialsResponse],
        request: vizier_service.ListTrialsRequest,
        response: vizier_service.ListTrialsResponse,
        *,
        metadata: Sequence[Tuple[str, str]] = ()
    ):
        """Instantiate the pager.

        Args:
            method (Callable): The method that was originally called, and
                which instantiated this pager.
            request (google.cloud.aiplatform_v1.types.ListTrialsRequest):
                The initial request object.
            response (google.cloud.aiplatform_v1.types.ListTrialsResponse):
                The initial response object.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.
        """
        self._method = method
        self._request = vizier_service.ListTrialsRequest(request)
        self._response = response
        self._metadata = metadata

    def __getattr__(self, name: str) -> Any:
        return getattr(self._response, name)

    @property
    def pages(self) -> Iterator[vizier_service.ListTrialsResponse]:
        yield self._response
        while self._response.next_page_token:
            self._request.page_token = self._response.next_page_token
            self._response = self._method(self._request, metadata=self._metadata)
            yield self._response

    def __iter__(self) -> Iterator[study.Trial]:
        for page in self.pages:
            yield from page.trials

    def __repr__(self) -> str:
        return "{0}<{1!r}>".format(self.__class__.__name__, self._response)

class ListTrialsAsyncPager:
    """A pager for iterating through ``list_trials`` requests.

    This class thinly wraps an initial
    :class:`google.cloud.aiplatform_v1.types.ListTrialsResponse` object, and
    provides an ``__aiter__`` method to iterate through its
    ``trials`` field.

    If there are more pages, the ``__aiter__`` method will make additional
    ``ListTrials`` requests and continue to iterate
    through the ``trials`` field on the
    corresponding responses.

    All the usual :class:`google.cloud.aiplatform_v1.types.ListTrialsResponse`
    attributes are available on the pager. If multiple requests are made, only
    the most recent response is retained, and thus used for attribute lookup.
    """

    def __init__(
        self,
        method: Callable[..., Awaitable[vizier_service.ListTrialsResponse]],
        request: vizier_service.ListTrialsRequest,
        response: vizier_service.ListTrialsResponse,
        *,
        metadata: Sequence[Tuple[str, str]] = ()
    ):
        """Instantiates the pager.

        Args:
            method (Callable): The method that was originally called, and
                which instantiated this pager.
            request (google.cloud.aiplatform_v1.types.ListTrialsRequest):
                The initial request object.
            response (google.cloud.aiplatform_v1.types.ListTrialsResponse):
                The initial response object.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.
        """
        self._method = method
        self._request = vizier_service.ListTrialsRequest(request)
        self._response = response
        self._metadata = metadata

    def __getattr__(self, name: str) -> Any:
        return getattr(self._response, name)

    @property
    async def pages(self) -> AsyncIterator[vizier_service.ListTrialsResponse]:
        yield self._response
        while self._response.next_page_token:
            self._request.page_token = self._response.next_page_token
            self._response = await self._method(self._request, metadata=self._metadata)
            yield self._response

    def __aiter__(self) -> AsyncIterator[study.Trial]:
        async def async_generator():
            async for page in self.pages:
                for response in page.trials:
                    yield response

        return async_generator()

    def __repr__(self) -> str:
        return "{0}<{1!r}>".format(self.__class__.__name__, self._response)


text:
void testListOutput (int N, int M, int nPower, int mPower, int numTests, string outputFile)
{
	rTime gameTime, roundTime;
	float numMilliSeconds = 0.0f;
	int i = 1, j = 0, baseN = N, baseM = M;
	ofstream output;
	output.open (outputFile.c_str (), ios::out);

	cout << "STARTING JOSEPHUS LIST GAME TESTING...\n";
	output << "STARTING JOSEPHUS LIST GAME TESTING...\n";
	for (i = 1; i <= numTests; i++)
	{
		cout << "TEST GAME " << i << "\n";
		output << "TEST GAME " << i << "\n";
		cout << "N: " << N << ", M: " << M << "\n";
		output << "N: " << N << ", M: " << M << "\n";
		gameTime.resetStartTime ();
		j = 0;
		numMilliSeconds = 0;

		N = getIntPower (baseN, nPower, i);
		M = getIntPower (baseM, mPower, i);

		cout << "N = " << N << ", M = " << M << "\n\n";
		ListMyJosephus listTestCircle (N, M);
		list<Person>::iterator l;
		l = listTestCircle.circ.begin ();

		while (listTestCircle.currentSize () != 1)
		{
			roundTime.resetStartTime ();
			j++;
			cout << "Round " << j << "\n";
			l = listTestCircle.eliminateNext (l);
			listTestCircle.printAll ();
			numMilliSeconds += roundTime.getTimeElapsedMili ();
		}
		cout << "Game Winner: " << listTestCircle.returnWinner () << "\n";
		cout << "Time of Game: " << (float)(gameTime.getTimeElapsedMili ()) << " Millisecond(s)\n";
		cout << "Average Round Time: " << (float)(numMilliSeconds / (float)j) << " Millisecond(s)\n";
		output << "Game Winner: " << listTestCircle.returnWinner () << "\n";
		output << "Time of Game: " << (float)(gameTime.getTimeElapsedMili ()) << " Millisecond(s)\n";
		output << "Average Round Time: " << (float)(numMilliSeconds / (float)j) << " Millisecond(s)\n\n";
		system ("pause");
	}
	cout << "TESTING COMPLETE!\n";
	output << "TESTING COMPLETE!\n";
	output.close ();
}

// test the list implementation with the values provided from the main menu and do the number of tests, changes to
//			N and M as needed. Also don't display all output on screen.
void testListNoOutput (int N, int M, int nPower, int mPower, int numTests, string outputFile)
{
	rTime gameTime, roundTime;
	float numMilliSeconds = 0.0f;
	int i = 1, j = 0, baseN = N, baseM = M;
	ofstream output;
	output.open (outputFile.c_str (), ios::out);

	cout << "STARTING JOSEPHUS LIST GAME TESTING...\n";
	output << "STARTING JOSEPHUS GAME TESTING...\n";
	for (i = 1; i <= numTests; i++)
	{
		output << "TEST GAME " << i << "\n";
		output << "N: " << N << ", M: " << M << "\n";
		gameTime.resetStartTime ();
		j = 0;
		numMilliSeconds = 0;

		N = getIntPower (baseN, nPower, i);
		M = getIntPower (baseM, mPower, i);

		ListMyJosephus listTestCircle (N, M);
		list<Person>::iterator i;
		i = listTestCircle.circ.begin ();

		while (listTestCircle.currentSize () != 1)
		{
			roundTime.resetStartTime ();
			j++;
			i = listTestCircle.eliminateNext (i);
			numMilliSeconds += roundTime.getTimeElapsedMili ();
		}
		output << "Game Winner: " << listTestCircle.returnWinner () << "\n";
		output << "Time of Game: " << (gameTime.getTimeElapsedMili ()) << " Millisecond(s)\n";
		output << "Average Round Time: " << (numMilliSeconds / (float)j) << " Millisecond(s)\n\n";
		cout << ".";
	}
	cout << "TESTING COMPLETE!\n";
	output << "TESTING COMPLETE!\n";
	output.close ();
}


text:
import { Component, Input, Output, EventEmitter, ContentChild, ElementRef, ViewChild, TemplateRef } from '@angular/core';
import { InputTemplate } from '../template/InputTemplate';
import { List } from '../list/List';
import { ListItem } from '../list/ListItem';

export type SearchBoxDataSource = { value: string }[];

export interface InputTemplateData {
	data: { value: string };
	events: {
		onChange: (value: string) => void,
		onKeydown: (event: KeyboardEvent) => void
	};
}

export interface ElementDataInput {
	selectedIndex: number;
};

export class SearchBoxListItem extends ListItem {
	constructor(private input: ElementDataInput, public value: string, index: number, count: number) {
		super(index, count);
	}

	public get selected(): boolean {
		return this.index === this.input.selectedIndex;
	}
}

@Component({
	selector: 'wx-searchbox',
	template: `<div (focusout)="lostFocus($event)">
	<ng-template [templatecreator]="inputTemplate.template" [data]="inputTemplateData"></ng-template>
	<div class="wx-searchbox-element-list" tabindex="0" #searchBoxList (keydown)="keydown($event)">
		<div [hidden]="!isOpen" class="wx-searchbox-list-elements" #elementContainer>
			<div *ngFor="let d of dataSource;let last=last;" (click)="selectValue(d.value)" class="wx-searchbox-list-element">
				<ng-template [templatecreator]="listElement.template" [data]="d"></ng-template>
				<ng-template [templatecreator]="listElementSeparator.template" *ngIf="!last && listElementSeparator"></ng-template>
			</div>
		</div>
	</div>
</div>`,
})
export class SearchboxComponent extends List {
	@ContentChild(InputTemplate) public inputTemplate: InputTemplate;
	@Output('valueChange') public readonly valueChange: EventEmitter<string> = new EventEmitter<string>();
	@Input('dataSource') protected dataSourceFactory: (text: string) => Promise<string[]>;
	@ViewChild('searchBoxList') protected searchBoxList: ElementRef;
	@ViewChild('elementContainer') protected elementContainer: ElementRef;

	protected inputTemplateData: InputTemplateData = { data: { value: '' }, events: { onChange: (value) => this.onChange(value), onKeydown: (event) => this.keydown(event) } };
	protected dataSource: SearchBoxListItem[] = [];
	protected isOpen: boolean = false;
	protected elementDataInput: ElementDataInput = {
		selectedIndex: 0
	};

	public ngAfterContentInit(): void {
		super.ngAfterContentInit();
		if (this.inputTemplate == null) {
			throw 'Invalid Searchbox component!\nInputTemplate is a mandatory template.';
		}
	}

	/**
	 * Sets the value
	 */
	@Input('value')
	public set setValue(value: string) {
		if (this.inputTemplateData.data.value !== value) {
			this.inputTemplateData.data.value = value;
			this.valueChange.emit(value);
		}
	}

	protected selectValue(value: string): void {
		this.setValue = value;
		this.isOpen = false;
	}

	protected lostFocus(event: MouseEvent): void {
		if (event.relatedTarget === this.searchBoxList.nativeElement) {
			if (!this.isOpen) {
				this.refreshList();
			}
		} else {
			this.isOpen = false;
		}
	}

	protected keydown(event: KeyboardEvent): void {
		if (!this.isOpen) {
			return;
		}
		if (event.keyCode === 13) { // Enter
			this.selectValue(this.dataSource[this.elementDataInput.selectedIndex].value);
		} else if (event.keyCode === 38) { // Up
			if (this.elementDataInput.selectedIndex > 0) {
				this.elementDataInput.selectedIndex--;
				const container = <HTMLScriptElement>this.elementContainer.nativeElement;
				const div = container.children[this.elementDataInput.selectedIndex];
				if ((<any>div).offsetTop < container.scrollTop) {
					container.scrollTop -= container.scrollTop - (<any>div).offsetTop;
				}
			}
		} else if (event.keyCode === 40) { // Down
			if (this.elementDataInput.selectedIndex + 1 < this.dataSource.length) {
				this.elementDataInput.selectedIndex++;
				const container = <HTMLScriptElement>this.elementContainer.nativeElement;
				const div = container.children[this.elementDataInput.selectedIndex];
				const offsetBottom = (<any>div).offsetTop + div.getBoundingClientRect().height;
				const scrollBottom = container.scrollTop + container.getBoundingClientRect().height;
				if (offsetBottom > scrollBottom) {
					container.scrollTop += offsetBottom - scrollBottom;
				}
			}
		}
	}

	protected onChange(value: string): void {
		this.inputTemplateData.data.value = value;
		this.valueChange.emit(value);
		this.refreshList();
	}

	protected refreshList(): void {
		if(this.dataSourceFactory) {
			this.dataSourceFactory(this.inputTemplateData.data.value).then(items => {
				this.dataSource = items.map((item, index) => { return new SearchBoxListItem(this.elementDataInput, item, index, items.length); });
				this.isOpen = true;
				this.elementDataInput.selectedIndex = 0;
				const container = <HTMLScriptElement>this.elementContainer.nativeElement;
				container.scrollTop = 0;
			});
		}
	}
}


text:
<?php declare(strict_types=1);

namespace PhpParser\Node\Expr;

use PhpParser\Node\Expr;

class List_ extends Expr
{
    /** @var (ArrayItem|null)[] List of items to assign to */
    public $items;

    /**
     * Constructs a list() destructuring node.
     *
     * @param (ArrayItem|null)[] $items      List of items to assign to
     * @param array              $attributes Additional attributes
     */
    public function __construct(array $items, array $attributes = []) {
        parent::__construct($attributes);
        $this->items = $items;
    }

    public function getSubNodeNames() : array {
        return ['items'];
    }

    public function getType() : string {
        return 'Expr_List';
    }
}


text:
import { Phase } from './phase';
import { Game } from '../game';
import { Action } from './actions/action';
import { List } from 'immutable';
export declare class ScorePhase extends Phase {
    update(game: Game): Game;
    actions(game: Game): List<Action>;
    private getCompletedProperties;
    private scoreProperty;
    private getFiguresOnProperty;
    private scoreCity;
    private getPointsPerTile;
    private getPlayersWithMajority;
}


text:
	<title>Portrait</title>
	<link rel="stylesheet" type="text/css" href="./styles/p-style.css">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

		$ 100,000,000.00

$ 100,000.00

TOTAL WIN

		 GAME PLAY ID: 87672323


text:
package com.facebook.buck.util.exceptions;

import java.util.Optional;
import javax.annotation.Nullable;

@SuppressWarnings("unused")
public class BuckExecutionException extends Exception
    implements ExceptionWithContext, WrapsException {
  private @Nullable final String context;

  public BuckExecutionException(String message) {
    this(message, null);
  }

  public BuckExecutionException(String message, @Nullable String context) {
    super(message);
    this.context = context;
  }

  public BuckExecutionException(
      String message, @Nullable Throwable cause, @Nullable String context) {
    super(message, cause);
    this.context = context;
  }

  public BuckExecutionException(Throwable cause) {
    this(cause, null);
  }

  public BuckExecutionException(Throwable cause, @Nullable String context) {
    super(cause);
    this.context = context;
  }

  @Override
  public Optional<String> getContext() {
    return Optional.ofNullable(context);
  }
}


text:
<?php

namespace Drupal\locale\Tests;

use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\simpletest\WebTestBase;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Component\Utility\SafeMarkup;

/**
 * Adds a new locale and translates its name. Checks the validation of
 * translation strings and search results.
 *
 * @group locale
 */
class LocaleTranslationUiTest extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('locale');

  /**
   * Enable interface translation to English.
   */
  public function testEnglishTranslation() {
    $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
    $this->drupalLogin($admin_user);

    $this->drupalPostForm('admin/config/regional/language/edit/en', array('locale_translate_english' => TRUE), t('Save language'));
    $this->assertLinkByHref('/admin/config/regional/translate?langcode=en', 0, 'Enabled interface translation to English.');
  }

  /**
   * Adds a language and tests string translation by users with the appropriate permissions.
   */
  public function testStringTranslation() {
    // User to add and remove language.
    $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
    // User to translate and delete string.
    $translate_user = $this->drupalCreateUser(array('translate interface', 'access administration pages'));
    // Code for the language.
    $langcode = 'xx';
    // The English name for the language. This will be translated.
    $name = $this->randomMachineName(16);
    // This will be the translation of $name.
    $translation = $this->randomMachineName(16);
    $translation_to_en = $this->randomMachineName(16);

    // Add custom language.
    $this->drupalLogin($admin_user);
    $edit = array(
      'predefined_langcode' => 'custom',
      'langcode' => $langcode,
      'label' => $name,
      'direction' => LanguageInterface::DIRECTION_LTR,
    );
    $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
    // Add string.
    t($name, array(), array('langcode' => $langcode))->render();
    // Reset locale cache.
    $this->container->get('string_translation')->reset();
    $this->assertRaw('"edit-languages-' . $langcode . '-weight"', 'Language code found.');
    $this->assertText(t($name), 'Test language added.');
    $this->drupalLogout();

    // Search for the name and translate it.
    $this->drupalLogin($translate_user);
    $search = array(
      'string' => $name,
      'langcode' => $langcode,
      'translation' => 'untranslated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText($name, 'Search found the string as untranslated.');

    // No t() here, it's surely not translated yet.
    $this->assertText($name, 'name found on edit screen.');
    $this->assertNoOption('edit-langcode', 'en', 'No way to translate the string to English.');
    $this->drupalLogout();
    $this->drupalLogin($admin_user);
    $this->drupalPostForm('admin/config/regional/language/edit/en', array('locale_translate_english' => TRUE), t('Save language'));
    $this->drupalLogout();
    $this->drupalLogin($translate_user);
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText($name, 'Search found the string as untranslated.');

    // Assume this is the only result, given the random name.
    $textarea = current($this->xpath('//textarea'));
    $lid = (string) $textarea[0]['name'];
    $edit = array(
      $lid => $translation,
    );
    $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
    $this->assertText(t('The strings have been saved.'), 'The strings have been saved.');
    $url_bits = explode('?', $this->getUrl());
    $this->assertEqual($url_bits[0], \Drupal::url('locale.translate_page', array(), array('absolute' => TRUE)), 'Correct page redirection.');
    $search = array(
      'string' => $name,
      'langcode' => $langcode,
      'translation' => 'translated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertRaw($translation, 'Non-English translation properly saved.');

    $search = array(
      'string' => $name,
      'langcode' => 'en',
      'translation' => 'untranslated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $textarea = current($this->xpath('//textarea'));
    $lid = (string) $textarea[0]['name'];
    $edit = array(
      $lid => $translation_to_en,
    );
    $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
    $search = array(
      'string' => $name,
      'langcode' => 'en',
      'translation' => 'translated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertRaw($translation_to_en, 'English translation properly saved.');

    $this->assertTrue($name != $translation && t($name, array(), array('langcode' => $langcode)) == $translation, 't() works for non-English.');
    // Refresh the locale() cache to get fresh data from t() below. We are in
    // the same HTTP request and therefore t() is not refreshed by saving the
    // translation above.
    $this->container->get('string_translation')->reset();
    // Now we should get the proper fresh translation from t().
    $this->assertTrue($name != $translation_to_en && t($name, array(), array('langcode' => 'en')) == $translation_to_en, 't() works for English.');
    $this->assertTrue(t($name, array(), array('langcode' => LanguageInterface::LANGCODE_SYSTEM)) == $name, 't() works for LanguageInterface::LANGCODE_SYSTEM.');

    $search = array(
      'string' => $name,
      'langcode' => 'en',
      'translation' => 'untranslated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText(t('No strings available.'), 'String is translated.');

    // Test invalidation of 'rendered' cache tag after string translation.
    $this->drupalLogout();
    $this->drupalGet('xx/user/login');
    $this->assertText('Enter the password that accompanies your username.');

    $this->drupalLogin($translate_user);
    $search = array(
      'string' => 'accompanies your username',
      'langcode' => $langcode,
      'translation' => 'untranslated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $textarea = current($this->xpath('//textarea'));
    $lid = (string) $textarea[0]['name'];
    $edit = array(
      $lid => 'Please enter your Llama username.',
    );
    $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));

    $this->drupalLogout();
    $this->drupalGet('xx/user/login');
    $this->assertText('Please enter your Llama username.');

    // Delete the language.
    $this->drupalLogin($admin_user);
    $path = 'admin/config/regional/language/delete/' . $langcode;
    // This a confirm form, we do not need any fields changed.
    $this->drupalPostForm($path, array(), t('Delete'));
    // We need raw here because %language and %langcode will add HTML.
    $t_args = array('%language' => $name, '%langcode' => $langcode);
    $this->assertRaw(t('The %language (%langcode) language has been removed.', $t_args), 'The test language has been removed.');
    // Reload to remove $name.
    $this->drupalGet($path);
    // Verify that language is no longer found.
    $this->assertResponse(404, 'Language no longer found.');
    $this->drupalLogout();

    // Delete the string.
    $this->drupalLogin($translate_user);
    $search = array(
      'string' => $name,
      'langcode' => 'en',
      'translation' => 'translated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    // Assume this is the only result, given the random name.
    $textarea = current($this->xpath('//textarea'));
    $lid = (string) $textarea[0]['name'];
    $edit = array(
      $lid => '',
    );
    $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
    $this->assertRaw($name, 'The strings have been saved.');
    $this->drupalLogin($translate_user);
    $search = array(
      'string' => $name,
      'langcode' => 'en',
      'translation' => 'untranslated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertNoText(t('No strings available.'), 'The translation has been removed');
  }

  /*
   * Adds a language and checks that the JavaScript translation files are
   * properly created and rebuilt on deletion.
   */
  public function testJavaScriptTranslation() {
    $user = $this->drupalCreateUser(array('translate interface', 'administer languages', 'access administration pages'));
    $this->drupalLogin($user);
    $config = $this->config('locale.settings');

    $langcode = 'xx';
    // The English name for the language. This will be translated.
    $name = $this->randomMachineName(16);

    // Add custom language.
    $edit = array(
      'predefined_langcode' => 'custom',
      'langcode' => $langcode,
      'label' => $name,
      'direction' => LanguageInterface::DIRECTION_LTR,
    );
    $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
    $this->container->get('language_manager')->reset();

    // Build the JavaScript translation file.

    // Retrieve the source string of the first string available in the
    // {locales_source} table and translate it.
    $query = db_select('locales_source', 's');
    $query->addJoin('INNER', 'locales_location', 'l', 's.lid = l.lid');
    $source = $query->fields('s', array('source'))
      ->condition('l.type', 'javascript')
      ->range(0, 1)
      ->execute()
      ->fetchField();

    $search = array(
      'string' => $source,
      'langcode' => $langcode,
      'translation' => 'all',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));

    $textarea = current($this->xpath('//textarea'));
    $lid = (string) $textarea[0]['name'];
    $edit = array(
      $lid => $this->randomMachineName(),
    );
    $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));

    // Trigger JavaScript translation parsing and building.
    _locale_rebuild_js($langcode);

    $locale_javascripts = \Drupal::state()->get('locale.translation.javascript') ?: array();
    $js_file = 'public://' . $config->get('javascript.directory') . '/' . $langcode . '_' . $locale_javascripts[$langcode] . '.js';
    $this->assertTrue($result = file_exists($js_file), SafeMarkup::format('JavaScript file created: %file', array('%file' => $result ? $js_file : 'not found')));

    // Test JavaScript translation rebuilding.
    file_unmanaged_delete($js_file);
    $this->assertTrue($result = !file_exists($js_file), SafeMarkup::format('JavaScript file deleted: %file', array('%file' => $result ? $js_file : 'found')));
    _locale_rebuild_js($langcode);
    $this->assertTrue($result = file_exists($js_file), SafeMarkup::format('JavaScript file rebuilt: %file', array('%file' => $result ? $js_file : 'not found')));
  }

  /**
   * Tests the validation of the translation input.
   */
  public function testStringValidation() {
    // User to add language and strings.
    $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'translate interface'));
    $this->drupalLogin($admin_user);
    $langcode = 'xx';
    // The English name for the language. This will be translated.
    $name = $this->randomMachineName(16);

    // These will be the invalid translations of $name.
    $key = $this->randomMachineName(16);
    $bad_translations[$key] = "<script>alert('xss');</script>" . $key;
    $key = $this->randomMachineName(16);
    $bad_translations[$key] = '<img SRC="javascript:alert(\'xss\');">' . $key;
    $key = $this->randomMachineName(16);
    $bad_translations[$key] = '<<SCRIPT>alert("xss");//<</SCRIPT>' . $key;
    $key = $this->randomMachineName(16);
    $bad_translations[$key] = "<BODY ONLOAD=alert('xss')>" . $key;

    // Add custom language.
    $edit = array(
      'predefined_langcode' => 'custom',
      'langcode' => $langcode,
      'label' => $name,
      'direction' => LanguageInterface::DIRECTION_LTR,
    );
    $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
    // Add string.
    t($name, array(), array('langcode' => $langcode))->render();
    // Reset locale cache.
    $search = array(
      'string' => $name,
      'langcode' => $langcode,
      'translation' => 'all',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    // Find the edit path.

    $textarea = current($this->xpath('//textarea'));
    $lid = (string) $textarea[0]['name'];
    foreach ($bad_translations as $translation) {
      $edit = array(
        $lid => $translation,
      );
      $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
      // Check for a form error on the textarea.
      $form_class = $this->xpath('//form[@id="locale-translate-edit-form"]//textarea/@class');
      $this->assertNotIdentical(FALSE, strpos($form_class[0], 'error'), 'The string was rejected as unsafe.');
      $this->assertNoText(t('The string has been saved.'), 'The string was not saved.');
    }
  }

  /**
   * Tests translation search form.
   */
  public function testStringSearch() {
    // User to add and remove language.
    $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
    // User to translate and delete string.
    $translate_user = $this->drupalCreateUser(array('translate interface', 'access administration pages'));

    // Code for the language.
    $langcode = 'xx';
    // The English name for the language. This will be translated.
    $name = $this->randomMachineName(16);
    // This will be the translation of $name.
    $translation = $this->randomMachineName(16);

    // Add custom language.
    $this->drupalLogin($admin_user);
    $edit = array(
      'predefined_langcode' => 'custom',
      'langcode' => $langcode,
      'label' => $name,
      'direction' => LanguageInterface::DIRECTION_LTR,
    );
    $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));

    $edit = array(
      'predefined_langcode' => 'custom',
      'langcode' => 'yy',
      'label' => $this->randomMachineName(16),
      'direction' => LanguageInterface::DIRECTION_LTR,
    );
    $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));

    // Add string.
    t($name, array(), array('langcode' => $langcode))->render();
    // Reset locale cache.
    $this->container->get('string_translation')->reset();
    $this->drupalLogout();

    // Search for the name.
    $this->drupalLogin($translate_user);
    $search = array(
      'string' => $name,
      'langcode' => $langcode,
      'translation' => 'all',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    // assertText() seems to remove the input field where $name always could be
    // found, so this is not a false assert. See how assertNoText succeeds
    // later.
    $this->assertText($name, 'Search found the string.');

    // Ensure untranslated string doesn't appear if searching on 'only
    // translated strings'.
    $search = array(
      'string' => $name,
      'langcode' => $langcode,
      'translation' => 'translated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText(t('No strings available.'), "Search didn't find the string.");

    // Ensure untranslated string appears if searching on 'only untranslated
    // strings'.
    $search = array(
      'string' => $name,
      'langcode' => $langcode,
      'translation' => 'untranslated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertNoText(t('No strings available.'), 'Search found the string.');

    // Add translation.
    // Assume this is the only result, given the random name.
    // We save the lid from the path.
    $textarea = current($this->xpath('//textarea'));
    $lid = (string) $textarea[0]['name'];
    $edit = array(
      $lid => $translation,
    );
    $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));

    // Ensure translated string does appear if searching on 'only
    // translated strings'.
    $search = array(
      'string' => $translation,
      'langcode' => $langcode,
      'translation' => 'translated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertNoText(t('No strings available.'), 'Search found the translation.');

    // Ensure translated source string doesn't appear if searching on 'only
    // untranslated strings'.
    $search = array(
      'string' => $name,
      'langcode' => $langcode,
      'translation' => 'untranslated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText(t('No strings available.'), "Search didn't find the source string.");

    // Ensure translated string doesn't appear if searching on 'only
    // untranslated strings'.
    $search = array(
      'string' => $translation,
      'langcode' => $langcode,
      'translation' => 'untranslated',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText(t('No strings available.'), "Search didn't find the translation.");

    // Ensure translated string does appear if searching on the custom language.
    $search = array(
      'string' => $translation,
      'langcode' => $langcode,
      'translation' => 'all',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertNoText(t('No strings available.'), 'Search found the translation.');

    // Ensure translated string doesn't appear if searching in System (English).
    $search = array(
      'string' => $translation,
      'langcode' => 'yy',
      'translation' => 'all',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText(t('No strings available.'), "Search didn't find the translation.");

    // Search for a string that isn't in the system.
    $unavailable_string = $this->randomMachineName(16);
    $search = array(
      'string' => $unavailable_string,
      'langcode' => $langcode,
      'translation' => 'all',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText(t('No strings available.'), "Search didn't find the invalid string.");
  }

  /**
   * Tests that only changed strings are saved customized when edited.
   */
  public function testUICustomizedStrings() {
    $user = $this->drupalCreateUser(array('translate interface', 'administer languages', 'access administration pages'));
    $this->drupalLogin($user);
    ConfigurableLanguage::createFromLangcode('de')->save();

    // Create test source string.
    $string = $this->container->get('locale.storage')->createString(array(
      'source' => $this->randomMachineName(100),
      'context' => $this->randomMachineName(20),
    ))->save();

    // Create translation for new string and save it as non-customized.
    $translation = $this->container->get('locale.storage')->createTranslation(array(
      'lid' => $string->lid,
      'language' => 'de',
      'translation' => $this->randomMachineName(100),
      'customized' => 0,
    ))->save();

    // Reset locale cache.
    $this->container->get('string_translation')->reset();

    // Ensure non-customized translation string does appear if searching
    // non-customized translation.
    $search = array(
      'string' => $string->getString(),
      'langcode' => 'de',
      'translation' => 'translated',
      'customized' => '0',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));

    $this->assertText($translation->getString(), 'Translation is found in search result.');

    // Submit the translations without changing the translation.
    $textarea = current($this->xpath('//textarea'));
    $lid = (string) $textarea[0]['name'];
    $edit = array(
      $lid => $translation->getString(),
    );
    $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));

    // Ensure unchanged translation string does appear if searching
    // non-customized translation.
    $search = array(
      'string' => $string->getString(),
      'langcode' => 'de',
      'translation' => 'translated',
      'customized' => '0',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText($string->getString(), 'Translation is not marked as customized.');

    // Submit the translations with a new translation.
    $textarea = current($this->xpath('//textarea'));
    $lid = (string) $textarea[0]['name'];
    $edit = array(
      $lid => $this->randomMachineName(100),
    );
    $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));

    // Ensure changed translation string does appear if searching customized
    // translation.
    $search = array(
      'string' => $string->getString(),
      'langcode' => 'de',
      'translation' => 'translated',
      'customized' => '1',
    );
    $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
    $this->assertText($string->getString(), "Translation is marked as customized.");
  }
}


text:
$(function(){
	//alert('works');
	$('#modalLink').click(function (){
		$('#modal').modal('show')
		.find('#modalContent')
		.load($(this).attr('value'));
	});
});


text:
package com.amazonaws.services.redshift.model;

import java.io.Serializable;

/**
 *

 * Describes an event.
 *

 */
public class Event implements Serializable, Cloneable {

    /**
     * The identifier for the source of the event.
     */
    private String sourceIdentifier;

    /**
     * The source type for this event.
     *

     * Constraints:

     * Allowed Values: cluster, cluster-parameter-group, cluster-security-group, cluster-snapshot
     */
    private String sourceType;

    /**
     * The text of this event.
     */
    private String message;

    /**
     * A list of the event categories.
Values: Configuration, Management,
     * Monitoring, Security
     */
    private com.amazonaws.internal.ListWithAutoConstructFlag<String> eventCategories;

    /**
     * The severity of the event.
Values: ERROR, INFO
     */
    private String severity;

    /**
     * The date and time of the event.
     */
    private java.util.Date date;

    /**
     * The identifier of the event.
     */
    private String eventId;

    /**
     * The identifier for the source of the event.
     *
     * @return The identifier for the source of the event.
     */
    public String getSourceIdentifier() {
        return sourceIdentifier;
    }

    /**
     * The identifier for the source of the event.
     *
     * @param sourceIdentifier The identifier for the source of the event.
     */
    public void setSourceIdentifier(String sourceIdentifier) {
        this.sourceIdentifier = sourceIdentifier;
    }

    /**
     * The identifier for the source of the event.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param sourceIdentifier The identifier for the source of the event.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public Event withSourceIdentifier(String sourceIdentifier) {
        this.sourceIdentifier = sourceIdentifier;
        return this;
    }

    /**
     * The source type for this event.
     *

     * Constraints:

     * Allowed Values: cluster, cluster-parameter-group, cluster-security-group, cluster-snapshot
     *
     * @return The source type for this event.
     *
     * @see SourceType
     */
    public String getSourceType() {
        return sourceType;
    }

    /**
     * The source type for this event.
     *

     * Constraints:

     * Allowed Values: cluster, cluster-parameter-group, cluster-security-group, cluster-snapshot
     *
     * @param sourceType The source type for this event.
     *
     * @see SourceType
     */
    public void setSourceType(String sourceType) {
        this.sourceType = sourceType;
    }

    /**
     * The source type for this event.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Allowed Values: cluster, cluster-parameter-group, cluster-security-group, cluster-snapshot
     *
     * @param sourceType The source type for this event.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     *
     * @see SourceType
     */
    public Event withSourceType(String sourceType) {
        this.sourceType = sourceType;
        return this;
    }

    /**
     * The source type for this event.
     *

     * Constraints:

     * Allowed Values: cluster, cluster-parameter-group, cluster-security-group, cluster-snapshot
     *
     * @param sourceType The source type for this event.
     *
     * @see SourceType
     */
    public void setSourceType(SourceType sourceType) {
        this.sourceType = sourceType.toString();
    }

    /**
     * The source type for this event.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Allowed Values: cluster, cluster-parameter-group, cluster-security-group, cluster-snapshot
     *
     * @param sourceType The source type for this event.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     *
     * @see SourceType
     */
    public Event withSourceType(SourceType sourceType) {
        this.sourceType = sourceType.toString();
        return this;
    }

    /**
     * The text of this event.
     *
     * @return The text of this event.
     */
    public String getMessage() {
        return message;
    }

    /**
     * The text of this event.
     *
     * @param message The text of this event.
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * The text of this event.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param message The text of this event.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public Event withMessage(String message) {
        this.message = message;
        return this;
    }

    /**
     * A list of the event categories.
Values: Configuration, Management,
     * Monitoring, Security
     *
     * @return A list of the event categories.
Values: Configuration, Management,
     *         Monitoring, Security
     */
    public java.util.List<String> getEventCategories() {
        if (eventCategories == null) {
              eventCategories = new com.amazonaws.internal.ListWithAutoConstructFlag<String>();
              eventCategories.setAutoConstruct(true);
        }
        return eventCategories;
    }

    /**
     * A list of the event categories.
Values: Configuration, Management,
     * Monitoring, Security
     *
     * @param eventCategories A list of the event categories.
Values: Configuration, Management,
     *         Monitoring, Security
     */
    public void setEventCategories(java.util.Collection<String> eventCategories) {
        if (eventCategories == null) {
            this.eventCategories = null;
            return;
        }
        com.amazonaws.internal.ListWithAutoConstructFlag<String> eventCategoriesCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(eventCategories.size());
        eventCategoriesCopy.addAll(eventCategories);
        this.eventCategories = eventCategoriesCopy;
    }

    /**
     * A list of the event categories.
Values: Configuration, Management,
     * Monitoring, Security
     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setEventCategories(java.util.Collection)} or {@link
     * #withEventCategories(java.util.Collection)} if you want to override
     * the existing values.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param eventCategories A list of the event categories.
Values: Configuration, Management,
     *         Monitoring, Security
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public Event withEventCategories(String... eventCategories) {
        if (getEventCategories() == null) setEventCategories(new java.util.ArrayList<String>(eventCategories.length));
        for (String value : eventCategories) {
            getEventCategories().add(value);
        }
        return this;
    }

    /**
     * A list of the event categories.
Values: Configuration, Management,
     * Monitoring, Security
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param eventCategories A list of the event categories.
Values: Configuration, Management,
     *         Monitoring, Security
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public Event withEventCategories(java.util.Collection<String> eventCategories) {
        if (eventCategories == null) {
            this.eventCategories = null;
        } else {
            com.amazonaws.internal.ListWithAutoConstructFlag<String> eventCategoriesCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(eventCategories.size());
            eventCategoriesCopy.addAll(eventCategories);
            this.eventCategories = eventCategoriesCopy;
        }

        return this;
    }

    /**
     * The severity of the event.
Values: ERROR, INFO
     *
     * @return The severity of the event.
Values: ERROR, INFO
     */
    public String getSeverity() {
        return severity;
    }

    /**
     * The severity of the event.
Values: ERROR, INFO
     *
     * @param severity The severity of the event.
Values: ERROR, INFO
     */
    public void setSeverity(String severity) {
        this.severity = severity;
    }

    /**
     * The severity of the event.
Values: ERROR, INFO
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param severity The severity of the event.
Values: ERROR, INFO
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public Event withSeverity(String severity) {
        this.severity = severity;
        return this;
    }

    /**
     * The date and time of the event.
     *
     * @return The date and time of the event.
     */
    public java.util.Date getDate() {
        return date;
    }

    /**
     * The date and time of the event.
     *
     * @param date The date and time of the event.
     */
    public void setDate(java.util.Date date) {
        this.date = date;
    }

    /**
     * The date and time of the event.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param date The date and time of the event.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public Event withDate(java.util.Date date) {
        this.date = date;
        return this;
    }

    /**
     * The identifier of the event.
     *
     * @return The identifier of the event.
     */
    public String getEventId() {
        return eventId;
    }

    /**
     * The identifier of the event.
     *
     * @param eventId The identifier of the event.
     */
    public void setEventId(String eventId) {
        this.eventId = eventId;
    }

    /**
     * The identifier of the event.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param eventId The identifier of the event.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public Event withEventId(String eventId) {
        this.eventId = eventId;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSourceIdentifier() != null) sb.append("SourceIdentifier: " + getSourceIdentifier() + ",");
        if (getSourceType() != null) sb.append("SourceType: " + getSourceType() + ",");
        if (getMessage() != null) sb.append("Message: " + getMessage() + ",");
        if (getEventCategories() != null) sb.append("EventCategories: " + getEventCategories() + ",");
        if (getSeverity() != null) sb.append("Severity: " + getSeverity() + ",");
        if (getDate() != null) sb.append("Date: " + getDate() + ",");
        if (getEventId() != null) sb.append("EventId: " + getEventId() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getSourceIdentifier() == null) ? 0 : getSourceIdentifier().hashCode());
        hashCode = prime * hashCode + ((getSourceType() == null) ? 0 : getSourceType().hashCode());
        hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode());
        hashCode = prime * hashCode + ((getEventCategories() == null) ? 0 : getEventCategories().hashCode());
        hashCode = prime * hashCode + ((getSeverity() == null) ? 0 : getSeverity().hashCode());
        hashCode = prime * hashCode + ((getDate() == null) ? 0 : getDate().hashCode());
        hashCode = prime * hashCode + ((getEventId() == null) ? 0 : getEventId().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof Event == false) return false;
        Event other = (Event)obj;

        if (other.getSourceIdentifier() == null ^ this.getSourceIdentifier() == null) return false;
        if (other.getSourceIdentifier() != null && other.getSourceIdentifier().equals(this.getSourceIdentifier()) == false) return false;
        if (other.getSourceType() == null ^ this.getSourceType() == null) return false;
        if (other.getSourceType() != null && other.getSourceType().equals(this.getSourceType()) == false) return false;
        if (other.getMessage() == null ^ this.getMessage() == null) return false;
        if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false) return false;
        if (other.getEventCategories() == null ^ this.getEventCategories() == null) return false;
        if (other.getEventCategories() != null && other.getEventCategories().equals(this.getEventCategories()) == false) return false;
        if (other.getSeverity() == null ^ this.getSeverity() == null) return false;
        if (other.getSeverity() != null && other.getSeverity().equals(this.getSeverity()) == false) return false;
        if (other.getDate() == null ^ this.getDate() == null) return false;
        if (other.getDate() != null && other.getDate().equals(this.getDate()) == false) return false;
        if (other.getEventId() == null ^ this.getEventId() == null) return false;
        if (other.getEventId() != null && other.getEventId().equals(this.getEventId()) == false) return false;
        return true;
    }

    @Override
    public Event clone() {
        try {
            return (Event) super.clone();

        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                    + "even though we're Cloneable!",
                    e);
        }

    }

}


text:
package com.njust.test.css;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.junit.Test;
import org.w3c.css.sac.InputSource;
import org.w3c.dom.css.CSSRule;
import org.w3c.dom.css.CSSStyleSheet;

import com.steadystate.css.dom.CSSRuleListImpl;
import com.steadystate.css.dom.CSSStyleDeclarationImpl;
import com.steadystate.css.dom.CSSStyleRuleImpl;
import com.steadystate.css.parser.CSSOMParser;

public class CssTest
{
    @Test
    public void readTest()
        throws IOException
    {
        String filePath = "E:\\commonltr.css";

        FileInputStream fileInputStream = new FileInputStream(filePath);
        InputSource source = new InputSource(new InputStreamReader(fileInputStream));
        CSSOMParser parser = new CSSOMParser();
        CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null);

        CSSRuleListImpl cssRules = (CSSRuleListImpl)stylesheet.getCssRules();
        List<CSSRule> rules = cssRules.getRules();
        for (CSSRule rule : rules)
        {
            CSSStyleRuleImpl styleRule = (CSSStyleRuleImpl)rule;
            CSSStyleDeclarationImpl style = (CSSStyleDeclarationImpl)styleRule.getStyle();

            String background = style.getBackground();
            if (!background.isEmpty())
            {
                System.out.println(background);
            }

            String backgroundImage = style.getBackgroundImage();
            if (!backgroundImage.isEmpty())
            {
                System.out.println(backgroundImage);
            }
        }

    }

}

//    url(icon-arrowrt.gif) 0px 2px no-repeat
//    url(icon-arrowdn.gif) 0px 4px no-repeat
//    url(icon-cc.png)


text:
function mostra_hid(val,id){

	campo=document.getElementById('hid_'+id);

	tendina=document.getElementById('default-select-'+id);
	sqlbox=document.getElementById('default-selectfrom-'+id);
	hid=document.getElementById('default-hidden-'+id);
	passwd=document.getElementById('default-password-'+id);
	enumbox=document.getElementById('enum-'+id);

	tendina.style.display='none';
	tendina.getElementsByTagName('textarea')[0].disabled='disabled';

	sqlbox.style.display='none';
	sqlbox.getElementsByTagName('textarea')[0].disabled='disabled';

	hid.style.display='none';
	hid.getElementsByTagName('input')[0].disabled='disabled';

	if(null!==enumbox){
		enumbox.style.display='none';
		enumbox.getElementsByTagName('textarea')[0].disabled='disabled';
	}

	if(passwd){

		passwd.style.display='none';
		passwd.getElementsByTagName('input')[0].disabled='disabled';
		passwd.getElementsByTagName('input')[1].disabled='disabled';
		passwd.getElementsByTagName('input')[2].disabled='disabled';

	}

	if(val=='autocompleter_from'){

		$('in_suggest_'+id).disabled='disabled';
	}
	else{
		if(null!==$('in_suggest_'+id)){
			$('in_suggest_'+id).disabled='';
		}
	}

	switch(val){
		case 'select': 	tendina.style.display='inline';
						tendina.getElementsByTagName('textarea')[0].disabled=false;

		break;

		case 'select_from':
		case 'autocompleter_from':

				sqlbox.style.display='inline';
				sqlbox.getElementsByTagName('textarea')[0].disabled=false;

		break;

		case 'hidden':  hid.style.display='inline';
						hid.getElementsByTagName('input')[0].disabled=false;
		break;

		case 'password':  passwd.style.display='inline';
						passwd.getElementsByTagName('input')[0].disabled=false;
						passwd.getElementsByTagName('input')[1].disabled=false;
						passwd.getElementsByTagName('input')[2].disabled=false;
		break;

		case 'select_enum': 	enumbox.style.display='inline';
		break;

		default: campo.style.display=''; return false;
	}

}


text:
package org.apache.commons.jci2;

import java.io.InputStream;
import java.net.URL;

import org.apache.commons.jci2.listeners.ReloadNotificationListener;
import org.apache.commons.jci2.stores.ResourceStore;
import org.apache.commons.jci2.stores.ResourceStoreClassLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * The ReloadingClassLoader uses a delegation mechansim to allow
 * classes to be reloaded. That means that loadClass calls may
 * return different results if the class was changed in the underlying
 * ResourceStore.
 *
 * @author tcurdt
 */
public class ReloadingClassLoader extends ClassLoader implements ReloadNotificationListener {

    private final Log log = LogFactory.getLog(ReloadingClassLoader.class);

    private final ClassLoader parent;
    private ResourceStore[] stores = new ResourceStore[0];
    private ClassLoader delegate;

    public ReloadingClassLoader( final ClassLoader pParent ) {
        super(pParent);
        parent = pParent;

        delegate = new ResourceStoreClassLoader(parent, stores);
    }

    public boolean addResourceStore( final ResourceStore pStore ) {
        try {
            final int n = stores.length;
            final ResourceStore[] newStores = new ResourceStore[n + 1];
            System.arraycopy(stores, 0, newStores, 1, n);
            newStores[0] = pStore;
            stores = newStores;
            delegate = new ResourceStoreClassLoader(parent, stores);
            return true;
        } catch ( final RuntimeException e ) {
            log.error("could not add resource store " + pStore);
        }
        return false;
    }

    public boolean removeResourceStore( final ResourceStore pStore ) {

        final int n = stores.length;
        int i = 0;

        // FIXME: this should be improved with a Map
        // find the pStore and index position with var i
        while ( ( i < n )  && ( stores[i] != pStore ) ) {
            i++;
        }

        // pStore was not found
        if ( i == n ) {
            return false;
        }

        // if stores length > 1 then array copy old values, else create new empty store
        final ResourceStore[] newStores = new ResourceStore[n - 1];
        if (i > 0) {
            System.arraycopy(stores, 0, newStores, 0, i);
        }
        if (i < n - 1) {
            System.arraycopy(stores, i + 1, newStores, i, (n - i - 1));
        }

        stores = newStores;
        delegate = new ResourceStoreClassLoader(parent, stores);
        return true;
    }

    public void handleNotification() {
        log.debug("reloading");
        delegate = new ResourceStoreClassLoader(parent, stores);
    }

    @Override
    public void clearAssertionStatus() {
        delegate.clearAssertionStatus();
    }
    @Override
    public URL getResource(final String name) {
        return delegate.getResource(name);
    }
    @Override
    public InputStream getResourceAsStream(final String name) {
        return delegate.getResourceAsStream(name);
    }
    @Override
    public Class<?> loadClass(final String name) throws ClassNotFoundException {
        return delegate.loadClass(name);
    }
    @Override
    public void setClassAssertionStatus(final String className, final boolean enabled) {
        delegate.setClassAssertionStatus(className, enabled);
    }
    @Override
    public void setDefaultAssertionStatus(final boolean enabled) {
        delegate.setDefaultAssertionStatus(enabled);
    }
    @Override
    public void setPackageAssertionStatus(final String packageName, final boolean enabled) {
        delegate.setPackageAssertionStatus(packageName, enabled);
    }
}


text:
@echo off
SET scriptdir=%~dp0
call powershell -NoProfile %scriptdir%\set-version-UnitsNet.ps1 -bump major
if %errorlevel% neq 0 exit /b %errorlevel%


text:
<?php

class LaravelRoutesTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testLandingResponseCode()
    {
        $response = $this->call('GET', '/');

        $this->assertEquals(200, $response->status());
    }

    public function testUnsupportedBrowserPage()
    {
        $this->visit('/unsupported-browser')
             ->see('update your browser')
             ->see('Internet Explorer');
    }
}


text:
#ifndef PATH_H
#define PATH_H

#include <limits.h>
#include <stdbool.h>

struct dbpath {
	char database[PATH_MAX];
	char schema[PATH_MAX];
	char table[PATH_MAX];
	char row[PATH_MAX];
	char column[PATH_MAX];
};

#define dbpath_component_is_valid(obj, comp) (((obj).comp)[0] != '\0')

#define dbpath_is_root(obj)     (!dbpath_component_is_valid(obj, database))
#define dbpath_is_database(obj) (!dbpath_component_is_valid(obj, schema))
#define dbpath_is_schema(obj)   (!dbpath_component_is_valid(obj, table))
#define dbpath_is_table(obj)    (!dbpath_component_is_valid(obj, row))
#define dbpath_is_row(obj)      (!dbpath_component_is_valid(obj, column))
#define dbpath_is_column(obj)   (dbpath_component_is_valid(obj, column))

extern int split_path(const char *in, struct dbpath *out);
extern const char *dbpath_to_string(const struct dbpath *in);
extern bool dbpaths_are_same_level(struct dbpath *path1, struct dbpath *path2);

#endif /* PATH_H */


text:
// Copyright (c) 2006 Rice University
// All Rights Reserved
// This code is covered by the Rice-WARP license
// See http://warp.rice.edu/license/ for details

/**
 * \file radio_controller_adv.h
 * \brief Header file for advanced functions of the radio controller.
 *
 * @version 1.09
 * @author Siddharth Gupta
 *
 * This file contains controls the advanced functionality of the radio boards, such as
 * DAC phase offsets, and all the various shutdown and standby states.
 */

#ifndef RADIO_CONTROLLER_ADV_H
#define RADIO_CONTROLLER_ADV_H

/***************************** Include Files *******************************/

#include "radio_prototypes.h"

/****************************** Functions **********************************/

void WarpRadio_v1_SHDNEnable(unsigned int radios);

void WarpRadio_v1_SHDNDisable(unsigned int radios);

void WarpRadio_v1_SHDNSoftControlEnable(unsigned int radios);

void WarpRadio_v1_SHDNSoftControlDisable(unsigned int radios);

void WarpRadio_v1_RxEnSoftControlEnable(unsigned int radios);

void WarpRadio_v1_RxEnSoftControlDisable(unsigned int radios);

void WarpRadio_v1_TxEnSoftControlEnable(unsigned int radios);

void WarpRadio_v1_TxEnSoftControlDisable(unsigned int radios);

void WarpRadio_v1_RxHpSoftControlEnable(unsigned int radios);

void WarpRadio_v1_RxHpSoftControlDisable(unsigned int radios);

void WarpRadio_v1_RxHpEnable(unsigned int radios);

void WarpRadio_v1_RxHpDisable(unsigned int radios);

char WarpRadio_v1_RssiHighBandwidth(char mode, unsigned int radios);

// Returns the temp of the 'radio' specified.
//char WarpRadio_v1_RSSITemp(unsigned char radio);

int WarpRadio_v1_DACSleep(char mode, unsigned int radios);

int WarpRadio_v1_DACFineGainAdj(char chan, unsigned char value, unsigned int radios);

int WarpRadio_v1_DACCoarseGainAdj(char chan, unsigned char value, unsigned int radios);

void WarpRadio_v1_ADCPdwn(char chan, unsigned char value, unsigned int radios);

#endif