text:
package com.cloudera.oryx.app.als;

import java.util.Collections;

import org.junit.Test;

import com.cloudera.oryx.common.OryxTest;

/**
 * Tests {@link MultiRescorerProvider} (implementations).
 */
public final class MultiRescorerProviderTest extends OryxTest {

  @Test
  public void testMultiRecommendRescorer() {
    RescorerProvider multi = MultiRescorerProvider.of(
        new SimpleModRescorerProvider(2), new SimpleModRescorerProvider(3));

    Rescorer provider = multi.getRecommendRescorer(Collections.singletonList("ABCDE"), null);
    assertNull(provider);

    Rescorer provider2 = multi.getRecommendRescorer(Collections.singletonList("AB"), null);
    assertNotNull(provider2);
    assertFalse(provider2 instanceof MultiRescorer);
    assertIsFiltered(provider2, "ABC");
    assertNotFiltered(provider2, "AB");
    assertNaN(provider2.rescore("ABC", 1.0));
    assertEquals(1.0, provider2.rescore("AB", 1.0));

    Rescorer provider3 = multi.getRecommendRescorer(Collections.singletonList("ABCDEF"), null);
    assertNotNull(provider3);
    assertInstanceOf(provider3, MultiRescorer.class);
    assertIsFiltered(provider3, "ABC");
    assertIsFiltered(provider3, "AB");
    assertNotFiltered(provider3, "ABCDEFABCDEF");
    assertNaN(provider3.rescore("ABC", 1.0));
    assertEquals(1.0, provider3.rescore("ABCDEFABCDEF", 1.0));
  }

  @Test
  public void testMultiRecommendToAnonymousRescorer() {
    RescorerProvider multi = MultiRescorerProvider.of(
        new SimpleModRescorerProvider(2), new SimpleModRescorerProvider(3));

    Rescorer provider = multi.getRecommendToAnonymousRescorer(
        Collections.singletonList("ABCDE"), null);
    assertNull(provider);

    Rescorer provider2 =
        multi.getRecommendToAnonymousRescorer(Collections.singletonList("AB"), null);
    assertNotNull(provider2);
    assertFalse(provider2 instanceof MultiRescorer);
    assertIsFiltered(provider2, "ABC");
    assertNotFiltered(provider2, "AB");

    Rescorer provider3 =
        multi.getRecommendToAnonymousRescorer(Collections.singletonList("ABCDEF"), null);
    assertNotNull(provider3);
    assertInstanceOf(provider3, MultiRescorer.class);
    assertIsFiltered(provider3, "ABC");
    assertIsFiltered(provider3, "AB");
    assertNotFiltered(provider3, "ABCDEF");
  }

  @Test
  public void testMultiMostPopularItemsRescorer() {
    RescorerProvider multi = MultiRescorerProvider.of(
        new SimpleModRescorerProvider(2), new SimpleModRescorerProvider(3));
    Rescorer provider = multi.getMostPopularItemsRescorer(null);
    assertNotNull(provider);
    assertInstanceOf(provider, MultiRescorer.class);
    assertIsFiltered(provider, "ABC");
    assertIsFiltered(provider, "AB");
    assertNotFiltered(provider, "ABCDEF");
  }

  @Test
  public void testMultiMostActiveUsersRescorer() {
    RescorerProvider multi = MultiRescorerProvider.of(
        new SimpleModRescorerProvider(2), new SimpleModRescorerProvider(3));
    Rescorer provider = multi.getMostActiveUsersRescorer(null);
    assertNotNull(provider);
    assertInstanceOf(provider, MultiRescorer.class);
    assertIsFiltered(provider, "ABC");
    assertIsFiltered(provider, "AB");
    assertNotFiltered(provider, "ABCDEF");
  }

  @Test
  public void testMultiMostSimilarItemsRescorer() {
    RescorerProvider multi = MultiRescorerProvider.of(
        new SimpleModRescorerProvider(2), new SimpleModRescorerProvider(3));
    Rescorer provider = multi.getMostSimilarItemsRescorer(null);
    assertNotNull(provider);
    assertInstanceOf(provider, MultiRescorer.class);
    assertIsFiltered(provider, "ABC");
    assertIsFiltered(provider, "ABCDE");
    assertNotFiltered(provider, "ABCDEFABCDEF");
  }

  private static void assertIsFiltered(Rescorer rescorer, String value) {
    assertTrue(rescorer + " should filter " + value, rescorer.isFiltered(value));
  }

  private static void assertNotFiltered(Rescorer rescorer, String value) {
    assertFalse(rescorer + " should not filter " + value, rescorer.isFiltered(value));
  }

}

redpajama_set_name: RedPajamaGithub


text:
"""
Find highly-connected k-mers.

k-mers are output into a .stoptags file, for later use in partitioning.

% python scripts/find-knots.py <base>
"""
from __future__ import print_function

import argparse
import glob
import os
import textwrap
import khmer
import sys
from khmer.kfile import check_input_files, check_space
from khmer import khmer_args
from khmer.khmer_args import (build_counting_args, info, add_loadhash_args,
                              report_on_config)

# counting hash parameters.
DEFAULT_COUNTING_HT_SIZE = 3e6                # number of bytes
DEFAULT_COUNTING_HT_N = 4                     # number of counting hash tables

# Lump removal parameters.  Probably shouldn't be changed, but who knows?
#
# explanation:
#
# We will walk EXCURSION_DISTANCE out from each tag; if we find more than
# EXCURSION_KMER_THRESHOLD kmers within that range, this will be a "big"
# excursion and we will track all k-mers visited.  If we find that any
# k-mer has been visited more than EXCURSION_KMER_COUNT_THRESHOLD times,
# we will mark it as BAD and make it a stop tag for traversal.

# don't change these!
EXCURSION_DISTANCE = 40
EXCURSION_KMER_THRESHOLD = 200
EXCURSION_KMER_COUNT_THRESHOLD = 2
# EXCURSION_KMER_COUNT_THRESHOLD=5 # -- works ok for non-diginormed data

def get_parser():
    epilog = """
    Load an k-mer presence table/tagset pair created by load-graph, and a set
    of pmap files created by partition-graph. Go through each pmap file,
    select the largest partition in each, and do the same kind of traversal as
    in :program:`make-initial-stoptags.py` from each of the waypoints in that
    partition; this should identify all of the HCKs in that partition. These
    HCKs are output to <graphbase>.stoptags after each pmap file.

    Parameter choice is reasonably important. See the pipeline in
    :doc:`partitioning-big-data` for an example run.

    This script is not very scalable and may blow up memory and die horribly.
    You should be able to use the intermediate stoptags to restart the
    process, and if you eliminate the already-processed pmap files, you can
    continue where you left off.
    """
    parser = build_counting_args(
        descr="Find all highly connected k-mers.",
        epilog=textwrap.dedent(epilog))

    parser.add_argument('graphbase', help='Basename for the input and output '
                        'files.')
    parser.add_argument('-f', '--force', default=False, action='store_true',
                        help='Continue past warnings')
    return parser

def main():
    info('find-knots.py', ['graph'])
    args = get_parser().parse_args()

    graphbase = args.graphbase

    # @RamRS: This might need some more work
    infiles = [graphbase + '.pt', graphbase + '.tagset']
    if os.path.exists(graphbase + '.stoptags'):
        infiles.append(graphbase + '.stoptags')
    for _ in infiles:
        check_input_files(_, args.force)

    check_space(infiles, args.force)

    print('loading k-mer presence table %s.pt' % graphbase, file=sys.stderr)
    htable = khmer.load_hashbits(graphbase + '.pt')

    print('loading tagset %s.tagset...' % graphbase, file=sys.stderr)
    htable.load_tagset(graphbase + '.tagset')

    initial_stoptags = False    # @CTB regularize with make-initial
    if os.path.exists(graphbase + '.stoptags'):
        print('loading stoptags %s.stoptags' % graphbase, file=sys.stderr)
        htable.load_stop_tags(graphbase + '.stoptags')
        initial_stoptags = True

    pmap_files = glob.glob(args.graphbase + '.subset.*.pmap')

    print('loading %d pmap files (first one: %s)' %
          (len(pmap_files), pmap_files[0]), file=sys.stderr)
    print('---', file=sys.stderr)
    print('output stoptags will be in',
          graphbase + '.stoptags', file=sys.stderr)
    if initial_stoptags:
        print(
            '(these output stoptags will include the already-loaded set)',
            file=sys.stderr)
    print('---', file=sys.stderr)

    # create counting hash
    ksize = htable.ksize()
    counting = khmer_args.create_countgraph(args, ksize=ksize)

    # load & merge
    for index, subset_file in enumerate(pmap_files):
        print('<-', subset_file, file=sys.stderr)
        subset = htable.load_subset_partitionmap(subset_file)

        print('** repartitioning subset... %s' % subset_file, file=sys.stderr)
        htable.repartition_largest_partition(subset, counting,
                                             EXCURSION_DISTANCE,
                                             EXCURSION_KMER_THRESHOLD,
                                             EXCURSION_KMER_COUNT_THRESHOLD)

        print('** merging subset... %s' % subset_file, file=sys.stderr)
        htable.merge_subset(subset)

        print('** repartitioning, round 2... %s' %
              subset_file, file=sys.stderr)
        size = htable.repartition_largest_partition(
            None, counting, EXCURSION_DISTANCE, EXCURSION_KMER_THRESHOLD,
            EXCURSION_KMER_COUNT_THRESHOLD)

        print('** repartitioned size:', size, file=sys.stderr)

        print('saving stoptags binary', file=sys.stderr)
        htable.save_stop_tags(graphbase + '.stoptags')
        os.rename(subset_file, subset_file + '.processed')
        print('(%d of %d)\n' % (index, len(pmap_files)), file=sys.stderr)

    print('done!', file=sys.stderr)

if __name__ == '__main__':
    main()


text:
      <homepage-header-component></homepage-header-component>

    <button (click)="runCollapsed($event)"
            class="navbar-toggler navbar-toggler-right"
            type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent"
            aria-expanded="false"
            aria-label="Toggle navigation"
    >

    </button>

          Home

          Code

          People

          Contact Us


text:
<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Plugin Tests</title>
		<base href="../../../">

		<link rel=StyleSheet href="./test/resources/qunit-2.10.0.css" type="text/css" media=screen />

Plugin-object Unit Tests


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Able Polecat: AblePolecat_AccessControl_Role_User_AuthenticatedInterface Interface Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Able Polecat
    0.7.0

Able Polecat Core Class Library

Main Page

Related Pages

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Class Hierarchy

Data Fields

Public Member Functions

AblePolecat_AccessControl_Role_User_AuthenticatedInterface Interface Reference

Inheritance diagram for AblePolecat_AccessControl_Role_User_AuthenticatedInterface:

  <map id="AblePolecat_AccessControl_Role_User_AuthenticatedInterface_map" name="AblePolecat_AccessControl_Role_User_AuthenticatedInterface_map">
<area href="interface_able_polecat___access_control___role___user_interface.html" alt="AblePolecat_AccessControl_Role_UserInterface" shape="rect" coords="214,224,633,248"/>
<area href="interface_able_polecat___access_control___role_interface.html" alt="AblePolecat_AccessControl_RoleInterface" shape="rect" coords="214,168,633,192"/>
<area href="interface_able_polecat___access_control___subject_interface.html" alt="AblePolecat_AccessControl_SubjectInterface" shape="rect" coords="0,112,419,136"/>
<area href="interface_able_polecat___cache_object_interface.html" alt="AblePolecat_CacheObjectInterface" shape="rect" coords="429,112,848,136"/>
<area href="interface_able_polecat___access_control___article___dynamic_interface.html" alt="AblePolecat_AccessControl_Article_DynamicInterface" shape="rect" coords="0,56,419,80"/>
<area href="interface_able_polecat___access_control___article_interface.html" alt="AblePolecat_AccessControl_ArticleInterface" shape="rect" coords="0,0,419,24"/>
<area href="class_able_polecat___access_control___role___user___authenticated.html" alt="AblePolecat_AccessControl_Role_User_Authenticated" shape="rect" coords="0,336,419,360"/>
<area href="interface_able_polecat___access_control___role___user___authenticated___o_auth2_interface.html" alt="AblePolecat_AccessControl_Role_User_Authenticated_OAuth2Interface" shape="rect" coords="429,336,848,360"/>
<area href="class_able_polecat___access_control___role___user___authenticated___o_auth2_abstract.html" alt="AblePolecat_AccessControl_Role_User_Authenticated_OAuth2Abstract" shape="rect" coords="429,392,848,416"/>
</map>

Public Member Functions

 	getAuthority ()

 Public Member Functions inherited from AblePolecat_AccessControl_Article_DynamicInterface

 	getId ()

 	getName ()

 Public Member Functions inherited from AblePolecat_CacheObjectInterface

 	sleep (AblePolecat_AccessControl_SubjectInterface $Subject=NULL)

Additional Inherited Members

 Static Public Member Functions inherited from AblePolecat_AccessControl_ArticleInterface

static 	getScope ()

 Static Public Member Functions inherited from AblePolecat_CacheObjectInterface

static 	wakeup (AblePolecat_AccessControl_SubjectInterface $Subject=NULL)

Member Function Documentation

          getAuthority
          (
          	)

Returns

string ID of authenticating authority.

Implemented in AblePolecat_AccessControl_Role_User_Authenticated.

The documentation for this interface was generated from the following file:

C:/wamp/www/polecat/public/core/AccessControl/Role/User/Authenticated.php

AblePolecat_AccessControl_Role_User_AuthenticatedInterface

Generated on Fri Apr 10 2015 11:24:45 for Able Polecat by

     1.8.9.1


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.3.4.5.1-4-9
description: >
    [[Call]] - length of parameters of 'target' is 0, length of
    'boundArgs' is 1, length of 'ExtraArgs' is 1, and with 'boundThis'
includes: [runTestCase.js]
---*/

function testcase() {
        var obj = { prop: "abc" };

        var func = function () {
            return this === obj && arguments[0] === 1 && arguments[1] === 2;
        };

        var newFunc = Function.prototype.bind.call(func, obj, 1);

        return newFunc(2);
    }
runTestCase(testcase);


text:
package dk.sample.rest.semantic.id;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class NonSensitiveSemanticIDTest {

    @Test
    public void testNormalPersonID() {
        DKPersonSample hansPedersen = new DKPersonSample("Hans","Peter","Pedersen","123100-1234");
        assertEquals("hans-peter-pedersen-1231", hansPedersen.getHumanReadableNonSensitiveID());
    }

    @Test
    public void testPersonIDNoMiddlename() {
        DKPersonSample hansPedersen = new DKPersonSample("Hans","","Pedersen","123100-1234");
        assertEquals("hans-pedersen-1231", hansPedersen.getHumanReadableNonSensitiveID());
    }

    @Test
    public void testPersonIDShortMiddlename() {
        DKPersonSample hansPedersen = new DKPersonSample("Hans","C","Pedersen","123100-1234");
        assertEquals("hans-c-pedersen-1231", hansPedersen.getHumanReadableNonSensitiveID());
    }

    @Test
    public void testPersonIDLongSirname() {
        DKPersonSample hansPedersen = new DKPersonSample("Hans","C","Pedersen-Jensen-Olsen","123100-1234");
        assertEquals("hans-c-pedersen-j-1231", hansPedersen.getHumanReadableNonSensitiveID());
    }

    @Test
    public void testPersonIDLongName() {
        DKPersonSample hansPedersen = new DKPersonSample("Hans Georg Henrik","Jannerik Clauserik ","Pedersen-Jensen-Olsen","123100-1234");
        assertEquals("hansgeorgh-jannerikcl-pedersen-j-1231", hansPedersen.getHumanReadableNonSensitiveID());
    }

    @Test
    public void testPersonIDSpecialName() {
        DKPersonSample soerenHaagear = new DKPersonSample("Søren","HøstBlomst","Hågemæger","123100-1234");
        assertEquals("soeren-hoestbloms-haagemaege-1231", soerenHaagear.getHumanReadableNonSensitiveID());
    }

    @Test
    public void testPersonIDNonUnique() {
        DKPersonSample soerenHaagear = new DKPersonSample("Søren","P","Æblegård","123100-1234");
        assertEquals("soeren-p-aeblegaard-1231", soerenHaagear.getHumanReadableNonSensitiveID());
        assertEquals("soeren-p-aeblegaard-1231-1", soerenHaagear.adjustHumanReadableNonSensitiveID(1));
        soerenHaagear = new DKPersonSample("Søren","P","Æblegård","123100-1234");
        assertEquals("soeren-p-aeblegaard-1231-2", soerenHaagear.adjustHumanReadableNonSensitiveID(2));
        soerenHaagear = new DKPersonSample("Søren","P","Æblegård","123100-1234");
        assertEquals("soeren-p-aeblegaard-1231-999", soerenHaagear.adjustHumanReadableNonSensitiveID(999));
    }

}


text:
module Google
  class APIClient
    ##
    # This class wraps a result returned by an API call.
    class Result
      def initialize(reference, request, response)
        @reference = reference
        @request = request
        @response = response
      end

      attr_reader :reference

      attr_reader :request

      attr_reader :response

      def status
        return @response[0]
      end

      def headers
        return @response[1]
      end

      def body
        return @body ||= (begin
          response_body = @response[2]
          merged_body = (response_body.inject(StringIO.new) do |accu, chunk|
            accu.write(chunk)
            accu
          end).string
        end)
      end

      def data
        return @data ||= (begin
          _, content_type = self.headers.detect do |h, v|
            h.downcase == 'Content-Type'.downcase
          end
          media_type = content_type[/^([^;]*);?.*$/, 1].strip.downcase
          data = self.body
          case media_type
          when 'application/json'
            data = ::JSON.parse(data)
            # Strip data wrapper, if present
            data = data['data'] if data.has_key?('data')
          else
            raise ArgumentError,
              "Content-Type not supported for parsing: #{media_type}"
          end
          if @reference.api_method && @reference.api_method.response_schema
            # Automatically parse using the schema designated for the
            # response of this API method.
            data = @reference.api_method.response_schema.new(data)
            data
          else
            # Otherwise, return the raw unparsed value.
            # This value must be indexable like a Hash.
            data
          end
        end)
      end

      def pagination_type
        return :token
      end

      def page_token_param
        return "pageToken"
      end

      def next_page_token
        if self.data.respond_to?(:next_page_token)
          return self.data.next_page_token
        elsif self.data.respond_to?(:[])
          return self.data["nextPageToken"]
        else
          raise TypeError, "Data object did not respond to #next_page_token."
        end
      end

      def next_page
        merged_parameters = Hash[self.reference.parameters].merge({
          self.page_token_param => self.next_page_token
        })
        # Because References can be coerced to Hashes, we can merge them,
        # preserving all context except the API method parameters that we're
        # using for pagination.
        return Google::APIClient::Reference.new(
          Hash[self.reference].merge(:parameters => merged_parameters)
        )
      end

      def prev_page_token
        if self.data.respond_to?(:prev_page_token)
          return self.data.prev_page_token
        elsif self.data.respond_to?(:[])
          return self.data["prevPageToken"]
        else
          raise TypeError, "Data object did not respond to #next_page_token."
        end
      end

      def prev_page
        merged_parameters = Hash[self.reference.parameters].merge({
          self.page_token_param => self.prev_page_token
        })
        # Because References can be coerced to Hashes, we can merge them,
        # preserving all context except the API method parameters that we're
        # using for pagination.
        return Google::APIClient::Reference.new(
          Hash[self.reference].merge(:parameters => merged_parameters)
        )
      end
    end
  end
end


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

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

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this._errorProvider = new System.Windows.Forms.ErrorProvider(this.components);
            ((System.ComponentModel.ISupportInitialize)(this._errorProvider)).BeginInit();
            this.SuspendLayout();
            //
            // _errorProvider
            //
            this._errorProvider.ContainerControl = this;
            //
            // MainForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "MainForm";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "GmailNotifier.NET";
            this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
            ((System.ComponentModel.ISupportInitialize)(this._errorProvider)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.ErrorProvider _errorProvider;
    }
}


text:
#ifndef VBOOT_REFERENCE_LOAD_FIRMWARE_FW_H_
#define VBOOT_REFERENCE_LOAD_FIRMWARE_FW_H_

#include "vboot_api.h"
#include "vboot_nvstorage.h"
#include "vboot_struct.h"

/**
 * Load the rewritable firmware.
 *
 * Pass the common and firmware params from VbSelectFirmware(), and a
 * VbNvContext.  Caller is responsible for calling VbNvSetup() and
 * VbNvTeardown() on the VbNvContext.
 *
 * Returns VBERROR_SUCCESS if successful.  If unsuccessful, sets a recovery
 * reason via VbNvStorage and returns an error code.
 */
int LoadFirmware(VbCommonParams *cparams, VbSelectFirmwareParams *fparams,
		 VbNvContext *vnc);

#endif  /* VBOOT_REFERENCE_LOAD_FIRMWARE_FW_H_ */


text:
/* global $componentController */
/* eslint-disable no-unused-expressions */
describe('Component: customDropdown ', function () {
  let ctrl
  let updateSpy

  beforeEach(function () {
    module('app.core', 'app.shared')
    bard.inject('$componentController')
    ctrl = $componentController('customDropdown', {}, {
      config: {
        'test': 'test'
      },
      items: ['item1', 'item2'],
      onUpdate: function () {},
      menuRight: true
    })
    updateSpy = sinon.stub(ctrl, 'onUpdate').returns(true)
  })

  it('is defined', function () {
    expect(ctrl).to.exist
  })

  it('should handle changes', () => {
    ctrl.$onChanges()
    expect(updateSpy).have.been.calledWith(
      {$changes: ['item1', 'item2'], $config: {test: 'test'}})
  })

  it('should handle actions', () => {
    const options = {
      isDisabled: false,
      actionFn: function () {}
    }
    const actionFnSpy = sinon.stub(options, 'actionFn').returns(true)
    ctrl.$onInit()
    ctrl.handleAction(options)
    expect(actionFnSpy).to.have.been.called
  })
})


text:
package com.hauldata.util.tokenizer;

import java.io.IOException;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.util.regex.Pattern;

public abstract class BaseTokenizer {

	private Reader reader;

	public enum CharType { unknown, whitespace, alphabetic, numeric, quote, delimiter, endOfLine };

	final static char cr = '\r';
	final static char lf = '\n';

	private final static char decimalPoint = '.';
	private final static char minusSign = '-';
	private final static char exponential = 'E';

	final static int maxSupportedCharCode = 255;
	private CharType[] charType = new CharType[maxSupportedCharCode + 1];

	public enum EscapeType { doubleQuote, json };

	private boolean eolIsSignificant;
	private boolean splitQuoteIsAllowed;
	private boolean negativeIsRespected;
	private EscapeType escapeType;

	private int lookaheadChar;
	private Token lookaheadToken;
	private Token lookbackToken;
	private int lineNumber;

	protected BaseTokenizer(Reader reader, boolean isNumericRecognized) {

		this.reader = reader;

		setCharType(CharType.unknown, 0, maxSupportedCharCode);

		if (isNumericRecognized) {
			setCharType(CharType.numeric, (int)'0', (int)'9');
		}

		charType[(int)cr] = CharType.endOfLine;
		charType[(int)lf] = CharType.endOfLine;

		eolIsSignificant = true;
		splitQuoteIsAllowed = true;
		negativeIsRespected = false;
		escapeType = EscapeType.doubleQuote;

		lineNumber = 1;

		lookaheadChar = noChar;
		lookaheadToken = null;
		lookbackToken = null;
	}

	protected BaseTokenizer(Reader reader) {
		this(reader, true);
	}

	/**
     * Sets the type of a range of characters.
     *
     * @return	this tokenizer
	 */
	public BaseTokenizer setCharType(CharType charType, int low, int hi) {
		for (int i = low; i <= hi; ++i) {
			this.charType[i] = charType;
		}
		return this;
	}

	/**
     * Sets the type of a single character.
     *
     * @return	this tokenizer
	 */
	public BaseTokenizer setCharType(CharType charType, char ch) {
		this.charType[(int)ch] = charType;
		return this;
	}

	protected CharType getCharType(char ch) {
		return charType[(int)ch];
	}

    /**
     * Determines whether or not ends of line are treated as tokens.
     * If the flag argument is true, this tokenizer treats end of lines
     * as tokens; the nextToken method returns an
     * EndOfLine object.
     *

     * If the flag is false, end-of-line characters are
     * treated as white space and serve only to separate tokens.
     *
     * @param	flag	true indicates that end-of-line characters
     *					are separate tokens; false indicates that
     *					end-of-line characters are white space.
     *
     * @return	this tokenizer
     * @see		java.io.StreamTokenizer#eolIsSignificant(boolean)
	 */
	public BaseTokenizer eolIsSignificant(boolean flag) {
        eolIsSignificant = flag;
		return this;
    }

	/**
     * Determines whether or not quoted strings may be split across lines.
     * If the flag argument is true, this tokenizer allows an opening quote
     * to appear on one line and the closing quote to appear on a subsequent
     * line.  The quoted string token includes any carriage return or
     * line break characters contained within the quotes.
     *

     * If the flag is false, an opening quote must be closed
     * on the same line.  If not, the token is terminated at end of line
     * and is returned as Unknown type instead of Quoted.
     *
     * This must only be used in conjunction with eolIsSignificant(true);
     * otherwise, results are unpredictable.
     *
     * @param	flag	true indicates that quoted string
     *					may be split across lines; false
     *					indicates that quoted string must be contained
     *					on a single line.
     *
     * @return	this tokenizer
     * @see		java.io.StreamTokenizer#eolIsSignificant(boolean)
	 */
	public BaseTokenizer splitQuoteIsAllowed(boolean flag) {
		splitQuoteIsAllowed = flag;
		return this;
	}

    /**
     * Determines whether or not the negative sign is considered
     * to be part of a numeric token.
     * If the flag argument is true, this tokenizer treats a leading negative
     * sign as part of a Numeric<Type> token; the object returned by
     * getValue() has a negative value.
     *

     * If the flag is false, a leading negative sign is
     * treated as as a separate delimiter token.
     *
     * @param	flag	true indicates that a leading negative
     *					sign is part of a numeric token; false
     *					indicates that leading negative sign is a distinct
     *					delimiter token.
     *
     * @return	this tokenizer
     * @see		java.io.StreamTokenizer#eolIsSignificant(boolean)
	 */
	public BaseTokenizer negativeIsRespected(boolean flag) {
		negativeIsRespected = flag;
		return this;
    }

	/**
	 * Determines how to escape special characters within quoted string.
	 *

	 * @param type	EscapeType.doubleQuote indicates that
	 *				the quote character is escaped by preceding it with
	 *				another quote character;
	 *
	 *				EscapeType.json indicates that backslash
	 *				is the escape character and JSON escape sequences are
	 *				recognized; see https://www.json.org/
	 *
     * @return	this tokenizer
	 */
	public BaseTokenizer escape(EscapeType type) {
		escapeType = type;
		return this;
	}

	/**
     * Returns true if this tokenizer has another token in its input.
     * This method may block while waiting for input to scan.
     * The tokenizer does not advance past any input.
     *
     * @return	true if and only if this tokenizer has another token
     * @throws	IOException if passed by the underlying
     *			java.io.Reader object of this tokenizer.
     */
    public boolean hasNext() throws IOException {
		return (peekToken() != null);
	}

    /**
     * Returns true if this tokenizer has another token on the
     * current line.  This must only be used in conjunction with
     * eolIsSignificant(true); otherwise, results are
     * unpredictable.
     *
     * This method may block while waiting for input to scan.
     * The tokenizer does not advance past any input.
     *
     * @return	true if and only if this tokenizer has another token
     * 			on the current line.
     * @throws	IOException if passed by the underlying
     *			java.io.Reader object of this tokenizer.
     */
    public boolean hasNextOnLine() throws IOException {
    	Object token = peekToken();
		return ((token != null) && !(token instanceof EndOfLine));
	}

    /**
     * Returns true if the next token in this tokenizer's input is a
     * non-whitespace delimiter.  The tokenizer does not advance past any input.
     *
     * @return	true if and only if this tokenizer's next token is a
     *			non-whitespace delimiter
     * @throws	IOException if passed by the underlying
     *			java.io.Reader object of this tokenizer.
     */
	public boolean hasNextDelimiter() throws IOException {
		return (peekToken() instanceof Delimiter);
	}

    /**
     * Scans the next token from the input stream of this tokenizer
     * and returns its value as an object or null if no tokens remain.
     * The following object types may be returned:
     *

     *
Numeric<Integer> - the token consists of all numeric digits within the range of Integer
     *
Numeric<Long> - the token consists of all numeric digits beyond the range of Integer but within the range of Long
     *
Numeric<BigInteger> - the token consists of all numeric digits beyond the range of Long
     *
Numeric<BigDecimal> - the token consists of numeric digits with one leading or embedded decimal point
     *
Word - the token is an identifier consisting of word characters starting with an alphabetic character
     *
Quoted - the token is quoted text
     *
Delimiter - the token is a non-whitespace delimiter
     *
EndOfLine - the token is end of line
     *
Unknown - the token contains an unrecognized combination of characters
     *
null - no tokens remain in the input stream
     *

     *

     * Typical clients of this
     * class first set up the syntax tables and then sit in a loop
     * calling nextToken to parse successive tokens until null
     * is returned.
     *
     * @return	an object representing the value of the scanned token or null
     * @throws	IOException if passed by the underlying
     *			java.io.Reader object of this scanner.
     * @throws	InputMismatchException if the next token is not a recognized type
     * @see		BaseTokenizer#eolIsSignificant(boolean)
     * @see		BaseTokenizer#useDelimiter(Pattern)
     * @see		BaseTokenizer#useDelimiter(String)
     */
	public Token nextToken() throws IOException, InputMismatchException {
		Token token = peekToken();
		lookaheadToken = null;
		return rememberToken(token);
	}

    /**
     * Scans the next token from the current line of the input stream
     * and returns its value as an object or null if no tokens remain
     * on the line.  This must only be used in conjunction with
     * eolIsSignificant(true); otherwise, results are
     * unpredictable.
     *

     * The last line of a text file is not guaranteed to be terminated
     * with an end-of-line character sequence.  It instead may be
     * terminated by end of file.  This method makes it unnecessary to
     * test for both end of line and end of file.
     *

     * If end of line is detected by this method, it is discarded.
     * If end of file is detected, it is effectively pushed back
     * so it will be detected by a subsequent call to
     * hasNext() or nextToken().
     *

     * This method cannot be used by the caller to detect end of file.
     * Another method must be used.
     *
     * @return	an object representing the value of the scanned token or
     *			null if end of line or end of file is found
     * @throws	IOException if passed by the underlying
     *			java.io.Read object of this scanner.
     * @throws	InputMismatchException if the next token is not a recognized type
     * @see		BaseTokenizer#eolIsSignificant(boolean)
     * @see		BaseTokenizer#nextToken()
     * @see		BaseTokenizer#hasNext()
     */
	public Token nextTokenOnLine() throws IOException, InputMismatchException {
		Token token = peekToken();
		if (token != null) {
			nextToken();
			if (token instanceof EndOfLine) {
				token = null;
			}
		}
		return rememberToken(token);
	}

	protected Token rememberToken(Token scannedToken) {
		lookbackToken = scannedToken;
		return scannedToken;
	}

	/**
	 * @return the last token scanned
	 */
	public Token lastToken() {
		return lookbackToken;
	}

	/**
     * @see		java.io.StreamTokenizer#lineno()
	 */
	public int lineno() {
		return lineNumber;
	}

	/**
	 * Closes the tokenizer and releases any system resources associated with it
	 * including the underlying Reader.
	 *
	 * @throws IOException
	 */
	public void close() throws IOException {
		reader.close();
	}

	// Physical token scanning

	protected Token peekToken() throws IOException, InputMismatchException {
		if (lookaheadToken == null) {
			lookaheadToken = getToken();
		}
		return lookaheadToken;
	}

	protected Token getToken() throws IOException {

		Token token = skipWhitespace();
		if (!(token instanceof Unknown)) {
			return token;
		}

		int intChar = nextChar();

		if (intChar == eofChar) {
			return null;
		}

		if (negativeIsRespected && ((char)intChar == minusSign)) {
			if (hasNextNumericChar()) {
				return parseInteger(token.hasLeadingWhitespace(), new StringBuilder(String.valueOf(minusSign)), true);
			}
			else if ((char)peekChar() == decimalPoint) {
				return parseDecimal(token.hasLeadingWhitespace(), new StringBuilder(String.valueOf(minusSign)), BigDecimal.ZERO, true);
			}
		}
		else if (((char)intChar == decimalPoint) && hasNextNumericChar()) {
			pushChar(intChar);
			return parseDecimal(token.hasLeadingWhitespace(), new StringBuilder(), BigDecimal.ZERO, false);
		}

		switch (charTypeOf(intChar)) {
		case delimiter:
			return parseDelimiter(token.hasLeadingWhitespace(), (char)intChar);
		case alphabetic:
			pushChar(intChar);
			return parseWord(token.hasLeadingWhitespace());
		case numeric:
			pushChar(intChar);
			return parseInteger(token.hasLeadingWhitespace(), new StringBuilder(), false);
		case quote:
			return parseQuoted(token.hasLeadingWhitespace(), (char)intChar);
		case endOfLine:
			return parseEndOfLine((char)intChar);
		default:
		case unknown:
			StringBuilder image = new StringBuilder(String.valueOf((char)intChar));
			return parseUnknown(token.hasLeadingWhitespace(), image);
		}
	}

	/**
	 * Skips whitespace characters in the input stream.
	 * @return an instance of Delimiter parsed from the input stream if the next token is a delimiter token,
	 * otherwise an instance of Unknown.  In the latter case, no token is actually parsed from the input stream
	 * but the hasLeadingWhitespace() member tells if whitespace was actually skipped.
	 * @throws IOException
	 */
	protected abstract Token skipWhitespace() throws IOException;

	protected abstract Delimiter parseDelimiter(boolean leadingWhitespace, char leader) throws IOException;

	protected abstract Token parseWord(boolean leadingWhitespace) throws IOException;

	private Token parseInteger(boolean leadingWhitespace, StringBuilder image, boolean negate) throws IOException {

		final int maxDiv10 = Integer.MAX_VALUE / 10;
		final int maxMod10 = Integer.MAX_VALUE - (maxDiv10 * 10);

		int value = 0;
		while (hasNextNumericChar())  {

			int intChar = nextChar();

			int digit = intChar - (int)'0';

			if ((value > maxDiv10) || ((value == maxDiv10) && (digit >= maxMod10))) {
				pushChar(intChar);
				return parseLong(leadingWhitespace, image, value, negate);
			}

			image.append((char)intChar);

			value = value * 10 + digit;
		}

		if ((char)peekChar() == decimalPoint) {
			return parseDecimal(leadingWhitespace, image, BigDecimal.valueOf(value), negate);
		}

		if ((char)peekChar() == exponential) {
			return parseScientific(leadingWhitespace, image, BigDecimal.valueOf(value), negate);
		}

		if (!hasNextTerminatingChar()) {
			return parseUnknown(leadingWhitespace, image);
		}

		if (negate) {
			value = -value;
		}

		return new Numeric<Integer>(leadingWhitespace, image.toString(), value);
	}

	private Token parseLong(boolean leadingWhitespace, StringBuilder image, int valueSoFar, boolean negate) throws IOException {

		final long maxDiv10 = Long.MAX_VALUE / 10;
		final long maxMod10 = Long.MAX_VALUE - (maxDiv10 * 10);

		long value = valueSoFar;
		while (hasNextNumericChar())  {

			int intChar = nextChar();

			int digit = intChar - (int)'0';

			if ((value > maxDiv10) || ((value == maxDiv10) && (digit >= maxMod10))) {
				pushChar(intChar);
				return parseBigInteger(leadingWhitespace, image, value, negate);
			}

			image.append((char)intChar);

			value = value * 10 + digit;
		}

		if ((char)peekChar() == decimalPoint) {
			return parseDecimal(leadingWhitespace, image, BigDecimal.valueOf(value), negate);
		}

		if ((char)peekChar() == exponential) {
			return parseScientific(leadingWhitespace, image, BigDecimal.valueOf(value), negate);
		}

		if (!hasNextTerminatingChar()) {
			return parseUnknown(leadingWhitespace, image);
		}

		if (negate) {
			value = -value;
		}

		return new Numeric<Long>(leadingWhitespace, image.toString(), value);
	}

	private Token parseBigInteger(boolean leadingWhitespace, StringBuilder image, long valueSoFar, boolean negate) throws IOException {

		BigInteger value = BigInteger.valueOf(valueSoFar);
		while (hasNextNumericChar())  {

			int intChar = nextChar();

			int digit = intChar - (int)'0';

			image.append((char)intChar);

			value = value.multiply(BigInteger.TEN).add(BigInteger.valueOf(digit));
		}

		if ((char)peekChar() == decimalPoint) {
			return parseDecimal(leadingWhitespace, image, new BigDecimal(value), negate);
		}

		if ((char)peekChar() == exponential) {
			return parseScientific(leadingWhitespace, image, new BigDecimal(value), negate);
		}

		if (!hasNextTerminatingChar()) {
			return parseUnknown(leadingWhitespace, image);
		}

		if (negate) {
			value = value.negate();
		}

		return new Numeric<BigInteger>(leadingWhitespace, image.toString(), value);
	}

	private Token parseDecimal(boolean leadingWhitespace, StringBuilder image, BigDecimal value, boolean negate) throws IOException {

		if ((char)nextChar() != decimalPoint) {
			throw new InputMismatchException("parseDecimal() requires decimal point to be the next character parsed");
		}

		image.append(decimalPoint);

		int decimalPlaces = 0;
		while (hasNextNumericChar())  {

			++decimalPlaces;

			int intChar = nextChar();

			int digit = intChar - (int)'0';

			image.append((char)intChar);

			value = value.add(BigDecimal.valueOf(digit, decimalPlaces));
		}

		if ((decimalPlaces == 0) || ((char)peekChar() == decimalPoint)) {
			return parseUnknown(leadingWhitespace, image);
		}

		if ((char)peekChar() == exponential) {
			return parseScientific(leadingWhitespace, image, value, negate);
		}

		if (!hasNextTerminatingChar()) {
			return parseUnknown(leadingWhitespace, image);
		}

		if (negate) {
			value = value.negate();
		}

		return new Numeric<BigDecimal>(leadingWhitespace, image.toString(), value);
	}

	private Token parseScientific(boolean leadingWhitespace, StringBuilder image, BigDecimal value, boolean negate) throws IOException {

		if ((char)nextChar() != exponential) {
			throw new InputMismatchException("parseScientific() requires \"" + String.valueOf(exponential) + "\" to be the next character parsed");
		}

		image.append(exponential);

		boolean negateExponent = false;
		if ((char)peekChar() == minusSign) {
			negateExponent = true;
			nextChar();
		}

		if (!hasNextNumericChar()) {
			return parseUnknown(leadingWhitespace, image);
		}

		int exponent = 0;
		while (hasNextNumericChar())  {

			int intChar = nextChar();

			image.append((char)intChar);

			int digit = intChar - (int)'0';

			exponent = exponent * 10 + digit;

			if (exponent > Double.MAX_EXPONENT) {
				return parseUnknown(leadingWhitespace, image);
			}
		}

		if (!hasNextTerminatingChar()) {
			return parseUnknown(leadingWhitespace, image);
		}

		if (negateExponent) {
			exponent = -exponent;
		}

		value = value.movePointRight(exponent);

		if (negate) {
			value = value.negate();
		}

		return new Numeric<BigDecimal>(leadingWhitespace, image.toString(), value);
	}

	private Token parseQuoted(boolean leadingWhitespace, char quote) throws IOException {

		StringBuilder image = new StringBuilder();

		boolean isQuoteClosed = false;

		int intChar;
		while (peekChar() != eofChar) {
			intChar = nextChar();

			if ((char)intChar == quote) {
				if ((escapeType == EscapeType.doubleQuote) && ((char)peekChar() == quote)) {
					nextChar();
					image.append(quote);
				}
				else {
					isQuoteClosed = true;
					break;
				}
			}
			else if ((escapeType == EscapeType.json) && ((char)intChar == '\\')) {
				intChar = nextJsonEscapeChar();
				if (intChar == noChar) {
					break;
				}
				else {
					image.append((char)intChar);
				}
			}
			else {
				if (!splitQuoteIsAllowed && (charTypeOf(intChar) == CharType.endOfLine)) {
					pushChar(intChar);
					break;
				}
				else {
					image.append((char)intChar);
				}
			}
		}

		if (!isQuoteClosed) {
			return new Unknown(leadingWhitespace, image.insert(0, quote).toString());
		}

		if (!hasNextTerminatingChar()) {
			return parseUnknown(leadingWhitespace, image.insert(0, quote).append(quote));
		}

		return new Quoted(leadingWhitespace, quote, image.toString());
	}

	private EndOfLine parseEndOfLine(char sentinel) throws IOException {

		if (sentinel == cr) {
			if ((char)peekChar() == lf) {
				nextChar();
			}
		}
		return EndOfLine.value;
	}

	protected Unknown parseUnknown(boolean leadingWhitespace, StringBuilder image) throws IOException {

		while (!hasNextTerminatingChar()) {
			image.append((char)nextChar());
		}
		return new Unknown(leadingWhitespace, image.toString());
	}

	// JSON escape scanning

	private int nextJsonEscapeChar() throws IOException {
		int intChar = nextChar();

		switch (intChar) {
		case 'b': return '\b';
		case 'f': return '\f';
		case 'n': return '\n';
		case 'r': return '\r';
		case 't': return '\t';
		case 'u': return nextJsonHexEscape();
		default: return intChar;
		}
	}

	private int nextJsonHexEscape() throws IOException {

		StringBuilder hex = new StringBuilder();
		for (int i = 0; i < 4; ++i) {
			int intChar = nextChar();
			if (intChar < 0) {
				return noChar;
			}
			char ch = (char)intChar;
			if (Character.digit(ch, 16) == -1) {
				return noChar;
			}
			hex.append(ch);
		}
		int intChar = Integer.parseInt(hex.toString(), 16);
		return (0 <= intChar) ? intChar : noChar;
	}

	// Logical character scanning

	protected boolean hasNextTerminatingChar() throws IOException {
		CharType type = charTypeOf(peekChar());
		return (type == CharType.delimiter) || (type == CharType.whitespace) || (type == CharType.endOfLine);
	}

	protected boolean hasNextNumericChar() throws IOException {
		CharType type = charTypeOf(peekChar());
		return (type == CharType.numeric);
	}

	protected CharType charTypeOf(int intChar) {
		return
				(intChar == eofChar) ? CharType.endOfLine :
				(intChar > maxSupportedCharCode) ? CharType.unknown :
				charType[intChar];
	}

	// Physical character scanning

	protected final int eofChar = -1;
	protected final int noChar = -2;

	protected int peekChar() throws IOException {
		if (lookaheadChar == noChar) {
			lookaheadChar = reader.read();
			if (lookaheadChar == lf) {
				++lineNumber;
			}
			if (!eolIsSignificant && ((lookaheadChar == cr) || (lookaheadChar == lf))) {
				lookaheadChar = (int)' ';
			}
		}
		return lookaheadChar;
	}

	protected int nextChar() throws IOException {
		int result = peekChar();
		lookaheadChar = noChar;
		return result;
	}

	protected void pushChar(int pushedChar) throws IOException {
		if (lookaheadChar != noChar) {
			throw new IOException("invalid pushChar()");
		}
		lookaheadChar = pushedChar;
	}
}


text:
//-----------------------------------------------------------------------
// <copyright file="SearchViewRepository.cs" company="Microsoft Corporation">
//     Copyright (c) Microsoft Corporation 2011. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WWTMVC5.Models;
using WWTMVC5.Repositories.Interfaces;

namespace WWTMVC5.Repositories
{
    /// <summary>
    /// Class representing the Search View repository having methods for retrieving community/content details
    /// from SQL Azure Layerscape database for searching.
    /// </summary>
    public class SearchViewRepository : RepositoryBase<SearchView>, ISearchViewRepository
    {
        /// <summary>
        /// Initializes a new instance of the SearchViewRepository class.
        /// </summary>
        /// <param name="earthOnlineDbContext">Instance of Layerscape db context</param>
        public SearchViewRepository(EarthOnlineEntities earthOnlineDbContext)
            : base(earthOnlineDbContext)
        {
        }

        /// <summary>
        /// Gets the count of items which are satisfying the given search condition.
        /// </summary>
        /// <param name="searchText">Text to be searched</param>
        /// <param name="userId">User who is searching</param>
        /// <param name="searchQueryDetails">Details about search like filters, sorting and pagination</param>
        /// <returns>Number of items satisfying the given search condition</returns>
        public int SearchCount(string searchText, long? userId, SearchQueryDetails searchQueryDetails)
        {
            var query = new StringBuilder("SELECT COUNT(*) FROM SearchView WHERE ");

            // Gets the WHERE clause for the search query
            query = query.Append(GetSearchQueryConditions(searchText, userId, searchQueryDetails));

            return EarthOnlineDbContext.Database.SqlQuery<int>(query.ToString()).FirstOrDefault();
        }

        /// <summary>
        /// Searches the communities and contents and returns the items which are satisfying the given search condition.
        /// </summary>
        /// <param name="searchText">Text to be searched</param>
        /// <param name="userId">User who is searching</param>
        /// <param name="skipCount">Items to be skipped, for pagination</param>
        /// <param name="takeCount">Items to be taken, for pagination</param>
        /// <param name="searchQueryDetails">Details about search like filters, sorting and pagination</param>
        /// <returns>Items satisfying the given search condition</returns>
        public IEnumerable<SearchView> Search(string searchText, long? userId, int skipCount, int takeCount, SearchQueryDetails searchQueryDetails)
        {
            var query = new StringBuilder("SELECT * FROM SearchView WHERE ");

            // Gets the WHERE clause for the search query
            query = query.Append(GetSearchQueryConditions(searchText, userId, searchQueryDetails));

            // Gets the ORDER BY clause for the search query
            query = query.Append(GetSearchOrderBy(searchQueryDetails));

            return EarthOnlineDbContext.Database.SqlQuery<SearchView>(query.ToString()).Skip(skipCount).Take(takeCount).ToList();
        }

        public async Task<IEnumerable<SearchView>> SearchAsync(string searchText, long? userId, int skipCount, int takeCount, SearchQueryDetails searchQueryDetails)
        {
            var query = new StringBuilder("SELECT * FROM SearchView WHERE ");

            // Gets the WHERE clause for the search query
            query = query.Append(GetSearchQueryConditions(searchText, userId, searchQueryDetails));

            // Gets the ORDER BY clause for the search query
            query = query.Append(GetSearchOrderBy(searchQueryDetails));

            var results =
                await EarthOnlineDbContext.Database.SqlQuery<SearchView>(query.ToString()).ToListAsync();

            return results.Skip(skipCount)
                        .Take(takeCount);
        }

        /// <summary>
        /// Gets the WHERE clause for the select query to search communities and contents.
        /// </summary>
        /// <param name="searchText">Text to be searched</param>
        /// <param name="userId">User who is searching</param>
        /// <param name="searchQueryDetails">Details about search like filters, sorting and pagination</param>
        /// <returns>Where condition to be used in the query</returns>
        private static string GetSearchQueryConditions(string searchText, long? userId, SearchQueryDetails searchQueryDetails)
        {
            var queryCondition = new StringBuilder(
                string.Format(CultureInfo.InvariantCulture, "(Name LIKE '%{0}%' OR Description LIKE '%{1}%' OR DistributedBy LIKE '%{2}%' OR Producer LIKE '%{3}%' OR Tags LIKE '%{4}%' OR Citation LIKE '%{5}%')", searchText, searchText, searchText, searchText, searchText, searchText));

            if (userId != null)
            {
                queryCondition = queryCondition.Append(string.Format(CultureInfo.InvariantCulture, " AND (AccessType = 'Public' OR Users Like '~{0}~')", userId));
            }

            if (searchQueryDetails.CategoryFilter.Count > 0)
            {
                var categoryList = string.Join(",", searchQueryDetails.CategoryFilter);
                queryCondition = queryCondition.Append(string.Format(CultureInfo.InvariantCulture, " AND (Category IN ({0}))", categoryList));
            }

            if (searchQueryDetails.ContentTypeFilter.Count > 0)
            {
                var contentTypeList = string.Join(",", searchQueryDetails.ContentTypeFilter);
                queryCondition = queryCondition.Append(string.Format(CultureInfo.InvariantCulture, " AND (ContentType IN ({0}))", contentTypeList));
            }

            return queryCondition.ToString();
        }

        /// <summary>
        /// Gets the ORDER BY clause for the select query while searching communities and contents.
        /// </summary>
        /// <param name="searchQueryDetails">Details about search like filters, sorting and pagination</param>
        /// <returns>Order by condition to be used in the query</returns>
        private static string GetSearchOrderBy(SearchQueryDetails searchQueryDetails)
        {
            // default order by is Rating.
            var orderBy = string.Empty;

            switch (searchQueryDetails.SortBy)
            {
                case SearchSortBy.Categories:
                    orderBy = " ORDER BY Category";
                    break;
                case SearchSortBy.DistributedBy:
                    orderBy = " ORDER BY DistributedBy";
                    break;
                case SearchSortBy.ContentType:
                    orderBy = " ORDER BY ContentType";
                    break;
                case SearchSortBy.None:
                case SearchSortBy.Rating:
                default:
                    orderBy = " ORDER BY Rating DESC, RatedPeople DESC";
                    break;
            }

            return orderBy;
        }
    }
}


text:
import os
import urllib
import webapp2
import jinja2

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)
# [END imports]

class MainHandler(webapp2.RequestHandler):
    def get(self):
      template = JINJA_ENVIRONMENT.get_template('index.html')
      self.response.headers.add_header("Access-Control-Allow-Origin", "*")
      self.response.write(template.render())

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)


text:
<?php
namespace frontend\controllers;

use common\models\Subscribers;
use Yii;
use yii\web\Controller;

/**
 * Site controller
 */
class SiteController extends Controller
{
    public function actionIndex()
    {
        $model = new Subscribers();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->render('success');
        }
        return $this->render('index', [
            'model' => $model
        ]);
    }

}


text:
<?xml version="1.0"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-parent</artifactId>
    <version>38</version>
  </parent>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-csv</artifactId>
  <version>1.3-SNAPSHOT</version>
  <name>Apache Commons CSV</name>
  <url>http://commons.apache.org/proper/commons-csv/</url>
  <description>
The Apache Commons CSV library provides a simple interface for reading and writing
CSV files of various types.
  </description>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>1.4.182</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <developers>
    <developer>
      <id>bayard</id>
      <name>Henri Yandell</name>
      <email>bayard@apache.org</email>
      <organization>The Apache Software Foundation</organization>
    </developer>
    <developer>
      <name>Martin van den Bemt</name>
      <id>mvdb</id>
      <email>mvdb@apache.org</email>
      <organization>The Apache Software Foundation</organization>
    </developer>
    <developer>
      <name>Yonik Seeley</name>
      <id>yonik</id>
      <email>yonik@apache.org</email>
      <organization>The Apache Software Foundation</organization>
    </developer>
    <developer>
      <name>Emmanuel Bourg</name>
      <id>ebourg</id>
      <email>ebourg@apache.org</email>
      <organization>Apache</organization>
    </developer>
    <developer>
      <name>Gary Gregory</name>
      <id>ggregory</id>
      <email>ggregory@apache.org</email>
      <url>http://www.garygregory.com</url>
      <timezone>-5</timezone>
    </developer>
    <developer>
      <name>Benedikt Ritter</name>
      <id>britter</id>
      <email>britter@apache.org</email>
      <organization>The Apache Software Foundation</organization>
    </developer>
  </developers>
  <contributors>
    <contributor>
      <name>Bob Smith</name>
    </contributor>
  </contributors>

  <scm>
    <connection>scm:svn:http://svn.apache.org/repos/asf/commons/proper/csv/trunk</connection>
    <developerConnection>scm:svn:https://svn.apache.org/repos/asf/commons/proper/csv/trunk</developerConnection>
    <url>http://svn.apache.org/viewvc/commons/proper/csv/trunk</url>
  </scm>

  <issueManagement>
    <system>jira</system>
    <url>http://issues.apache.org/jira/browse/CSV</url>
  </issueManagement>

  <distributionManagement>
    <site>
      <id>apache.website</id>
      <name>Apache Commons Site</name>
      <url>scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-csv/</url>
    </site>
  </distributionManagement>

  <properties>
    <commons.release.version>1.3</commons.release.version>
    <commons.release.desc>(Java 6.0+)</commons.release.desc>
    <!-- The RC version used in the staging repository URL. -->
    <commons.rc.version>RC1</commons.rc.version>
    <commons.componentid>csv</commons.componentid>
    <commons.jira.id>CSV</commons.jira.id>
    <commons.jira.pid>12313222</commons.jira.pid>
    <maven.compiler.source>1.6</maven.compiler.source>
    <maven.compiler.target>1.6</maven.compiler.target>
    <!-- Ensure copies work OK (can be removed later when this is in parent POM) -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <commons.encoding>UTF-8</commons.encoding>

    <checkstyle.version>2.16</checkstyle.version>
    <checkstyle.header.file>${basedir}/LICENSE-header.txt</checkstyle.header.file>
    <checkstyle.resourceExcludes>LICENSE.txt, NOTICE.txt</checkstyle.resourceExcludes>
  </properties>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-scm-publish-plugin</artifactId>
          <version>1.1</version>
          <configuration>
            <ignorePathsToDelete>
              <ignorePathToDelete>archives/**</ignorePathToDelete>
            </ignorePathsToDelete>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <testExcludes>
            <testExclude>**/*Benchmark*</testExclude>
          </testExcludes>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptors>
             <descriptor>src/assembly/bin.xml</descriptor>
             <descriptor>src/assembly/src.xml</descriptor>
          </descriptors>
          <tarLongFileMode>gnu</tarLongFileMode>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>**/perf/PerformanceTest.java</exclude>
          </excludes>
        </configuration>
      </plugin>
      <!-- Allow checkstyle to be run interactively; keep in sync with report config below -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
        <version>${checkstyle.version}</version>
        <configuration>
          <configLocation>${basedir}/checkstyle.xml</configLocation>
          <enableRulesSummary>false</enableRulesSummary>
        </configuration>
      </plugin>

      <!-- We need to add our test data files to rat exclusions -->
      <!-- Needed for command-line access, e.g mvn apache-rat:rat and mvn apache-rat:check -->
      <plugin>
        <groupId>org.apache.rat</groupId>
        <artifactId>apache-rat-plugin</artifactId>
        <version>${commons.rat.version}</version>
        <!-- Should agree with config in reporting section -->
        <configuration>
          <excludes>
            <exclude>src/test/resources/CSVFileParser/bom.csv</exclude>
            <exclude>src/test/resources/CSVFileParser/test.csv</exclude>
            <exclude>src/test/resources/CSVFileParser/test_default.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/test_default_comment.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/test_rfc4180.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/test_rfc4180_trim.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/testCSV85.csv</exclude>
            <exclude>src/test/resources/CSVFileParser/testCSV85_default.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/testCSV85_ignoreEmpty.txt</exclude>
            <exclude>src/test/resources/ferc.gov/contract.txt</exclude>
            <exclude>src/test/resources/ferc.gov/transaction.txt</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <reporting>
    <plugins>
      <!-- Keep in sync with build config above -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
        <version>${checkstyle.version}</version>
        <configuration>
          <configLocation>${basedir}/checkstyle.xml</configLocation>
          <enableRulesSummary>false</enableRulesSummary>
        </configuration>
        <!-- We need to specify reportSets because 2.9.1 creates two reports -->
        <reportSets>
          <reportSet>
            <reports>
              <report>checkstyle</report>
            </reports>
          </reportSet>
        </reportSets>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
        <version>3.5</version>
        <configuration>
          <targetJdk>${maven.compiler.target}</targetJdk>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>3.0.2</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>taglist-maven-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <tagListOptions>
            <tagClasses>
              <tagClass>
                <displayName>Needs Work</displayName>
                <tags>
                  <tag>
                    <matchString>TODO</matchString>
                    <matchType>exact</matchType>
                  </tag>
                  <tag>
                    <matchString>FIXME</matchString>
                    <matchType>exact</matchType>
                  </tag>
                  <tag>
                    <matchString>XXX</matchString>
                    <matchType>exact</matchType>
                  </tag>
                </tags>
              </tagClass>
              <tagClass>
                <displayName>Noteable Markers</displayName>
                <tags>
                  <tag>
                    <matchString>NOTE</matchString>
                    <matchType>exact</matchType>
                  </tag>
                  <tag>
                    <matchString>NOPMD</matchString>
                    <matchType>exact</matchType>
                  </tag>
                  <tag>
                    <matchString>NOSONAR</matchString>
                    <matchType>exact</matchType>
                  </tag>
                </tags>
              </tagClass>
            </tagClasses>
          </tagListOptions>
        </configuration>
      </plugin>
      <!--
          NOTE: this requires Maven 3.0.x; when used with Maven 2.2.1, the following error is seen:
          Embedded error: Error rendering Maven report: org.dom4j.DocumentFactory cannot be cast to org.dom4j.DocumentFactory
       -->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>javancss-maven-plugin</artifactId>
        <version>2.0</version>
      </plugin>

      <!-- We need to add our test data files to rat exclusions -->
      <plugin>
        <groupId>org.apache.rat</groupId>
        <artifactId>apache-rat-plugin</artifactId>
        <version>${commons.rat.version}</version>
        <!-- Should agree with config in build section -->
        <configuration>
          <excludes>
            <exclude>src/test/resources/CSVFileParser/bom.csv</exclude>
            <exclude>src/test/resources/CSVFileParser/test.csv</exclude>
            <exclude>src/test/resources/CSVFileParser/test_default.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/test_default_comment.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/test_rfc4180.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/test_rfc4180_trim.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/testCSV85.csv</exclude>
            <exclude>src/test/resources/CSVFileParser/testCSV85_default.txt</exclude>
            <exclude>src/test/resources/CSVFileParser/testCSV85_ignoreEmpty.txt</exclude>
            <exclude>src/test/resources/ferc.gov/contract.txt</exclude>
            <exclude>src/test/resources/ferc.gov/transaction.txt</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </reporting>

  <profiles>
    <profile>
      <id>setup-checkout</id>
      <activation>
        <file>
          <missing>site-content</missing>
        </file>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.8</version>
            <executions>
              <execution>
                <id>prepare-checkout</id>
                <phase>pre-site</phase>
                <goals>
                  <goal>run</goal>
                </goals>
                <configuration>
                  <tasks>
                    <exec executable="svn">
                      <arg line="checkout --depth immediates ${commons.scmPubUrl} ${commons.scmPubCheckoutDirectory}" />
                    </exec>

                    <exec executable="svn">
                      <arg line="update --set-depth exclude ${commons.scmPubCheckoutDirectory}/javadocs" />
                    </exec>

                    <pathconvert pathsep=" " property="dirs">
                      <dirset dir="${commons.scmPubCheckoutDirectory}" includes="*" />
                    </pathconvert>
                    <exec executable="svn">
                      <arg line="update --set-depth infinity ${dirs}" />
                    </exec>
                  </tasks>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>

    <!-- Profile to build and run the benchmarks. Use 'mvn test -Pbenchmark', and add '-Dbenchmark=foo' to run only the foo benchmark -->
    <profile>
      <id>benchmark</id>

      <dependencies>
        <dependency>
          <groupId>org.openjdk.jmh</groupId>
          <artifactId>jmh-core</artifactId>
          <version>1.5.2</version>
          <scope>test</scope>
        </dependency>

        <dependency>
          <groupId>org.openjdk.jmh</groupId>
          <artifactId>jmh-generator-annprocess</artifactId>
          <version>1.5.2</version>
          <scope>test</scope>
        </dependency>

        <dependency>
          <groupId>genjava</groupId>
          <artifactId>gj-csv</artifactId>
          <version>1.0</version>
          <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.javacsv</groupId>
            <artifactId>javacsv</artifactId>
            <version>2.0</version>
          <scope>test</scope>
        </dependency>

        <dependency>
          <groupId>com.opencsv</groupId>
          <artifactId>opencsv</artifactId>
          <version>3.1</version>
          <scope>test</scope>
        </dependency>

        <dependency>
          <groupId>net.sf.supercsv</groupId>
          <artifactId>super-csv</artifactId>
          <version>2.2.1</version>
        </dependency>

        <!-- Not in Maven Central, download manually from http://kasparov.skife.org/csv/csv-1.0.jar and install with:
             mvn install:install-file -Dfile=E:/Java/skife.org/csv-1.0.jar -DgroupId=org.skife.kasparov -DartifactId=csv -Dversion=1.0 -Dpackaging=jar -->
        <dependency>
          <groupId>org.skife.kasparov</groupId>
          <artifactId>csv</artifactId>
          <version>1.0</version>
        </dependency>

        <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-lang3</artifactId>
          <version>3.4</version>
        </dependency>
      </dependencies>

      <properties>
        <skipTests>true</skipTests>
        <benchmark>org.apache</benchmark>
      </properties>

      <build>
        <plugins>
          <!-- Enable the compilation of the benchmarks -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration combine.self="override">
              <testIncludes>
                <testInclude>**/*</testInclude>
              </testIncludes>
            </configuration>
          </plugin>

          <!-- Hook the benchmarks to the test phase -->
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <executions>
              <execution>
                <id>benchmark</id>
                <phase>test</phase>
                <goals>
                  <goal>exec</goal>
                </goals>
                <configuration>
                  <classpathScope>test</classpathScope>
                  <executable>java</executable>
                  <arguments>
                    <argument>-classpath</argument>
                    <classpath/>
                    <argument>org.openjdk.jmh.Main</argument>
                    <argument>-rf</argument>
                    <argument>json</argument>
                    <argument>-rff</argument>
                    <argument>target/jmh-result.json</argument>
                    <argument>${benchmark}</argument>
                  </arguments>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
package org.ovirt.engine.core.common.queries;

import javax.xml.bind.annotation.XmlType;

@XmlType(name = "ConfigurationValues")
public enum ConfigurationValues {
    MaxNumOfVmCpus,
    MaxNumOfVmSockets,
    MaxNumOfCpuPerSocket,
    VirtualMachineDomainName,
    VdcVersion,
    // GetAllAdDomains,
    SSLEnabled,
    CipherSuite,
    VmPoolLeaseDays,
    VmPoolLeaseStartTime,
    VmPoolLeaseEndTime,
    MaxVmsInPool,
    MaxVdsMemOverCommit,
    MaxVdsMemOverCommitForServers,
    AdUserName,
    // TODO remove remarks and AdUserPassword completely in version 3.1.
    // AdUserPassword field format has been changed.
    // AdUserPassword,
    LocalAdminPassword,
    ValidNumOfMonitors,
    EnableUSBAsDefault,
    SpiceSecureChannels,
    SpiceReleaseCursorKeys,
    SpiceToggleFullScreenKeys,
    HighUtilizationForEvenlyDistribute,
    RDPLoginWithFQN,
    SpiceUsbAutoShare,
    ExportDefaultPath,
    ImportDefaultPath,
    ComputerADPaths,
    PowerClientGUI,
    VdsSelectionAlgorithm,
    LowUtilizationForEvenlyDistribute,
    LowUtilizationForPowerSave,
    HighUtilizationForPowerSave,
    CpuOverCommitDurationMinutes,
    InstallVds,
    IrsClusterStatusRefreshRate,
    AsyncTaskPollingRate,
    VdsFenceType,
    VdsFenceOptions,
    VdsFenceOptionMapping,
    VcpuConsumptionPercentage,
    CertificateFingerPrint,
    SearchResultsLimit,
    MaxDiskSize,
    RedirectServletReportsPage,
    RedirectServletReportsPageError,
    EnableSpiceRootCertificateValidation,
    VMMinMemorySizeInMB,
    VM32BitMaxMemorySizeInMB,
    VM64BitMaxMemorySizeInMB,
    VmPriorityMaxValue,
    StorageDomainNameSizeLimit,
    StoragePoolNameSizeLimit,
    SANWipeAfterDelete,
    AuthenticationMethod,
    LocalStorageEnabled,
    UserDefinedVMProperties,
    PredefinedVMProperties,
    SupportCustomProperties,
    VdsFenceOptionTypes,
    ServerCPUList,
    SupportedClusterLevels,
    ProductRPMVersion,
    RhevhLocalFSPath,
    CustomPublicConfig_AppsWebSite;

    public int getValue() {
        return this.ordinal();
    }

    public static ConfigurationValues forValue(int value) {
        return values()[value];
    }
}


text:
import type { Options } from "../options";
import * as N from "../types";
import { Position } from "../util/location";

import { types as ct, type TokContext } from "./context";
import { types as tt, type TokenType } from "./types";

type TopicContextState = {
  // When a topic binding has been currently established,
  // then this is 1. Otherwise, it is 0. This is forwards compatible
  // with a future plugin for multiple lexical topics.
  maxNumOfResolvableTopics: number,

  // When a topic binding has been currently established, and if that binding
  // has been used as a topic reference `#`, then this is 0. Otherwise, it is
  // `null`. This is forwards compatible with a future plugin for multiple
  // lexical topics.
  maxTopicIndex: null | 0,
};

export default class State {
  strict: boolean;
  curLine: number;

  // And, if locations are used, the {line, column} object
  // corresponding to those offsets
  startLoc: Position;
  endLoc: Position;

  init(options: Options): void {
    this.strict =
      options.strictMode === false ? false : options.sourceType === "module";

    this.curLine = options.startLine;
    this.startLoc = this.endLoc = this.curPosition();
  }

  errors: SyntaxError[] = [];

  // Used to signify the start of a potential arrow function
  potentialArrowAt: number = -1;

  // Used to signify the start of an expression which looks like a
  // typed arrow function, but it isn't
  // e.g. a ? (b) : c => d
  //          ^
  noArrowAt: number[] = [];

  // Used to signify the start of an expression whose params, if it looks like
  // an arrow function, shouldn't be converted to assignable nodes.
  // This is used to defer the validation of typed arrow functions inside
  // conditional expressions.
  // e.g. a ? (b) : c => d
  //          ^
  noArrowParamsConversionAt: number[] = [];

  // Flags to track
  inParameters: boolean = false;
  maybeInArrowParameters: boolean = false;
  // This flag is used to track async arrow head across function declarations.
  // e.g. async (foo = function (await) {}) => {}
  // When parsing `await` in this expression, `maybeInAsyncArrowHead` is true
  // but `maybeInArrowParameters` is false
  maybeInAsyncArrowHead: boolean = false;
  inPipeline: boolean = false;
  inType: boolean = false;
  noAnonFunctionType: boolean = false;
  inPropertyName: boolean = false;
  hasFlowComment: boolean = false;
  isIterator: boolean = false;

  // For the smartPipelines plugin:
  topicContext: TopicContextState = {
    maxNumOfResolvableTopics: 0,
    maxTopicIndex: null,
  };

  // For the F# plugin
  soloAwait: boolean = false;
  inFSharpPipelineDirectBody: boolean = false;

  // Labels in scope.
  labels: Array<{
    kind: ?("loop" | "switch"),
    name?: ?string,
    statementStart?: number,
  }> = [];

  // Leading decorators. Last element of the stack represents the decorators in current context.
  // Supports nesting of decorators, e.g. @foo(@bar class inner {}) class outer {}
  // where @foo belongs to the outer class and @bar to the inner
  decoratorStack: Array<Array<N.Decorator>> = [[]];

  // Positions to delayed-check that yield/await does not exist in default parameters.
  yieldPos: number = -1;
  awaitPos: number = -1;

  // Comment store.
  comments: Array<N.Comment> = [];

  // Comment attachment store
  trailingComments: Array<N.Comment> = [];
  leadingComments: Array<N.Comment> = [];
  commentStack: Array<{
    start: number,
    leadingComments: ?Array<N.Comment>,
    trailingComments: ?Array<N.Comment>,
    type: string,
  }> = [];
  // $FlowIgnore this is initialized when the parser starts.
  commentPreviousNode: N.Node = null;

  // The current position of the tokenizer in the input.
  pos: number = 0;
  lineStart: number = 0;

  // Properties of the current token:
  // Its type
  type: TokenType = tt.eof;

  // For tokens that include more information than their type, the value
  value: any = null;

  // Its start and end offset
  start: number = 0;
  end: number = 0;

  // Position information for the previous token
  // $FlowIgnore this is initialized when generating the second token.
  lastTokEndLoc: Position = null;
  // $FlowIgnore this is initialized when generating the second token.
  lastTokStartLoc: Position = null;
  lastTokStart: number = 0;
  lastTokEnd: number = 0;

  // The context stack is used to superficially track syntactic
  // context to predict whether a regular expression is allowed in a
  // given position.
  context: Array<TokContext> = [ct.braceStatement];
  exprAllowed: boolean = true;

  // Used to signal to callers of `readWord1` whether the word
  // contained any escape sequences. This is needed because words with
  // escape sequences must not be interpreted as keywords.
  containsEsc: boolean = false;

  // This property is used to throw an error for
  // an octal literal in a directive that occurs prior
  // to a "use strict" directive.
  octalPositions: number[] = [];

  // Names of exports store. `default` is stored as a name for both
  // `export default foo;` and `export { foo as default };`.
  exportedIdentifiers: Array<string> = [];

  // Tokens length in token store
  tokensLength: number = 0;

  curPosition(): Position {
    return new Position(this.curLine, this.pos - this.lineStart);
  }

  clone(skipArrays?: boolean): State {
    const state = new State();
    const keys = Object.keys(this);
    for (let i = 0, length = keys.length; i < length; i++) {
      const key = keys[i];
      // $FlowIgnore
      let val = this[key];

      if (!skipArrays && Array.isArray(val)) {
        val = val.slice();
      }

      // $FlowIgnore
      state[key] = val;
    }

    return state;
  }
}


text:
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault(
        "DJANGO_SETTINGS_MODULE",
        "NCKU_Course.settings.default")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)