text:
require_relative "bc"
require_relative "m"
require_relative "messages"
require_relative "rf"

class VirtualMachine
  include Inspector
  attr_accessor :instructions, :interpreting, :running,
                :max_stack_depth, :memory
  attr_reader :stack_ptr, :isp, :cycles, :max_stack_depth, :stack

  def initialize()
    @max_stack_depth = 100
    @instructions = Array.new
    @memory = Memory.new
    @returns = Array.new(size=100, default=0)
    @cycles = 0
    @stack = Array.new(size=100, default=0)
    @isp = 0
    @debug = false
    @interactive = false
    @interpreting = false # i.e. interpreting
    @running = true # main program operation
    @stack_ptr = -1 # "last element"

  end

  def halt_vm()
    @running = false
    if @debug then puts "Halting vardi..." end
    exit(0)
  end
  def start_vm()
    @running = true
    program_loop
  end

  def start_interpreter()
    @interpreting = true
    program_loop
  end

  def halt_interpreter()
    @interpreting = false
  end

  def set_stack_ptr val
    @stack_ptr = val unless val == @max_stack_depth
  end

  def pretty_print_instructions
    puts VMInfo::PP_INSTRUCTIONS + @instructions.to_s
  end

  def step
    @isp +=1
  end

  def step_back
    @isp -= 1 unless @isp == 0
  end

  def fetch()
    if  @isp == @instructions.length then return -1 end
    val = @instructions[@isp]
    step()
    return val
  end

  def peek_instr
    if  @isp == @instructions.length then return -1 end
    val = @instructions[@isp]
    return val
  end

  def i_to_hex i
    return i.to_s(16).upcase
  end

  def bytecode_exit
    if @debug then debug_bytecode_exit end
    halt_interpreter()
    halt_vm() unless @interactive
  end

  def interpret()
    @cycles += 1

    #fetch
    instr = fetch()

    #decode
    case instr
    when -1
      puts "Overran!"
      bytecode_exit
    when Bytecode::NOP
      if @debug then debug_bytecode_nop end

    when Bytecode::PEEK
      if @debug then debug_bytecode_peek end
      puts @stack.last.to_s

    when Bytecode::PRINT
      if @debug then debug_bytecode_print  end
      print @stack.pop.to_s

    when Bytecode::CONS
      a = fetch()
      @stack.push(a)
      if @debug then debug_bytecode_cons end
      #if @debug then puts "\tCONS.#{@stack.last.to_s}" end

    when Bytecode::POP
      if @debug then debug_bytecode_pop end
      @stack.pop()

    when Bytecode::JMP
      if @debug then debug_bytecode_jmp end
      addr = fetch()
      @isp = addr

    when Bytecode::JMS
      if @debug then debug_bytecode_jms end
      upper = @stack.pop().to_s(16)
      lower = @stack.pop().to_s(16)
      addr = (upper + lower).to_i(16)
      @isp = addr

    when Bytecode::JIZ
      if @debug then debug_bytecode_jiz end
      v = @stack.last()
      if v == 0
        addr = fetch()
        @isp = addr
        if @debug then puts "TRUE" end
      elsif
        fetch() #skip jmp marker
        if @debug then puts "FALSE" end
      end

    when Bytecode::TEXT
      if @debug then debug_bytecode_text end
      print @stack.pop.chr
      $stdout.flush()

    when Bytecode::AND
      if @debug then debug_bytecode_and end
      #pop, AND, push
      a = @stack.pop()
      b = @stack.pop()
      c = a & b
      @stack.push(c)

    when Bytecode::NOT
      if @debug then debug_bytecode_not end
      #pop, NOT, push
      a = @stack.pop()
      c = ~a
      @stack.push(c)

    when Bytecode::SWAP
      if @debug then debug_bytecode_swap end
      last = @stack.pop()
      older = @stack.pop()
      @stack.push(last).push(older)

    when Bytecode::DUP
      if @debug then debug_bytecode_dup end
      @stack.push(@stack.last)

    when Bytecode::RSWP
      if @debug then debug_bytecode_rswp end
      addr = @returns.pop()
      val = @stack.pop()
      @returns.push(val)
      @stack.push(addr)

    when Bytecode::ISWP
#      if @debug then puts "\tISWP.*0x#{@instructions[@isp].to_s(16)}<-0x#{@stack.last.to_s(16)}" end
      if @debug then debug_bytecode_iswp end
      instr = @instructions[@isp]
      val = @stack.pop()
      @stack.push(instr)
      @instructions[@isp] = val

    when Bytecode::DEC
      if @debug then debug_bytecode_dec end
      a = @stack.pop()
      @stack.push(a-1)

    when Bytecode::ADD
      if @debug then debug_bytecode_add end
      a = @stack.pop()
      b = @stack.pop()
      @stack.push(b+a)

    when Bytecode::SUB
      if @debug then debug_bytecode_sub end
      a = @stack.pop()
      b = @stack.pop()
      @stack.push(b-a)
      if @debug then puts "RES: #{@stack.last()}"end

    when Bytecode::MUL
      if @debug then debug_bytecode_mul end
      a = @stack.pop()
      b = @stack.pop()
      @stack.push(b*a)

    when Bytecode::DIV
      if @debug then debug_bytecode_div end
      a = @stack.pop()
      b = @stack.pop()
      @stack.push(b/a)

    when Bytecode::CRAY
    #TODO: Malbolge crazy operator
      if @debug then debug_bytecode_cray end

    when Bytecode::JVM
      #if @debug then puts "\t***COFFEETIME***" end
      if @debug then debug_bytecode_jvm end
      duration = fetch()
      sleep(duration)

    when Bytecode::EXIT
      if @debug then debug_bytecode_exit end
      bytecode_exit

    when Bytecode::RET
      if @debug then debug_bytecode_ret end
#     if @debug then puts "\tRET.0x#{@returns.last.to_s(16)}" end
      addr = @returns.pop()
      @isp = addr

    when Bytecode::CALL
#      if @debug then puts "\tCALL.*0x#{@instructions[@isp].to_s(16)}<-0x#{(@isp-1).to_s(16)}" end
      if @debug then debug_bytecode_call end
      addr = fetch()
      current = @isp
      @isp = addr
      @returns.push(current)

    when Bytecode::CLS
      if @debug then puts "\tCLS.*0x#{@stack.last.to_s(16)}<-0x#{(@isp-1).to_s(16)}" end
      @returns.push(@isp)
      addr = @stack.pop()
      @isp = addr

    when Bytecode::LOAD
      if @debug then puts "\tLOAD" end
      upper = @stack.pop().to_s(16)
      lower = @stack.pop().to_s(16)
      addr = (upper + lower).to_i(16)
      value = @stack.pop()
      if @debug then puts "ADDR: *0x#{addr.to_s(16).upcase}\nDATA: #{value}"  end
      @memory.load(addr,value)

    when Bytecode::FETCH
      if @debug then puts "\tFETCH" end
      upper = @stack.pop().to_s(16)
      lower = @stack.pop().to_s(16)
      addr = (upper + lower).to_i(16)
      value = @memory.fetch(addr)
      if @debug then puts "ADDR: *0x#{addr.to_s(16).upcase}\nDATA: #{value}" end
      @stack.push(value)

    else
      #curse programmer in hex
      puts VMInfo::MAL_INSTR
      puts "#{@isp} -> [#{i_to_hex ( @instructions[@isp] ) }]."
      @running = false
    end

    if (@isp == @instructions.length) then halt_interpreter() end
    # Let us exit even if programmer forgot to 0x1111
    #if @instructions.length <= @isp then @running = false end
  end

  def set_flags
    if ARGV.include?("-d")
      @debug = true
    end
    if ARGV.include?("-i")
      @interactive = true
    end
    if ARGV.include?("-h")
      halt_interpreter()
    end

  end

  def program_loop
   while @running
    if @interactive
      handle_input
    end
    if @interpreting
      interpret()
    end
   end

  end

  def load_file
    file_name = ARGV[0].to_s
    raise RuntimeError.new("No file was given.") unless File.exist?(file_name) && File.readable?(file_name)
    file = IO.read(file_name)
    file.each_byte do |byte|
      @instructions << byte.to_i
    end
  end

  def print_stats()
    puts "Program length: #{@instructions.length} bytes. Executed #{@cycles} cycles."
  end

  def start
    set_flags
    load_file
    if @debug
      pretty_print_instructions()
    end
    start_interpreter()
    if @debug
      print_stats()
    end
  end

end


text:
package com.mopub.common;

import android.content.Context;
import android.content.SharedPreferences;
import com.mopub.common.factories.MethodBuilderFactory;
import com.mopub.common.util.MoPubLog;

import static com.mopub.common.util.Reflection.MethodBuilder;
import static com.mopub.common.util.Reflection.classFound;
import static com.mopub.mobileads.AdTypeTranslator.CustomEventType;
import static com.mopub.mobileads.AdTypeTranslator.CustomEventType.ADMOB_BANNER;
import static com.mopub.mobileads.AdTypeTranslator.CustomEventType.ADMOB_INTERSTITIAL;
import static com.mopub.mobileads.AdTypeTranslator.CustomEventType.GOOGLE_PLAY_BANNER;
import static com.mopub.mobileads.AdTypeTranslator.CustomEventType.GOOGLE_PLAY_INTERSTITIAL;

public class GpsHelper {
    static public final int GOOGLE_PLAY_SUCCESS_CODE = 0;
    static public final String ADVERTISING_ID_KEY = "advertisingId";
    static public final String IS_LIMIT_AD_TRACKING_ENABLED_KEY = "isLimitAdTrackingEnabled";
    private static String sPlayServicesUtilClassName = "com.google.android.gms.common.GooglePlayServicesUtil";
    private static String sAdvertisingIdClientClassName = "com.google.android.gms.ads.identifier.AdvertisingIdClient";

    public interface GpsHelperListener {
        public void onFetchAdInfoCompleted();
    }

    static public CustomEventType convertAdMobToGooglePlayServices(final Context context, final CustomEventType customEventType) {
        // In both cases, only check if GooglePlayServices is available if absolutely necessary
        if (customEventType == ADMOB_BANNER &&
                classFound(GOOGLE_PLAY_BANNER.toString()) &&
                isGpsAvailable(context)) {
            return GOOGLE_PLAY_BANNER;
        } else if (customEventType == ADMOB_INTERSTITIAL &&
                classFound(GOOGLE_PLAY_INTERSTITIAL.toString()) &&
                isGpsAvailable(context)) {
            return GOOGLE_PLAY_INTERSTITIAL;
        }

        return customEventType;
    }

    static boolean isGpsAvailable(final Context context) {
        try {
            MethodBuilder methodBuilder = MethodBuilderFactory.create(null, "isGooglePlayServicesAvailable")
                    .setStatic(Class.forName(sPlayServicesUtilClassName))
                    .addParam(Context.class, context);

            Object result = methodBuilder.execute();

            return (result != null && (Integer) result == GOOGLE_PLAY_SUCCESS_CODE);
        } catch (Exception exception) {
            return false;
        }
    }

    static String getAdvertisingId(final Context context) {
        final String defaultValue = null;
        if (isGpsAvailable(context)) {
            return SharedPreferencesHelper.getSharedPreferences(context)
                    .getString(ADVERTISING_ID_KEY, defaultValue);
        } else {
            return defaultValue;
        }
    }

    static public boolean isLimitAdTrackingEnabled(Context context) {
        final boolean defaultValue = false;
        if (isGpsAvailable(context)) {
            return SharedPreferencesHelper.getSharedPreferences(context)
                    .getBoolean(IS_LIMIT_AD_TRACKING_ENABLED_KEY, defaultValue);
        } else {
            return defaultValue;
        }
    }

    static boolean isSharedPreferencesPopluated(final Context context) {
        SharedPreferences sharedPreferences = SharedPreferencesHelper.getSharedPreferences(context);
        return sharedPreferences.contains(ADVERTISING_ID_KEY) &&
                sharedPreferences.contains(IS_LIMIT_AD_TRACKING_ENABLED_KEY);
    }

    static public void asyncFetchAdvertisingInfoIfNotCached(final Context context, final GpsHelperListener gpsHelperListener) {
        // This method guarantees that the Google Play Services (GPS) advertising info will
        // be populated if GPS is available and the ad info is not already cached
        // The above will happen before the callback is run
        if (isGpsAvailable(context) && !isSharedPreferencesPopluated(context)) {
            asyncFetchAdvertisingInfo(context, gpsHelperListener);
        } else {
            gpsHelperListener.onFetchAdInfoCompleted();
        }
    }

    static public void asyncFetchAdvertisingInfo(final Context context) {
        asyncFetchAdvertisingInfo(context, null);
    }

    static public void asyncFetchAdvertisingInfo(final Context context, final GpsHelperListener gpsHelperListener) {
        if (!classFound(sAdvertisingIdClientClassName)) {
            if (gpsHelperListener != null) {
                gpsHelperListener.onFetchAdInfoCompleted();
            }
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MethodBuilder methodBuilder = MethodBuilderFactory.create(null, "getAdvertisingIdInfo")
                            .setStatic(Class.forName(sAdvertisingIdClientClassName))
                            .addParam(Context.class, context);

                    Object adInfo = methodBuilder.execute();

                    if (adInfo != null) {
                        updateSharedPreferences(context, adInfo);
                    }
                } catch (Exception exception) {
                    MoPubLog.d("Unable to obtain AdvertisingIdClient.getAdvertisingIdInfo()");
                } finally {
                    if (gpsHelperListener != null) {
                        gpsHelperListener.onFetchAdInfoCompleted();
                    }
                }
            }
        }).start();
    }

    static void updateSharedPreferences(final Context context, final Object adInfo) {
        String advertisingId = reflectedGetAdvertisingId(adInfo, null);
        boolean isLimitAdTrackingEnabled = reflectedIsLimitAdTrackingEnabled(adInfo, false);

        /*
         * Committing using the editor is atomic; a single editor must always commit
         * to ensure that the state of the GPS variables are in sync.
         */

        SharedPreferencesHelper.getSharedPreferences(context)
                .edit()
                .putString(ADVERTISING_ID_KEY, advertisingId)
                .putBoolean(IS_LIMIT_AD_TRACKING_ENABLED_KEY, isLimitAdTrackingEnabled)
                .commit();
    }

    static String reflectedGetAdvertisingId(final Object adInfo, final String defaultValue) {
        try {
            return (String) MethodBuilderFactory.create(adInfo, "getId").execute();
        } catch (Exception exception) {
            return defaultValue;
        }
    }

    static boolean reflectedIsLimitAdTrackingEnabled(final Object adInfo, final boolean defaultValue) {
        try {
            Boolean result = (Boolean) MethodBuilderFactory.create(adInfo, "isLimitAdTrackingEnabled").execute();
            return (result != null) ? result : defaultValue;
        } catch (Exception exception) {
            return defaultValue;
        }
    }

    @Deprecated
    static public void setClassNamesForTesting() {
        // This method is used for testing only to help alleviate pain with testing
        // unlinked libraries via reflection
        // Set class names to something that is linked so Class.forName method doesn't throw
        String className = "java.lang.Class";
        sPlayServicesUtilClassName = className;
        sAdvertisingIdClientClassName = className;
    }
}

redpajama_set_name: RedPajamaGithub


text:
const ElFormItem = require('../form/src/form-item');

ElFormItem.install = function(Vue) {
  Vue.component(ElFormItem.name, ElFormItem);
};

module.exports = ElFormItem;


text:
<widget-modal widget-modal-title="Configure Feature Widget">
<form name="configForm"
	ng-submit="ctrl.submit(configForm.$valid, ctrl.collectorItemId)"
	novalidate="novalidate">

			Agile Content Tool Type: <select
				name="collectorId" class="form-control" ng-model="ctrl.collectorId"
				ng-init="ctrl.collectorId"
				ng-change="ctrl.evaluateTypeSelection()"
				ng-options="featureTypeOption.value for featureTypeOption in ctrl.featureTypeOptions | orderBy: 'value' track by featureTypeOption.id"
				required>
				<option value="">{{ctrl.typeDropdownPlaceholder}}</option>
			</select>

Please select
				a valid feature data source

			Team/Project Name: <select
				name="collectorItemId" class="form-control"
				ng-model="ctrl.collectorItemId"
				ng-options="item.teamName for item in ctrl.scopeOwners | orderBy: 'teamName' track by item.value"
				ng-disabled="ctrl.toolsDropdownDisabled"
				required>
				<option value="">{{ctrl.toolsDropdownPlaceholder}}</option>
			</select>

Please select
				a valid team / project

		<button type="submit" class="btn btn-primary btn-wide">Save</button>

</form>
</widget-modal>


text:
"""The webapp and rendering engine

"""

import datetime

import flask

from flask_flatpages import FlatPages

import iso8601

app = flask.Flask(__name__)
app.config.from_object('gamecraft.config.Config')
# If you want more page types just add 'em here
event_pages = FlatPages(app=app, name="events")
posts_pages = FlatPages(app=app, name="posts")
pr_pages = FlatPages(app=app, name="pressreleases")

@app.route("/")
def index():
    return flask.render_template("index.html")

@app.route("/about/")
def about():
    return flask.render_template("about.html")

@app.route("/events/")
def events():
    today = datetime.datetime.combine(datetime.date.today(), datetime.time(0, 0, 0)).replace(tzinfo=iso8601.iso8601.UTC)
    p = iso8601.parse_date
    all_events = sorted(event_pages, key=lambda event: event.meta['start'])
    future_events = [event for event in all_events if p(event.meta['start']) >= today]
    past_events = [event for event in all_events if p(event.meta['start']) < today]
    return flask.render_template("events.html", past_events=past_events, future_events=future_events)

@app.route("/events/<event>/")
def view_event(event):
    event = event_pages.get_or_404(event)
    return flask.render_template("event.html", event=event)

@app.route("/pressreleases/")
def pressreleases():
    today = datetime.datetime.combine(datetime.date.today(), datetime.time(0, 0, 0)).replace(tzinfo=iso8601.iso8601.UTC)
    p = iso8601.parse_date
    all_prs = sorted(pr_pages, key=lambda pr: pr.meta['start'])
    current_prs = [pr for pr in all_prs if p(pr.meta['start']) > today]
    past_prs = [pr for pr in all_prs if p(pr.meta['start']) < today]
    return flask.render_template("pressreleases.html", current_prs=current_prs, past_prs=past_prs)

@app.route("/pressreleases/<pr>/")
def view_pressrelease(pr):
    pr = pr_pages.get_or_404(pr)
    return flask.render_template("pr.html", pr=pr)

@app.route("/posts/")
def posts():
    all_posts = sorted(posts_pages, reverse=True, key=lambda p: p.meta['published'])

    # posts = [post for post in posts_pages]
    return flask.render_template("posts.html", posts=all_posts)

@app.route("/posts/<post>/")
def view_post(post):
    post = posts_pages.get_or_404(post)
    return flask.render_template("post.html", post=post)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VsoRestApiNetWrapper
{
    enum AuthenticationType
    {
        Basic,
        NotSet,
        OAuth
    }
}


text:
#include <Python.h>

#ifndef BLOCK_LOCATOR_H
#define BLOCK_LOCATOR_H

#define MAX_EXC_STRING 4096

typedef struct {
    int error;
    int lineno;
    Py_UNICODE *selprop;
    int selprop_sz;
    Py_UNICODE *codestr;
    int codestr_sz;
} Block;

typedef struct _lineno_stack {
    int lineno;
    struct _lineno_stack* next;
} _lineno_stack;

typedef struct {
    char exc[MAX_EXC_STRING];
    PyUnicodeObject *py_codestr;
    Py_UNICODE *codestr;
    Py_UNICODE *codestr_ptr;
    Py_ssize_t codestr_sz;
    _lineno_stack* lineno_stack;
    int lineno;
    int par;
    Py_UNICODE instr;
    int depth;
    int skip;
    Py_UNICODE *init;
    Py_UNICODE *lose;
    Py_UNICODE *start;
    Py_UNICODE *end;
    Block block;
} BlockLocator;

void BlockLocator_initialize(void);
void BlockLocator_finalize(void);

Block* BlockLocator_iternext(BlockLocator *self);
BlockLocator *BlockLocator_new(PyUnicodeObject *codestr);
void BlockLocator_del(BlockLocator *self);

#endif


text:
<?php

declare(strict_types=1);

namespace Keboola\AdWordsExtractor;

class Exception extends \Exception
{
    public static function reportError(string $message, string $customerId, string $query, array $data = []): Exception
    {
        $result = [
            'error' => 'DownloadReport Error. ' . $message,
            'customerId' => $customerId,
            'query' => $query,
        ];
        if ($data) {
            $result['data'] = $data;
        }
        return new static(\GuzzleHttp\json_encode($result));
    }
}


text:
<?php

namespace main\repositories;

/**
 * Repository for interacting with the Google Calendar service
 */
class GoogleCalendar extends \rakelley\jhframe\classes\Repository
{
    use \rakelley\jhframe\traits\ConfigAware;

    /**
     * Google_Service_Calendar instance
     * @var object
     */
    protected $calendar;
    /**
     * IFilter instance
     * @var object
     */
    protected $filter;
    /**
     * Calendar ID
     * @var string
     */
    protected $id;

    function __construct(
        \rakelley\jhframe\interfaces\services\IFilter $filter,
        \Google_Service_Calendar $calendar
    ) {
        $this->filter = $filter;
        $this->calendar = $calendar;

        $this->id = $this->getConfig()->Get('SECRETS', 'google_calendarid');
    }

    /**
     * Get list of upcoming events
     *
     * @return array|null Null if no upcoming events
     */
    public function getUpcomingEvents()
    {
        $params = [
            'timeMin'      => date(\DateTime::RFC3339),
            'singleEvents' => true,
            'orderBy'      => 'startTime',
        ];
        $events = $this->calendar->events->listEvents($this->id, $params)
                                         ->getItems();

        if ($events) {
            $result = array_filter(array_map([$this, 'filterEvent'], $events));
        } else {
            $result = null;
        }

        return ($result) ?: null;
    }

    /**
     * Converts event object into usable array with sanitized values.
     *
     * @param  object $event \Google_Service_Calendar_Event
     * @return array|null    Incomplete/malformed events return null
     *     string 'date'  Event date in m/d format
     *     string 'title' Event title
     *     string 'link'  Event URL
     */
    protected function filterEvent(\Google_Service_Calendar_Event $event)
    {
        $date = $this->filter->Date($event->getStart()->getDateTime(), 'm/d');
        $title = $this->filter->plainText($event->getSummary());
        $link = $this->filter->Url($event->getHtmlLink());

        if ($date && $title && $link) {
            return ['date' => $date, 'title' => $title, 'link' => $link];
        } else {
            return null;
        }
    }
}


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"CoolSegmentVC";
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)nextAction:(id)sender {
    NextChildViewController *vc = [[NextChildViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

@end


text:
package org.apache.carbondata.examples

import java.io.File

import org.apache.spark.sql.SparkSession

import org.apache.carbondata.core.constants.CarbonCommonConstants
import org.apache.carbondata.core.util.CarbonProperties

/**
 * For alter table relative syntax, you can refer to DDL operation
 * document (ddl-operation-on-carbondata.md)
 */
object AlterTableExample {

  def main(args: Array[String]): Unit = {

    val rootPath = new File(this.getClass.getResource("/").getPath
                            + "../../../..").getCanonicalPath

    val storeLocation = s"$rootPath/examples/spark2/target/store"
    val warehouse = s"$rootPath/examples/spark2/target/warehouse"
    val metastoredb = s"$rootPath/examples/spark2/target/metastore_db"

    CarbonProperties.getInstance()
      .addProperty(CarbonCommonConstants.CARBON_TIMESTAMP_FORMAT, "yyyy/MM/dd")

    import org.apache.spark.sql.CarbonSession._

    val spark = SparkSession
      .builder()
      .master("local")
      .appName("AlterTableExample")
      .config("spark.sql.warehouse.dir", warehouse)
      .getOrCreateCarbonSession(storeLocation, metastoredb)

    spark.sparkContext.setLogLevel("WARN")

    spark.sql("DROP TABLE IF EXISTS carbon_table")
    spark.sql("DROP TABLE IF EXISTS new_carbon_table")

    spark.sql(
      s"""
         | CREATE TABLE carbon_table(
         | shortField SHORT,
         | intField INT,
         | bigintField LONG,
         | doubleField DOUBLE,
         | stringField STRING,
         | timestampField TIMESTAMP,
         | decimalField DECIMAL(18,2),
         | dateField DATE,
         | charField CHAR(5),
         | floatField FLOAT,
         | complexData ARRAY<STRING>
         | )
         | STORED BY 'carbondata'
         | TBLPROPERTIES('DICTIONARY_INCLUDE'='dateField, charField')
       """.stripMargin)

    // Alter table change data type
    spark.sql("DESCRIBE FORMATTED carbon_table").show()
    spark.sql("ALTER TABLE carbon_table CHANGE intField intField BIGINT").show()

    // Alter table add columns
    spark.sql("DESCRIBE FORMATTED carbon_table").show()
    spark.sql("ALTER TABLE carbon_table ADD COLUMNS (newField STRING) " +
              "TBLPROPERTIES ('DEFAULT.VALUE.newField'='def')").show()

    // Alter table drop columns
    spark.sql("DESCRIBE FORMATTED carbon_table").show()
    spark.sql("ALTER TABLE carbon_table DROP COLUMNS (newField)").show()
    spark.sql("DESCRIBE FORMATTED carbon_table").show()

    // Alter table rename table name
    spark.sql("SHOW TABLES").show()
    spark.sql("ALTER TABLE carbon_table RENAME TO new_carbon_table").show()
    spark.sql("SHOW TABLES").show()

    spark.sql("DROP TABLE IF EXISTS carbon_table")
    spark.sql("DROP TABLE IF EXISTS new_carbon_table")

    spark.stop()

  }
}


text:
@echo off
echo Active Directory batch add script...
echo.
set /P ADNum=Number of users to add: %=%
set /P ADUser=Common user name (example: if 'user' then the added users will be 'user1', 'user2', etc): %=%
set /P ADPwd=Initial password: %=%
set /P ADDom=Domain name (example: for mydomain.com, enter 'mydomain'): %=%
set /P ADTld=Top level domain (example: for mydomain.com, enter 'com'): %=%
set /P ADOu=Organizational Unit (example: Users): %=%
cls
echo Config done.
echo Will run dsadd %ADNum% times with the following settings:
echo.
echo OU: cn=%ADUser% (num),ou=%ADOu%,dc=%ADDom%,dc=%ADTld%
echo UPN: %ADUser%(num)@%ADDom%.%ADTld%
echo First name: %ADUser%
echo Last name: (num)
echo Email: %ADUser%(num)@%ADDom%.%ADTld%
echo Initial password: %ADPwd%
echo.
choice /c yn /n /m "Okay [Y/N]?"
set ADChoice=%ERRORLEVEL%
if %ADChoice% EQU 1 (
        FOR /L %%A IN (1, 1, %ADNum%) DO dsadd user "cn=%ADUser% %%A,ou=%ADOu%,dc=%ADDom%,dc=%ADTld%" -upn %ADUser%%%A@%ADDom%.%ADTld% -fn %ADUser% -ln %%A -display "%ADUser% %%A" -pwd %ADPwd% -email %ADUser%%%A@%ADDom%.%ADTld% -disabled no -mustchpwd yes
)
set /P ADdummy=Done. Press ENTER to quit.


text:
package org.osrse.game.logic.map;

import org.osrse.game.logic.Entity;
import org.osrse.game.logic.player.Player;

public class InlineWalking {

    public static boolean failedWalking(Entity player) {
        if (player.getAttribute("stunned") == Boolean.TRUE) {
        	if(player instanceof Player)
        		((Player)player).sendMessage("You're stunned.");
            return true;
        }
        if (player.getAttribute("cantMove") == Boolean.TRUE || player.getAttribute("busy") == Boolean.TRUE) {
            return true;
        }
        /*
        if (player.hasTick("animator_tick") || player.hasTick("trap_action")) {
        	return true;
        } */
        return false;
    }
}


text:
function usage()
{
cat << EOF
usage: hardLeft.sh -r PUBRATE -n NAMESPACE

PUBRATE is the rate at which to publish the bagy file. Default is 100. If you
   want to run a simulation at 0.1 of real time, set this to 10, for example.
NAMESPACE is the robot name. Default is catvehicle
EOF
}

NS=/catvehicle
PUBRATE=100

while getopts n:r: flag; do
  case $flag in
    n)
      NS=/$OPTARG
      ;;
    r)
      PUBRATE=$OPTARG
      ;;
    ?)
      usage;
      exit;
      ;;
  esac
done

echo "Car $NS receiving inputs with latched rate"
rostopic pub -r 100 -f hardLeft.bagy $NS/cmd_vel_safe geometry_msgs/Twist


text:
{% load humanize i18n %}

    {% if object_list %}
        {% for topic in object_list %}

{{ topic.title }}

                {% if show_node %}
                    {{ topic.node.name }}
                    ·
                {% endif %}
                {{ topic.author.username }}
                ·

{{ topic.num_replies }} / {{ topic.num_hits }}

                ·

{{ topic.last_reply_on|naturaltime }}

    {% endfor %}
    {% else %}

{% trans "No topic." %}

    {% endif %}


text:
namespace gdata {

//============================== GetAboutOperation =============================

// This class performs the operation for fetching About data.
class GetAboutOperation : public GetDataOperation {
 public:
  GetAboutOperation(GDataOperationRegistry* registry,
                    const GetDataCallback& callback);
  virtual ~GetAboutOperation();

 protected:
  // Overridden from GetDataOperation.
  virtual GURL GetURL() const OVERRIDE;

 private:
  DISALLOW_COPY_AND_ASSIGN(GetAboutOperation);
};

//============================= GetApplistOperation ============================

// This class performs the operation for fetching Applist.
class GetApplistOperation : public GetDataOperation {
 public:
  GetApplistOperation(GDataOperationRegistry* registry,
                      const GetDataCallback& callback);
  virtual ~GetApplistOperation();

 protected:
  // Overridden from GetDataOperation.
  virtual GURL GetURL() const OVERRIDE;

 private:
  DISALLOW_COPY_AND_ASSIGN(GetApplistOperation);
};

}  // namespace gdata

#endif  // CHROME_BROWSER_CHROMEOS_GDATA_DRIVE_API_OPERATIONS_H_


text:
FROM node:4.8.0-alpine
MAINTAINER Ming Jin <skyairmj@gmail.com>

# ARG user=app
# ARG group=app
ENV APP_HOME /var/app_home
ENV NODE_ENV production
# RUN addgroup -S ${group} && adduser -S -D -s /bin/sh -h $APP_HOME ${usser} ${group}

EXPOSE 3000
VOLUME ["$APP_HOME/uploads"]
ENTRYPOINT ["npm", "start"]

COPY . $APP_HOME
# RUN chown -R ${user} $APP_HOME

WORKDIR $APP_HOME
RUN npm install --production


text:
import { IDisplayManager } from './displayManager';
import { NodeMaterialBlock } from 'babylonjs/Materials/Node/nodeMaterialBlock';

export class OutputDisplayManager implements IDisplayManager {
    public getHeaderClass(block: NodeMaterialBlock) {
        return "";
    }

    public shouldDisplayPortLabels(block: NodeMaterialBlock): boolean {
        return true;
    }

    public getHeaderText(block: NodeMaterialBlock): string {
        return block.name;
    }

    public getBackgroundColor(block: NodeMaterialBlock): string {
        return "rgb(106, 44, 131)";
    }

    public updatePreviewContent(block: NodeMaterialBlock, contentArea: HTMLDivElement): void {
        contentArea.classList.add("output-block");
    }
}


text:
import React, { Component } from 'react';
import Dummy from './components/Dummy';

export default class App extends Component {
	render() {
		return (

						<button type="button"
								className="navbar-toggle collapsed"
								data-toggle="collapse"
								data-target="#navbar"
								aria-expanded="false"
								aria-controls="navbar">
						Toggle navigation

						</button>
						Webpack boilerplate

Home

About

Contact

Webpack boilerplate forever !

							It uses :

Webpack (dev and prod config)

React (hot reload enabled)

Bootstrap, React and jQuery packaged

Less for styles (hot reload enabled)

Karma, Jasmine and PhantomJS for tests

                        <Dummy/>

		);
	}
}


text:
<?php
namespace FrontCore\Forms;

use Zend\InputFilter\InputFilter;

class FrontCoreSystemFormValidator extends InputFilter
{
	public function __construct($elements)
	{
		foreach ($elements as $element)
		{
			if (is_array($element))
			{
				if (strtolower($element["type"] == "submit") || strtolower($element["name"] == "submit"))
				{
					//ignore element
					continue;
				}//end if

				if (isset($element["type"]))
				{
					unset($element["type"]);
				}//end if

				try {
					$this->add($element);
				} catch (\Exception $e) {
//@TODO display proper error. This throws exceptions where validators are not set properly or not contained within its own array
					var_dump($e); exit;
				}
			}//end if
		}//end foreach
	}//end function
}//end class


text:
function showGraph(divId, filename, w, h) {
  var g = new OpenLayers.Map(divId, {});
  var options = {numZoomLevels: 20};
  var b = new OpenLayers.Bounds(0, 0, w, h);
  var s = new OpenLayers.Size(g.getSize().w / 20, g.getSize().h / 20);
  var layer = new OpenLayers.Layer.Image('Graph', filename, b, s, options);
  g.addLayer(layer);
  g.zoomToMaxExtent();
}


text:
import { CompletionItemPriority } from '@grafana/experimental';
import { Monaco, monacoTypes } from '@grafana/ui';

import { afterLabelValue, insideLabelValue } from '../__mocks__/dynamic-label-test-data';
import MonacoMock from '../__mocks__/monarch/Monaco';
import TextModel from '../__mocks__/monarch/TextModel';

import { DynamicLabelsCompletionItemProvider } from './CompletionItemProvider';
import cloudWatchDynamicLabelsLanguageDefinition from './definition';
import { DYNAMIC_LABEL_PATTERNS } from './language';

const getSuggestions = async (value: string, position: monacoTypes.IPosition) => {
  const setup = new DynamicLabelsCompletionItemProvider();
  const monaco = MonacoMock as Monaco;
  const provider = setup.getCompletionProvider(monaco, cloudWatchDynamicLabelsLanguageDefinition);
  const { suggestions } = await provider.provideCompletionItems(
    TextModel(value) as monacoTypes.editor.ITextModel,
    position
  );
  return suggestions;
};

describe('Dynamic labels: CompletionItemProvider', () => {
  describe('getSuggestions', () => {
    it('returns all dynamic labels in case current token is a whitespace', async () => {
      const { query, position } = afterLabelValue;
      const suggestions = await getSuggestions(query, position);
      expect(suggestions.length).toEqual(DYNAMIC_LABEL_PATTERNS.length + 1); // + 1 for the dimension suggestions
    });

    it('should return suggestion for dimension label that has high prio', async () => {
      const { query, position } = afterLabelValue;
      const suggestions = await getSuggestions(query, position);
      expect(suggestions.length).toBeTruthy();
      const highPrioSuggestsions = suggestions.filter((s) => s.sortText === CompletionItemPriority.High);
      expect(highPrioSuggestsions.length).toBe(1);
      expect(highPrioSuggestsions[0].label).toBe("${PROP('Dim.')}");
    });

    it('doesnt return suggestions if cursor is inside a dynamic label', async () => {
      const { query, position } = insideLabelValue;
      const suggestions = await getSuggestions(query, position);
      expect(suggestions.length).toBe(0);
    });
  });
});


text:
/****************************************************************************
 *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
 *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
 ****************************************************************************/

/*
 * unctrl.h
 *
 * Display a printable version of a control character.
 * Control characters are displayed in caret notation (^x), DELETE is displayed
 * as ^?. Printable characters are displayed as is.
 */

/* $Id: unctrl.h.in,v 1.11 2009/04/18 21:00:52 tom Exp $ */

#ifndef NCURSES_UNCTRL_H_incl
#define NCURSES_UNCTRL_H_incl	1

#undef  NCURSES_VERSION
#define NCURSES_VERSION "6.0"

#ifdef __cplusplus
extern "C" {
#endif

#include <ncursesw/curses.h>

#undef unctrl
NCURSES_EXPORT(NCURSES_CONST char *) unctrl (chtype);

#if 0
NCURSES_EXPORT(NCURSES_CONST char *) NCURSES_SP_NAME(unctrl) (SCREEN*, chtype);
#endif

#ifdef __cplusplus
}
#endif

#endif /* NCURSES_UNCTRL_H_incl */


text:
export GitCredential, PlainTextCred, SSHKeyCred, SSHAgentCred, DefaultCred

abstract GitCredential

type PlainTextCred <: GitCredential
    ptr::Ptr{Void}

    PlainTextCred(ptr::Ptr{Void}) = begin
        @assert ptr != C_NULL
        cred = new(ptr)
        return cred
    end
end

PlainTextCred(;username::MaybeString=nothing,
               password::MaybeString=nothing) = begin
    is(username, nothing) && throw(ArgumentError("username must be defined"))
    cred_ptr = Ptr{Void}[0]
    @check ccall((:git_cred_userpass_plaintext_new, libgit2), Cint,
                 (Ptr{Ptr{Void}}, Ptr{UInt8}, Ptr{UInt8}),
                 cred_ptr, username, password != nothing ? password : C_NULL)
    return PlainTextCred(cred_ptr[1])
end

type SSHKeyCred <: GitCredential
    ptr::Ptr{Void}

    SSHKeyCred(ptr::Ptr{Void}) = begin
        @assert ptr != C_NULL
        cred = new(ptr)
        return cred
    end
end

SSHKeyCred(;username::MaybeString=nothing,
            publickey::MaybeString=nothing,
            privatekey::MaybeString=nothing,
            passphrase::MaybeString=nothing) = begin
    is(username, nothing) && throw(ArgumentError("username must be defined"))
    is(privatekey, nothing) && throw(ArgumentError("privatekey must be defined"))
    cred_ptr = Ptr{Void}[0]
    @check ccall((:git_cred_ssh_key_new, libgit2), Cint,
                 (Ptr{Ptr{Void}}, Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}),
                 cred,
                 username,
                 publickey != nothing ? publickey : C_NULL,
                 privatekey,
                 passphrase != nothing ? passphrase : C_NULL)
    return SSHKeyCred(cred_ptr[1])
end

type SSHAgentCred <: GitCredential
    ptr::Ptr{Void}

    SSHAgentCred(ptr::Ptr{Void}) = begin
        @assert ptr != C_NULL
    end
end

SSHAgentCred(username::AbstractString) = begin
    cred_ptr = Ptr{Void}[0]
    @check ccall((:git_cred_ssh_key_from_agent, libgit2), Cint,
                 (Ptr{Ptr{Void}}, Ptr{UInt8}), cred_ptr, username)
    return SSHAgentCred(cred_ptr[1])
end

type DefaultCred <: GitCredential
    ptr::Ptr{Void}

    DefaultCred(ptr::Ptr{Void}) = begin
        @assert ptr != C_NULL
        cred = new(ptr)
        return cred
    end
end

DefaultCred() = begin
    cred_ptr = Ptr{Void}[0]
    @check ccall((:git_cred_default_new, libgit2), Cint, (Ptr{Ptr{Void}},), cred_ptr)
    return DefaultCred(cred_ptr[1])
end


text:
import React from 'react';
import createReactClass from 'create-react-class';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Route } from 'react-router-dom';
import { ConnectedRouter } from 'react-router-redux';
import history from 'Routing/history';
import configureStore from 'Redux/configureStore';
import { setStore } from 'ValueObjects/AssetProxy';
import { ErrorBoundary } from 'UI'
import registry from 'Lib/registry';
import App from 'App/App';
import 'EditorWidgets';
import 'MarkdownPlugins';
import './index.css';

/**
 * Log the version number.
 */
console.log(`Netlify CMS version ${NETLIFY_CMS_VERSION}`);

/**
 * Create mount element dynamically.
 */
const el = document.createElement('div');
el.id = 'nc-root';
document.body.appendChild(el);

/**
 * Configure Redux store.
 */
const store = configureStore();
setStore(store);

/**
 * Create connected root component.
 */
const Root = () => (
  <ErrorBoundary>
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <Route component={App}/>
      </ConnectedRouter>
    </Provider>
  </ErrorBoundary>
);

/**
 * Render application root.
 */
render(<Root />, el);

/**
 * Add extension hooks to global scope.
 */
const CMS = { ...registry };
if (typeof window !== 'undefined') {
  window.CMS = CMS;
  window.createClass = window.createClass || createReactClass;
  window.h = window.h || React.createElement;
}

/**
 * Export the registry for projects that import the CMS.
 */
export default CMS;


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>gymsystems_client documentation</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="icon" type="image/x-icon" href="../images/favicon.ico">
	      <link rel="stylesheet" href="../styles/style.css">

            gymsystems_client documentation
            <button type="button" class="btn btn-default btn-menu ion-ios-menu" id="btn-menu"></button>

<input type="text" placeholder="Type to search">
            <compodoc-menu></compodoc-menu>

                   <compodoc-menu mode="normal"></compodoc-menu>

Modules

AppRoutingModule

        Info

        Source

File

            src/app/app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './views/home/home.component';
import { LoginComponent } from './views/home/login/login.component';
import { LogoutComponent } from './views/home/logout/logout.component';
import { RegisterComponent } from './views/home/register/register.component';
import { ResetComponent } from './views/home/reset/reset.component';
import { CanActivateRegistration } from './views/home/register/registration-activation.guard';

const APP_ROUTES: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent, canActivate: [CanActivateRegistration] },
  { path: 'reset', component: ResetComponent },
  { path: 'logout', component: LogoutComponent },

  // Lazy loaded modules
  { path: 'configure', loadChildren: () => "import('./views/configure/configure.module').then(m => m.ConfigureModule)" },
  { path: 'event', loadChildren: () => "import('./views/event/event.module').then(m => m.EventModule)" },

  // Catch all redirect to home
  { path: '**', redirectTo: '' },
];

@NgModule({
  imports: [RouterModule.forRoot(APP_ROUTES)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

 result-matching ""

No results matching ""


text:
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Modal = factory());
}(this, (function () { 'use strict';

  var addEventListener = 'addEventListener';

  var removeEventListener = 'removeEventListener';

  var supportPassive = (function () {
    var result = false;
    try {
      var opts = Object.defineProperty({}, 'passive', {
        get: function get() {
          result = true;
          return result;
        },
      });
      document[addEventListener]('DOMContentLoaded', function wrap() {
        document[removeEventListener]('DOMContentLoaded', wrap, opts);
      }, opts);
    } catch (e) {
      throw Error('Passive events are not supported');
    }

    return result;
  })();

  // general event options

  var passiveHandler = supportPassive ? { passive: true } : false;

  var transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend';

  var supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style;

  var transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration';

  var transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty';

  function getElementTransitionDuration(element) {
    var computedStyle = getComputedStyle(element);
    var propertyValue = computedStyle[transitionProperty];
    var durationValue = computedStyle[transitionDuration];
    var durationScale = durationValue.includes('ms') ? 1 : 1000;
    var duration = supportTransition && propertyValue && propertyValue !== 'none'
      ? parseFloat(durationValue) * durationScale : 0;

    return !Number.isNaN(duration) ? duration : 0;
  }

  function emulateTransitionEnd(element, handler) {
    var called = 0;
    var endEvent = new Event(transitionEndEvent);
    var duration = getElementTransitionDuration(element);

    if (duration) {
      element.addEventListener(transitionEndEvent, function transitionEndWrapper(e) {
        if (e.target === element) {
          handler.apply(element, [e]);
          element.removeEventListener(transitionEndEvent, transitionEndWrapper);
          called = 1;
        }
      });
      setTimeout(function () {
        if (!called) { element.dispatchEvent(endEvent); }
      }, duration + 17);
    } else {
      handler.apply(element, [endEvent]);
    }
  }

  function queryElement(selector, parent) {
    var lookUp = parent && parent instanceof Element ? parent : document;
    return selector instanceof Element ? selector : lookUp.querySelector(selector);
  }

  function reflow(element) {
    return element.offsetHeight;
  }

  function bootstrapCustomEvent(eventType, componentName, eventProperties) {
    var OriginalCustomEvent = new CustomEvent((eventType + ".bs." + componentName), { cancelable: true });

    if (typeof eventProperties !== 'undefined') {
      Object.keys(eventProperties).forEach(function (key) {
        Object.defineProperty(OriginalCustomEvent, key, {
          value: eventProperties[key],
        });
      });
    }
    return OriginalCustomEvent;
  }

  function dispatchCustomEvent(customEvent) {
    if (this) { this.dispatchEvent(customEvent); }
  }

  function setFocus(element) {
    element.focus();
  }

  /* Native JavaScript for Bootstrap 4 | Modal
  -------------------------------------------- */

  // MODAL DEFINITION
  // ================

  function Modal(elem, opsInput) { // element can be the modal/triggering button
    var element;

    // set options
    var options = opsInput || {};

    // bind, modal
    var self = this;
    var modal;

    // custom events
    var showCustomEvent;
    var shownCustomEvent;
    var hideCustomEvent;
    var hiddenCustomEvent;
    // event targets and other
    var relatedTarget = null;
    var scrollBarWidth;
    var overlay;
    var overlayDelay;

    // also find fixed-top / fixed-bottom items
    var fixedItems;
    var ops = {};

    // private methods
    function setScrollbar() {
      var bodyClassList = document.body.classList;
      var openModal = bodyClassList.contains('modal-open');
      var bodyPad = parseInt(getComputedStyle(document.body).paddingRight, 10);
      var docClientHeight = document.documentElement.clientHeight;
      var docScrollHeight = document.documentElement.scrollHeight;
      var bodyClientHeight = document.body.clientHeight;
      var bodyScrollHeight = document.body.scrollHeight;
      var bodyOverflow = docClientHeight !== docScrollHeight
                      || bodyClientHeight !== bodyScrollHeight;
      var modalOverflow = modal.clientHeight !== modal.scrollHeight;

      scrollBarWidth = measureScrollbar();

      modal.style.paddingRight = !modalOverflow && scrollBarWidth ? (scrollBarWidth + "px") : '';
      document.body.style.paddingRight = modalOverflow || bodyOverflow
        ? ((bodyPad + (openModal ? 0 : scrollBarWidth)) + "px") : '';

      if (fixedItems.length) {
        fixedItems.forEach(function (fixed) {
          var itemPad = getComputedStyle(fixed).paddingRight;
          fixed.style.paddingRight = modalOverflow || bodyOverflow
            ? ((parseInt(itemPad, 10) + (openModal ? 0 : scrollBarWidth)) + "px")
            : ((parseInt(itemPad, 10)) + "px");
        });
      }
    }
    function resetScrollbar() {
      document.body.style.paddingRight = '';
      modal.style.paddingRight = '';
      if (fixedItems.length) {
        fixedItems.forEach(function (fixed) {
          fixed.style.paddingRight = '';
        });
      }
    }
    function measureScrollbar() {
      var scrollDiv = document.createElement('div');
      scrollDiv.className = 'modal-scrollbar-measure'; // this is here to stay
      document.body.appendChild(scrollDiv);
      var widthValue = scrollDiv.offsetWidth - scrollDiv.clientWidth;
      document.body.removeChild(scrollDiv);
      return widthValue;
    }
    function createOverlay() {
      var newOverlay = document.createElement('div');
      overlay = queryElement('.modal-backdrop');

      if (overlay === null) {
        newOverlay.setAttribute('class', ("modal-backdrop" + (ops.animation ? ' fade' : '')));
        overlay = newOverlay;
        document.body.appendChild(overlay);
      }
      return overlay;
    }
    function removeOverlay() {
      overlay = queryElement('.modal-backdrop');
      if (overlay && !document.getElementsByClassName('modal show')[0]) {
        document.body.removeChild(overlay); overlay = null;
      }
      if (overlay === null) {
        document.body.classList.remove('modal-open');
        resetScrollbar();
      }
    }
    function toggleEvents(add) {
      var action = add ? 'addEventListener' : 'removeEventListener';
      window[action]('resize', self.update, passiveHandler);
      modal[action]('click', dismissHandler, false);
      document[action]('keydown', keyHandler, false);
    }
    // triggers
    function beforeShow() {
      modal.style.display = 'block';

      setScrollbar();
      if (!document.getElementsByClassName('modal show')[0]) { document.body.classList.add('modal-open'); }

      modal.classList.add('show');
      modal.setAttribute('aria-hidden', false);

      if (modal.classList.contains('fade')) { emulateTransitionEnd(modal, triggerShow); }
      else { triggerShow(); }
    }
    function triggerShow() {
      setFocus(modal);
      modal.isAnimating = false;

      toggleEvents(1);

      shownCustomEvent = bootstrapCustomEvent('shown', 'modal', { relatedTarget: relatedTarget });
      dispatchCustomEvent.call(modal, shownCustomEvent);
    }
    function triggerHide(force) {
      modal.style.display = '';
      if (element) { setFocus(element); }

      overlay = queryElement('.modal-backdrop');

      // force can also be the transitionEvent object, we wanna make sure it's not
      if (force !== 1 && overlay && overlay.classList.contains('show') && !document.getElementsByClassName('modal show')[0]) {
        overlay.classList.remove('show');
        emulateTransitionEnd(overlay, removeOverlay);
      } else {
        removeOverlay();
      }

      toggleEvents();

      modal.isAnimating = false;

      hiddenCustomEvent = bootstrapCustomEvent('hidden', 'modal');
      dispatchCustomEvent.call(modal, hiddenCustomEvent);
    }
    // handlers
    function clickHandler(e) {
      if (modal.isAnimating) { return; }
      var clickTarget = e.target;
      var modalID = "#" + (modal.getAttribute('id'));
      var targetAttrValue = clickTarget.getAttribute('data-target') || clickTarget.getAttribute('href');
      var elemAttrValue = element.getAttribute('data-target') || element.getAttribute('href');

      if (!modal.classList.contains('show')
          && ((clickTarget === element && targetAttrValue === modalID)
          || (element.contains(clickTarget) && elemAttrValue === modalID))) {
        modal.modalTrigger = element;
        relatedTarget = element;
        self.show();
        e.preventDefault();
      }
    }
    function keyHandler(ref) {
      var which = ref.which;

      if (!modal.isAnimating && ops.keyboard && which === 27 && modal.classList.contains('show')) {
        self.hide();
      }
    }
    function dismissHandler(e) {
      if (modal.isAnimating) { return; }
      var clickTarget = e.target;
      var hasData = clickTarget.getAttribute('data-dismiss') === 'modal';
      var parentWithData = clickTarget.closest('[data-dismiss="modal"]');

      if (modal.classList.contains('show') && (parentWithData || hasData
          || (clickTarget === modal && ops.backdrop !== 'static'))) {
        self.hide(); relatedTarget = null;
        e.preventDefault();
      }
    }

    // public methods
    self.toggle = function () {
      if (modal.classList.contains('show')) { self.hide(); } else { self.show(); }
    };
    self.show = function () {
      if (modal.classList.contains('show') && !!modal.isAnimating) { return; }

      showCustomEvent = bootstrapCustomEvent('show', 'modal', { relatedTarget: relatedTarget });
      dispatchCustomEvent.call(modal, showCustomEvent);

      if (showCustomEvent.defaultPrevented) { return; }

      modal.isAnimating = true;

      // we elegantly hide any opened modal
      var currentOpen = document.getElementsByClassName('modal show')[0];
      if (currentOpen && currentOpen !== modal) {
        if (currentOpen.modalTrigger) { currentOpen.modalTrigger.Modal.hide(); }
        if (currentOpen.Modal) { currentOpen.Modal.hide(); }
      }

      if (ops.backdrop) { overlay = createOverlay(); }

      if (overlay && !currentOpen && !overlay.classList.contains('show')) {
        reflow(overlay);
        overlayDelay = getElementTransitionDuration(overlay);
        overlay.classList.add('show');
      }

      if (!currentOpen) { setTimeout(beforeShow, overlay && overlayDelay ? overlayDelay : 0); }
      else { beforeShow(); }
    };
    self.hide = function (force) {
      if (!modal.classList.contains('show')) { return; }

      hideCustomEvent = bootstrapCustomEvent('hide', 'modal');
      dispatchCustomEvent.call(modal, hideCustomEvent);
      if (hideCustomEvent.defaultPrevented) { return; }

      modal.isAnimating = true;

      modal.classList.remove('show');
      modal.setAttribute('aria-hidden', true);

      if (modal.classList.contains('fade') && force !== 1) { emulateTransitionEnd(modal, triggerHide); }
      else { triggerHide(); }
    };
    self.setContent = function (content) {
      queryElement('.modal-content', modal).innerHTML = content;
    };
    self.update = function () {
      if (modal.classList.contains('show')) {
        setScrollbar();
      }
    };
    self.dispose = function () {
      self.hide(1);
      if (element) { element.removeEventListener('click', clickHandler, false); delete element.Modal; } else { delete modal.Modal; }
    };

    // init

    // the modal (both JavaScript / DATA API init) / triggering button element (DATA API)
    element = queryElement(elem);

    // determine modal, triggering element
    var checkModal = queryElement(element.getAttribute('data-target') || element.getAttribute('href'));
    modal = element.classList.contains('modal') ? element : checkModal;

    // set fixed items
    fixedItems = Array.from(document.getElementsByClassName('fixed-top'))
      .concat(Array.from(document.getElementsByClassName('fixed-bottom')));

    if (element.classList.contains('modal')) { element = null; } // modal is now independent of it's triggering element

    // reset on re-init
    if (element && element.Modal) { element.Modal.dispose(); }
    if (modal && modal.Modal) { modal.Modal.dispose(); }

    // set options
    ops.keyboard = !(options.keyboard === false || modal.getAttribute('data-keyboard') === 'false');
    ops.backdrop = options.backdrop === 'static' || modal.getAttribute('data-backdrop') === 'static' ? 'static' : true;
    ops.backdrop = options.backdrop === false || modal.getAttribute('data-backdrop') === 'false' ? false : ops.backdrop;
    ops.animation = !!modal.classList.contains('fade');
    ops.content = options.content; // JavaScript only

    // set an initial state of the modal
    modal.isAnimating = false;

    // prevent adding event handlers over and over
    // modal is independent of a triggering element
    if (element && !element.Modal) {
      element.addEventListener('click', clickHandler, false);
    }

    if (ops.content) {
      self.setContent(ops.content.trim());
    }

    // set associations
    if (element) {
      modal.modalTrigger = element;
      element.Modal = self;
    } else {
      modal.Modal = self;
    }
  }

  return Modal;

})));


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Extensions;
using Abp.Runtime.Session;
using Abp.UI;
using BodeAbp.Zero.Roles.Domain;
using Abp.Runtime.Caching;
using BodeAbp.Zero.Permissions.Domain;

namespace BodeAbp.Zero.Navigations.Domain
{
    /// <summary>
    /// 导航菜单 领域服务
    /// </summary>
    public class NavigationManager : IDomainService
    {
        /// <summary>
        /// Gets current session information.
        /// </summary>
        public IAbpSession AbpSession { get; set; }

        private readonly IRepository<UserRole, long> _userRoleRepository;
        private readonly IRepository<Navigation> _navigationRepository;
        private readonly IRepository<RoleNavigation> _roleNavigationRepository;

        private readonly ICacheManager _cacheManager;

        private readonly IRepository<RolePermission, long> _rolePermissionRepository;

        private readonly string _userNavigationCacheKey = "BodeAbp.Zero.UserNavigations";

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="navigationRepository"></param>
        /// <param name="roleNavigationRepository"></param>
        /// <param name="userRoleRepository"></param>
        /// <param name="cacheManager"></param>
        public NavigationManager(IRepository<Navigation> navigationRepository
            , IRepository<RoleNavigation> roleNavigationRepository
            , IRepository<UserRole, long> userRoleRepository
            , ICacheManager cacheManager
            , IRepository<RolePermission, long> rolePermissionRepository)
        {
            _navigationRepository = navigationRepository;
            _userRoleRepository = userRoleRepository;
            _roleNavigationRepository = roleNavigationRepository;

            _cacheManager = cacheManager;
            _rolePermissionRepository = rolePermissionRepository;
        }

        /// <summary>
        /// 创建  菜单
        /// </summary>
        /// <param name="navigation">菜单</param>
        /// <returns></returns>
        public async Task CreateNavigationAsync(Navigation navigation)
        {
            CheckNavigationAsync(navigation);
            var orderNos = _navigationRepository.GetAll().Where(p => p.ParentId == navigation.ParentId).Select(p => p.OrderNo).ToArray();
            navigation.OrderNo = orderNos.Any() ? orderNos.Max() + 1 : 1;
            await _navigationRepository.InsertAsync(navigation);
        }

        /// <summary>
        /// 修改  菜单
        /// </summary>
        /// <param name="navigation">菜单</param>
        /// <returns></returns>
        public async Task UpdateNavigationAsync(Navigation navigation)
        {
            CheckNavigationAsync(navigation);
            await _navigationRepository.UpdateAsync(navigation);
        }

        /// <summary>
        /// 菜单升序
        /// </summary>
        /// <param name="navigationId">菜单Id</param>
        /// <returns></returns>
        public async Task NavigationUpAsync(int navigationId)
        {
            navigationId.CheckGreaterThan("navigationId", 0);
            var navigation = await _navigationRepository.GetAsync(navigationId);
            await NavigationUpAsync(navigation);
        }

        /// <summary>
        /// 菜单升序
        /// </summary>
        /// <param name="navigation">菜单</param>
        /// <returns></returns>
        public async Task NavigationUpAsync(Navigation navigation)
        {
            navigation.CheckNotNull("navigation");

            var preNavigation = _navigationRepository.GetAll().Where(p => p.OrderNo < navigation.OrderNo && p.ParentId == navigation.ParentId)
                .OrderByDescending(p => p.OrderNo).Take(1).FirstOrDefault();

            if (preNavigation != null)
            {
                int orderNo = navigation.OrderNo;
                navigation.OrderNo = preNavigation.OrderNo;
                preNavigation.OrderNo = orderNo;

                await _navigationRepository.UpdateAsync(navigation);
                await _navigationRepository.UpdateAsync(preNavigation);
            }
        }

        /// <summary>
        /// 菜单降序
        /// </summary>
        /// <param name="navigationId">菜单Id</param>
        /// <returns></returns>
        public async Task NavigationDownAsync(int navigationId)
        {
            navigationId.CheckGreaterThan("navigationId", 0);
            var navigation = await _navigationRepository.GetAsync(navigationId);
            await NavigationDownAsync(navigation);
        }

        /// <summary>
        /// 菜单降序
        /// </summary>
        /// <param name="navigation">菜单</param>
        /// <returns></returns>
        public async Task NavigationDownAsync(Navigation navigation)
        {
            navigation.CheckNotNull("navigation");
            var nextNavigation = _navigationRepository.GetAll().Where(p => p.OrderNo > navigation.OrderNo && p.ParentId == navigation.ParentId)
                .OrderBy(p => p.OrderNo).Take(1).FirstOrDefault();

            if (nextNavigation != null)
            {
                int orderNo = navigation.OrderNo;
                navigation.OrderNo = nextNavigation.OrderNo;
                nextNavigation.OrderNo = orderNo;

                await _navigationRepository.UpdateAsync(navigation);
                await _navigationRepository.UpdateAsync(nextNavigation);
            }
        }

        /// <summary>
        /// 获取用户导航菜单
        /// </summary>
        /// <returns></returns>
        public async Task<ICollection<NavigationInfo>> GetUserNavigations()
        {
            Expression<Func<Navigation, bool>> exp = p => p.NavigationType == NavigationType.Anonymouse;
            if (AbpSession.UserId.HasValue)
            {
                exp = exp.Or(p => p.NavigationType == NavigationType.Logined);
                var roleIds = _userRoleRepository.GetAll().Where(p => p.UserId == AbpSession.UserId.Value).Select(p => p.RoleId).ToList();

                var navigationIds = _roleNavigationRepository.GetAll().Where(p => roleIds.Contains(p.RoleId)).Select(p => p.NavigationId).ToList();
                exp = exp.Or(p => p.NavigationType == NavigationType.RoleLimit && navigationIds.Contains(p.Id));
            }

            return await QueryNavigationTrees(exp);
        }
        /// <summary>
        /// (改)(新)获取用户导航菜单
        /// </summary>
        /// <returns></returns>
        public async Task<ICollection<NavigationInfo>> GetUserRoleNavigation()
        {
            Expression<Func<Navigation, bool>> exp = p => p.NavigationType == NavigationType.Anonymouse;
            if (AbpSession.UserId.HasValue)
            {
                exp = exp.Or(p => p.NavigationType == NavigationType.Logined);
                var roleIds = _userRoleRepository.GetAll().Where(p => p.UserId == AbpSession.UserId.Value).Select(p => p.RoleId).ToList();
                var permissionNames = await _rolePermissionRepository.GetAll().Where(n => roleIds.Contains(n.RoleId)).Select(n => n.Name).Distinct().ToListAsync();
                exp= exp.Or(n =>n.NavigationType == NavigationType.RoleLimit && permissionNames.Contains(n.RequiredPermissionName));
            }

            return await QueryNavigationTrees(exp);
        }

        /// <summary>
        /// 获取全部菜单
        /// </summary>
        /// <returns></returns>
        public async Task<ICollection<NavigationInfo>> GetAllNavigations()
        {
            return await QueryNavigationTrees(p => true);
        }

        /// <summary>
        /// 检查用户是否拥有权限
        /// </summary>
        /// <param name="url">url地址</param>
        /// <returns></returns>
        public async Task<bool> CheckUserNavigation(string url)
        {
            var navigation = (await GetAllNavigationInfos()).FirstOrDefault(p => CompareNavigationUrl(p, url));

            if (navigation == null || navigation.NavigationType == NavigationType.Anonymouse) return true;
            if (navigation.NavigationType == NavigationType.Logined && AbpSession.UserId.HasValue) return true;

            if (navigation.NavigationType == NavigationType.RoleLimit)
            {
                if (!AbpSession.UserId.HasValue) return false;
                return (await GetUserNavigationInfos()).Any(p => CompareNavigationUrl(p, url));
            }
            return false;
        }

        /// <summary>
        /// 获取角色关联的菜单
        /// </summary>
        /// <returns></returns>
        public async Task<ICollection<NavigationInfo>> GetRoleAndMenu(int roleid)
        {
            var navigations = await _navigationRepository.GetAll().AsNoTracking().OrderBy(p => p.OrderNo).Select(p => new
            {
                p.Id,
                p.Name,
                p.Url,
                p.Remark,
                p.Icon,
                p.ParentId,
                p.NavigationType
            }).ToListAsync();

            var roleNavigationList = await _roleNavigationRepository.GetAll().Where(n => n.RoleId == roleid).ToListAsync();

            Func<int, NavigationInfo[]> getChildren = null;
            getChildren = parentId =>
            {
                if (navigations.Any(m => m.ParentId == parentId))
                {
                    return navigations.Where(m => m.ParentId == parentId).Select(m => new NavigationInfo()
                    {
                        Id = m.Id,
                        Name = m.Name,
                        Url = m.Url,
                        Remark = m.Remark,
                        Icon = m.Icon,
                        ParentId = m.ParentId,
                        NavigationType = m.NavigationType,
                        Children = getChildren(m.Id),
                        IsRelation = roleNavigationList.Count(n => n.NavigationId == m.Id) > 0
                    }).ToArray();
                }
                return new NavigationInfo[] { };
            };

            return getChildren(0);
        }

        /// <summary>
        /// 角色关联菜单
        /// </summary>
        /// <returns></returns>
        public async Task CreateRoleAndMenu(int roleid, string menuids)
        {
            var menidlist = menuids.Split(',').Select(n => new RoleNavigation
            {
                CreationTime = DateTime.Now,
                CreatorUserId = AbpSession.UserId,
                NavigationId = int.Parse(n),
                RoleId = roleid
            }).ToList();
            var frontList = await _roleNavigationRepository.GetAll().Where(n => n.RoleId == roleid).ToListAsync();
            var noMaplist = new List<RoleNavigation>(); //共同拥有的
            var addMaplist = menidlist;       //最后新增的数据
            var delMaplist = frontList;               //待删除数据
            if (frontList.Count > 0)
            {
                //取出共同拥有的数据
                foreach (var couponProductMap in menidlist)
                {
                    noMaplist.AddRange(frontList.Where(productMap => couponProductMap.RoleId == productMap.RoleId && productMap.NavigationId == couponProductMap.NavigationId));
                }
                //新增的数据移除共同拥有的数据
                foreach (var productMap in noMaplist)
                {
                    addMaplist.RemoveAll(n => n.RoleId == productMap.RoleId && n.NavigationId == productMap.NavigationId);
                }
                //删除的数据移除共同拥有的数据
                foreach (var productMap in noMaplist)
                {
                    delMaplist.RemoveAll(n => n.RoleId == productMap.RoleId && n.NavigationId == productMap.NavigationId);
                }
            }
            //新增新数据
            foreach (var map in addMaplist)
            {
                await _roleNavigationRepository.InsertAsync(map);
            }
            //删除旧数据
            foreach (var map in delMaplist)
            {
                await _roleNavigationRepository.DeleteAsync(map);
            }

            var userIds = await _userRoleRepository.GetAll().AsNoTracking()
                .Where(p => p.RoleId == roleid).Select(p => p.UserId)
                .ToArrayAsync();

            //删除缓存
            var cacher = _cacheManager.GetCache(_userNavigationCacheKey).AsTyped<long, ICollection<NavigationInfo>>();
            foreach (var userId in userIds)
            {
                cacher.Remove(userId);
            }
        }

        #region 私有方法

        private void CheckNavigationAsync(Navigation navigation)
        {
            navigation.CheckNotNull("navigation");
            if (_navigationRepository.CheckExists(p => p.ParentId == navigation.ParentId && p.Name == navigation.Name, navigation.Id))
            {
                throw new UserFriendlyException("该菜单已存在");
            }

            if (navigation.ParentId != 0 && !_navigationRepository.CheckExists(p => p.Id == navigation.ParentId))
            {
                throw new UserFriendlyException("指定的父级菜单不存在");
            }
        }

        /// <summary>
        /// 获取用户导航信息集合
        /// </summary>
        /// <returns></returns>
        private async Task<ICollection<NavigationInfo>> GetUserNavigationInfos()
        {
            var cacheKey = AbpSession.UserId.HasValue ? AbpSession.UserId.Value : 0;

            return await _cacheManager
                .GetCache(_userNavigationCacheKey)
                .GetAsync(cacheKey, () =>
                {
                    Expression<Func<Navigation, bool>> exp = p => p.NavigationType == NavigationType.Anonymouse;
                    if (AbpSession.UserId.HasValue)
                    {
                        exp = exp.Or(p => p.NavigationType == NavigationType.Logined);
                        var roleIds = _userRoleRepository.GetAll().Where(p => p.UserId == AbpSession.UserId.Value).Select(p => p.RoleId).ToList();
                        var navigationIds = _roleNavigationRepository.GetAll().Where(p => roleIds.Contains(p.RoleId)).Select(p => p.NavigationId).ToList();
                        exp = exp.Or(p => p.NavigationType == NavigationType.RoleLimit && navigationIds.Contains(p.Id));
                    }
                    return QueryNavigations(exp);
                });
        }

        /// <summary>
        /// 获取所有导航信息集合
        /// </summary>
        /// <returns></returns>
        private async Task<ICollection<NavigationInfo>> GetAllNavigationInfos()
        {
            return await _cacheManager
                .GetCache(_userNavigationCacheKey)
                .GetAsync("all", () => QueryNavigations(p => true));
        }

        /// <summary>
        /// 根据条件查询导航信息集合
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        private async Task<ICollection<NavigationInfo>> QueryNavigations(Expression<Func<Navigation, bool>> query)
        {
            var navigations = await _navigationRepository.GetAll().AsNoTracking().Where(query).OrderBy(p => p.OrderNo).Select(p => new NavigationInfo
            {
                Id = p.Id,
                Name = p.Name,
                Url = p.Url,
                Remark = p.Remark,
                Icon = p.Icon,
                ParentId = p.ParentId,
                NavigationType = p.NavigationType,
                RequiredPermissionName = p.RequiredPermissionName
            }).ToListAsync();

            return navigations;
        }

        /// <summary>
        /// 根据条件查询导航信息集合(树形,递归)
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        private async Task<ICollection<NavigationInfo>> QueryNavigationTrees(Expression<Func<Navigation, bool>> query)
        {
            var navigations = await QueryNavigations(query);

            Func<int, NavigationInfo[]> getChildren = null;
            getChildren = parentId =>
            {
                if (navigations.Any(m => m.ParentId == parentId))
                {
                    return navigations.Where(m => m.ParentId == parentId).Select(m => new NavigationInfo()
                    {
                        Id = m.Id,
                        Name = m.Name,
                        Url = m.Url,
                        Remark = m.Remark,
                        Icon = m.Icon,
                        ParentId = m.ParentId,
                        NavigationType = m.NavigationType,
                        Children = getChildren(m.Id),
                        RequiredPermissionName=m.RequiredPermissionName
                    }).ToArray();
                }
                return new NavigationInfo[] { };
            };

            return getChildren(0);
        }

        /// <summary>
        /// 比较导航信息与url是否匹配
        /// </summary>
        /// <param name="navigation">导航信息</param>
        /// <param name="url">url</param>
        /// <returns></returns>
        private bool CompareNavigationUrl(NavigationInfo navigation, string url)
        {
            url = url.ToLower().Trim().TrimEnd(new[] { '#' });
            var navigationUrl = navigation.Url.ToLower().Trim().TrimEnd(new[] { '#' });

            var urlIndex = url.IndexOf("?");
            if (urlIndex <= 0) return url == navigationUrl;

            var start = url.Substring(0, urlIndex);
            if (!navigationUrl.StartsWith(start)) return false;

            Func<string, Dictionary<string, string>> getParamFunc = p =>
            {
                var paramDic = new Dictionary<string, string>();
                int paramIndex = p.IndexOf("?");
                if (paramIndex <= 0) return paramDic;

                string param = p.Substring(paramIndex + 1);
                var keyValues = param.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in keyValues)
                {
                    var arr = item.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries).Select(m => m.Trim()).ToArray();
                    if (arr.Count() != 2) continue;
                    paramDic.Add(arr[0], arr[1]);
                }
                return paramDic;
            };

            var urlParams = getParamFunc(url);
            var navigationParams = getParamFunc(navigationUrl);
            foreach (var item in navigationParams)
            {
                if (!urlParams.ContainsKey(item.Key) || urlParams[item.Key] != item.Value) return false;
            }
            return true;
        }

        #endregion

    }
}


text:
package com.google.code.ssm.aop.counter;

import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

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

import org.hamcrest.CoreMatchers;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameters;

import com.google.code.ssm.api.ParameterValueKeyProvider;
import com.google.code.ssm.api.counter.IncrementCounterInCache;

/**
 *
 * @author Jakub Białek
 *
 */
public class IncrementCounterInCacheAdviceTest extends AbstractCounterTest<IncrementCounterInCacheAdvice> {

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] { //
                { true, "incrCounter1", new Class[] { int.class }, new Object[] { 1 } }, //
                        { true, "incrCounter2", new Class[] { int.class, int.class }, new Object[] { 2, 5 } }, //
                        { false, "incrCounter20", new Class[] {}, new Object[] {} }, //

                });
    }

    public IncrementCounterInCacheAdviceTest(final boolean isValid, final String methodName, final Class<?>[] paramTypes,
            final Object[] params) {
        super(isValid, methodName, paramTypes, params, null);
    }

    @Before
    public void setUp() {
        super.setUp(new TestService());
    }

    @Test
    public void validIncrementCounterInCache() throws Throwable {
        Assume.assumeTrue(isValid);

        advice.incrementSingle(pjp);

        verify(cache).incr(cacheKey, 1, 1L);
    }

    @Test
    public void invalidIncrementCounterInCache() throws Throwable {
        Assume.assumeThat(isValid, CoreMatchers.is(false));

        advice.incrementSingle(pjp);

        verify(cache, never()).incr(cacheKey, 1, 1L);
    }

    @Override
    protected IncrementCounterInCacheAdvice createAdvice() {
        return new IncrementCounterInCacheAdvice();
    }

    @SuppressWarnings("unused")
    private static class TestService {

        @IncrementCounterInCache(namespace = NS)
        public void incrCounter1(@ParameterValueKeyProvider final int id1) {

        }

        @IncrementCounterInCache(namespace = NS)
        public int incrCounter2(@ParameterValueKeyProvider(order = 2) final int id1, @ParameterValueKeyProvider(order = 5) final int id2) {
            return 1;
        }

        // no @ParameterValueKeyProvider
        @IncrementCounterInCache(namespace = NS)
        public void incrCounter20() {

        }

    }

}


text:
package org.bouncycastle.bcpg.sig;

import org.bouncycastle.bcpg.SignatureSubpacket;

/**
 * packet giving signature creation time.
 */
public class PreferredAlgorithms
    extends SignatureSubpacket
{
    private static byte[] intToByteArray(
        int[]    v)
    {
        byte[]    data = new byte[v.length];

        for (int i = 0; i != v.length; i++)
        {
            data[i] = (byte)v[i];
        }

        return data;
    }

    public PreferredAlgorithms(
        int        type,
        boolean    critical,
        boolean    isLongLength,
        byte[]     data)
    {
        super(type, critical, isLongLength, data);
    }

    public PreferredAlgorithms(
        int        type,
        boolean    critical,
        int[]      preferences)
    {
        super(type, critical, false, intToByteArray(preferences));
    }

    public int[] getPreferences()
    {
        int[]    v = new int[data.length];

        for (int i = 0; i != v.length; i++)
        {
            v[i] = data[i] & 0xff;
        }

        return v;
    }
}


text:
package com.amar.hello2.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import com.amar.hello2.R;

public class ShowFragment extends Fragment
{

    WebView webview = null;

    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
    {
        View view = inflater.inflate( R.layout.show, container, false );
        webview = ( WebView ) view.findViewById( R.id.webview );
        return view;
    }

    @Override
    public void onAttach( Activity activity )
    {
        super.onAttach( activity );
    }

    public WebView getWebView()
    {
        return webview;
    }
}


text:
using AcademyEF.Models;
using AcademyEF.Repositories;
using AcademyEF.ViewModels.AccountVM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AcademyEF.Services
{
    public class UsersService : BaseService<User>
    {
        public UsersService()
        {

        }

        public UsersService(UnitOfWork unit):base(unit)
        {

        }

        public User CheckUsernameOrMail(AccountEditVM user)
        {
            UsersService userService = new UsersService();
            User userMail = userService.GetAll().FirstOrDefault((u => u.Email == user.Email || u.Username == user.Username.ToLower()));
            if (userMail != null)
            {
                return userMail;
            }
            else
                return null;
        }
    }
}


text:
/*
 * Powered By cuichen
 * Since 2014 - 2015
 */
package com.seeyoui.kensite.framework.system.persistence;

import java.util.List;

import com.seeyoui.kensite.common.exception.CRUDException;
import com.seeyoui.kensite.framework.system.domain.SysMenu;
import com.seeyoui.kensite.framework.system.domain.SysRoleMenu;

/**
 * @author cuichen
 * @version 1.0
 * @since 1.0
 */
public interface SysRoleMenuMapper {

	/**
	 * 查询数据TREE
	 * @param map
	 * @return
	 * @throws CRUDException
	 */
	public List<SysMenu> tree(SysRoleMenu sysRoleMenu);

	/**
	 * 数据新增
	 * @param sysRoleMenu
	 */
	public void save(SysRoleMenu sysRoleMenu);

	/**
	 * 数据删除
	 * @param listId
	 */
	public void delete(String roleid);
}


text:
hot-enough-text
===============

Uses Tessel + Twilio to send a text notification when something is hot enough.

I regularly put water on the stove to boil, get distracted, and completely forget to check on it. This project closes the water-boiling loop by sending me a text message when the water is boiling.

This is also easily adaptable to other situations as well– just change the threshold temperature and use it to know when you can put meat on the grill, [salmon in the smokehouse](http://www.instructables.com/id/How-to-Smoke-Salmon/).

I use a thermocouple (not Tessel's climate module) because a thermocouple is versatile, can take high temperatures, and is fine to immerse in water. Tim wrote [a Node library for it](https://www.npmjs.com/package/thermocouple-max31855), so it's not difficult to use one.

## Materials

* [Tessel](//tessel.io)
* [Thermocouple Amplifier MAX31855 breakout board](http://www.adafruit.com/product/269)
* [Thermocouple](http://www.adafruit.com/products/270)

## Hardware setup

1. Assemble the thermocouple and thermocouple amplifier according to [Adafruit's instructions](https://learn.adafruit.com/thermocouple/wiring-the-thermocouple)
1. Connect the thermocouple amplifier to Tessel. It talks over [SPI](https://github.com/tessel/docs/blob/master/tutorials/communication-protocols.md#spi), so we need to connect chip select, clock, and data, as well as power and ground. From the thermocouple amplifier to Tessel's GPIO bank:
  * Vin > 3.3V (power)
  * 3Vo > nothing, we don't need this one
  * GND > GND (ground)
  * DO > MISO (this is data from the thermocouple coming in to Tessel)
  * CS > TX/G1 (chip select– we're using a digital GPIO pin to tell the amplifier when we're talking to it)
  * CLK > SCK (different names for the clock pin)
  ![](https://lh6.googleusercontent.com/-rouT78pE2_U/VKG0f_RF3QI/AAAAAAAALpQ/B_sAqWNMatE/w926-h521-no/20141229_110637.jpg)
  ![](https://lh4.googleusercontent.com/-2mD7RGs3eyU/VKG0eyNzfbI/AAAAAAAALpE/_NUo1dzSxsE/w926-h521-no/20141229_110617.jpg)
1. Put the end of the thermocouple in the thing you're heating up.

## Software setup

1. Set up your Twilio account ([it's free!](https://www.twilio.com/try-twilio))
1. [Install your Tessel](start.tessel.io)

## Run instructions

1. Clone this repo
1. Set up your config.json file based on the example-config.json file
1. Run `npm install` to install Node dependencies
1. In `index.js`, set your temperature threshold
1. [Connect Tessel to the internet](http://start.tessel.io/wifi)
1. Run the code on Tessel: `tessel run index.js`
1. If you want to run the code disconnected from your computer, run `tessel push index.js` to push the code into Tessel's memory, then use an [alternate power source](https://tessel.io/docs/untethered). Just remember to make sure Tessel's connected to the internet, or it won't be able to send the text.


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!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/html; charset=UTF-8" />
    <title>Release 4.5: Collections API</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Berkeley DB Programmer's Reference Guide" />
    <link rel="up" href="upgrade_4_5_toc.html" title="Chapter 42. Upgrading Berkeley DB 4.4 applications to Berkeley DB 4.5" />
    <link rel="prev" href="upgrade_4_5_pagesize.html" title="Release 4.5: DB->set_pagesize" />
    <link rel="next" href="upgrade_4_5_config.html" title="Release 4.5: --enable-pthread_self" />

          Release 4.5: Collections API

          Prev
          Chapter 42. Upgrading Berkeley DB 4.4 applications to Berkeley DB 4.5
           Next

Release 4.5: Collections API

The changes to the Collections API are compatible with prior releases,
with one exception: the Iterator object returned by the
StoredCollection.iterator() method can no longer be explicitly cast to
StoredIterator because a different implementation class is now used for
iterators. If you depend on the StoredIterator class, you must now call
StoredCollection.storedIterator() instead. Note the
StoredIterator.close(Iterator) static method is compatible with the new
iterator implementation, so no changes are necessary if you are using
that method to close iterators.

          Prev

            Up

           Next

          Release 4.5: DB->set_pagesize

            Home

           Release 4.5: --enable-pthread_self


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface com.fasterxml.jackson.dataformat.xml.XmlNameProcessor (Jackson-dataformat-XML 2.14.0 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.fasterxml.jackson.dataformat.xml.XmlNameProcessor

Packages that use XmlNameProcessor

Package
Description

com.fasterxml.jackson.dataformat.xml

Package that contains XML-based backends which can serialize POJOs
 to and deserialize from XML, using Stax XML parsers and generators
 for XML processing and mostly standard Jackson data binding otherwise.

com.fasterxml.jackson.dataformat.xml.deser

com.fasterxml.jackson.dataformat.xml.ser

Uses of XmlNameProcessor in com.fasterxml.jackson.dataformat.xml

Fields in com.fasterxml.jackson.dataformat.xml declared as XmlNameProcessor

Modifier and Type
Field and Description

protected XmlNameProcessor
XmlFactory._nameProcessor

protected XmlNameProcessor
XmlFactoryBuilder._nameProcessor

See XmlNameProcessor and XmlNameProcessors

Methods in com.fasterxml.jackson.dataformat.xml that return XmlNameProcessor

Modifier and Type
Method and Description

XmlNameProcessor
XmlFactory.getXmlNameProcessor()

static XmlNameProcessor
XmlNameProcessors.newAlwaysOnBase64Processor()

Similar to XmlNameProcessors.newBase64Processor(String), however, names will
 always be escaped with base64.

static XmlNameProcessor
XmlNameProcessors.newBase64Processor()

Convenience method
 equivalent to calling XmlNameProcessors.newBase64Processor(String) with "base64_tag_"

static XmlNameProcessor
XmlNameProcessors.newBase64Processor(String prefix)

Generates a new processor that escapes all names that contains characters
 OTHER than following characters:

 Lower- or upper-case ASCII letter (a to z, A to Z)

 Digit (0 to 9) in position OTHER than the first characters

 Underscore

 Hyphen (-) in position OTHER than the first character

 Colon (only  exposed if underlying parser is in non-namespace-aware mode)

 with a base64-encoded version.

static XmlNameProcessor
XmlNameProcessors.newPassthroughProcessor()

Generates a new processor that does nothing and just passes through the
 names as-is.

static XmlNameProcessor
XmlNameProcessors.newReplacementProcessor()

Convenience method
 equivalent to calling XmlNameProcessors.newReplacementProcessor(String) with "_"

static XmlNameProcessor
XmlNameProcessors.newReplacementProcessor(String replacement)

Generates a new processor that replaces all characters that are NOT one of:

 Lower- or upper-case ASCII letter (a to z, A to Z)

 Digit (0 to 9) in position OTHER than the first character

 Underscore

 Hyphen (-) in position OTHER than the first character

 Colon (only  exposed if underlying parser is in non-namespace-aware mode)

 in an
 XML name with a replacement string.

XmlNameProcessor
XmlFactoryBuilder.xmlNameProcessor()

Methods in com.fasterxml.jackson.dataformat.xml with parameters of type XmlNameProcessor

Modifier and Type
Method and Description

void
XmlMapper.setXmlNameProcessor(XmlNameProcessor processor)

void
XmlFactory.setXmlNameProcessor(XmlNameProcessor processor)

XmlMapper.Builder
XmlMapper.Builder.xmlNameProcessor(XmlNameProcessor processor)

XmlFactoryBuilder
XmlFactoryBuilder.xmlNameProcessor(XmlNameProcessor nameProcessor)

Constructors in com.fasterxml.jackson.dataformat.xml with parameters of type XmlNameProcessor

Constructor and Description

XmlFactory(com.fasterxml.jackson.core.ObjectCodec oc,
          int xpFeatures,
          int xgFeatures,
          XMLInputFactory xmlIn,
          XMLOutputFactory xmlOut,
          String nameForTextElem,
          XmlNameProcessor nameProcessor)

Uses of XmlNameProcessor in com.fasterxml.jackson.dataformat.xml.deser

Fields in com.fasterxml.jackson.dataformat.xml.deser declared as XmlNameProcessor

Modifier and Type
Field and Description

protected XmlNameProcessor
XmlTokenStream._nameProcessor

Constructors in com.fasterxml.jackson.dataformat.xml.deser with parameters of type XmlNameProcessor

Constructor and Description

FromXmlParser(com.fasterxml.jackson.core.io.IOContext ctxt,
             int genericParserFeatures,
             int xmlFeatures,
             com.fasterxml.jackson.core.ObjectCodec codec,
             XMLStreamReader xmlReader,
             XmlNameProcessor tagProcessor)

XmlTokenStream(XMLStreamReader xmlReader,
              com.fasterxml.jackson.core.io.ContentReference sourceRef,
              int formatFeatures,
              XmlNameProcessor nameProcessor)

Uses of XmlNameProcessor in com.fasterxml.jackson.dataformat.xml.ser

Fields in com.fasterxml.jackson.dataformat.xml.ser declared as XmlNameProcessor

Modifier and Type
Field and Description

protected XmlNameProcessor
ToXmlGenerator._nameProcessor

Escapes names with invalid XML characters

Constructors in com.fasterxml.jackson.dataformat.xml.ser with parameters of type XmlNameProcessor

Constructor and Description

ToXmlGenerator(com.fasterxml.jackson.core.io.IOContext ctxt,
              int stdFeatures,
              int xmlFeatures,
              com.fasterxml.jackson.core.ObjectCodec codec,
              XMLStreamWriter sw,
              XmlNameProcessor nameProcessor)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2022 FasterXML. All rights reserved.


text:
from constance import settings, utils

class Config(object):
    """
    The global config wrapper that handles the backend.
    """
    def __init__(self):
        super(Config, self).__setattr__('_backend',
            utils.import_module_attr(settings.BACKEND)())

    def __getattr__(self, key):
        try:
            default, help_text = settings.CONFIG[key][0], settings.CONFIG[key][1]
        except KeyError:
            raise AttributeError(key)
        result = self._backend.get(key)
        if result is None:
            result = default
            setattr(self, key, default)
            return result
        return result

    def __setattr__(self, key, value):
        if key not in settings.CONFIG:
            raise AttributeError(key)
        self._backend.set(key, value)

    def __dir__(self):
        return settings.CONFIG.keys()


text:
import unittest
from .enron_util import truncate_message

class TruncateMessageTest(unittest.TestCase):
    def run_template(self, useful, junk):

        msg = '{}{}'.format(
            useful, junk

        )
        self.assertEqual(
            useful,
            truncate_message(msg)
        )

    def test_truncate_message_1(self):
        self.run_template(
            'His extension is 3-5612. Vince    ',
            '-----Original Message----- From: \\'
        )

    def test_truncate_message_2(self):
        self.run_template(
            'I  already complied? ',
            '---------------------- Forwarded by Steven J Kean/NA/Enron on 07/11/2001  01:19 PM ---------------------------  '
        )

    def test_truncate_message_3(self):
        self.run_template(
            'His extension is 3-5612. Vince    ',
            '-----original message----- From: \\'
        )

    def test_truncate_message_4(self):
        self.run_template(
            'His extension is 3-5612. Vince    ----nice',
            ''
        )

    def test_truncate_message_5(self):
        self.run_template(
            'when we merged in 1997. ',
            '---------------------- Forwarded by Steven'
        )

    def test_truncate_message_6(self):
        self.run_template(
            'Best, Jeff ',
            '********************************************************************** Financial  California'
        )

    def test_truncate_message_7(self):
        self.run_template(
            'aaa ',
            'JAMES@ENRON COMMUNICATIONS 07/05/2001 01:09 PM'
        )

    def test_truncate_message_8(self):
        self.run_template(
            'gloves off.         James D Steffes ',
            '07/06/2001 10:04 PM To:	Jeffrey T Hodge/Enron@EnronXGate, Robert'
        )

    def test_truncate_message_8(self):
        self.run_template(
            '"wgramm" ',
            '<wgramm@osf1.gmu.edu> on 07/17/2001 03:23:19 PM Please respond to <wgramm@osf1.gmu.edu>   To:	"Jerry Ellig" <jellig@gmu.edu>, "Steve Kean" <skean'
        )


text:
package org.missionassetfund.apps.android.fragments;

import org.missionassetfund.apps.android.R;
import org.missionassetfund.apps.android.adapters.FrequencyAdapter;
import org.missionassetfund.apps.android.interfaces.OnInputFormListener;
import org.missionassetfund.apps.android.models.GoalPaymentInterval;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

public class FrequencyInputFragment extends Fragment {
    private OnInputFormListener onInputFormListener;

    private Spinner spFrequency;
    private ImageButton btnBack;
    private ImageButton btnNext;

    private FrequencyAdapter frequencyAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_frequency_input, container, false);

        // Setup view
        spFrequency = (Spinner) view.findViewById(R.id.spFrequency);
        btnBack = (ImageButton) view.findViewById(R.id.btnBack);
        btnNext = (ImageButton) view.findViewById(R.id.btnNext);

        // Populate spinner
        frequencyAdapter = new FrequencyAdapter(getActivity(), GoalPaymentInterval.values());

        spFrequency.setAdapter(frequencyAdapter);

        // Setup listener
        btnNext.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO(jose): Have next button disable until spFrequency has
                // value
                if (spFrequency.getSelectedItem() != null) {
                    GoalPaymentInterval frequency = (GoalPaymentInterval) spFrequency
                            .getSelectedItem();
                    onInputFormListener.OnNextSelected(FrequencyInputFragment.class,
                            frequency.toString());
                } else {
                    Toast.makeText(getActivity(), getString(R.string.error_category_require),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onInputFormListener.OnBackSelected(FrequencyInputFragment.class);
            }
        });

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof OnInputFormListener) {
            onInputFormListener = (OnInputFormListener) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implement OnInputFormListener");
        }
    }

    public GoalPaymentInterval getFrequencySelected() {
        return (GoalPaymentInterval) spFrequency.getSelectedItem();
    }
}


text:
Smash is still a work in progress, so you must build from source and there is no
install step.

See also [development notes](development.md).

## Prereqs

- golang
- node+yarn

## Building

```sh
$ (cd web && yarn)  # Install prerequisites.
$ make run
```


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>CSS Backgrounds and Borders Test: background-size - one <percentage> and one auto keyword values</title>
    <link rel="author" title="Intel" href="http://www.intel.com">
    <link rel="reviewer" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/">
    <link rel="help" href="http://www.w3.org/TR/css3-background/#the-background-size" title="3.9. Sizing Images: the 'background-size' property">
    <link rel="match" href="../reference/ref-filled-green-100px-square.xht">
    <meta name="flags" content="image">
    <meta name="assert" content="Check if 'background-size' has one percentage and one auto values, then the first value is the width of the corresponding background image and the second value (corresponding to the height of the background image) is resolved by using the image's intrinsic ratio (in this test, the image's intrinsic ratio is 1:1) and (multiplied by) the size of the other dimension. Therefore the used height of the background-size in this test should be 100px.">

Test passes if there is a filled green square and no red.


text:
var Bookshelf = require("bookshelf");
var _ = require('lodash');

var Model = require('../models/base');

BaseCollection = module.exports = Bookshelf.primary.Collection.extend({
		model: Model
});