text:
/**
 * @fileoverview CheckStyle XML reporter
 * @author Ian Christian Myers
 */
"use strict";

//------------------------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------------------------

/**
 * Returns the severity of warning or error
 * @param {object} message message object to examine
 * @returns {string} severity level
 * @private
 */
function getMessageType(message) {
    if (message.fatal || message.severity === 2) {
        return "error";
    } else {
        return "warning";
    }
}

/**
 * Returns the escaped value for a character
 * @param {string} s string to examine
 * @returns {string} severity level
 * @private
 */
function xmlEscape(s) {
    return ("" + s).replace(/[<>&"']/g, function(c) {
        switch (c) {
            case "<":
                return "<";
            case ">":
                return ">";
            case "&":
                return "&";
            case "\"":
                return """;
            case "'":
                return "'";
            default:
                throw new Error("unreachable");
        }
    });
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = function(results) {

    var output = "";

    output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    output += "<checkstyle version=\"4.3\">";

    results.forEach(function(result) {
        var messages = result.messages;

        output += "<file name=\"" + xmlEscape(result.filePath) + "\">";

        messages.forEach(function(message) {
            output += "<error line=\"" + xmlEscape(message.line) + "\" " +
                "column=\"" + xmlEscape(message.column) + "\" " +
                "severity=\"" + xmlEscape(getMessageType(message)) + "\" " +
                "message=\"" + xmlEscape(message.message) +
                (message.ruleId ? " (" + message.ruleId + ")" : "") + "\" " +
                "source=\"" + (message.ruleId ? xmlEscape("eslint.rules." + message.ruleId) : "") + "\" />";
        });

        output += "</file>";

    });

    output += "</checkstyle>";

    return output;
};


text:
package com.badlydrawngames.general;

import com.badlogic.gdx.Screen;

public class GameScreen<T> implements Screen {
	protected T game;

	public GameScreen (T game) {
		this.game = game;
	}

	@Override
	public void dispose () {
	}

	@Override
	public void hide () {
	}

	@Override
	public void pause () {
	}

	@Override
	public void render (float delta) {
	}

	@Override
	public void resize (int width, int height) {
	}

	@Override
	public void resume () {
	}

	@Override
	public void show () {
	}
}

redpajama_set_name: RedPajamaGithub


text: INSERT INTO `migrator_test_timestamps` (`title`) VALUES ('test2');


text:
using GalaSoft.MvvmLight;
using ShooterKiosk.Properties;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Data;

namespace ShooterKiosk.ViewModel.Internal
{
    public abstract class MemberVisitRegistrationViewModelBase : ViewModelBase, IMemberVisitRegistrationViewModel
    {
        protected readonly IMainViewModel _mainViewModel;
        protected readonly ICollectionView _members;

        private string _selectedMember;
        private string _memberSearchName;

        public MemberVisitRegistrationViewModelBase(IMainViewModel mainViewModel)
        {
            Debug.Assert(mainViewModel != null);
            Debug.Assert(mainViewModel.People != null);

            _mainViewModel = mainViewModel;

            _members = CollectionViewSource.GetDefaultView(_mainViewModel.People);
            _members.Filter = MemberStartsWithSearchText;
        }

        private bool MemberStartsWithSearchText(object o)
        {
            Debug.Assert(o != null);

            if (string.IsNullOrEmpty(_memberSearchName))
            {
                return true;
            }

            var memberName = o as string;
            Debug.Assert(memberName != null);

            return memberName.ToLowerInvariant().Contains(_memberSearchName.ToLowerInvariant());
        }

        public string MemberSearchName
        {
            get
            {
                return _memberSearchName;
            }
            set
            {
                if (ReferenceEquals(_memberSearchName, value))
                {
                    return;
                }

                _memberSearchName = value;
                Members.Refresh();
                RaisePropertyChanged(nameof(MemberSearchName));
            }
        }

        public string CancelButtonLabel => Resources.MemVisReg_Button_Cancel;

        public string NameSearchLabel => Resources.MemVisReg_Label_NameSearch;

        public string RegisterButtonLabel => Resources.MemVisReg_Button_Register;

        public string ScreenHeading => Resources.MemVisReg_ScreenHeading;

        public ICollectionView Members => _members;

        public string SelectedMember
        {
            get
            {
                return _selectedMember;
            }
            set
            {
                if (ReferenceEquals(_selectedMember, value))
                {
                    return;
                }

                _selectedMember = value;
                RaisePropertyChanged(nameof(SelectedMember));
            }
        }
    }
}


text:
gitCommitNum=$(git rev-list HEAD --count)
gitBranch=$(git rev-parse --abbrev-ref HEAD)
gitCommitHash=$(git rev-parse --verify HEAD --short)
gitIsDirty=$([[ $(git diff --shortstat 2> /dev/null | tail -n1) != "" ]] && echo " *Dirty Repo")

if [ -z "$gitCommitNum" ]; then
gitCommitNum="Unknown Version"
fi

if [ -z "$gitBranch" ]; then
gitBranch="Unknown Branch"
fi

if [ -z "$gitCommitHash" ]; then
gitCommitHash="Unknown Commit"
fi

defaults write "${TARGET_BUILD_DIR}/$INFOPLIST_PATH" "CFBundleShortVersionString" "Git Commit # $gitCommitNum"
defaults write "${TARGET_BUILD_DIR}/$INFOPLIST_PATH" "CFBundleVersion" "$gitBranch - $gitCommitHash $gitIsDirty"

echo 'GIT_COMMIT_NUMBER is '$gitCommitNum
echo 'git Commit Hash is '$gitCommitHash


text:
title: "Permutation in String"
description: "Some description ..."
authors: ["lek-tin"]
tags: ["leetcode", "hashmap", "sliding-window"]
categories: ["algorithm"]
date: 2020-05-23T18:05:03-07:00
lastmod: 2020-05-23T18:05:03-07:00
draft: false
archive: false
---

Given two strings `s1` and `s2`, write a function to return true if `s2` contains the permutation of `s1`. In other words, one of the first string's permutations is the **substring** of the second string.

### Example 1:

```
Input: s1 = "ab" s2 = "eidbaooo"
Output: True
Explanation: s2 contains one permutation of s1 ("ba").
```

### Example 2:

```
Input:s1= "ab" s2 = "eidboaoo"
Output: False
```

#### Constraints:

1. The input strings only contain lower case letters.
2. The length of both given strings is in range `[1, 10,000]`.

### Solution

Java
```java
```


text:
package org.apache.carbondata.core.scan.result.vector.impl.directread;

import java.util.BitSet;

import org.apache.carbondata.common.annotations.InterfaceAudience;
import org.apache.carbondata.common.annotations.InterfaceStability;

/**
 * It is sort of a marker interface to let execution engine know that it is appendable/sequential
 * data adding vector. It means we cannot add random rowids to it.
 */
@InterfaceStability.Evolving
@InterfaceAudience.Internal
public interface SequentialFill {

  /**
   * Set the null bitset
   * @param nullBits
   */
  void setNullBits(BitSet nullBits);
}


text:
/**
 */
package CIM.IEC61968.AssetModels;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.eclipse.emf.common.util.Enumerator;

/**
 *
 * A representation of the literals of the enumeration 'Corporate Standard Kind',
 * and utility methods for working with them.
 *
 * @see CIM.IEC61968.AssetModels.AssetModelsPackage#getCorporateStandardKind()
 * @model
 * @generated
 */
public enum CorporateStandardKind implements Enumerator {
	/**
	 * The 'Under Evaluation' literal object.
	 *
	 *
	 * @see #UNDER_EVALUATION_VALUE
	 * @generated
	 * @ordered
	 */
	UNDER_EVALUATION(0, "underEvaluation", "underEvaluation"),

	/**
	 * The 'Other' literal object.
	 *
	 *
	 * @see #OTHER_VALUE
	 * @generated
	 * @ordered
	 */
	OTHER(1, "other", "other"),

	/**
	 * The 'Standard' literal object.
	 *
	 *
	 * @see #STANDARD_VALUE
	 * @generated
	 * @ordered
	 */
	STANDARD(2, "standard", "standard"),

	/**
	 * The 'Experimental' literal object.
	 *
	 *
	 * @see #EXPERIMENTAL_VALUE
	 * @generated
	 * @ordered
	 */
	EXPERIMENTAL(3, "experimental", "experimental");

	/**
	 * The 'Under Evaluation' literal value.
	 *
	 *

	 * If the meaning of 'Under Evaluation' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #UNDER_EVALUATION
	 * @model name="underEvaluation"
	 * @generated
	 * @ordered
	 */
	public static final int UNDER_EVALUATION_VALUE = 0;

	/**
	 * The 'Other' literal value.
	 *
	 *

	 * If the meaning of 'Other' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #OTHER
	 * @model name="other"
	 * @generated
	 * @ordered
	 */
	public static final int OTHER_VALUE = 1;

	/**
	 * The 'Standard' literal value.
	 *
	 *

	 * If the meaning of 'Standard' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #STANDARD
	 * @model name="standard"
	 * @generated
	 * @ordered
	 */
	public static final int STANDARD_VALUE = 2;

	/**
	 * The 'Experimental' literal value.
	 *
	 *

	 * If the meaning of 'Experimental' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #EXPERIMENTAL
	 * @model name="experimental"
	 * @generated
	 * @ordered
	 */
	public static final int EXPERIMENTAL_VALUE = 3;

	/**
	 * An array of all the 'Corporate Standard Kind' enumerators.
	 *
	 *
	 * @generated
	 */
	private static final CorporateStandardKind[] VALUES_ARRAY =
		new CorporateStandardKind[] {
			UNDER_EVALUATION,
			OTHER,
			STANDARD,
			EXPERIMENTAL,
		};

	/**
	 * A public read-only list of all the 'Corporate Standard Kind' enumerators.
	 *
	 *
	 * @generated
	 */
	public static final List<CorporateStandardKind> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));

	/**
	 * Returns the 'Corporate Standard Kind' literal with the specified literal value.
	 *
	 *
	 * @param literal the literal.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static CorporateStandardKind get(String literal) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			CorporateStandardKind result = VALUES_ARRAY[i];
			if (result.toString().equals(literal)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Corporate Standard Kind' literal with the specified name.
	 *
	 *
	 * @param name the name.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static CorporateStandardKind getByName(String name) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			CorporateStandardKind result = VALUES_ARRAY[i];
			if (result.getName().equals(name)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Corporate Standard Kind' literal with the specified integer value.
	 *
	 *
	 * @param value the integer value.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static CorporateStandardKind get(int value) {
		switch (value) {
			case UNDER_EVALUATION_VALUE: return UNDER_EVALUATION;
			case OTHER_VALUE: return OTHER;
			case STANDARD_VALUE: return STANDARD;
			case EXPERIMENTAL_VALUE: return EXPERIMENTAL;
		}
		return null;
	}

	/**
	 *
	 *
	 * @generated
	 */
	private final int value;

	/**
	 *
	 *
	 * @generated
	 */
	private final String name;

	/**
	 *
	 *
	 * @generated
	 */
	private final String literal;

	/**
	 * Only this class can construct instances.
	 *
	 *
	 * @generated
	 */
	private CorporateStandardKind(int value, String name, String literal) {
		this.value = value;
		this.name = name;
		this.literal = literal;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public int getValue() {
	  return value;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getName() {
	  return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getLiteral() {
	  return literal;
	}

	/**
	 * Returns the literal value of the enumerator, which is its string representation.
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		return literal;
	}

} //CorporateStandardKind


text:
import java.io.{BufferedReader, FileReader}

object Settings {
  import java.io.{BufferedWriter, File, FileWriter}

  def using[A <: AutoCloseable, B](resource: A)
                                  (block: A => B): B = {
    try block(resource) finally resource.close()
  }

  def readLines(file: File): String =
    using(new BufferedReader(new FileReader(file))) { _.readLine() }

  def justForTravis(home: String): Unit = {
    val configDir = new File(s"$home/.config/")
    configDir.mkdir()
    val hubFile = new File(configDir, "hub")
    using(new BufferedWriter(new FileWriter(hubFile))) { bw =>
      bw.write(
        """- user: travis
          |  oauth_token: 12345678901234567890
          |  protocol: https
          |""".stripMargin
      )
    }
    ()
  }

  lazy val gitHubId: String = try {
    val home = System.getProperty("user.home")
    if (home=="/home/travis") justForTravis(home)
    val hubConfigFile = new File(s"$home/.config/hub")
    if (hubConfigFile.exists)
      readLines(hubConfigFile)
        .split("\n")
        .find(_.contains("user:"))
        .map(_.split(" ").slice(2, 3).mkString)
        .mkString
    else
      "noGithubUserFound"
  } catch {
    case ex: java.io.IOException =>
      System.err.println(s"project/Settings.scala error: ${ ex.getMessage }; ${ ex }")
      sys.exit(-1)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Rezolver.Tests.Types
{
    public class DefaultCtor : NoCtor
    {
		public const int ExpectedValue = -1;
		public DefaultCtor()
		{
			Value = ExpectedValue;
		}
	}
}


text:
<?php

use Illuminate\Support\Str;

return [
	/*
	|--------------------------------------------------------------------------
	| Default Database Connection Name
	|--------------------------------------------------------------------------
	|
	| Here you may specify which of the database connections below you wish
	| to use as your default connection for all database work. Of course
	| you may use many connections at once using the Database library.
	|
	*/

	'default' => env('DB_CONNECTION', 'mysql'),

	/*
	|--------------------------------------------------------------------------
	| Database Connections
	|--------------------------------------------------------------------------
	|
	| Here are each of the database connections setup for your application.
	| Of course, examples of configuring each database platform that is
	| supported by Laravel is shown below to make development simple.
	|
	|
	| All database work in Laravel is done through the PHP PDO facilities
	| so make sure you have the driver for your particular database of
	| choice installed on your machine before you begin development.
	|
	*/

	'connections' => [
		'sqlite' => [
			'driver' => 'sqlite',
			'url' => env('DATABASE_URL'),
			'database' => env('DB_DATABASE', database_path('database.sqlite')),
			'prefix' => '',
			'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
		],

		'mysql' => [
			'driver' => 'mysql',
			'url' => env('DATABASE_URL'),
			'host' => env('DB_HOST', '127.0.0.1'),
			'port' => env('DB_PORT', '3306'),
			'database' => env('DB_DATABASE', 'forge'),
			'username' => env('DB_USERNAME', 'forge'),
			'password' => env('DB_PASSWORD', ''),
			'unix_socket' => env('DB_SOCKET', ''),
			'charset' => 'utf8mb4',
			'collation' => 'utf8mb4_unicode_ci',
			// The timezone of the DB connection should always be set in order
			// to ensure that the PHP application and the DB server have a
			// mutual understanding how SQL datetime strings without an
			// explicit timezone indication such as `YYYY-MM-DD hh:mm:ss`
			// shall be interpreted.
			// The setting here must not be changed and must match the
			// assumption in \App\Models\PatchedBaseModel.
			'timezone' => '+00:00',
			'prefix' => '',
			'prefix_indexes' => true,
			'strict' => true,
			'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',
			'options' => extension_loaded('pdo_mysql') ? array_filter([
				PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
			]) : [],
		],

		'pgsql' => [
			'driver' => 'pgsql',
			'url' => env('DATABASE_URL'),
			'host' => env('DB_HOST', '127.0.0.1'),
			'port' => env('DB_PORT', '5432'),
			'database' => env('DB_DATABASE', 'forge'),
			'username' => env('DB_USERNAME', 'forge'),
			'password' => env('DB_PASSWORD', ''),
			'charset' => 'utf8',
			// The timezone of the DB connection should always be set in order
			// to ensure that the PHP application and the DB server have a
			// mutual understanding how SQL datetime strings without an
			// explicit timezone indication such as `YYYY-MM-DD hh:mm:ss`
			// shall be interpreted.
			// The setting here must not be changed and must match the
			// assumption in \App\Models\PatchedBaseModel.
			'timezone' => 'UTC',
			'prefix' => '',
			'prefix_indexes' => true,
			'schema' => 'public',
			'sslmode' => 'prefer',
		],

		'sqlsrv' => [
			'driver' => 'sqlsrv',
			'url' => env('DATABASE_URL'),
			'host' => env('DB_HOST', 'localhost'),
			'port' => env('DB_PORT', '1433'),
			'database' => env('DB_DATABASE', 'forge'),
			'username' => env('DB_USERNAME', 'forge'),
			'password' => env('DB_PASSWORD', ''),
			'charset' => 'utf8',
			'prefix' => '',
			'prefix_indexes' => true,
		],
	],

	/*
	|--------------------------------------------------------------------------
	| Migration Repository Table
	|--------------------------------------------------------------------------
	|
	| This table keeps track of all the migrations that have already run for
	| your application. Using this information, we can determine which of
	| the migrations on disk haven't actually been run in the database.
	|
	*/

	'migrations' => 'migrations',

	/*
	|--------------------------------------------------------------------------
	| Redis Databases
	|--------------------------------------------------------------------------
	|
	| Redis is an open source, fast, and advanced key-value store that also
	| provides a richer body of commands than a typical key-value system
	| such as APC or Memcached. Laravel makes it easy to dig right in.
	|
	*/

	'redis' => [
		'client' => env('REDIS_CLIENT', 'phpredis'),

		'options' => [
			'cluster' => env('REDIS_CLUSTER', 'redis'),
			'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_') . '_database_'),
		],

		'default' => [
			'url' => env('REDIS_URL'),
			'host' => env('REDIS_HOST', '127.0.0.1'),
			'password' => env('REDIS_PASSWORD', null),
			'port' => env('REDIS_PORT', '6379'),
			'database' => env('REDIS_DB', '0'),
		],

		'cache' => [
			'url' => env('REDIS_URL'),
			'host' => env('REDIS_HOST', '127.0.0.1'),
			'password' => env('REDIS_PASSWORD', null),
			'port' => env('REDIS_PORT', '6379'),
			'database' => env('REDIS_CACHE_DB', '1'),
		],
	],
];


text:
"""
Copyright (c) 2004-Present Pivotal Software, Inc.

This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import os
import time
import tinctest
from gppylib.commands.base import Command, REMOTE, WorkerPool
from tinctest.main import TINCException
from mpp.lib.config import GPDBConfig

class GpRecoversegException(TINCException): pass

class GpRecoverseg():
    '''Class for gprecoverseg utility methods '''

    def __init__(self):
        self.gphome = os.environ.get('GPHOME')
        self.rc = None
        self.stdout = None
        self.stderr = None

    def run_using_workerpool(self, option=''):
        if not (set(option.split()) <= set(['-F' , '-r', '--persistent-check', ' '])):
            raise GpRecoversegException('Not a valid option with gprecoverseg')

        rcvr_cmd = 'gprecoverseg -a  %s' % option
        cmd = Command(name='Run gprecoverseg', cmdStr='source %s/greenplum_path.sh;%s' % (self.gphome, rcvr_cmd))
        tinctest.logger.info("Running gprecoverseg : %s" % cmd)

        pool = WorkerPool(numWorkers=1, daemonize=True)
        pool.addCommand(cmd)

    def run(self,option=' ', validate=True, results=True):
        '''
        @type option: string
        @param option: gprecoverseg option (-F or -r)
        '''
        if not (set(option.split()) <= set(['-F' , '-r', '--persistent-check', ' '])):
            raise GpRecoversegException('Not a valid option with gprecoverseg')
        rcvr_cmd = 'gprecoverseg -a  %s' % option
        cmd = Command(name='Run gprecoverseg', cmdStr='source %s/greenplum_path.sh;%s' % (self.gphome, rcvr_cmd))
        tinctest.logger.info("Running gprecoverseg : %s" % cmd)
        cmd.run(validateAfter=validate)

        if results:
            result = cmd.get_results()
            self.rc, self.stdout, self.stderr = result.rc, result.stdout, result.stderr
            if result.rc != 0 or result.stderr:
                return False
            return True

    def wait_till_insync_transition(self):
        pass

class GpRecover(GpRecoverseg):
    '''Class for gprecoverseg utility methods '''

    MAX_COUNTER=400

    def __init__(self, config=None):
        if config is not None:
            self.config = config
        else:
            self.config = GPDBConfig()
        self.gphome = os.environ.get('GPHOME')

    def incremental(self, workerPool=False):
        '''Incremental Recoverseg '''
        tinctest.logger.info('Running Incremental gprecoverseg...')
        if workerPool:
            return self.run_using_workerpool()
        else:
            return self.run()

    def full(self):
        '''Full Recoverseg '''
        tinctest.logger.info('Running Full gprecoverseg...')
        return self.run(option = '-F')

    def rebalance(self):
        '''Run gprecoverseg to rebalance the cluster '''
        tinctest.logger.info('Running gprecoverseg rebalance...')
        return self.run(option = '-r')

    def wait_till_insync_transition(self):
        '''
            Poll till all the segments transition to insync state.
            Number of trials set to MAX_COUNTER
        '''
        counter= 1
        while(not self.config.is_not_insync_segments()):
            if counter > self.MAX_COUNTER:
                raise Exception('Segments did not come insync after 20 minutes')
            else:
                counter = counter + 1
                time.sleep(3) #Wait 3 secs before polling again
        tinctest.logger.info('Segments are synchronized ...')
        return True

    def recover_rebalance_segs(self):
        if not self.config.is_balanced_segments():
            # recover
            if not self.incremental():
                raise Exception('Gprecvoerseg failed')
            if not self.wait_till_insync_transition():
                raise Exception('Segments not in sync')
            tinctest.logger.info('Segments recovered and back in sync')

            # rebalance
            if not self.rebalance():
                raise Exception('Gprecvoerseg -r failed')
            if not self.wait_till_insync_transition():
                raise Exception('Segments not in sync')
            tinctest.logger.info('Segments rebalanced and back in sync')


text:
#ifndef BACKTRACE_H
#define BACKTRACE_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
typedef int (*backtrace_callback)(uintptr_t ip, void* args);

enum {
    BACKTRACE_CONTINUE,
    BACKTRACE_ABORT,
};

int mybacktrace(backtrace_callback callback, void* args, void* uc_mcontext);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif /* BACKTRACE_H */


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

<title>UpdateCheckResults</title>
<meta name="date" content="2015-09-02">
<link rel="stylesheet" type="text/css" href="../../../../../dev_javadoc.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.appengine.tools.info

Class UpdateCheckResults

java.lang.Object

com.google.appengine.tools.info.UpdateCheckResults

public class UpdateCheckResults
extends java.lang.Object

Makes information about the local SDK version and the latest remote
 version available.

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
UpdateCheckResults.VersionComparator

VersionComparator compares strings that represent dotted
 version numbers (e.g.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

Version
getLocalVersion()

Returns a Version for the current local SDK.

Version
getRemoteVersion()

Returns a Version for the remote servers.

boolean
isApiVersionSupportedLocally(java.lang.String apiVersion)

Returns true if apiVersion is supported by the local SDK.

boolean
isApiVersionSupportedRemotely(java.lang.String apiVersion)

Returns true if apiVersion is supported on the server.

boolean
isLocalApiVersionNoLongerSupported()

Returns true if the server does not support any of the API
 versions supported by the local SDK.

boolean
isNewerApiVersionAvailable()

Returns true if the server supports a new API version that the
 local SDK does not.

boolean
isNewerReleaseAvailable()

Returns true if there is a newer SDK release available on the
 remote server.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getLocalVersion

public Version getLocalVersion()

Returns a Version for the current local SDK.

getRemoteVersion

public Version getRemoteVersion()

Returns a Version for the remote servers.

isNewerReleaseAvailable

public boolean isNewerReleaseAvailable()

Returns true if there is a newer SDK release available on the
 remote server.

isNewerApiVersionAvailable

public boolean isNewerApiVersionAvailable()

Returns true if the server supports a new API version that the
 local SDK does not.

isLocalApiVersionNoLongerSupported

public boolean isLocalApiVersionNoLongerSupported()

Returns true if the server does not support any of the API
 versions supported by the local SDK.

isApiVersionSupportedRemotely

public boolean isApiVersionSupportedRemotely(java.lang.String apiVersion)

Returns true if apiVersion is supported on the server.

isApiVersionSupportedLocally

public boolean isApiVersionSupportedLocally(java.lang.String apiVersion)

Returns true if apiVersion is supported by the local SDK.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package de.grafelhaft.winespray.app.util;

import java.util.Collection;
import java.util.Locale;

import de.grafelhaft.winespray.model.DataPoint;
import de.grafelhaft.winespray.model.Run;
import de.grafelhaft.winespray.model.SensorData;
import de.grafelhaft.winespray.model.Session;

/**
 * Created by @author Markus Graf.
 */

public class MathUtils {

    public static String format2Decimals(double value) {
        return String.format(Locale.US, "%.2f", value);
    }

    public static String format2Decimals(double value, int decimals) {
        return String.format(Locale.US, "%." + decimals + "f", value);
    }

    public static String formatDecimalToPercent(double value) {
        return Integer.toString((int) (value * 100));
    }

    /**
     * Calculates the recycled volume.
     *
     * @param injectedVolume Volume used for the injection pump system.
     * @param returnedVolume Volume that is returned into the tank.
     * @return
     */
    public static double calcRecycledVolume(double injectedVolume, double returnedVolume) {
        return returnedVolume - injectedVolume;
    }

    /**
     * Calculates the used volume.
     *
     * @param ejectedVolume  Volume that is ejected by the nozzles.
     * @param injectedVolume Volume used for the injection pump system.
     * @param returnedVolume Volume that is returned into the tank.
     * @return
     */
    public static double calcUsedVolume(double ejectedVolume, double injectedVolume, double returnedVolume) {
        return (ejectedVolume - (returnedVolume - injectedVolume));
    }

    /**
     * Calculates the recycle rate.
     *
     * @param ejectedVolume  Volume that is ejected by the nozzles.
     * @param injectedVolume Volume used for the injection pump system.
     * @param returnedVolume Volume that is returned into the tank.
     * @return
     */
    public static double calcRecycleRate(double ejectedVolume, double injectedVolume, double returnedVolume) {
        if (ejectedVolume > 0) {
            return (calcRecycledVolume(injectedVolume, returnedVolume) / ejectedVolume);
        }
        return 0;
    }

    public static double calcLiterPerSquareMeter(double literPerSecond, double speedMeterPerSecond, double workingWidth) {
        if (speedMeterPerSecond > 0 && workingWidth > 0) {
            return (literPerSecond / (speedMeterPerSecond * workingWidth));
        }
        return 0;
    }

    public static double calcLiterPerSquareMeter(double literPerSecond, double speedMeterPerSecond, double workingWidth, int nozzleCount) {
        if (speedMeterPerSecond > 0 && workingWidth > 0) {
            return calcLiterPerSquareMeter(literPerSecond, speedMeterPerSecond, workingWidth * nozzleCount);
        }
        return 0;
    }

    public static double calcLiterPerHectare(double literPerSecond, double speedMeterPerSecond, double workingWidth) {
        double value = calcLiterPerSquareMeter(literPerSecond, speedMeterPerSecond, workingWidth) * 10000; //because 1 hectare == 10.000 meters
        return value > 0 ? value : 0;
    }

    public static double calcLiterPerHectare(double literPerSecond, double speedMeterPerSecond, double workingWidth, int nozzleCount) {
        double value = calcLiterPerSquareMeter(literPerSecond, speedMeterPerSecond, workingWidth, nozzleCount) * 10000; //because 1 hectare == 10.000 meters
        return value > 0 ? value : 0;
    }

    public static double calcLiterPerSecond(double literPerSquareMeter, double speedMeterPerSecond, double workingWidth) {
        return (literPerSquareMeter * speedMeterPerSecond * workingWidth);
    }

    public static double calcSingleNozzleEjection(double fullNozzleEjection, int nozzleCount) {
        return (fullNozzleEjection / nozzleCount);
    }

    public static double calcAverageSpeed(Session session) {
        double value = 0;
        for (Run r : session.getRuns()) {
            value += calcAverageSpeed(r.getDataPoints());
        }
        if (session.getRuns().size() > 0) {
            return value / session.getRuns().size();
        }
        return 0;
    }

    public static double calcAverageSpeed(Run run) {
        return calcAverageSpeed(run.getDataPoints());
    }

    public static double calcAverageSpeed(Collection<DataPoint> dataPoints) {
        double speed = 0.0;
        int i = 0;
        for (DataPoint d : dataPoints) {
            if (d.getLocation() != null) {
                speed += d.getLocation().getSpeed();
                i++;
            }
        }
        if (i > 0) {
            return speed / i;
        }
        return 0;
    }

    public static double calcAverageVolume(Session session, int sensorPurpose) {
        if (session.getRuns().size() > 0) {
            double value = 0;
            for (Run r : session.getRuns()) {
                value += calcAverageVolume(r, sensorPurpose);
            }
            return value / session.getRuns().size();
        }
        return 0;
    }

    public static double calcAverageVolume(Run run, int sensorPurpose) {
        return calcAverageVolume(run.getDataPoints(), sensorPurpose);
    }

    public static double calcAverageVolume(Collection<DataPoint> dataPoints, int sensorPurpose) {
        if (dataPoints.size() > 0) {

            double value = 0;
            int sensorCount = 0;

            for (DataPoint d : dataPoints) {

                for (SensorData sd : d.getData()) {

                    if (sd.getSensor().getPurpose() == sensorPurpose) {
                        sensorCount++;
                        value += sd.getValue();
                    }

                }

            }

            if (sensorCount > 0) {
                return value / sensorCount;
            }
        }
        return 0;
    }

    public static double calcSumVolume(Session session, int sensorPurpose, int interval) {
        double value = 0;
        for (Run r : session.getRuns()) {
            value += calcSumVolume(r, sensorPurpose, interval);
        }
        return value;
    }

    public static double calcSumVolume(Run run, int sensorPurpose, int interval) {
        return calcSumVolume(run.getDataPoints(), sensorPurpose, interval);
    }

    public static double calcSumVolume(Collection<DataPoint> dataPoints, int sensorPurpose, int interval) {
        double value = 0;
        for (DataPoint d : dataPoints) {

            for (SensorData sd : d.getData()) {

                if (sd.getSensor().getPurpose() == sensorPurpose) {
                    value += sd.getValue();
                }

            }

        }
        return value * (interval / 1000); //because milliseconds
    }

    public static double calcSumVolumePerSquareMeter(double areaSize, Session session, int sensorPurpose, int interval) {
        double value = 0;
        for (Run r : session.getRuns()) {
            value += calcSumVolumePerSquareMeter(areaSize, r, sensorPurpose, interval);
        }
        return value;
    }

    public static double calcSumVolumePerSquareMeter(double areaSize, Run run, int sensorPurpose, int interval) {
        return calcSumVolumePerSquareMeter(areaSize, run.getDataPoints(), sensorPurpose, interval);
    }

    public static double calcSumVolumePerSquareMeter(double areaSize, Collection<DataPoint> dataPoints, int sensorPurpose, int interval) {
        double sum = calcSumVolume(dataPoints, sensorPurpose, interval);
        double perSqMeter = 0;
        if (areaSize > 0) {
            perSqMeter = sum / areaSize;
        }
        return perSqMeter;
    }

    public static double calcVolumePerSquareMeter(double areaSize, double volume) {
        return volume / areaSize;
    }

    public static double calcSumPerHectare(double areaSize, Session session, int sensorPurpose, int interval) {
        return calcSumVolumePerSquareMeter(areaSize, session, sensorPurpose, interval) * 10000;
    }

    public static double calcSumPerHectare(double areaSize, Run run, int sensorPurpose, int interval) {
        return calcSumVolumePerSquareMeter(areaSize, run, sensorPurpose, interval) * 10000;
    }

    public static double calcSumPerHectare(double areaSize, Collection<DataPoint> dataPoints, int sensorPurpose, int interval) {
        return calcSumVolumePerSquareMeter(areaSize, dataPoints, sensorPurpose, interval) * 10000;
    }

    public static double calcVolumePerHectare(double areaSize, double volume) {
        return calcVolumePerSquareMeter(areaSize, volume) * 10000;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="1.0dip" android:color="#40ffffff" />
    <solid android:color="#26000000" />
    <corners android:radius="4.0dip" />
    <padding android:left="1.0dip" android:top="1.0dip" android:right="1.0dip" android:bottom="1.0dip" />
</shape>


text:
ifeq ($(OS), Windows_NT)
	EXECLEAN = execlean-windows
	CLEANER = clean-windows
	DLL = .dll
	LDL =
else
	EXECLEAN = execlean-linux
	CLEANER = clean-linux
	DLL = .so
	LDL = -ldl
endif

CC = gcc
CPP = g++
CPPFLAGS = -g -Wall
CFLAGS = -g -Wall -std=c11
DLLFLAGS = -shared -fPIC

SRC = leapfrog use_lib
OUT = out.exe
EXTRA = -I./include
EXE = -D OUT_EXE

.PHONY: ctest cpptest clean-linux clean-windows clean cleanall execlean-linux execlean-windows

.PHONY: pypi_upload pybuild

all:
	$(CC) $(CFLAGS) $(DLLFLAGS) ./csrc/leapfrog.c -o ./lpfgopt/leapfrog_c$(DLL) $(EXTRA)

ctest:
	$(CC) $(CFLAGS) $(foreach var,$(SRC), ./csrc/$(var).c)\
	 -o $(OUT) $(EXTRA) $(EXE)

cpptest: all
	$(CPP) $(CPPFLAGS) ./csrc/use_dll.cpp -o $(OUT) $(LDL)

execlean-linux:
	rm -f *.exe

clean-linux: execlean-linux
	rm -f ./lpfgopt/*.so ./lpfgopt/*.dll
	rm -rf ./build ./dist ./*.egg-info

execlean-windows:
	del *.exe

clean-windows: execlean-windows
	del .\lpfgopt\*.dll
	del .\lpfgopt\*.so
	if exist .\build rmdir /S/Q .\build
	if exist .\dist  rmdir /S/Q .\dist
	if exist .\lpfgopt.egg-info rmdir /S/Q .\lpfgopt.egg-info

cleanall: $(CLEANER)

clean: $(EXECLEAN)

pybuild:
	python setup.py sdist bdist_wheel

pypi_upload: pybuild
	python -m twine upload dist/*


text:
 var _LTracker = _LTracker || [];
    _LTracker.push({
        'logglyKey': 'TOKEN',
        'sendConsoleErrors' : true,
        'tag' : 'click-tracking'
    });

/* global jQuery */
(function ($) {
     $.fn.captureMeOn.engines.loggly = function(logObject) {
        _LTracker.push(logObject);
     }
})(jQuery);


text:
package com.microsoft.bingads.api.test.entities.negative_site.campaign.site.read;

import com.microsoft.bingads.api.test.entities.negative_site.campaign.site.BulkCampaignNegativeSiteTest;
import com.microsoft.bingads.bulk.entities.BulkCampaignNegativeSite;
import com.microsoft.bingads.internal.functionalinterfaces.Function;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

public class BulkCampaignNegativeSiteReadFromRowValuesWebsiteTest extends BulkCampaignNegativeSiteTest {

    @Parameter(value = 1)
    public String expectedResult;

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
            {"Test text", "Test text"},
            {"", ""},
            {null, null}
        });
    }

    @Test
    public void testRead() {
        this.<String>testReadProperty("Website", this.datum, this.expectedResult, new Function<BulkCampaignNegativeSite, String>() {
            @Override
            public String apply(BulkCampaignNegativeSite c) {
                return c.getWebsite();
            }
        });
    }
}


text:
/*@import url("../widgets/summary/style.css");
@import url("../widgets/map/style.css");
@import url("../widgets/chat/style.css");*/
/*@import url("../widgets/media/style.css");*/
@import url("../widgets/platform/css/ngDialog.css");
@import url("../widgets/platform/css/ngDialog-theme-default.css");
@import url("../widgets/platform/css/ngDialog-theme-plain.css");
@import url("../widgets/platform/css/bootstrap.min.css");
/*@import url("../widgets/platform/css/Kamato/style.css");*/
/*=======super dimin*/
@import url("../widgets/platform/css/animate.min.css");
@import url("../widgets/platform/css/font-awesome.min.css");
@import url("../widgets/platform/css/form.css");
@import url("../widgets/platform/css/calendar.css");
@import url("../widgets/platform/css/icons.css");
@import url("../widgets/platform/css/generics.css");
@import url("../widgets/platform/css/style.css");
@import url("../widgets/platform/css/Kamato/style.css");
/*=======super dimin*/
/*@import url("../widgets/artmatch/style.css");*/

/*html, body {
  height: 100%;
  margin: 0;
  padding: 0;
  background: #333;
}*/
/*
div.ng-scope {

	width: 100%;
	height: 100%;
	display: block;

}*/
/*
div[ng-view] {
	width: 100%;
	height: 100%;
}

.hide {
	display: none;
}*/


text:
CREATE EXTENSION IF NOT EXISTS "ltree";

-- Rename parent_id column
ALTER TABLE iterations RENAME parent_id to path;

-- Need to convert the path column to text in order to
-- replace non-locale characters with an underscore
ALTER TABLE iterations ALTER path TYPE text USING path::text;

-- Need to update values of Iteration's' ParentID in order to migrate it to ltree
-- Replace every non-C-LOCALE character with an underscore
UPDATE iterations SET path = regexp_replace(path, '[^a-zA-Z0-9_\.]', '_', 'g');

-- Finally values in path are now in good shape for ltree and can be casted automatically to type ltree
-- Convert the parent column from type uuid to ltree
ALTER TABLE iterations ALTER path TYPE ltree USING path::ltree;

-- Enable full text search operaions using GIST index on path
CREATE INDEX iteration_path_gist_idx ON iterations USING GIST (path);


text:
package com.opengamma.engine.depgraph.ambiguity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.util.ArgumentChecker;

/**
 * Service for checking whether, and how, any given value requirement may be ambiguous.
 */
public final class FullRequirementResolution {

  private final ValueRequirement _requirement;
  private final List<Collection<RequirementResolution>> _resolutions = new ArrayList<>();
  private int _hashCode;

  public FullRequirementResolution(final ValueRequirement requirement) {
    _requirement = ArgumentChecker.notNull(requirement, "requirement");
    _hashCode = getClass().hashCode() * 31 + _requirement.hashCode();
  }

  /**
   * Returns the requirement this resolution result describes.
   *
   * @return the requirement, not null
   */
  public ValueRequirement getRequirement() {
    return _requirement;
  }

  /**
   * Returns all of the possible resolutions in descending priority order.
   * <p>
   * Each entry in the list will, under non-ambiguous circumstances, be a singleton collection. When an ambiguity exists elements will be sets containing all of
   * the possible resolutions with null included if non-resolution is a possible outcome.
   *
   * @return the resolutions, not null
   */
  public List<Collection<RequirementResolution>> getResolutions() {
    return Collections.unmodifiableList(_resolutions);
  }

  // Note: there is not a addResolution method to avoid confusion. It would add a singleton set; repeated calls to it would not be
  // the same as making a single call to addResolutions which is the
  // more typical behavior when there appear to be bulk and single operation

  /**
   * Stores a resolution result set into the overall result. If this is a non-ambiguous result, the collection must contain only a single value. If this is an
   * ambiguous result, the collection may contain all possible values and null if one of the outcomes was non-resolution.
   *
   * @param resolutions
   *          the possible resolutions for this value requirement, not null, and non-empty
   * @throws IllegalArgumentException
   *           if the parameters are invalid or attempt to create a recursive structure
   */
  public void addResolutions(Collection<RequirementResolution> resolutions) {
    resolutions = Collections.unmodifiableSet(new HashSet<>(resolutions));
    final int size = resolutions.size();
    if (size == 0) {
      // Empty is not allowed
      throw new IllegalArgumentException("resolutions");
    } else if (size == 1) {
      if (resolutions.contains(null)) {
        // Nulls are only allowed when there is an ambiguity
        throw new IllegalArgumentException("resolutions");
      }
      resolutions = Collections.singleton(resolutions.iterator().next());
    }
    for (final RequirementResolution resolution : resolutions) {
      if (resolution != null && resolution.contains(this)) {
        throw new IllegalArgumentException("Circular reference from " + resolution + " to " + this);
      }
    }
    _resolutions.add(resolutions);
    _hashCode = _hashCode * 31 + resolutions.hashCode();
  }

  /**
   * Tests whether the given resolution is present in any of the inputs to this resolution. This prevents recursive structures from being constructed.
   *
   * @param parent
   *          the parent
   * @return true if the resolution is present in any inputs
   */
  /* package */boolean contains(final FullRequirementResolution parent) {
    for (final Collection<RequirementResolution> resolutions : _resolutions) {
      for (final RequirementResolution resolution : resolutions) {
        if (resolution != null && resolution.contains(parent)) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Tests if there is any ambiguity in this resolution. This only applies to the exact value requirement; there may be ambiguities in resolving items deeper in
   * the graph but which have no effect on this requirement.
   *
   * @return true if there is an ambiguity, false otherwise
   */
  public boolean isAmbiguous() {
    for (final Collection<RequirementResolution> resolutions : _resolutions) {
      if (resolutions.size() > 1) {
        return true;
      }
    }
    return false;
  }

  /**
   * Tests if there is any ambiguity in this resolution or any of its inputs.
   *
   * @return true if there is an ambiguity, false otherwise
   */
  public boolean isDeeplyAmbiguous() {
    for (final Collection<RequirementResolution> resolutions : _resolutions) {
      if (resolutions.size() > 1) {
        return true;
      }
      if (resolutions.iterator().next().isAmbiguous()) {
        return true;
      }
    }
    return false;
  }

  /**
   * Tests if there is a successful resolution of this requirement.
   *
   * @return true if there is a resolution, false otherwise
   */
  public boolean isResolved() {
    return !_resolutions.isEmpty();
  }

  // Object

  @Override
  public boolean equals(final Object o) {
    if (o == this) {
      return true;
    }
    if (!(o instanceof FullRequirementResolution)) {
      return false;
    }
    final FullRequirementResolution other = (FullRequirementResolution) o;
    return _hashCode == other._hashCode && _requirement.equals(other._requirement) && _resolutions.equals(other._resolutions);
  }

  @Override
  public int hashCode() {
    return _hashCode;
  }

  @Override
  public String toString() {
    return _requirement + "->" + _resolutions;
  }

}


text:
<?php

namespace Bludata\Doctrine\ORM\Repositories;

use Bludata\Doctrine\Common\Contracts\EntityContract;
use Bludata\Doctrine\Common\Contracts\QueryWorkerContract;
use Bludata\Doctrine\Common\Contracts\RepositoryContract;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping\ClassMetadata;

abstract class BaseRepository extends EntityRepository implements RepositoryContract
{
    public function getEntityManager(): EntityManager
    {
        return parent::getEntityManager();
    }

    public function getClassMetadata(): ClassMetadata
    {
        return parent::getClassMetadata();
    }

    public function createQueryWorker(): QueryWorkerContract
    {
        return new QueryWorker($this);
    }

    public function findAll(): QueryWorkerContract
    {
        return $this->createQueryWorker();
    }

    public function findOneBy(array $criteria, bool $abort = true): ?EntityContract
    {
        $findAll = $this->findAll();

        foreach ($criteria as $key => $value) {
            $findAll->andWhere($key, '=', $value);
        }

        $entity = $findAll->getOneResult();

        if ($entity instanceof EntityContract) {
            return $entity;
        }

        if (!$entity && $abort) {
            abort(404, 'Registro não encontrado');
        }

        return null;
    }

    public function find($id, bool $abort = true): ?EntityContract
    {
        return $this->findOneBy(['id' => $id], $abort);
    }

    public function findAllRemoved(): QueryWorkerContract
    {
        disableSoftDeleteableFilter();

        return $this->findAll()
                    ->andWhere('deletedAt', 'isnotnull');
    }

    public function findRemoved($id, bool $abort = true): ?EntityContract
    {
        $entity = $this->findAllRemoved()
                        ->andWhere('id', '=', $id)
                        ->getOneResult();

        enableSoftDeleteableFilter();

        if ($entity) {
            return $entity;
        }

        abort(404, 'Registro não encontrado');
    }

    public function createEntity(): EntityContract
    {
        $entityName = $this->getEntityName();

        return new $entityName();
    }

    public function remove(EntityContract $entity): EntityContract
    {
        $this->getEntityManager()
                ->remove($entity);

        return $entity;
    }
}


text:
extern "Java"
{
  namespace javax
  {
    namespace imageio
    {
        class ImageIO$ReaderFormatFilter;
    }
  }
}

class javax::imageio::ImageIO$ReaderFormatFilter : public ::java::lang::Object
{

public:
  ImageIO$ReaderFormatFilter(::java::lang::String *);
  jboolean filter(::java::lang::Object *);
private:
  ::java::lang::String * __attribute__((aligned(__alignof__( ::java::lang::Object)))) formatName;
public:
  static ::java::lang::Class class$;
};

#endif // __javax_imageio_ImageIO$ReaderFormatFilter__


text:
package org.apache.camel.model;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.apache.camel.Expression;
import org.apache.camel.Processor;
import org.apache.camel.builder.ExpressionBuilder;
import org.apache.camel.model.language.ExpressionDefinition;
import org.apache.camel.processor.Delayer;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.RouteContext;

/**
 * Delays processing for a specified length of time
 *
 * @version
 */
@Metadata(label = "eip,routing")
@XmlRootElement(name = "delay")
@XmlAccessorType(XmlAccessType.FIELD)
public class DelayDefinition extends ExpressionNode implements ExecutorServiceAwareDefinition<DelayDefinition> {

    // TODO: Camel 3.0 Should extend NoOutputExpressionNode

    @XmlTransient
    private ExecutorService executorService;
    @XmlAttribute
    private String executorServiceRef;
    @XmlAttribute @Metadata(defaultValue = "false")
    private Boolean asyncDelayed;
    @XmlAttribute @Metadata(defaultValue = "true")
    private Boolean callerRunsWhenRejected;

    public DelayDefinition() {
    }

    public DelayDefinition(Expression delay) {
        super(delay);
    }

    @Override
    public String getLabel() {
        return "delay[" + getExpression() + "]";
    }

    @Override
    public String toString() {
        return "Delay[" + getExpression() + " -> " + getOutputs() + "]";
    }

    @Override
    public Processor createProcessor(RouteContext routeContext) throws Exception {
        Processor childProcessor = this.createChildProcessor(routeContext, false);
        Expression delay = createAbsoluteTimeDelayExpression(routeContext);

        boolean async = getAsyncDelayed() != null && getAsyncDelayed();
        boolean shutdownThreadPool = ProcessorDefinitionHelper.willCreateNewThreadPool(routeContext, this, async);
        ScheduledExecutorService threadPool = ProcessorDefinitionHelper.getConfiguredScheduledExecutorService(routeContext, "Delay", this, async);

        Delayer answer = new Delayer(routeContext.getCamelContext(), childProcessor, delay, threadPool, shutdownThreadPool);
        if (getAsyncDelayed() != null) {
            answer.setAsyncDelayed(getAsyncDelayed());
        }
        if (getCallerRunsWhenRejected() == null) {
            // should be default true
            answer.setCallerRunsWhenRejected(true);
        } else {
            answer.setCallerRunsWhenRejected(getCallerRunsWhenRejected());
        }
        return answer;
    }

    private Expression createAbsoluteTimeDelayExpression(RouteContext routeContext) {
        ExpressionDefinition expr = getExpression();
        if (expr != null) {
            return expr.createExpression(routeContext);
        }
        return null;
    }

    // Fluent API
    // -------------------------------------------------------------------------

    /**
     * Sets the delay time in millis to delay
     *
     * @param delay delay time in millis
     * @return the builder
     */
    public DelayDefinition delayTime(Long delay) {
        setExpression(ExpressionNodeHelper.toExpressionDefinition(ExpressionBuilder.constantExpression(delay)));
        return this;
    }

    /**
     * Whether or not the caller should run the task when it was rejected by the thread pool.
     *

     * Is by default <tt>true</tt>
     *
     * @param callerRunsWhenRejected whether or not the caller should run
     * @return the builder
     */
    public DelayDefinition callerRunsWhenRejected(boolean callerRunsWhenRejected) {
        setCallerRunsWhenRejected(callerRunsWhenRejected);
        return this;
    }

    /**
     * Enables asynchronous delay which means the thread will noy block while delaying.
     */
    public DelayDefinition asyncDelayed() {
        setAsyncDelayed(true);
        return this;
    }

    /**
     * To use a custom Thread Pool if asyncDelay has been enabled.
     */
    public DelayDefinition executorService(ExecutorService executorService) {
        setExecutorService(executorService);
        return this;
    }

    /**
     * Refers to a custom Thread Pool if asyncDelay has been enabled.
     */
    public DelayDefinition executorServiceRef(String executorServiceRef) {
        setExecutorServiceRef(executorServiceRef);
        return this;
    }

    // Properties
    // -------------------------------------------------------------------------

    /**
     * Expression to define how long time to wait (in millis)
     */
    @Override
    public void setExpression(ExpressionDefinition expression) {
        // override to include javadoc what the expression is used for
        super.setExpression(expression);
    }

    public Boolean getAsyncDelayed() {
        return asyncDelayed;
    }

    public void setAsyncDelayed(Boolean asyncDelayed) {
        this.asyncDelayed = asyncDelayed;
    }

    public Boolean getCallerRunsWhenRejected() {
        return callerRunsWhenRejected;
    }

    public void setCallerRunsWhenRejected(Boolean callerRunsWhenRejected) {
        this.callerRunsWhenRejected = callerRunsWhenRejected;
    }

    public ExecutorService getExecutorService() {
        return executorService;
    }

    public void setExecutorService(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public String getExecutorServiceRef() {
        return executorServiceRef;
    }

    public void setExecutorServiceRef(String executorServiceRef) {
        this.executorServiceRef = executorServiceRef;
    }
}


text:
package bench

import java.util.Date

case class OK()
case class Ready()
case class Go(doUntil: Date)
case class TearDown()
case class TearDownOnOnlyOneActor()

case class Result(ok: Boolean)
case class Stat(endAt: Long,  elapsedMillis: Long, operation: String, ok: Boolean) {
  override def toString: String = {
    s"$endAt,$elapsedMillis,$operation,$ok"
  }
}


text:
/* eslint-disable fp/no-nil */
import { INCREMENT, DECREMENT } from './actions'

export default (state = { count: 0 }, action) => {
  switch (action.type) {
    case INCREMENT: return { count: state.count + 1 }
    case DECREMENT: return { count: state.count - 1 }
    default: return state
  }
}


text:
insert into Movie (id, title, filePath) values (1, 'testMovie1', 'testMovie1.avi');
insert into Episode (id, title, filePath, season, episode) values (2, 'testEpisode1', 'testEpisode1.avi', 1, 1);
insert into Series (id, title, filePath, imdbId) values (3, 'testSeries1', 'testPath', 'testSeriesID');


text:
<?php

use Titon\Cache\Storage\FileSystemStorage;
use Titon\Common\Config;
use Titon\Debug\Debugger;
use Titon\Mvc\Application;

/**
 * --------------------------------------------------------------
 *  Development
 * --------------------------------------------------------------
 *
 * Configuration pertaining to development environments should
 * be defined here. It will be bootstrapped automatically.
 */

$app = Application::getInstance();

/**
 * Update caching to use the file system.
 */
$app->get('cache')->addStorage('default', new FileSystemStorage([
    'directory' => TEMP_DIR . 'cache/'
]));

/**
 * Enable error reporting.
 */
Debugger::enable(true);

/**
 * Define database login credentials.
 */
Config::set('db.default', [
    'host' => 'localhost',
    'port' => 3306,
    'user' => 'root',
    'pass' => '',
    'database' => '',
    'encoding' => 'utf8'
]);


text:
package test;

import org.jetbrains.annotations.NotNull;
import test.kotlin.*;

public class TopLevelFunctionWithNameSimilarToClassInDataFlowInspection {
    void other(@NotNull Object some) {
        Object foo = TopLevelFunctionWithNameSimilarToClassInDataFlowInspectionKt.foo(some);
    }
}


text:
<?php require_once '..\BD\eventoBD.php'; ?>

<?php
$idact = $_GET['id'];
EliminarEvento($idact);
header('Location: ../Admin/adminPetGestor.php');

?>


text:
package org.elasticsearch.script.mustache;

import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestActions;
import org.elasticsearch.rest.action.RestToXContentListener;
import org.elasticsearch.script.ScriptService;

import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;

public class RestRenderSearchTemplateAction extends BaseRestHandler {

    @Inject
    public RestRenderSearchTemplateAction(Settings settings, RestController controller) {
        super(settings);
        controller.registerHandler(GET, "/_render/template", this);
        controller.registerHandler(POST, "/_render/template", this);
        controller.registerHandler(GET, "/_render/template/{id}", this);
        controller.registerHandler(POST, "/_render/template/{id}", this);
    }

    @Override
    public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception {
        // Creates the render template request
        SearchTemplateRequest renderRequest = RestSearchTemplateAction.parse(RestActions.getRestContent(request));
        renderRequest.setSimulate(true);

        String id = request.param("id");
        if (id != null) {
            renderRequest.setScriptType(ScriptService.ScriptType.STORED);
            renderRequest.setScript(id);
        }

        client.execute(SearchTemplateAction.INSTANCE, renderRequest, new RestToXContentListener<>(channel));
    }
}


text:
/* Sheet Version */
.charsheet .sheet-version::after {
	content: 'Sheet Version 2.00';
}

/* ----------------------- */
/*          new css        */
/* ----------------------- */

/* --------- General Styling ------- */

span{
	padding:2px 4px 2px 4px;
}

*{ /* Defines a CSS variable */

	--gray: #d9d9d9;
}
.charsheet {
	background-color: white;
}

textarea{
	width: 98%;
	height: 110px;
}

div.sheet-main{
	width: 750px;
	padding: 15px;
}

div.sheet-section{
	display: flex;
	flex-direction: column;
	margin: 0em 0em 1em 0em;
	border: 2px solid var(--gray);
}

div.sheet-title,
div.sheet-sub-title{
	background-color: var(--gray);
	text-align: center;
	width: 100%;
}
div.sheet-title span,
div.sheet-sub-title span,
span.sheet-sub-title{
	font-weight: 600;
}

/* ----  Section specific ------ */

/*   Header  */
div.sheet-header{
	flex-flow: row wrap;
	align-items: center;
	background-image: url(https://parahumans.files.wordpress.com/2011/06/cityscape2.jpg);
	background-size: 750px 110px;
	background-repeat: no-repeat;
	text-shadow:-2px 0 #000000,0 2px #000000,2px 0 #000000,0 -2px #000000;
	color: white;
}

div.sheet-header span.sheet-title{
	font-size: 300%;
	width: 250px;
}

div.sheet-header span.sheet-version{
	font-size: small;
}

div.sheet-header{
	display: flex;
	justify-content: center;
}

div.sheet-header input{
	width: 350px;
	font-size: 28px;
	margin-bottom: 20px;
}

/*   Main info  */
div.sheet-main-info{
	display: flex;
	flex-flow: row wrap;
}

div.sheet-main-info div{
	display: flex;
	flex-flow: row nowrap;
	width: 50%;
}

div.sheet-main-info span{
	background-color: var(--gray);
	font-weight: 600;
	width: 100px;
}

div.sheet-main-info input{
	width: 255px;
	margin: 0px 0px 4px 2px;
	padding-bottom: 1px;
	border-style: none none solid none;
	border-width: 1px;
	border-color: black;
	border-radius: 0px;
}

/*  WOUNDS */
div.sheet-wounds{
	display:grid;
	grid-template-columns: 5.5em repeat(8, 1fr);
	grid-template-rows: 0.5fr repeat(3, 1fr);
	height: 125px;
}

div.sheet-wounds div.sheet-title{
	grid-column: span 9;
	grid-row: 1;
	display: flex;
	align-items: center;
	justify-content: center;
}
div.sheet-wounds div.sheet-title span{
	padding: 1px;
}

div.sheet-wounds input[type="text"]{
	width: 80px;
	margin-left: 2px;
}

div.sheet-wounds div{
	border: 1px solid var(--gray);
}

/* Stats & Gear */

div.sheet-stats-inventory{
	display: flex;
}

/* Stats */
div.sheet-stats{
	display: grid;
	grid-auto-flow: column;
	grid-template-rows: 0.2fr 1fr 1fr 1fr 1fr;
	grid-template-columns: 1fr 1fr 1fr 1fr;
	grid-auto-flow: column;
	height:520px;
	width: 46%;
}

div.sheet-stats div{
	border: 1px solid var(--gray);
}

div.sheet-stats div.sheet-title{
	grid-column: span 4;
	grid-row: 1;
	display: flex;
	justify-content: center;
}
div.sheet-stats div:not(.sheet-title){
	display: flex;
	flex-flow: column;
	justify-content: center;
}

div.sheet-stats div.sheet-img-size{
	background-size: 75px 75px;
	background-repeat: no-repeat;
	align-items: center;
	justify-content: flex-end;
}

div.sheet-stats div.sheet-img-size span{
	font-weight: 600;
}

div.sheet-stats div.sheet-info span{
	display: flex;
	flex-flow: column;
	align-items: center;
}

div.sheet-stats div.sheet-brawn-img{
	background-image: url(https://raw.githubusercontent.com/Roll20/roll20-character-sheets/master/Weaverdice/images/brawn.png);
}
div.sheet-stats div.sheet-athletics-img{
	background-image: url(https://raw.githubusercontent.com/Roll20/roll20-character-sheets/master/Weaverdice/images/athletics.png);
}
div.sheet-stats div.sheet-dexterity-img{
	background-image: url(https://raw.githubusercontent.com/Roll20/roll20-character-sheets/master/Weaverdice/images/dexterity.png);
}
div.sheet-stats div.sheet-wits-img{
	background-image: url(https://raw.githubusercontent.com/Roll20/roll20-character-sheets/master/Weaverdice/images/wits.png);
}
div.sheet-stats div.sheet-social-img{
	background-image: url(https://raw.githubusercontent.com/Roll20/roll20-character-sheets/master/Weaverdice/images/social.png);
}
div.sheet-stats div.sheet-knowledge-img{
	background-image: url(https://raw.githubusercontent.com/Roll20/roll20-character-sheets/master/Weaverdice/images/knowledge.png);
}
div.sheet-stats div.sheet-guts-img{
	background-image: url(https://raw.githubusercontent.com/Roll20/roll20-character-sheets/master/Weaverdice/images/guts.png);
}

/* Inventory */
div.sheet-inventory{
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 53%;
	margin-left: 1em;
}

div.sheet-inventory div.sheet-title{
	display: flex;
	flex-flow: row nowrap;
	justify-content: space-between;
	width: 100%;
}

div.sheet-inventory span{
	text-align: center;
}
div.sheet-inventory input[name="attr_gearname"]{
	width: 120px;
}
div.sheet-inventory input[name="attr_gearnotes"]{
	width: 225px;
}
div.sheet-inventory input[type="number"]{
	width: 32px;
}

/* Skills */
div.sheet-skill{
	display: flex;
	flex-flow: row nowrap;
}
div.sheet-skill .sheet-name{
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: flex-start;
	width: 115px;
}
div.sheet-skill .sheet-name input[type="text"]{
	width: 110px;
	margin-top: 5px;
}
div.sheet-skill .sheet-info{
	display: flex;
	flex-direction: column;
	width: 600px;
}

div.sheet-skill .sheet-dice-row{
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	padding: 4px 5px 4px 5px;
}
div.sheet-skill select.sheet-dice{
	width: 40px;
	margin-bottom: 0px;
}
div.sheet-skill select.sheet-stat{
	width: 90px;
	margin-bottom: 0px;
}
div.sheet-skill .sheet-dice-row input[type="text"]{
	width: 90px;
}
div.sheet-skill textarea{
	width: 102%;
	margin-left: 3px;
}

/* territory, allies  */
p {
	margin-bottom: 0px;
}
table{
	border-collapse: collapse;
	margin-right: auto;
	margin-bottom: 1em;
}
table  .sheet-section {
	width: 345px;
}
table  .sheet-name {
	width: 88pt;
}
table .sheet-notes {
	width: 196pt;
}
table .sheet-gray-border {
	border-right-style: solid;
	padding: 2pt;
	vertical-align: top;
	border: 1pt solid #d9d9d9;
}
table .sheet-bg-gray {
	background-color: #d9d9d9;
}
table .sheet-graysides {
	padding: 2pt;
	vertical-align: top;
	border-width: 1pt;
	border-color: white var(--gray);
	border-style: solid;
}
p.sheet-gap {
	height: 4pt;
	width: 1em;
}
table .sheet-center{
	display: flex;
	justify-content: center;
}

/*   Appearance  */
div.sheet-appearance{
	display: flex;
	flex-direction: row;
}

div.sheet-appearance div.sheet-section{
	display: flex;
	flex-direction: column;
	width: 49%;
}
div.sheet-appearance div.sheet-section:last-child{
	margin-left: 1em;
}

div.sheet-appearance span{
	background-color: var(--gray);
	text-align: center;
	font-weight: 600;
}

div.sheet-appearance textarea{
	width: 97%;
}

/* footer */
p.sheet-footer{
	text-align: center;
	font-size:10px;
}

/* ------------------ Old CSS ------------------- */

/* changes die button icon to d6*/
.charsheet button[type=roll].sheet-d6-dice::before {
	font-family: 'dicefontd6',arial;
	content: 'F ';
	color: red;
}

/* Change wounds tracker into hearts */

/* 1 - Hide actual radio */
.charsheet input[type="radio"]{
	opacity: 0;
	width: 20px;
	height: 20px;
	position: relative;
	left: 45px;
	margin: -10px;
	cursor: pointer;
	z-index: 1;
}

/* 2 - Fake radio */
.charsheet input[type="radio"] + span::before{
	margin-left: 30px;
	border: solid 1px #a8a8a8;
	line-height: 14px;
	text-align: center;
	display: inline-block;
	vertical-align: middle;

	-moz-box-shadow: 0 0 2px #ccc;
	-webkit-box-shadow: 0 0 2px #ccc;
	box-shadow: 0 0 2px #ccc;

	background: #f6f6f6;
	background: -moz-radial-gradient(#f6f6f6, #dfdfdf);
	background: -webkit-radial-gradient(#f6f6f6, #dfdfdf);
	background: -ms-radial-gradient(#f6f6f6, #dfdfdf);
	background: -o-radial-gradient(#f6f6f6, #dfdfdf);
	background: radial-gradient(#f6f6f6, #dfdfdf);

	content: '❤';
	color: red;
	width: 12px;
	height: 12px;
	font-size: 35px;

	-moz-border-radius: 50%;
	-webkit-border-radius: 50%;
	border-radius: 50%;
}

/* Remove dot from all radios _after_ selected one */
.charsheet input[type="radio"]:checked ~ input[type="radio"] + span::before {
	content: "";
}

/*-------------------------------------------*/
/*------------- Roll Templates---------------*/

/* ----------- BLUE -----------*/
.sheet-rolltemplate-blue table {
 width:100%;
 background-color:white;
 border:1px solid rgba(51, 51, 255,1)
}
.sheet-rolltemplate-blue caption {
 background-color:rgba(51, 51, 255,1);
 color:white;
 font-family:"Helvetica Neue",Helvetica,sans-serif;
 font-weight:300;
 font-size:1.1em;
 padding:5px
}
.sheet-rolltemplate-blue td {
 padding:5px;
 line-height:1.4em;
 vertical-align:top
}
.sheet-rolltemplate-blue td:first-child {
 font-weight:bold;
 text-align:right;
 min-width:50px;
 padding-right:10px
}
.sheet-rolltemplate-blue tr:nth-child(even) {
 background-color:#eee
}
/* ----------- GREEN -----------*/
.sheet-rolltemplate-green table {
 width:100%;
 background-color:white;
 border:1px solid rgba(0, 153, 51,1)
}
.sheet-rolltemplate-green caption {
 background-color:rgba(0, 153, 51,1);
 color:white;
 font-family:"Helvetica Neue",Helvetica,sans-serif;
 font-weight:300;
 font-size:1.1em;
 padding:5px
}
.sheet-rolltemplate-green td {
 padding:5px;
 line-height:1.4em;
 vertical-align:top
}
.sheet-rolltemplate-green td:first-child {
 font-weight:bold;
 text-align:right;
 min-width:50px;
 padding-right:10px
}
.sheet-rolltemplate-green tr:nth-child(even) {
 background-color:#eee
}
/* ----------- RED -----------*/
.sheet-rolltemplate-red table {
 width:100%;
 background-color:white;
 border:1px solid rgba(204, 0, 0,1)
}
.sheet-rolltemplate-red caption {
 background-color:rgba(204, 0, 0,1);
 color:white;
 font-family:"Helvetica Neue",Helvetica,sans-serif;
 font-weight:300;
 font-size:1.1em;
 padding:5px
}
.sheet-rolltemplate-red td {
 padding:5px;
 line-height:1.4em;
 vertical-align:top
}
.sheet-rolltemplate-red td:first-child {
 font-weight:bold;
 text-align:right;
 min-width:50px;
 padding-right:10px
}
.sheet-rolltemplate-red tr:nth-child(even) {
 background-color:#eee
}
/* ----------- BLACK -----------*/
.sheet-rolltemplate-black table {
 width:100%;
 background-color:white;
 border:1px solid rgba(0, 0, 0,1)
}
.sheet-rolltemplate-black caption {
 background-color:rgba(0, 0, 0,1);
 color:white;
 font-family:"Helvetica Neue",Helvetica,sans-serif;
 font-weight:300;
 font-size:1.1em;
 padding:5px
}
.sheet-rolltemplate-black td {
 padding:5px;
 line-height:1.4em;
 vertical-align:top
}
.sheet-rolltemplate-black td:first-child {
 font-weight:bold;
 text-align:right;
 min-width:50px;
 padding-right:10px
}
.sheet-rolltemplate-black tr:nth-child(even) {
 background-color:#eee
}


text:
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.packages;

import com.google.devtools.build.lib.cmdline.BazelModuleContext;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import java.util.HashMap;
import java.util.Map;
import net.starlark.java.eval.Module;
import net.starlark.java.eval.StarlarkThread;

/**
 * Converts a label literal string into a {@link Label} object, using the appropriate base package
 * and repo mapping.
 */
public class LabelConverter {

  /**
   * Returns a label converter for the given thread, which MUST be evaluating a .bzl file. It uses
   * the package containing the .bzl file as the base package, and the repo mapping of the repo
   * containing the .bzl file.
   */
  public static LabelConverter forBzlEvaluatingThread(StarlarkThread thread) {
    BazelModuleContext moduleContext =
        BazelModuleContext.of(Module.ofInnermostEnclosingStarlarkFunction(thread));
    return new LabelConverter(moduleContext.packageContext());
  }

  private final Label.PackageContext packageContext;
  private final Map<String, Label> labelCache = new HashMap<>();

  public LabelConverter(Label.PackageContext packageContext) {
    this.packageContext = packageContext;
  }

  /** Creates a label converter using the given base package and repo mapping. */
  public LabelConverter(PackageIdentifier base, RepositoryMapping repositoryMapping) {
    this(Label.PackageContext.of(base, repositoryMapping));
  }

  /** Returns the base package identifier that relative labels will be resolved against. */
  PackageIdentifier getBasePackage() {
    return packageContext.packageIdentifier();
  }

  /** Returns the Label corresponding to the input, using the current conversion context. */
  public Label convert(String input) throws LabelSyntaxException {
    // Optimization: First check the package-local map, avoiding Label validation, Label
    // construction, and global Interner lookup. This approach tends to be very profitable
    // overall, since it's common for the targets in a single package to have duplicate
    // label-strings across all their attribute values.
    Label converted = labelCache.get(input);
    if (converted == null) {
      converted = Label.parseWithPackageContext(input, packageContext);
      labelCache.put(input, converted);
    }
    return converted;
  }

  @Override
  public String toString() {
    return getBasePackage().toString();
  }
}


text:
<?php

namespace Jnaxo\CountryCodes;

use Illuminate\Database\Eloquent\Model;
use Jnaxo\CountryCodes\AdministrativeArea;

class AdministrativeDivision extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'ctrystore_administrative_divisions';

    /* Relationships */

    public function administrativeAreas()
    {
        return $this->hasMany(AdministrativeArea::class);
    }
}


text:
echo "==============================================="
echo "exec postinstall.sh"
echo "==============================================="

sudo apt-get -y update
sudo apt-get -y upgrade
sudo apt-get -y install linux-headers-$(uname -r) build-essential
sudo apt-get -y install zlib1g-dev libssl-dev libreadline-gplv2-dev libyaml-dev wget curl
sudo apt-get clean

# Installing vagrant keys
mkdir -pm 700 /home/vagrant/.ssh
wget --no-check-certificate 'https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub' -O /home/vagrant/.ssh/authorized_keys
chmod 0600 /home/vagrant/.ssh/authorized_keys
chown -R vagrant /home/vagrant/.ssh

# Installing the virtualbox guest additions
sudo apt-get -y install dkms
sudo mount -o loop /home/vagrant/VBoxGuestAdditions.iso /mnt
sudo sh /mnt/VBoxLinuxAdditions.run
sudo umount /mnt
sudo /etc/init.d/vboxadd setup

#sudo rm /home/vagrant/VBoxGuestAdditions*.iso

sudo sed -i -e 's/%sudo\tALL=(ALL:ALL) ALL/%sudo\tALL=(ALL:ALL) NOPASSWD:ALL/' /etc/sudoers

curl -L https://www.opscode.com/chef/install.sh | sudo bash


text:
"""A collection of utility functions."""

import json
from os import path

import click
from docker.client import Client
from docker.utils import kwargs_from_env

_LOG_LEVEL = 0
LOG_PREFIXES = {
    0: click.style('>', fg='white', bold=True),
    1: click.style('>>', fg='cyan', bold=True),
    2: click.style('>>>', fg='blue', bold=True),
}
_DOCKER_CLIENT = None

def set_log_level(log_level):
    """Set the log level to use.

    Log levels are provided as an integer, and the following levels are available:
    0: The default log level
    1: Info level logging
    2: Debug level logging
    """
    if log_level not in [0, 1, 2]:
        return False

    global _LOG_LEVEL  # pylint: disable = global-statement
    _LOG_LEVEL = log_level
    return True

def get_log_level():
    """Get the current log level."""
    return _LOG_LEVEL

def _print(message, log_level, prefix, **kwargs):
    """Print a message to the console, depending on log level."""
    if log_level <= get_log_level():
        if prefix:
            click.secho('{} '.format(LOG_PREFIXES[log_level]), nl=False)

        return click.secho(message, **kwargs)

def log(message, prefix=True, **kwargs):
    """Print a default level log message."""
    return _print(message, log_level=0, prefix=prefix, **kwargs)

def info(message, prefix=True, **kwargs):
    """Print an info level log message."""
    return _print(message, log_level=1, prefix=prefix, **kwargs)

def debug(message, prefix=True, **kwargs):
    """Print a debug level log message."""
    return _print(message, log_level=2, prefix=prefix, **kwargs)

def docker_client():
    """Create a Docker client instance or return an existing one."""
    global _DOCKER_CLIENT  # pylint: disable = global-statement

    if _DOCKER_CLIENT:
        return _DOCKER_CLIENT
    else:
        # assert_hostname=False is required when using boot2docker, it's taken as a hint from Fig: https://github.com/docker/fig/blob/master/compose/cli/docker_client.py#L29
        _DOCKER_CLIENT = Client(**kwargs_from_env(assert_hostname=False))
        return _DOCKER_CLIENT

def pull_image(wanted_image):
    """Download Docker image if it isn't already local."""
    if ':' not in wanted_image:
        wanted_image = '{}:latest'.format(wanted_image)

    debug('Checking if "{}" is among the local images in Docker.'.format(wanted_image))
    for image in docker_client().images(name=wanted_image.split(':')[0]):
        if wanted_image in image['RepoTags']:
            info('Docker image found.')
            return True

    log('The Docker image "{}" was not found locally, pulling it: '.format(wanted_image), nl=False)
    for data in docker_client().pull(wanted_image, stream=True):
        data = data.decode('utf-8')
        line = json.loads(data)
        if not line.get('error'):
            continue

        log('Failed! Error message follows:', fg='red', bold=True, prefix=False)
        log('  {}'.format(line['error']), err=True, prefix=False)
        return False

    log('Done.', fg='green', prefix=False)
    return True

def convert_volumes_list(volumes):
    """Turn a dict into a list of binds in the format Docker loves."""
    binds = dict()
    for local, container in volumes.items():
        binds[path.abspath(local)] = container
    return binds


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

	<title>caIntegrator</title>
	<LINK href="bigStyle.css" rel="stylesheet" type="text/css">

	Home >
	            Build Query >
                Refine Query >
                Select Presentation >
                Generate Report

		<form name="test" method="get">

  caIntegrator Advanced Search

		<input type="radio" class="radio" name="menu" value="0" checked selected onclick="javascript:document.forms[0].rpt.disabled=true;">
		Create a New Query/Report
		[?]

Study Data Set

							<select name="dataSet" onchange="javascript:moveEm(this);">
								<option>            </option>
								<option>Rembrandt (GMDI)</option>
								<option>I-SPY</option>
								<option>Other</option>

							</select>

Generating Institution

							<select name="generatingInstitution">
								<option>             </option>

							</select>

		<input type="Radio" name="menu" class="radio" value="1" onclick="javascript:document.forms[0].rpt.disabled=false;">
		Upload a saved Query
		[?]

		<input type="file" name="rpt" disabled>

		  <input type="button" class="xbutton" style="width:100px;" value="continue" onclick="javascript:location.href='aSearchMenu.html';">

		</form>

		Advanced Search Areas

			Gene Expression Analysis

			Cytoband

			Gene

			Clone/Probeset

			Gene Ontology (GO) Classifications

			Pathways

			Array Platform

			Differential Gene Expression

			Comparative Genomic Analysis

            Cytoband

			SNP Id

			Genomic Annotation Track

			Chromosomal Abnormality

			Copy Number

			Clinical Study Analysis

            Prior Therapy

			Demographics

			Histopathology

			Survival

			Interventions

		Note: Please move your mouse over the
		[?]
		links for help throughout the application.

Quick Search

		<form>
		Enter a Name

		<input type="text" name="quickSearchName" size="15">

		<input type="submit" value="Go">
		[?]

		</form>
		Examples

		Gene - act1

		Locus Link ID - YHR023W

		GenBank AccNo. - L00683

		Clone - 70353

		Sample Name - E09441

		</form>


text:
{-# LANGUAGE CPP #-}
#ifndef MIN_VERSION_base
#include "../dist/build/autogen/cabal_macros.h"
#endif
-- | This module is mutually exclusive with @Calico.MonadIO@.
module Calico.IO (
    -- * File I\/O
    IO.IO
  , IO.Handle
  , IO.FilePath

    -- ** Standard streams
  , IO.stdin
  , IO.stdout
  , IO.stderr
  , IO.isEOF
  , IO.getChar
  , IO.getContents
  , IO.getLine
  , IO.readIO
  , IO.readLn
  , IO.putChar
  , putStr
  , putStr'
  , putStrLn
  , putStrLn'
  , print
  , print'

    -- ** Simple I/O
  , IO.readFile
  , IO.writeFile
  , IO.appendFile

    -- ** Open/close
  , IO.IOMode(..)
  , IO.withFile
  , IO.openFile
  , IO.withBinaryFile
  , IO.openBinaryFile
  , IO.openBinaryTempFile
  , IO.hClose

    -- ** Read/write
  , IO.hGetBuf
  , IO.hGetBufSome
  , IO.hGetBufNonBlocking
  , IO.hWaitForInput
  , IO.hReady
  , IO.hGetChar
  , IO.hGetContents
  , IO.hGetLine
  , IO.hLookAhead
  , IO.hPutBuf
  , IO.hPutBufNonBlocking
  , IO.hPutChar
  , hPutStr
  , hPutStr'
  , hPutStrLn
  , hPutStrLn'
  , hPrint
  , hPrint'
  , HPrintfType
  , hPrintf

    -- ** Position
  , IO.hFileSize
  , IO.hSetFileSize
  , IO.hIsEOF
  , IO.hTell
  , IO.SeekMode(..)
  , IO.hSeek

    -- ** Buffering
  , IO.BufferMode(..)
  , IO.hGetBuffering
  , IO.hSetBuffering
  , hFlush

    -- ** Encoding
  , IO.TextEncoding
  , IO.latin1
  , IO.utf8
  , IO.utf16
  , IO.hGetEncoding
  , IO.hSetEncoding
  , IO.hSetBinaryMode

    -- ** Miscellaneous attributes
  , IO.hIsReadable
  , IO.hIsWritable
  , IO.hIsSeekable
  , IO.hIsTerminalDevice

    -- * Environment
  , getArgs
  , withArgs
  , getProgName
  , withProgName
#if MIN_VERSION_base(4, 6, 0)
  , getExecutablePath
#endif
  , lookupEnv
  , getEnv
#if MIN_VERSION_base(4, 7, 0)
  , setEnv
  , unsetEnv
#endif
  , getEnvironment

    -- ** Exit
  , ExitCode(..)
  , exitWith
  , exitFailure
  , exitSuccess

    -- * I\/O errors
  , IO.IOError
  , IO.ioError
  , IO.userError
  , IO.mkIOError
  , IO.modifyIOError
  , IO.annotateIOError
  , IO.ioeGetErrorType
  , IO.ioeGetLocation
  , IO.ioeGetErrorString
  , IO.ioeGetHandle
  , IO.ioeGetFileName
  , IO.ioeSetErrorType
  , IO.ioeSetErrorString
  , IO.ioeSetLocation
  , IO.ioeSetHandle
  , IO.ioeSetFileName
  , IO.isAlreadyExistsError
  , IO.isDoesNotExistError
  , IO.isAlreadyInUseError
  , IO.isFullError
  , IO.isEOFError
  , IO.isIllegalOperation
  , IO.isPermissionError
  , IO.isUserError
  , IO.IOErrorType
  , IO.alreadyExistsErrorType
  , IO.doesNotExistErrorType
  , IO.alreadyInUseErrorType
  , IO.fullErrorType
  , IO.eofErrorType
  , IO.illegalOperationErrorType
  , IO.permissionErrorType
  , IO.userErrorType
  , IO.isAlreadyExistsErrorType
  , IO.isDoesNotExistErrorType
  , IO.isAlreadyInUseErrorType
  , IO.isFullErrorType
  , IO.isEOFErrorType
  , IO.isIllegalOperationErrorType
  , IO.isPermissionErrorType
  , IO.isUserErrorType

  ) where
import Prelude ()
import Calico.Base
import System.IO (Handle, IO, hFlush, hPrint, hPutStr, hPutStrLn,
                  print, putStr, putStrLn, stdout)
import Text.Printf (HPrintfType, hPrintf)
import System.Environment hiding (lookupEnv)
import System.Exit
import qualified System.Environment as Env
import qualified System.IO as IO
import qualified System.IO.Error as IO

putStr' :: String -> IO ()
putStr' = (>> hFlush stdout) . putStr

putStrLn' :: String -> IO ()
putStrLn' = (>> hFlush stdout) . putStrLn

print' :: Show a => a -> IO ()
print' = (>> hFlush stdout) . print

hPutStr' :: Handle -> String -> IO ()
hPutStr' h = (>> hFlush h) . hPutStr h

hPutStrLn' :: Handle -> String -> IO ()
hPutStrLn' h = (>> hFlush h) . hPutStrLn h

hPrint' :: Show a => Handle -> a -> IO ()
hPrint' h = (>> hFlush h) . hPrint h

lookupEnv :: String -> IO (Maybe String)
#if MIN_VERSION_base(4, 6, 0)
lookupEnv = Env.lookupEnv
#else
lookupEnv n = (Just <$> getEnv n)
  `IO.catch` \ e -> if IO.isDoesNotExistError e
                    then return Nothing
                    else IO.ioError e
#endif


text:
Please take a look at the [live site](http://srlm.io)

## Author

**Cody Lewis**
- <https://github.com/srlm-io>

## Notes
To run use
```
bundle exec jekyll serve --drafts --watch
````

You may need to

```
sudo apt install ruby ruby-dev ruby-bundler zlib1g-dev
sudo gem install jekyll
cd /path/to/repo
bundle install --path vendor/bundle
```

first. The site will appear at [http://localhost:4000](http://localhost:4000), and you can develop drafts in the `_drafts` folder.

This site is based on the Poole template [here](https://github.com/poole/poole). Take a look there for markdown examples.

## License

Open sourced under the [MIT license](LICENSE.md).


text:
"""Support for NSW Rural Fire Service Feeds."""
from datetime import timedelta
import logging
from typing import Optional

import voluptuous as vol

from homeassistant.components.geo_location import PLATFORM_SCHEMA, GeolocationEvent
from homeassistant.const import (
    ATTR_ATTRIBUTION,
    ATTR_LOCATION,
    CONF_LATITUDE,
    CONF_LONGITUDE,
    CONF_RADIUS,
    CONF_SCAN_INTERVAL,
    EVENT_HOMEASSISTANT_START,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
from homeassistant.helpers.event import track_time_interval

_LOGGER = logging.getLogger(__name__)

ATTR_CATEGORY = "category"
ATTR_COUNCIL_AREA = "council_area"
ATTR_EXTERNAL_ID = "external_id"
ATTR_FIRE = "fire"
ATTR_PUBLICATION_DATE = "publication_date"
ATTR_RESPONSIBLE_AGENCY = "responsible_agency"
ATTR_SIZE = "size"
ATTR_STATUS = "status"
ATTR_TYPE = "type"

CONF_CATEGORIES = "categories"

DEFAULT_RADIUS_IN_KM = 20.0
DEFAULT_UNIT_OF_MEASUREMENT = "km"

SCAN_INTERVAL = timedelta(minutes=5)

SIGNAL_DELETE_ENTITY = "nsw_rural_fire_service_feed_delete_{}"
SIGNAL_UPDATE_ENTITY = "nsw_rural_fire_service_feed_update_{}"

SOURCE = "nsw_rural_fire_service_feed"

VALID_CATEGORIES = ["Advice", "Emergency Warning", "Not Applicable", "Watch and Act"]

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Optional(CONF_CATEGORIES, default=[]): vol.All(
            cv.ensure_list, [vol.In(VALID_CATEGORIES)]
        ),
        vol.Optional(CONF_LATITUDE): cv.latitude,
        vol.Optional(CONF_LONGITUDE): cv.longitude,
        vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS_IN_KM): vol.Coerce(float),
    }
)

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the NSW Rural Fire Service Feed platform."""
    scan_interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
    coordinates = (
        config.get(CONF_LATITUDE, hass.config.latitude),
        config.get(CONF_LONGITUDE, hass.config.longitude),
    )
    radius_in_km = config[CONF_RADIUS]
    categories = config.get(CONF_CATEGORIES)
    # Initialize the entity manager.
    feed = NswRuralFireServiceFeedEntityManager(
        hass, add_entities, scan_interval, coordinates, radius_in_km, categories
    )

    def start_feed_manager(event):
        """Start feed manager."""
        feed.startup()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_feed_manager)

class NswRuralFireServiceFeedEntityManager:
    """Feed Entity Manager for NSW Rural Fire Service GeoJSON feed."""

    def __init__(
        self, hass, add_entities, scan_interval, coordinates, radius_in_km, categories
    ):
        """Initialize the Feed Entity Manager."""
        from geojson_client.nsw_rural_fire_service_feed import (
            NswRuralFireServiceFeedManager,
        )

        self._hass = hass
        self._feed_manager = NswRuralFireServiceFeedManager(
            self._generate_entity,
            self._update_entity,
            self._remove_entity,
            coordinates,
            filter_radius=radius_in_km,
            filter_categories=categories,
        )
        self._add_entities = add_entities
        self._scan_interval = scan_interval

    def startup(self):
        """Start up this manager."""
        self._feed_manager.update()
        self._init_regular_updates()

    def _init_regular_updates(self):
        """Schedule regular updates at the specified interval."""
        track_time_interval(
            self._hass, lambda now: self._feed_manager.update(), self._scan_interval
        )

    def get_entry(self, external_id):
        """Get feed entry by external id."""
        return self._feed_manager.feed_entries.get(external_id)

    def _generate_entity(self, external_id):
        """Generate new entity."""
        new_entity = NswRuralFireServiceLocationEvent(self, external_id)
        # Add new entities to HA.
        self._add_entities([new_entity], True)

    def _update_entity(self, external_id):
        """Update entity."""
        dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY.format(external_id))

    def _remove_entity(self, external_id):
        """Remove entity."""
        dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(external_id))

class NswRuralFireServiceLocationEvent(GeolocationEvent):
    """This represents an external event with NSW Rural Fire Service data."""

    def __init__(self, feed_manager, external_id):
        """Initialize entity with data from feed entry."""
        self._feed_manager = feed_manager
        self._external_id = external_id
        self._name = None
        self._distance = None
        self._latitude = None
        self._longitude = None
        self._attribution = None
        self._category = None
        self._publication_date = None
        self._location = None
        self._council_area = None
        self._status = None
        self._type = None
        self._fire = None
        self._size = None
        self._responsible_agency = None
        self._remove_signal_delete = None
        self._remove_signal_update = None

    async def async_added_to_hass(self):
        """Call when entity is added to hass."""
        self._remove_signal_delete = async_dispatcher_connect(
            self.hass,
            SIGNAL_DELETE_ENTITY.format(self._external_id),
            self._delete_callback,
        )
        self._remove_signal_update = async_dispatcher_connect(
            self.hass,
            SIGNAL_UPDATE_ENTITY.format(self._external_id),
            self._update_callback,
        )

    @callback
    def _delete_callback(self):
        """Remove this entity."""
        self._remove_signal_delete()
        self._remove_signal_update()
        self.hass.async_create_task(self.async_remove())

    @callback
    def _update_callback(self):
        """Call update method."""
        self.async_schedule_update_ha_state(True)

    @property
    def should_poll(self):
        """No polling needed for NSW Rural Fire Service location events."""
        return False

    async def async_update(self):
        """Update this entity from the data held in the feed manager."""
        _LOGGER.debug("Updating %s", self._external_id)
        feed_entry = self._feed_manager.get_entry(self._external_id)
        if feed_entry:
            self._update_from_feed(feed_entry)

    def _update_from_feed(self, feed_entry):
        """Update the internal state from the provided feed entry."""
        self._name = feed_entry.title
        self._distance = feed_entry.distance_to_home
        self._latitude = feed_entry.coordinates[0]
        self._longitude = feed_entry.coordinates[1]
        self._attribution = feed_entry.attribution
        self._category = feed_entry.category
        self._publication_date = feed_entry.publication_date
        self._location = feed_entry.location
        self._council_area = feed_entry.council_area
        self._status = feed_entry.status
        self._type = feed_entry.type
        self._fire = feed_entry.fire
        self._size = feed_entry.size
        self._responsible_agency = feed_entry.responsible_agency

    @property
    def icon(self):
        """Return the icon to use in the frontend."""
        if self._fire:
            return "mdi:fire"
        return "mdi:alarm-light"

    @property
    def source(self) -> str:
        """Return source value of this external event."""
        return SOURCE

    @property
    def name(self) -> Optional[str]:
        """Return the name of the entity."""
        return self._name

    @property
    def distance(self) -> Optional[float]:
        """Return distance value of this external event."""
        return self._distance

    @property
    def latitude(self) -> Optional[float]:
        """Return latitude value of this external event."""
        return self._latitude

    @property
    def longitude(self) -> Optional[float]:
        """Return longitude value of this external event."""
        return self._longitude

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement."""
        return DEFAULT_UNIT_OF_MEASUREMENT

    @property
    def device_state_attributes(self):
        """Return the device state attributes."""
        attributes = {}
        for key, value in (
            (ATTR_EXTERNAL_ID, self._external_id),
            (ATTR_CATEGORY, self._category),
            (ATTR_LOCATION, self._location),
            (ATTR_ATTRIBUTION, self._attribution),
            (ATTR_PUBLICATION_DATE, self._publication_date),
            (ATTR_COUNCIL_AREA, self._council_area),
            (ATTR_STATUS, self._status),
            (ATTR_TYPE, self._type),
            (ATTR_FIRE, self._fire),
            (ATTR_SIZE, self._size),
            (ATTR_RESPONSIBLE_AGENCY, self._responsible_agency),
        ):
            if value or isinstance(value, bool):
                attributes[key] = value
        return attributes


text:
import './style/index.css';

export * from './titlebar';


text:
namespace Rcpp {

    template <bool OUTPUT>
    class Rstreambuf : public std::streambuf {
    public:
        Rstreambuf(){}

    protected:
        virtual std::streamsize xsputn(const char *s, std::streamsize n);

        virtual int overflow(int c = traits_type::eof());

        virtual int sync();
    };

    template <bool OUTPUT>
    class Rostream : public std::ostream {
        typedef Rstreambuf<OUTPUT> Buffer;
        Buffer buf;
    public:
        Rostream() : std::ostream( &buf ) {}
    };
							// #nocov start
    template <> inline std::streamsize Rstreambuf<true>::xsputn(const char *s, std::streamsize num) {
        Rprintf("%.*s", num, s);
        return num;
    }
    template <> inline std::streamsize Rstreambuf<false>::xsputn(const char *s, std::streamsize num) {
        REprintf("%.*s", num, s);
        return num;
    }

    template <> inline int Rstreambuf<true>::overflow(int c) {
        if (c != traits_type::eof()) {
            char_type ch = traits_type::to_char_type(c);
            return xsputn(&ch, 1) == 1 ? c : traits_type::eof();
        }
        return c;
    }
    template <> inline int Rstreambuf<false>::overflow(int c) {
        if (c != traits_type::eof()) {
            char_type ch = traits_type::to_char_type(c);
            return xsputn(&ch, 1) == 1 ? c : traits_type::eof();
        }
        return c;
    }

    template <> inline int Rstreambuf<true>::sync() {
        ::R_FlushConsole();
        return 0;
    }
    template <> inline int Rstreambuf<false>::sync() {
        ::R_FlushConsole();
        return 0;
    }								// #nocov end
    static Rostream<true>  Rcout;
    static Rostream<false> Rcerr;

}

#endif