text:
local Plugin = Plugin

local hudTexts = {}
local squadNumberLastSetTimes = {}
local squadNumbers = {}
local gameState = {}
gameState.gameIsInProgressLastSetToTrue = 0
gameState.gameIsInProgressLastSetToFalse = 0
gameState.gameIsInProgress = false

TGNS.HookNetworkMessage(Plugin.GAME_IN_PROGRESS, function(message)
	gameState.gameIsInProgress = message.b
	if gameState.gameIsInProgress then
		gameState.gameIsInProgressLastSetToTrue = Shared.GetTime()
	else
		gameState.gameIsInProgressLastSetToFalse = Shared.GetTime()
		TGNS.DoFor(CHUDOptionsToDisableDuringWinOrLose, function(key)
			if CHUDOptions and CHUDOptions[key] then
				CHUDOptions[key].disabled = false
			end
		end)
		tunnelDescriptions = {}
	end
end)

TGNS.HookNetworkMessage(Plugin.SQUAD_CONFIRMED, function(message)
	squadNumberLastSetTimes[message.c] = Shared.GetTime()
	squadNumbers[message.c] = message.s
end)

function hudTexts.initializeSquadHudText()
	if hudTexts.squadNumbersHudText then
		hudTexts.squadNumbersHudText:Remove()
	end
	hudTexts.squadNumbersHudText = Shine.ScreenText.Add( "Squad", {
		X = 0.04, Y = 0.61,
		Text = "",
		Duration = math.huge,
		R = 255, G = 255, B = 255,
		Alignment = 2,
		Size = 2,
		FadeIn = 0.5
	} )

function hudTexts.squadNumbersHudText:UpdateText()
		local text = ""
		local squadNumberLastSetTime = squadNumberLastSetTimes[Client.GetLocalClientIndex()] or 0
		local secondsSinceSquadNumberLastSet = math.floor(Shared.GetTime() - squadNumberLastSetTime)
		local shouldHideSquadNumberToCauseBlinkingEffect = (secondsSinceSquadNumberLastSet < 6 and secondsSinceSquadNumberLastSet % 2 == 0) or (secondsSinceSquadNumberLastSet > 10)
		local squadNumber = squadNumbers[Client.GetLocalClientIndex()] or 0
		local isCommander = Scoreboard_GetPlayerData(Client.GetLocalClientIndex(), "IsCommander")
		if squadNumber ~= 0 and not isCommander and not shouldHideSquadNumberToCauseBlinkingEffect then
			if Client.GetLocalClientTeamNumber() == kMarineTeamType then
				text = string.format("\nSquad %s", squadNumber)
			else
				local plannedLifeFormNames = {"Skulk", "Gorge", "Lerk", "Fade", "Onos", "KHAMM"}
				text = string.format("\n%s", plannedLifeFormNames[squadNumber])
			end
		end
		self.Obj:SetText(text)
	end
end

function hudTexts.initializeAlienLifeformsHudText()
	local updateAlienLifeformsReviewHudText = function(textObj, title, commanderCountPredicate, onosCountPredicate, fadeCountPredicate, lerkCountPredicate, gorgeCountPredicate, skulkCountPredicate, noPlansCountPredicate, footerPredicate)
		local text = ""
		if not gameState.gameIsInProgress and Shared.GetTime() - gameState.gameIsInProgressLastSetToFalse > TGNS.ENDGAME_TIME_TO_READYROOM + 1 then
			local playerIsAlien = Client.GetLocalClientTeamNumber() == kAlienTeamType
			local playerIsCommander = Scoreboard_GetPlayerData(Client.GetLocalClientIndex(), "IsCommander")
			if playerIsAlien then
				local commanderNames = {}
				local onosNames = {}
				local fadeNames = {}
				local lerkNames = {}
				local gorgeNames = {}
				local skulkNames = {}
				local noPlansNames = {}
				TGNS.DoForPairs(squadNumbers, function(clientIndex, squadNumber)
					local teamNumber = Scoreboard_GetPlayerData(clientIndex, "EntityTeamNumber")
					if teamNumber == kAlienTeamType then
						local playerName = Scoreboard_GetPlayerData(clientIndex, "Name")
						if squadNumber == 6 then
							table.insert(commanderNames, playerName)
						elseif squadNumber == 5 then
							table.insert(onosNames, playerName)
						elseif squadNumber == 4 then
							table.insert(fadeNames, playerName)
						elseif squadNumber == 3 then
							table.insert(lerkNames, playerName)
						elseif squadNumber == 2 then
							table.insert(gorgeNames, playerName)
						elseif squadNumber == 1 then
							table.insert(skulkNames, playerName)
						elseif squadNumber == 0 then
							table.insert(noPlansNames, playerName)
						end
					end
				end)
				local getNamesDisplay = function(names)
					local result = ""
					if #names >= 1 then
						local namesToDisplay = TGNS.Take(names, 3)
						if #names > 3 then
							table.insert(namesToDisplay, "...")
						end
						result = string.format("(%s)", TGNS.Join(TGNS.Select(namesToDisplay, function(n) return TGNS.Truncate(n, 3) end), ", "))
					end
					return result
				end

				local lines = {}
				table.insert(lines, title)
				table.insert(lines, commanderCountPredicate(#commanderNames) and string.format("%sx Commander %s", #commanderNames, getNamesDisplay(commanderNames)) or "")
				table.insert(lines, onosCountPredicate(#onosNames) and string.format("%sx Onos %s", #onosNames, getNamesDisplay(onosNames)) or "")
				table.insert(lines, fadeCountPredicate(#fadeNames) and string.format("%sx Fade %s", #fadeNames, getNamesDisplay(fadeNames)) or "")
				table.insert(lines, lerkCountPredicate(#lerkNames) and string.format("%sx Lerk %s", #lerkNames, getNamesDisplay(lerkNames)) or "")
				table.insert(lines, gorgeCountPredicate(#gorgeNames) and string.format("%sx Gorge %s", #gorgeNames, getNamesDisplay(gorgeNames)) or "")
				table.insert(lines, skulkCountPredicate(#skulkNames) and string.format("%sx Skulk/Wildcard %s", #skulkNames, getNamesDisplay(skulkNames)) or "")
				table.insert(lines, noPlansCountPredicate(#noPlansNames) and string.format("%sx ??? %s", #noPlansNames, getNamesDisplay(noPlansNames)) or "")
				if math.floor(Shared.GetTime()) % 2 == 0 then
					table.insert(lines, footerPredicate() and "Click your scoreboard row's circle to choose." or "")
				end

				text = TGNS.Join(lines, "\n")
			end
		end
		textObj:SetText(text)
	end

	if hudTexts.alienLifeformsReviewHudText1 then
		hudTexts.alienLifeformsReviewHudText1:Remove()
	end
	if hudTexts.alienLifeformsReviewHudText2 then
		hudTexts.alienLifeformsReviewHudText2:Remove()
	end
	hudTexts.alienLifeformsReviewHudText1 = Shine.ScreenText.Add( "AlienLifeformsReviewHudText1", {
		X = 0.70, Y = 0.35,
		Text = "",
		Duration = math.huge,
		R = 218, G = 165, B = 31,
		Alignment = TGNS.ShineTextAlignmentMin,
		Size = 2,
		FadeIn = 0
	} )
	hudTexts.alienLifeformsReviewHudText2 = Shine.ScreenText.Add( "AlienLifeformsReviewHudText2", {
		X = 0.70, Y = 0.35,
		Text = "",
		Duration = math.huge,
		R = 255, G = 0, B = 0,
		Alignment = TGNS.ShineTextAlignmentMin,
		Size = 2,
		FadeIn = 0
	} )

	local commanderCountPredicate1 = function(count) return count == 1 end
	local onosCountPredicate1 = function(count) return count > 0 end
	local fadeCountPredicate1 = function(count) return count > 0 end
	local lerkCountPredicate1 = function(count) return count > 0 end
	local gorgeCountPredicate1 = function(count) return count > 0 end
	local skulkCountPredicate1 = function(count) return true end
	local noPlansCountPredicate1 = function(count) return false end
	local footerPredicate1 = function() return false end

	local commanderCountPredicate2 = function(count) return count ~= 1 end
	local onosCountPredicate2 = function(count) return count == 0 end
	local fadeCountPredicate2 = function(count) return count == 0 end
	local lerkCountPredicate2 = function(count) return count == 0 end
	local gorgeCountPredicate2 = function(count) return count == 0 end
	local skulkCountPredicate2 = function(count) return false end
	local noPlansCountPredicate2 = function(count) return count > 0 end
	local footerPredicate2 = function() return (squadNumbers[Client.GetLocalClientIndex()] or 0) == 0 end

	function hudTexts.alienLifeformsReviewHudText1:UpdateText()
		updateAlienLifeformsReviewHudText(self.Obj, "Planned Roles:", commanderCountPredicate1, onosCountPredicate1, fadeCountPredicate1, lerkCountPredicate1, gorgeCountPredicate1, skulkCountPredicate1, noPlansCountPredicate1, footerPredicate1)
	end
	function hudTexts.alienLifeformsReviewHudText2:UpdateText()
		updateAlienLifeformsReviewHudText(self.Obj, "", commanderCountPredicate2, onosCountPredicate2, fadeCountPredicate2, lerkCountPredicate2, gorgeCountPredicate2, skulkCountPredicate2, noPlansCountPredicate2, footerPredicate2)
	end
end

function hudTexts.initializeSkillImbalanceHudText()
	if hudTexts.skillImbalanceHudText then
		hudTexts.skillImbalanceHudText:Remove()
	end
	hudTexts.skillImbalanceHudText = Shine.ScreenText.Add( "SkillImbalanceHudText", {
		X = 0.2, Y = 0.35,
		Text = "",
		Duration = math.huge,
		R = 0, G = 165, B = 0,
		Alignment = TGNS.ShineTextAlignmentCenter,
		Size = 2,
		FadeIn = 0
	} )

function hudTexts.skillImbalanceHudText:UpdateText()
		local text = ""
		if Shine.GetGamemode() == "ns2" and not captainsEnabled and not gameState.gameIsInProgress and not gameState.gameIsInCountdown and Shared.GetTime() - gameState.gameIsInProgressLastSetToFalse > TGNS.ENDGAME_TIME_TO_READYROOM + 1 and (Client.GetLocalClientTeamNumber() == kAlienTeamType or Client.GetLocalClientTeamNumber() == kMarineTeamType) then
			text = string.format("Chat 'switch' if you want to play %s.\n\nIf you see skill imbalance pre-game:\nChat 'swap' to learn how to help.\n\nDon't complain about teams. See above.", Client.GetLocalClientTeamNumber() == kAlienTeamType and "Marines" or "Aliens")
		end
		self.Obj:SetText(text)
	end
end

function Plugin:OnResolutionChanged( OldX, OldY, NewX, NewY )
	hudTexts.initializeSquadHudText()
	hudTexts.initializeAlienLifeformsHudText()
	hudTexts.initializeSkillImbalanceHudText()
end

function Plugin:Initialise()
	self.Enabled = true

	hudTexts.initializeSquadHudText()
	hudTexts.initializeAlienLifeformsHudText()
	hudTexts.initializeSkillImbalanceHudText()

	return true
end

function Plugin:Cleanup()
    --Cleanup your extra stuff like timers, data etc.
    self.BaseClass.Cleanup( self )
end


text:
Flames
=======

Do you have a secret crush??
Want to know the scope of your relationship with the crush??
The `Flames` tool is the one you are looking for.
Flames stands for Friendship, Love, Affair, Marriage, Enmity and Sisterhood.

Installation
------------

    sudo gem install flames

Demo
----

    http://flames.heroku.com/

Usage
-----

    Flames.compute(`your_name`, `your_crushs_name`)

Example
-------

    require "rubygems"
    require "flames"
    Flames.compute("Brad Pit", "Angelina")

This will result in `Marriage`!!!
Have fun playing!!!

Author
------

Copyright (c) 2011 B V Satyaram <[bvsatyaram.com](http://bvsatyaram.com)>, released under the MIT license

redpajama_set_name: RedPajamaGithub


text:
using DevTreks.Data;
using DevTreks.Models;
using DevTreks.Services;
using DevTreks.Helpers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Exceptions = DevTreks.Exceptions;

namespace DevTreks.ViewModels
{
    /// <summary>
    ///Purpose:		View Model class for filling in member login, joinin, and payment handling views
    ///Author:		www.devtreks.org
    ///Date:		2016, March
    ///Notes;
    /// </summary>
    public class MemberViewModel
    {
        public MemberViewModel(ContentURI initialURI)
        {
            this.Member = new AccountToMember();
            //different use of initialURI because not as much work done here
            ContentURIData = initialURI;
        }
        public ContentURI ContentURIData { get; set; }
        public AccountToMember Member { get; set; }
        public string ErrorMessage { get; set; }

        public void Logout(Microsoft.AspNetCore.Http.HttpContext context)
        {
            HtmlMemberExtensions.SignOut(context);
        }

        public async Task<bool> SetClubAndMember(HttpContext context,
            IMemberService memberService)
        {
            bool bHasSet = false;
            //set up initial club and member
            bool bIsInitView = true;
            MemberHelper oMemberHelper = new MemberHelper();
            bHasSet = await oMemberHelper.SetClubAndMemberAsync(context, bIsInitView, memberService,
                ContentURIData);
            if (ContentURIData.URIMember != null)
            {
                this.Member = ContentURIData.URIMember;
            }
            return bHasSet;
        }

        public async Task<string> UpdatePaymentHandling(HttpContext context, IMemberService memberService,
            AccountToMember loggedInMember)
        {
            string sError = Exceptions.DevTreksErrors.MakeStandardErrorMsg(
                 string.Empty, "MEMBERVIEW_NOPAYS");
            //await memberService.UpdatePaymentHandlingAsync(loggedInMember);
            return sError;
        }

    }
}


text:
#ifndef ORILIB_PACKETSEARCHDECISION_T_H
#define ORILIB_PACKETSEARCHDECISION_T_H

#include "ORILIB_t.h"
#include <oros/sysilib/Decision_t.h>		//for Decision_t type

#define ORILIB_PACKETSEARCHDECISION_N_DECWAYS 2

typedef struct {
  Uint32 transitionMap[ORILIB_PACKETSEARCHDECISION_N_DECWAYS];
} ORILIB_t_PacketSearchDecision_Conf;

#endif /* ORILIB_PACKETSEARCHDECISION_T_H */


text:
module System.Taffybar.Widget.Text.MemoryMonitor (textMemoryMonitorNew, showMemoryInfo) where

import Control.Monad.IO.Class ( MonadIO )
import qualified Data.Text as T
import qualified Text.StringTemplate as ST
import System.Taffybar.Information.Memory
import System.Taffybar.Widget.Generic.PollingLabel ( pollingLabelNew )
import qualified GI.Gtk
import Text.Printf ( printf )

-- | Creates a simple textual memory monitor. It updates once every polling
-- period (in seconds).
textMemoryMonitorNew :: MonadIO m
                     => String -- ^ Format. You can use variables: "used", "total", "free", "buffer",
                               -- "cache", "rest", "available", "swapUsed", "swapTotal", "swapFree".
                     -> Double -- ^ Polling period in seconds.
                     -> m GI.Gtk.Widget
textMemoryMonitorNew fmt period = do
    label <- pollingLabelNew period (showMemoryInfo fmt 3 <$> parseMeminfo)
    GI.Gtk.toWidget label

showMemoryInfo :: String -> Int -> MemoryInfo -> T.Text
showMemoryInfo fmt prec info =
  let template = ST.newSTMP fmt
      labels = [ "used"
               , "total"
               , "free"
               , "buffer"
               , "cache"
               , "rest"
               , "available"
               , "swapUsed"
               , "swapTotal"
               , "swapFree"
               ]
      actions = [ memoryUsed
                , memoryTotal
                , memoryFree
                , memoryBuffer
                , memoryCache
                , memoryRest
                , memoryAvailable
                , memorySwapUsed
                , memorySwapTotal
                , memorySwapFree
                ]
      actions' = map (toAuto prec .) actions
      stats = [f info | f <- actions']
      template' = ST.setManyAttrib (zip labels stats) template
  in ST.render template'

toAuto :: Int -> Double -> String
toAuto prec value = printf "%.*f%s" p v unit
  where value' = max 0 value
        mag :: Int
        mag = if value' == 0 then 0 else max 0 $ min 2 $ floor $ logBase 1024 value'
        v = value' / 1024 ** fromIntegral mag
        unit = case mag of
          0 -> "MiB"
          1 -> "GiB"
          2 -> "TiB"
          _ -> "??B" -- unreachable
        p :: Int
        p = max 0 $ floor $ fromIntegral prec - logBase 10 v


text:
/**
 * Created by siriscac on 21/07/16.
 */

import {Observable, BehaviorSubject} from 'rxjs';
import {Injectable} from "@angular/core";

@Injectable()
export class WindowSize {
    width$: Observable<number>;
    height$: Observable<number>;

    constructor() {
        let windowSize$ = new BehaviorSubject(getWindowSize());
        this.width$ = (windowSize$.pluck('width') as Observable<number>).distinctUntilChanged();
        this.height$ = (windowSize$.pluck('height') as Observable<number>).distinctUntilChanged();

        Observable.fromEvent(window, 'resize')
            .map(getWindowSize)
            .subscribe(windowSize$);
    }
}

function getWindowSize() {
    return {
        height: window.innerHeight,
        width: window.innerWidth
    };
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<model model-package="com.dianping.cat.home.service.client" enable-merger="true"  enable-sax-parser="true"
	enable-base-visitor="true"  enable-json-parser="true" enable-json-builder="true" enable-native-parser="true"  enable-native-builder="true"
	enable-xml-parser="false"  enable-xml-builder="false">
  <entity name="client-report" root="true">
    <attribute name="domain" value-type="String" key="true" />
    <attribute name="start-time" value-type="Date" format="yyyy-MM-dd HH:mm:ss" />
    <attribute name="end-time" value-type="Date" format="yyyy-MM-dd HH:mm:ss" />
    <entity-ref name="domain" type="map" names="domains"  method-find-or-create="true"/>
  </entity>
  <entity name="domain">
    <attribute name="id" value-type="String" key="true"/>
    <attribute name="totalCount" value-type="long" primitive="true" method-inc="true" />
    <attribute name="failureCount" value-type="long" primitive="true" method-inc="true" />
    <attribute name="failurePercent" primitive="true" value-type="double" />
    <attribute name="sum" value-type="double" primitive="true" method-inc="true" />
    <attribute name="avg" value-type="double" primitive="true" />
    <entity-ref name="method" type="map" names="methods" method-find-or-create="true" />
  </entity>
  <entity name="method">
    <attribute name="id" value-type="String" key="true"/>
    <attribute name="service" value-type="String" />
    <attribute name="totalCount" value-type="long" primitive="true" method-inc="true" />
    <attribute name="failureCount" value-type="long" primitive="true" method-inc="true" />
    <attribute name="failurePercent" value-type="double" primitive="true" />
    <attribute name="sum" value-type="double" primitive="true" method-inc="true" />
    <attribute name="avg" value-type="double" primitive="true" />
    <attribute name="qps" value-type="double" primitive="true" />
    <attribute name="timeout" value-type="double" primitive="true" />
  </entity>
</model>


text:
// Copyright 2014 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.skyframe;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.Actions;
import com.google.devtools.build.lib.actions.Actions.GeneratingActions;
import com.google.devtools.build.lib.actions.ArtifactFactory;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.analysis.buildinfo.BuildInfoCollection;
import com.google.devtools.build.lib.analysis.buildinfo.BuildInfoFactory;
import com.google.devtools.build.lib.analysis.buildinfo.BuildInfoFactory.BuildInfoContext;
import com.google.devtools.build.lib.analysis.buildinfo.BuildInfoFactory.BuildInfoType;
import com.google.devtools.build.lib.analysis.buildinfo.BuildInfoKey;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
import com.google.devtools.build.lib.bugreport.BugReport;
import com.google.devtools.build.lib.skyframe.BuildInfoCollectionValue.BuildInfoKeyAndConfig;
import com.google.devtools.build.lib.skyframe.PrecomputedValue.Precomputed;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import com.google.devtools.build.skyframe.SkyframeLookupResult;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * Creates a {@link BuildInfoCollectionValue}. Only depends on the unique {@link
 * WorkspaceStatusValue} and the constant {@link #BUILD_INFO_FACTORIES} injected value.
 *
 * <p>For more information, see {@link
 * com.google.devtools.build.lib.analysis.buildinfo.BuildInfoFactory}.
 */
public class BuildInfoCollectionFunction implements SkyFunction {

  public static final Precomputed<Map<BuildInfoKey, BuildInfoFactory>> BUILD_INFO_FACTORIES =
      new Precomputed<>("build_info_factories");

  private final ActionKeyContext actionKeyContext;
  private final ArtifactFactory artifactFactory;

  BuildInfoCollectionFunction(ActionKeyContext actionKeyContext, ArtifactFactory artifactFactory) {
    this.actionKeyContext = actionKeyContext;
    this.artifactFactory = artifactFactory;
  }

  @Override
  @Nullable
  public SkyValue compute(SkyKey skyKey, Environment env) throws InterruptedException {
    final BuildInfoKeyAndConfig keyAndConfig = (BuildInfoKeyAndConfig) skyKey.argument();
    ImmutableSet<SkyKey> keysToRequest =
        ImmutableSet.of(WorkspaceStatusValue.BUILD_INFO_KEY, keyAndConfig.getConfigurationKey());
    SkyframeLookupResult result = env.getValuesAndExceptions(keysToRequest);
    if (env.valuesMissing()) {
      return null;
    }
    WorkspaceStatusValue infoArtifactValue =
        (WorkspaceStatusValue) result.get(WorkspaceStatusValue.BUILD_INFO_KEY);
    if (infoArtifactValue == null) {
      BugReport.logUnexpected("Value for: BuildInfoKey was missing, this should never happen");
      return null;
    }

    BuildConfigurationValue config =
        (BuildConfigurationValue) result.get(keyAndConfig.getConfigurationKey());
    if (config == null) {
      BugReport.logUnexpected(
          "Value for: '%s' was missing, this should never happen",
          keyAndConfig.getConfigurationKey());
      return null;
    }
    Map<BuildInfoKey, BuildInfoFactory> buildInfoFactories = BUILD_INFO_FACTORIES.get(env);
    BuildInfoFactory buildInfoFactory = buildInfoFactories.get(keyAndConfig.getInfoKey());
    Preconditions.checkState(buildInfoFactory.isEnabled(config));

    BuildInfoContext context =
        (rootRelativePath, root, type) ->
            type == BuildInfoType.NO_REBUILD
                ? artifactFactory.getConstantMetadataArtifact(rootRelativePath, root, keyAndConfig)
                : artifactFactory.getDerivedArtifact(rootRelativePath, root, keyAndConfig);
    BuildInfoCollection collection =
        buildInfoFactory.create(
            context,
            config,
            infoArtifactValue.getStableArtifact(),
            infoArtifactValue.getVolatileArtifact());
    GeneratingActions generatingActions;
    try {
      generatingActions =
          Actions.assignOwnersAndFilterSharedActionsAndThrowActionConflict(
              actionKeyContext,
              collection.getActions(),
              keyAndConfig,
              /*outputFiles=*/ null);
    } catch (ActionConflictException | Actions.ArtifactGeneratedByOtherRuleException e) {
      throw new IllegalStateException("Errors not expected in build info: " + skyKey, e);
    }
    return new BuildInfoCollectionValue(collection, generatingActions);
  }
}


text:
package identity

import (
	"fmt"
	"regexp"
	"strings"
	"sync"
)

// Glob is glob like pattern that matches identity strings of some kind.
//
// It is a string of the form "kind:<pattern>" where 'kind' is one of Kind
// constants and 'pattern' is a wildcard pattern to apply to identity name.
//
// The only supported glob syntax is '*', which matches zero or more characters.
//
// Case sensitive. Doesn't support multi-line strings or patterns. There's no
// way to match '*' itself.
type Glob string

// MakeGlob ensures 'glob' string looks like a valid identity glob and
// returns it as Glob value.
func MakeGlob(glob string) (Glob, error) {
	g := Glob(glob)
	if err := g.Validate(); err != nil {
		return "", err
	}
	return g, nil
}

// Validate checks that the identity glob string is well-formed.
func (g Glob) Validate() error {
	chunks := strings.SplitN(string(g), ":", 2)
	if len(chunks) != 2 {
		return fmt.Errorf("auth: bad identity glob string %q", g)
	}
	if KnownKinds[Kind(chunks[0])] == nil {
		return fmt.Errorf("auth: bad identity glob kind %q", chunks[0])
	}
	if chunks[1] == "" {
		return fmt.Errorf("auth: identity glob can't be empty")
	}
	if _, err := cache.translate(chunks[1]); err != nil {
		return fmt.Errorf("auth: bad identity glob pattern %q - %s", chunks[1], err)
	}
	return nil
}

// Kind returns identity glob kind. If identity glob string is invalid returns
// Anonymous.
func (g Glob) Kind() Kind {
	chunks := strings.SplitN(string(g), ":", 2)
	if len(chunks) != 2 {
		return Anonymous
	}
	return Kind(chunks[0])
}

// Pattern returns a pattern part of the identity glob. If the identity glob
// string is invalid returns empty string.
func (g Glob) Pattern() string {
	chunks := strings.SplitN(string(g), ":", 2)
	if len(chunks) != 2 {
		return ""
	}
	return chunks[1]
}

// Match returns true if glob matches an identity. If identity string
// or identity glob string are invalid, returns false.
func (g Glob) Match(id Identity) bool {
	globChunks := strings.SplitN(string(g), ":", 2)
	if len(globChunks) != 2 || KnownKinds[Kind(globChunks[0])] == nil {
		return false
	}
	globKind := globChunks[0]
	pattern := globChunks[1]

	idChunks := strings.SplitN(string(id), ":", 2)
	if len(idChunks) != 2 || KnownKinds[Kind(idChunks[0])] == nil {
		return false
	}
	idKind := idChunks[0]
	name := idChunks[1]

	if idKind != globKind {
		return false
	}
	if strings.ContainsRune(name, '\n') {
		return false
	}

	re, err := cache.translate(pattern)
	if err != nil {
		return false
	}
	return re.MatchString(name)
}

// Preprocess splits the glob into its kind and a regexp against identity names.
//
// For example "user:*@example.com" => ("user", "^.*@example\.com$"). Returns
// an error if the glob is malformed.
func (g Glob) Preprocess() (kind Kind, regexp string, err error) {
	globChunks := strings.SplitN(string(g), ":", 2)
	if len(globChunks) != 2 || KnownKinds[Kind(globChunks[0])] == nil {
		return "", "", fmt.Errorf("bad identity glob format")
	}
	kind = Kind(globChunks[0])
	regexp, err = translate(globChunks[1])
	return
}

////

var cache patternCache

// patternCache implements caching for compiled pattern regexps, similar to how
// python does that. Uses extremely dumb algorithm that assumes there are less
// than 500 active patterns in the process. That's how python runtime does it
// too.
type patternCache struct {
	sync.RWMutex
	cache map[string]cacheEntry
}

type cacheEntry struct {
	re  *regexp.Regexp
	err error
}

// translate grabs converted regexp from cache or calls 'translate' to get it.
func (c *patternCache) translate(pat string) (*regexp.Regexp, error) {
	c.RLock()
	val, ok := c.cache[pat]
	c.RUnlock()
	if ok {
		return val.re, val.err
	}

	c.Lock()
	defer c.Unlock()
	if val, ok := c.cache[pat]; ok {
		return val.re, val.err
	}

	if c.cache == nil || len(c.cache) > 500 {
		c.cache = map[string]cacheEntry{}
	}

	var re *regexp.Regexp
	reStr, err := translate(pat)
	if err == nil {
		re, err = regexp.Compile(reStr)
	}

	c.cache[pat] = cacheEntry{re, err}
	return re, err
}

// translate converts glob pattern to a regular expression string.
func translate(pat string) (string, error) {
	res := "^"
	for _, runeVal := range pat {
		switch runeVal {
		case '\n':
			return "", fmt.Errorf("new lines are not supported in globs")
		case '*':
			res += ".*"
		default:
			res += regexp.QuoteMeta(string(runeVal))
		}
	}
	return res + "$", nil
}


text:
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Moq;
using NPoco;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Sync;
using Umbraco.Cms.Infrastructure.Persistence;
using Umbraco.Cms.Infrastructure.Telemetry.Providers;

namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Telemetry;

[TestFixture]
public class SystemInformationTelemetryProviderTests
{
    [Test]
    [TestCase(ModelsMode.Nothing)]
    [TestCase(ModelsMode.InMemoryAuto)]
    [TestCase(ModelsMode.SourceCodeAuto)]
    [TestCase(ModelsMode.SourceCodeManual)]
    public void ReportsModelsModeCorrectly(ModelsMode modelsMode)
    {
        var telemetryProvider = CreateProvider(modelsMode);
        var usageInformation = telemetryProvider.GetInformation().ToArray();

        var actual = usageInformation.FirstOrDefault(x => x.Name == Constants.Telemetry.ModelsBuilderMode);
        Assert.IsNotNull(actual?.Data);
        Assert.AreEqual(modelsMode.ToString(), actual.Data);
    }

    [Test]
    [TestCase(true)]
    [TestCase(false)]
    public void ReportsDebugModeCorrectly(bool isDebug)
    {
        var telemetryProvider = CreateProvider(isDebug: isDebug);
        var usageInformation = telemetryProvider.GetInformation().ToArray();

        var actual = usageInformation.FirstOrDefault(x => x.Name == Constants.Telemetry.IsDebug);
        Assert.IsNotNull(actual?.Data);
        Assert.AreEqual(isDebug, actual.Data);
    }

    [Test]
    [TestCase("en-US")]
    [TestCase("de-DE")]
    [TestCase("en-NZ")]
    [TestCase("sv-SE")]
    public void ReportsOsLanguageCorrectly(string culture)
    {
        Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
        var telemetryProvider = CreateProvider();

        var usageInformation = telemetryProvider.GetInformation().ToArray();
        var actual = usageInformation.FirstOrDefault(x => x.Name == Constants.Telemetry.OsLanguage);

        Assert.NotNull(actual?.Data);
        Assert.AreEqual(culture, actual.Data.ToString());
    }

    [Test]
    [TestCase(GlobalSettings.StaticUmbracoPath, false)]
    [TestCase("mycustompath", true)]
    [TestCase("~/notUmbraco", true)]
    [TestCase("/umbraco", true)]
    [TestCase("umbraco", true)]
    public void ReportsCustomUmbracoPathCorrectly(string path, bool isCustom)
    {
        var telemetryProvider = CreateProvider(umbracoPath: path);

        var usageInformation = telemetryProvider.GetInformation().ToArray();
        var actual = usageInformation.FirstOrDefault(x => x.Name == Constants.Telemetry.CustomUmbracoPath);

        Assert.NotNull(actual?.Data);
        Assert.AreEqual(isCustom, actual.Data);
    }

    [Test]
    [TestCase("Development")]
    [TestCase("Staging")]
    [TestCase("Production")]
    public void ReportsCorrectAspEnvironment(string environment)
    {
        var telemetryProvider = CreateProvider(environment: environment);

        var usageInformation = telemetryProvider.GetInformation().ToArray();
        var actual = usageInformation.FirstOrDefault(x => x.Name == Constants.Telemetry.AspEnvironment);

        Assert.NotNull(actual?.Data);
        Assert.AreEqual(environment, actual.Data);
    }

    private SystemInformationTelemetryProvider CreateProvider(
        ModelsMode modelsMode = ModelsMode.InMemoryAuto,
        bool isDebug = true,
        string umbracoPath = "",
        string environment = "")
    {
        var hostEnvironment = new Mock<IHostEnvironment>();
        hostEnvironment.Setup(x => x.EnvironmentName).Returns(environment);

        var databaseMock = new Mock<IUmbracoDatabase>();
        databaseMock.Setup(x => x.DatabaseType.GetProviderName()).Returns("SQL");

        return new SystemInformationTelemetryProvider(
            Mock.Of<IUmbracoVersion>(),
            Mock.Of<ILocalizationService>(),
            Mock.Of<IOptionsMonitor<ModelsBuilderSettings>>(x => x.CurrentValue == new ModelsBuilderSettings{ ModelsMode = modelsMode }),
            Mock.Of<IOptionsMonitor<HostingSettings>>(x => x.CurrentValue == new HostingSettings { Debug = isDebug }),
            Mock.Of<IOptionsMonitor<GlobalSettings>>(x => x.CurrentValue == new GlobalSettings { UmbracoPath = umbracoPath }),
            hostEnvironment.Object,
            Mock.Of<IUmbracoDatabaseFactory>(x => x.CreateDatabase() == Mock.Of<IUmbracoDatabase>(y => y.DatabaseType == DatabaseType.SQLite)),
            Mock.Of<IServerRoleAccessor>());
    }
}


text:
opal_filter "language" do
  fails "The alias keyword operates on the object's metaclass when used in instance_eval"
  fails "The alias keyword operates on methods defined via attr, attr_reader, and attr_accessor"
  fails "The alias keyword operates on methods with splat arguments defined in a superclass using text block for class eval"
  fails "The alias keyword is not allowed against Fixnum or String instances"

  fails "The unpacking splat operator (*) when applied to a non-Array value attempts to coerce it to Array if the object respond_to?(:to_a)"
  fails "The unpacking splat operator (*) unpacks arguments as if they were listed statically"

  fails "The BEGIN keyword runs in a shared scope"
  fails "The BEGIN keyword accesses variables outside the eval scope"
  fails "The BEGIN keyword must appear in a top-level context"
  fails "The BEGIN keyword runs first in a given code unit"
  fails "The BEGIN keyword runs multiple begins in FIFO order"

  fails "A block allows for a leading space before the arguments"
  fails "A block taking |a, b| arguments calls #to_ary to convert a single yielded object to an Array"
  fails "A block taking |a, b| arguments raises an TypeError if #to_ary does not return an Array"
  fails "A block taking |a, *b| arguments calls #to_ary to convert a single yielded object to an Array"
  fails "A block taking |a, *b| arguments raises an TypeError if #to_ary does not return an Array"
  fails "A block taking |*| arguments does not raise an exception when no values are yielded"
  fails "A block taking |*| arguments does not raise an exception when values are yielded"
  fails "A block taking |*| arguments does not call #to_ary if the object does not respond to #to_ary"
  fails "A block taking |a, | arguments assigns nil to the argument when no values are yielded"
  fails "A block taking |a, | arguments assgins the argument a single value yielded"
  fails "A block taking |a, | arguments assigns the argument the first value yielded"
  fails "A block taking |a, | arguments assigns the argument the first of several values yielded when it is an Array"
  fails "A block taking |a, | arguments assigns nil to the argument when passed an empty Array"
  fails "A block taking |a, | arguments assigns the argument the first element of the Array when passed a single Array"
  fails "A block taking |a, | arguments calls #to_ary to convert a single yielded object to an Array"
  fails "A block taking |a, | arguments does not call #to_ary if the single yielded object is an Array"
  fails "A block taking |a, | arguments does not call #to_ary if the object does not respond to #to_ary"
  fails "A block taking |a, | arguments raises an TypeError if #to_ary does not return an Array"
  fails "A block taking |(a, b)| arguments calls #to_ary to convert a single yielded object to an Array"
  fails "A block taking |(a, b)| arguments raises an TypeError if #to_ary does not return an Array"
  fails "A block taking |(a, b), c| arguments assigns nil to the arguments when yielded no values"
  fails "A block taking |(a, b), c| arguments destructures a single one-level Array value yielded"
  fails "A block taking |(a, b), c| arguments calls #to_ary to convert a single yielded object to an Array"
  fails "A block taking |(a, b), c| arguments does not call #to_ary if the single yielded object is an Array"
  fails "A block taking |(a, b), c| arguments does not call #to_ary if the object does not respond to #to_ary"
  fails "A block taking |(a, b), c| arguments raises an TypeError if #to_ary does not return an Array"
  fails "A block taking nested |a, (b, (c, d))| assigns nil to the arguments when yielded no values"
  fails "A block taking nested |a, (b, (c, d))| destructures separate yielded values"
  fails "A block taking nested |a, (b, (c, d))| destructures a single multi-level Array value yielded"
  fails "A block taking nested |a, (b, (c, d))| destructures a single multi-level Array value yielded"
  fails "A block taking nested |a, ((b, c), d)| assigns nil to the arguments when yielded no values"
  fails "A block taking nested |a, ((b, c), d)| destructures separate yielded values"
  fails "A block taking nested |a, ((b, c), d)| destructures a single multi-level Array value yielded"
  fails "A block taking nested |a, ((b, c), d)| destructures a single multi-level Array value yielded"

  fails "A class variable defined in a module is not defined in these classes"
  fails "A class variable defined in a module is only updated in the module a method defined in the module is used"
  fails "A class variable defined in a module is updated in the class when a Method defined in the class is used"
  fails "A class variable defined in a module can be accessed inside the class using the module methods"
  fails "A class variable defined in a module is defined in the extended module"
  fails "A class variable defined in a module is not defined in the extending module"
  fails "A class variable defined in a module can be accessed from classes that extend the module"
  fails "A class variable defined in a module can be accessed from modules that extend the module"

  fails "A class definition raises TypeError if the constant qualifying the class is nil"
  fails "A class definition raises TypeError if any constant qualifying the class is not a Module"
  fails "A class definition allows using self as the superclass if self is a class"
  fails "A class definition raises TypeError if constant given as class name exists and is not a Module"
  fails "A class definition raises a TypeError if inheriting from a metaclass"
  fails "A class definition extending an object (sclass) raises a TypeError when trying to extend numbers"
  fails "A class definition extending an object (sclass) can use return to cause the enclosing method to return"

  fails "An instance method with keyword arguments when there is a single keyword argument raises an argument error when an unknown keyword argument is provided"

  fails "The defined? keyword for a scoped constant returns nil when an undefined constant is scoped to a defined constant"
  fails "The defined? keyword for a top-level scoped constant returns nil when an undefined constant is scoped to a defined constant"
  fails "The defined? keyword for an expression with logical connectives returns nil for an expression with 'not' and an unset instance variable"
  fails "The defined? keyword for an expression with logical connectives returns nil for an expression with 'not' and an unset global variable"
  fails "The defined? keyword for an expression with logical connectives returns nil for an expression with '!' and an unset instance variable"
  fails "The defined? keyword for an expression with logical connectives returns nil for an expression with '!' and an unset global variable"
  fails "The defined? keyword for an expression with logical connectives returns nil for an expression with 'not' and an unset class variable"
  fails "The defined? keyword for an expression with logical connectives returns nil for an expression with '!' and an unset class variable"
  fails "The defined? keyword for loop expressions returns 'expression' for a 'retry' expression"
  fails "The defined? keyword for literals for a literal Array returns nil if one element is not defined"
  fails "The defined? keyword for literals for a literal Array returns nil if all elements are not defined"
  fails "The defined? keyword for variables returns nil for a global variable that has been read but not assigned to"

  fails "An ensure block inside a begin block is executed even when a symbol is thrown in it's corresponding begin block"
  fails "An ensure block inside a method is executed even when a symbol is thrown in the method"

  fails "The if expression with a boolean range ('flip-flop' operator) keeps flip-flops from interfering"
  fails "The if expression with a boolean range ('flip-flop' operator) scopes state by flip-flop"
  fails "The if expression with a boolean range ('flip-flop' operator) evaluates the second conditions lazily with exclusive-end range"
  fails "The if expression with a boolean range ('flip-flop' operator) evaluates the second conditions lazily with inclusive-end range"
  fails "The if expression with a boolean range ('flip-flop' operator) evaluates the first conditions lazily with exclusive-end range"
  fails "The if expression with a boolean range ('flip-flop' operator) evaluates the first conditions lazily with inclusive-end range"
  fails "The if expression with a boolean range ('flip-flop' operator) allows combining two flip-flops"
  fails "The if expression with a boolean range ('flip-flop' operator) mimics a sed conditional with a many-element exclusive-end range"
  fails "The if expression with a boolean range ('flip-flop' operator) mimics a sed conditional with a zero-element exclusive-end range"
  fails "The if expression with a boolean range ('flip-flop' operator) mimics an awk conditional with a many-element inclusive-end range"
  fails "The if expression with a boolean range ('flip-flop' operator) mimics an awk conditional with a single-element inclusive-end range"

  fails "calling methods on the metaclass calls a method defined on the metaclass of the metaclass"
  fails "A constant on a metaclass is not preserved when the object is duped"
  fails "A constant on a metaclass does not appear in the object's class constant list"
  fails "A constant on a metaclass appears in the metaclass constant list"
  fails "A constant on a metaclass raises a NameError for anonymous_module::CONST"
  fails "A constant on a metaclass cannot be accessed via object::CONST"
  fails "A constant on a metaclass is not defined in the metaclass opener's scope"
  fails "A constant on a metaclass is not defined on the object's class"
  fails "self in a metaclass body (class << obj) raises a TypeError for symbols"
  fails "self in a metaclass body (class << obj) raises a TypeError for numbers"

  fails "The or operator has a lower precedence than 'next' in 'next true or false'"

  fails "A method call evaluates block pass after arguments"

  fails "not() returns false if the argument is true"
  fails "not() returns true if the argument is false"
  fails "not() returns true if the argument is nil"

  fails "Operators * / % are left-associative"

  fails "A Proc taking |(a, b)| arguments raises an TypeError if #to_ary does not return an Array"
  fails "A Proc taking |(a, b)| arguments calls #to_ary to convert a single passed object to an Array"
  fails "A Proc taking |(a, b)| arguments destructures a single Array value yielded"
  fails "A Proc taking |(a, b)| arguments raises an ArgumentError when passed no values"
  fails "A Proc taking |a, | arguments does not call #to_ary to convert a single passed object to an Array"
  fails "A Proc taking |a, | arguments does not destructure when passed a single Array"
  fails "A Proc taking |a, | arguments assigns the argument the value passed"
  fails "A Proc taking |a, | arguments raises an ArgumentError when passed more than one value"
  fails "A Proc taking |a, | arguments raises an ArgumentError when passed no values"
  fails "A Proc taking |*| arguments does not call #to_ary to convert a single passed object to an Array"
  fails "A Proc taking |*| arguments does not raise an exception when passed multiple values"
  fails "A Proc taking |*| arguments does not raise an exception when passed no values"
  fails "A Proc taking |a, *b| arguments raises an ArgumentError if passed no values"
  fails "A Proc taking |a, b| arguments does not call #to_ary to convert a single passed object to an Array"
  fails "A Proc taking |a, b| arguments raises an ArgumentError if passed one value"
  fails "A Proc taking |a, b| arguments raises an ArgumentError if passed no values"
  fails "A Proc taking |a| arguments raises an ArgumentError if no value is passed"
  fails "A Proc taking || arguments raises an ArgumentError if a value is passed"
  fails "A Proc taking zero arguments raises an ArgumentErro if a value is passed"

  fails "The redo statement triggers ensure block when re-executing a block"

  fails "The rescue keyword parses  'a += b rescue c' as 'a += (b rescue c)'"
  fails "The rescue keyword will not rescue errors raised in an else block in the rescue block above it"
  fails "The rescue keyword will execute an else block only if no exceptions were raised"

  fails "The retry statement re-executes the closest block"
  fails "The retry statement raises a SyntaxError when used outside of a begin statement"
  fails "The retry keyword inside a begin block's rescue block causes the begin block to be executed again"

  fails "Invoking a method with manditory and optional arguments raises an ArgumentError if too many values are passed"
  fails "Invoking a method with optional arguments raises ArgumentError if extra arguments are passed"
  fails "Invoking a method raises a SyntaxError with both a literal block and an object as block"
  fails "Invoking a method with an object as a block uses 'to_proc' for coercion"

  fails "Instantiating a singleton class raises a TypeError when allocate is called"
  fails "Instantiating a singleton class raises a TypeError when new is called"
  fails "Class methods of a singleton class for a singleton class include class methods of the singleton class of Class"
  fails "Class methods of a singleton class for a class include instance methods of the singleton class of Class"
  fails "Class methods of a singleton class for a class include class methods of Class"
  fails "Instance methods of a singleton class for a singleton class includes instance methods of the singleton class of Class"
  fails "A constant on a singleton class is not preserved when the object is duped"
  fails "A constant on a singleton class does not appear in the object's class constant list"
  fails "A constant on a singleton class raises a NameError for anonymous_module::CONST"
  fails "A constant on a singleton class cannot be accessed via object::CONST"
  fails "A constant on a singleton class is not defined in the singleton class opener's scope"
  fails "A constant on a singleton class is not defined on the object's class"
  fails "A singleton class doesn't have singleton class"
  fails "A singleton class for BasicObject has the proper level of superclass for Class"
  fails "A singleton class for BasicObject has Class as it's superclass"
  fails "A singleton class is a subclass of the same level of superclass's singleton class"
  fails "A singleton class is a subclass of a superclass's singleton class"
  fails "A singleton class is a subclass of the same level of Class's singleton class"
  fails "A singleton class is a subclass of Class's singleton class"
  fails "A singleton class inherits from Class for classes"
  fails "A singleton class raises a TypeError for symbols"
  fails "A singleton class raises a TypeError for Fixnum's"

  fails "The super keyword calls the correct method when the method visibility is modified"
  fails "The super keyword passes along modified rest args when they were originally empty"
  fails "The super keyword passes along modified rest args when they weren't originally empty"
  fails "The super keyword raises an error error when super method does not exist"
  fails "The super keyword raises a RuntimeError when called with implicit arguments from a method defined with define_method"
  fails "The super keyword without explicit arguments passes optional arguments that have a default value"
  fails "The super keyword without explicit arguments passes optional arguments that have a default value but were modified"
  fails "The super keyword without explicit arguments passes optional arguments that have a non-default value but were modified"
  fails "The super keyword without explicit arguments passes rest arguments including any modifications"
  fails "The super keyword without explicit arguments passes arguments and rest arguments including any modifications"

  fails "The until modifier with begin .. end block restart the current iteration without reevaluting condition with redo"
  fails "The until modifier with begin .. end block skips to end of body with next"
  fails "The until modifier with begin .. end block evaluates condition after block execution"
  fails "The until modifier with begin .. end block runs block at least once (even if the expression is true)"
  fails "The until modifier restarts the current iteration without reevaluating condition with redo"
  fails "The until expression restarts the current iteration without reevaluating condition with redo"

  fails "Multiple assignment, array-style returns an array of all rhs values"
  fails "Multiple assignment has the proper return value"
  fails "Multiple assignments with grouping supports multiple levels of nested groupings"
  fails "Multiple assignments with grouping A group on the lhs is considered one position and treats its corresponding rhs position like an Array"
  fails "Operator assignment 'obj[idx] op= expr' returns result of rhs not result of []="
  fails "Operator assignment 'obj[idx] op= expr' handles splat index (idx) arguments with normal arguments"
  fails "Operator assignment 'obj[idx] op= expr' handles multiple splat index (idx) arguments"
  fails "Operator assignment 'obj[idx] op= expr' handles single splat index (idx) arguments"
  fails "Operator assignment 'obj[idx] op= expr' handles empty splat index (idx) arguments"
  fails "Operator assignment 'obj[idx] op= expr' handles complex index (idx) arguments"
  fails "Operator assignment 'obj[idx] op= expr' handles empty index (idx) arguments"
  fails "Conditional operator assignment 'obj[idx] op= expr' uses short-circuit arg evaluation"
  fails "Conditional operator assignment 'obj[idx] op= expr' may not assign at all, depending on the truthiness of lhs"
  fails "Conditional operator assignment 'obj[idx] op= expr' is equivalent to 'obj[idx] op obj[idx] = expr'"
  fails "Unconditional operator assignment 'obj[idx] op= expr' is equivalent to 'obj[idx] = obj[idx] op expr'"
  fails "Conditional operator assignment 'obj.meth op= expr' uses short-circuit arg evaluation"
  fails "Conditional operator assignment 'obj.meth op= expr' may not assign at all, depending on the truthiness of lhs"
  fails "Conditional operator assignment 'var op= expr' uses short-circuit arg evaluation"
  fails "Conditional operator assignment 'var op= expr' may not assign at all, depending on the truthiness of lhs"
  fails "Assigning multiple values allows complex parallel assignment"
  fails "Assigning multiple values calls #to_ary on RHS arg if the corresponding LHS var is a splat"
  fails "Assigning multiple values returns the rhs values used for assignment as an array"

  fails "Basic multiple assignment with a splatted single RHS value does not call #to_a on an Array subclass instance"
  fails "Basic multiple assignment with a splatted single RHS value does not call #to_a on an Array instance"
  fails "Basic multiple assignment with a single RHS value does not call #to_a on an Array subclass instance"
  fails "Basic multiple assignment with a single RHS value does not call #to_ary on an Array subclass instance"
  fails "Basic assignment allows the assignment of the rhs to the lhs using the rhs splat operator"

  fails "The defined? keyword when called with a method name having a module as receiver returns nil if the class is not defined"
  fails "The defined? keyword when called with a method name having a module as receiver returns nil if the subclass is not defined"
  fails "The defined? keyword when called with a method name having a local variable as receiver returns nil if the variable does not exist"
  fails "The defined? keyword when called with a method name having a method call as a receiver returns nil if evaluating the receiver raises an exception"
  fails "The defined? keyword for an expression returns nil for an expression with == and an undefined method"
  fails "The defined? keyword for an expression returns nil for an expression with != and an undefined method"
  fails "The defined? keyword for an expression returns nil for an expression with !~ and an undefined method"
  fails "The defined? keyword for an expression with logical connectives returns nil for an expression with '!' and an undefined method"
  fails "The defined? keyword for an expression with logical connectives returns nil for an expression with 'not' and an undefined method"
  fails "The defined? keyword for an expression with logical connectives does not propagate an exception raised by a method in a 'not' expression"
  fails "The defined? keyword for an expression with logical connectives calls a method in a 'not' expression and returns 'method'"
  fails "The defined? keyword for variables when a String matches a Regexp returns nil for non-captures"
  fails "The defined? keyword for variables when a Regexp matches a String returns nil for non-captures"
  fails "The defined? keyword for a simple constant returns 'constant' when the constant is defined"
  fails "The defined? keyword for a simple constant returns nil when the constant is not defined"
  fails "The defined? keyword for a simple constant does not call Object.const_missing if the constant is not defined"
  fails "The defined? keyword for a simple constant returns 'constant' for an included module"
  fails "The defined? keyword for a simple constant returns 'constant' for a constant defined in an included module"
  fails "The defined? keyword for a scoped constant does not call .const_missing if the constant is not defined"
  fails "The defined? keyword for yield returns nil if no block is passed to a method not taking a block parameter"
  fails "The defined? keyword for yield returns nil if no block is passed to a method taking a block parameter"
  fails "The defined? keyword for super returns nil when a superclass undef's the method"
  fails "The defined? keyword for super for a method taking no arguments returns nil when no superclass method exists"
  fails "The defined? keyword for super for a method taking no arguments returns nil from a block when no superclass method exists"
  fails "The defined? keyword for super for a method taking arguments returns nil when no superclass method exists"
  fails "The defined? keyword for super for a method taking arguments returns nil from a block when no superclass method exists"

  fails "The defined? keyword for super for a method taking no arguments returns nil from a #define_method when no superclass method exists"
  fails "The defined? keyword for super for a method taking no arguments returns nil from a block in a #define_method when no superclass method exists"
  fails "The defined? keyword for super for a method taking arguments returns nil from a #define_method when no superclass method exists"
  fails "The defined? keyword for super for a method taking arguments returns nil from a block in a #define_method when no superclass method exists"

  fails "The __FILE__ pseudo-variable equals the absolute path of a file loaded by an absolute path" # we can't clear $LOADED_FEATURES, should be treated as readonly
  fails "The __FILE__ pseudo-variable equals the absolute path of a file loaded by a relative path" # we can't clear $LOADED_FEATURES, should be treated as readonly

  fails "A number literal can be an integer literal with trailing 'r' to represent a Rational"
  fails "A number literal can be a decimal literal with trailing 'r' to represent a Rational"
  fails "A number literal can be a hexadecimal literal with trailing 'r' to represent a Rational"
  fails "A number literal can be an octal literal with trailing 'r' to represent a Rational"
  fails "A number literal can be a binary literal with trailing 'r' to represent a Rational"
  fails "A number literal can be an integer literal with trailing 'i' to represent a Complex"
  fails "A number literal can be a decimal literal with trailing 'i' to represent a Complex"
  fails "A number literal can be a hexadecimal literal with trailing 'i' to represent a Complex"
  fails "A number literal can be a octal literal with trailing 'i' to represent a Complex"
  fails "A number literal can be a binary literal with trailing 'i' to represent a Complex"
end


text:
using namespace boost;

int main()
{
	// Step 1. An instance of 'io_service' class is required by
	// socket constructor.
	asio::io_service ios;

	// Step 2. Creating an object of 'tcp' class representing
	// a TCP protocol with IPv6 as underlying protocol.
	asio::ip::tcp protocol = asio::ip::tcp::v6();

	// Step 3. Instantiating an acceptor socket object.
	asio::ip::tcp::acceptor acceptor(ios);

	// Used to store information about error that happens
	// while opening the acceptor socket.
	boost::system::error_code ec;

	// Step 4. Opening the acceptor socket.
	acceptor.open(protocol, ec);

	if (ec.value() != 0) {
		// Failed to open the socket.
		std::cout
			<< "Failed to open the acceptor socket!"
			<< "Error code = "
			<< ec.value() << ". Message: " << ec.message();
		return ec.value();
	}

	return 0;
}


text:
<?php
/*
include("header.php");
echo "Here's the database table we're using:
";
echo "";
echo "
You entered: ";
print_r($_POST);
include("footer.php");
*/

$error = 0;

if(empty($_POST[TRAINER_FNAME])){
	$error = 1;
} else if(empty($_POST[AGE]) || ($_POST[AGE] < 1) || ($_POST[AGE] >= 999)){
	$error = 3;
}
//profanity filters
else if(
		   strstr(strtolower($_POST[TRAINER_FNAME]), "penis")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "penis")
		|| strstr(strtolower($_POST[TRAINER_FNAME]), "cunt")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "cunt")
		|| strstr(strtolower($_POST[TRAINER_FNAME]), "shit")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "shit")
		|| strstr(strtolower($_POST[TRAINER_FNAME]), "ass")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "ass")
		|| strstr(strtolower($_POST[TRAINER_FNAME]), "balls")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "balls")
		|| strstr(strtolower($_POST[TRAINER_FNAME]), "cum")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "cum")
		|| strstr(strtolower($_POST[TRAINER_FNAME]), "fuck")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "fuck")
		|| strstr(strtolower($_POST[TRAINER_FNAME]), "vagina")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "vagina")
		|| strstr(strtolower($_POST[TRAINER_FNAME]), "pussy")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "pussy")
		|| strstr(strtolower($_POST[TRAINER_FNAME]), "cock")
		|| strstr(strtolower($_POST[TRAINER_LNAME]), "cock")
		){
	$error = 69;
}

if($error != 0){
header('Location: index.php?error=' . $error);
} else {
include("header.php"); ?>

<?php
$trainer_fname = mysql_real_escape_string($_POST[TRAINER_FNAME]);
$trainer_lname = mysql_real_escape_string($_POST[TRAINER_LNAME]);
$age = mysql_real_escape_string($_POST[AGE]);
$gender = mysql_real_escape_string($_POST[GENDER]);

	$sql="INSERT INTO TRAINER (TRAINER_FNAME, TRAINER_LNAME, AGE, GENDER)
	VALUES ('$trainer_fname','$trainer_lname','$age', '$gender')";

	if (!mysql_query($sql,$mysql_handle)){
		  die('Error: ' . mysql_error());
  	}

	echo "
";
	echo "
Wait, $_POST[TRAINER_FNAME],
it's dangerous out there!
 Assemble your team!

";
	echo "Quick, choose 6 Pokemon for your team!\n";
?>
<form id="TEAM" action="teamform.php" method="POST">
<?php
	for($i=1; $i<=6; $i++){
		$result = mysql_query('SELECT * from POKEMON'); //gotta select 'em all
		echo "Pokemon " . $i . ":";
		echo "<select name=\"PK$i\">\n";
			while ($row = mysql_fetch_assoc($result)) {
			echo "<option value =\"" . $row['ID'] . "\">" . $row['PKMN_NAME'] . "</option>";
		}
		echo "</select>
\n";
	}
?>
<?php echo "<input type=\"hidden\" name=\"TRAINER_ID\" value=\"" . mysql_insert_id() . "\">"; ?>
<input type="submit" value="Submit" />
</form>

<?php
include("footer.php");
}
?>


text:
<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * API.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Payment;

use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\FilesystemCache;
use EasyWeChat\Core\AbstractAPI;
use EasyWeChat\Core\Exception;
use EasyWeChat\Support\Collection;
use EasyWeChat\Support\XML;
use Psr\Http\Message\ResponseInterface;

/**
 * Class API.
 */
class API extends AbstractAPI
{
    /**
     * Merchant instance.
     *
     * @var Merchant
     */
    protected $merchant;

    /**
     * Sandbox box mode.
     *
     * @var bool
     */
    protected $sandboxEnabled = false;

    /**
     * Sandbox sign key.
     *
     * @var string
     */
    protected $sandboxSignKey;

    /**
     * Cache.
     *
     * @var Cache
     */
    protected $cache;

    const API_HOST = 'https://api.mch.weixin.qq.com';

    // api
    const API_PAY_ORDER = '/pay/micropay';
    const API_PREPARE_ORDER = '/pay/unifiedorder';
    const API_QUERY = '/pay/orderquery';
    const API_CLOSE = '/pay/closeorder';
    const API_REVERSE = '/secapi/pay/reverse';
    const API_REFUND = '/secapi/pay/refund';
    const API_QUERY_REFUND = '/pay/refundquery';
    const API_DOWNLOAD_BILL = '/pay/downloadbill';
    const API_REPORT = '/payitil/report';

    const API_URL_SHORTEN = 'https://api.mch.weixin.qq.com/tools/shorturl';
    const API_AUTH_CODE_TO_OPENID = 'https://api.mch.weixin.qq.com/tools/authcodetoopenid';
    const API_SANDBOX_SIGN_KEY = 'https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey';

    // order id types.
    const TRANSACTION_ID = 'transaction_id';
    const OUT_TRADE_NO = 'out_trade_no';
    const OUT_REFUND_NO = 'out_refund_no';
    const REFUND_ID = 'refund_id';

    // bill types.
    const BILL_TYPE_ALL = 'ALL';
    const BILL_TYPE_SUCCESS = 'SUCCESS';
    const BILL_TYPE_REFUND = 'REFUND';
    const BILL_TYPE_REVOKED = 'REVOKED';

    /**
     * API constructor.
     *
     * @param \EasyWeChat\Payment\Merchant   $merchant
     * @param \EasyWeChat\Payment\Cache|null $cache
     */
    public function __construct(Merchant $merchant, Cache $cache = null)
    {
        $this->merchant = $merchant;
        $this->cache = $cache;
    }

    /**
     * Pay the order.
     *
     * @param Order $order
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function pay(Order $order)
    {
        return $this->request($this->wrapApi(self::API_PAY_ORDER), $order->all());
    }

    /**
     * Prepare order to pay.
     *
     * @param Order $order
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function prepare(Order $order)
    {
        $order->notify_url = $order->get('notify_url', $this->merchant->notify_url);
        if (is_null($order->spbill_create_ip)) {
            $order->spbill_create_ip = ($order->trade_type === Order::NATIVE) ? get_server_ip() : get_client_ip();
        }

        return $this->request($this->wrapApi(self::API_PREPARE_ORDER), $order->all());
    }

    /**
     * Query order.
     *
     * @param string $orderNo
     * @param string $type
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function query($orderNo, $type = self::OUT_TRADE_NO)
    {
        $params = [
            $type => $orderNo,
        ];

        return $this->request($this->wrapApi(self::API_QUERY), $params);
    }

    /**
     * Query order by transaction_id.
     *
     * @param string $transactionId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryByTransactionId($transactionId)
    {
        return $this->query($transactionId, self::TRANSACTION_ID);
    }

    /**
     * Close order by out_trade_no.
     *
     * @param $tradeNo
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function close($tradeNo)
    {
        $params = [
            'out_trade_no' => $tradeNo,
        ];

        return $this->request($this->wrapApi(self::API_CLOSE), $params);
    }

    /**
     * Reverse order.
     *
     * @param string $orderNo
     * @param string $type
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function reverse($orderNo, $type = self::OUT_TRADE_NO)
    {
        $params = [
            $type => $orderNo,
        ];

        return $this->safeRequest($this->wrapApi(self::API_REVERSE), $params);
    }

    /**
     * Reverse order by transaction_id.
     *
     * @param int $transactionId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function reverseByTransactionId($transactionId)
    {
        return $this->reverse($transactionId, self::TRANSACTION_ID);
    }

    /**
     * Make a refund request.
     *
     * @param string $orderNo
     * @param float  $totalFee
     * @param float  $refundFee
     * @param string $opUserId
     * @param string $type
     * @param string $refundAccount
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function refund(
        $orderNo,
        $refundNo,
        $totalFee,
        $refundFee = null,
        $opUserId = null,
        $type = self::OUT_TRADE_NO,
        $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS'
        ) {
        $params = [
            $type => $orderNo,
            'out_refund_no' => $refundNo,
            'total_fee' => $totalFee,
            'refund_fee' => $refundFee ?: $totalFee,
            'refund_fee_type' => $this->merchant->fee_type,
            'refund_account' => $refundAccount,
            'op_user_id' => $opUserId ?: $this->merchant->merchant_id,
        ];

        return $this->safeRequest($this->wrapApi(self::API_REFUND), $params);
    }

    /**
     * Refund by transaction id.
     *
     * @param string $orderNo
     * @param float  $totalFee
     * @param float  $refundFee
     * @param string $opUserId
     * @param string $refundAccount
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function refundByTransactionId(
        $orderNo,
        $refundNo,
        $totalFee,
        $refundFee = null,
        $opUserId = null,
        $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS'
        ) {
        return $this->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, self::TRANSACTION_ID, $refundAccount);
    }

    /**
     * Query refund status.
     *
     * @param string $orderNo
     * @param string $type
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryRefund($orderNo, $type = self::OUT_TRADE_NO)
    {
        $params = [
            $type => $orderNo,
        ];

        return $this->request($this->wrapApi(self::API_QUERY_REFUND), $params);
    }

    /**
     * Query refund status by out_refund_no.
     *
     * @param string $refundNo
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryRefundByRefundNo($refundNo)
    {
        return $this->queryRefund($refundNo, self::OUT_REFUND_NO);
    }

    /**
     * Query refund status by transaction_id.
     *
     * @param string $transactionId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryRefundByTransactionId($transactionId)
    {
        return $this->queryRefund($transactionId, self::TRANSACTION_ID);
    }

    /**
     * Query refund status by refund_id.
     *
     * @param string $refundId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function queryRefundByRefundId($refundId)
    {
        return $this->queryRefund($refundId, self::REFUND_ID);
    }

    /**
     * Download bill history as a table file.
     *
     * @param string $date
     * @param string $type
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function downloadBill($date, $type = self::BILL_TYPE_ALL)
    {
        $params = [
            'bill_date' => $date,
            'bill_type' => $type,
        ];

        return $this->request($this->wrapApi(self::API_DOWNLOAD_BILL), $params, 'post', [\GuzzleHttp\RequestOptions::STREAM => true], true)->getBody();
    }

    /**
     * Convert long url to short url.
     *
     * @param string $url
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function urlShorten($url)
    {
        return $this->request(self::API_URL_SHORTEN, ['long_url' => $url]);
    }

    /**
     * Report API status to WeChat.
     *
     * @param string $api
     * @param int    $timeConsuming
     * @param string $resultCode
     * @param string $returnCode
     * @param array  $other         ex: err_code,err_code_des,out_trade_no,user_ip...
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function report($api, $timeConsuming, $resultCode, $returnCode, array $other = [])
    {
        $params = array_merge([
            'interface_url' => $api,
            'execute_time_' => $timeConsuming,
            'return_code' => $returnCode,
            'return_msg' => null,
            'result_code' => $resultCode,
            'user_ip' => get_client_ip(),
            'time' => time(),
        ], $other);

        return $this->request($this->wrapApi(self::API_REPORT), $params);
    }

    /**
     * Get openid by auth code.
     *
     * @param string $authCode
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function authCodeToOpenId($authCode)
    {
        return $this->request(self::API_AUTH_CODE_TO_OPENID, ['auth_code' => $authCode]);
    }

    /**
     * Merchant setter.
     *
     * @param Merchant $merchant
     *
     * @return $this
     */
    public function setMerchant(Merchant $merchant)
    {
        $this->merchant = $merchant;
    }

    /**
     * Merchant getter.
     *
     * @return Merchant
     */
    public function getMerchant()
    {
        return $this->merchant;
    }

    /**
     * Set sandbox mode.
     *
     * @param bool $enabled
     *
     * @return $this
     */
    public function sandboxMode($enabled = false)
    {
        $this->sandboxEnabled = $enabled;

        return $this;
    }

    /**
     * Make a API request.
     *
     * @param string $api
     * @param array  $params
     * @param string $method
     * @param array  $options
     * @param bool   $returnResponse
     *
     * @return \EasyWeChat\Support\Collection|\Psr\Http\Message\ResponseInterface
     */
    protected function request($api, array $params, $method = 'post', array $options = [], $returnResponse = false)
    {
        $params = array_merge($params, $this->merchant->only(['sub_appid', 'sub_mch_id']));

        $params['appid'] = $this->merchant->app_id;
        $params['mch_id'] = $this->merchant->merchant_id;
        $params['device_info'] = $this->merchant->device_info;
        $params['nonce_str'] = uniqid();
        $params = array_filter($params);

        $params['sign'] = generate_sign($params, $this->getSignkey($api), 'md5');

        $options = array_merge([
            'body' => XML::build($params),
        ], $options);

        $response = $this->getHttp()->request($api, $method, $options);

        return $returnResponse ? $response : $this->parseResponse($response);
    }

    /**
     * Return key to sign.
     *
     * @param string $api
     *
     * @return string
     */
    protected function getSignkey($api)
    {
        return $this->sandboxEnabled && $api !== self::API_SANDBOX_SIGN_KEY ? $this->getSandboxSignKey() : $this->merchant->key;
    }

    /**
     * Request with SSL.
     *
     * @param string $api
     * @param array  $params
     * @param string $method
     *
     * @return \EasyWeChat\Support\Collection
     */
    protected function safeRequest($api, array $params, $method = 'post')
    {
        $options = [
            'cert' => $this->merchant->get('cert_path'),
            'ssl_key' => $this->merchant->get('key_path'),
        ];

        return $this->request($api, $params, $method, $options);
    }

    /**
     * Parse Response XML to array.
     *
     * @param ResponseInterface $response
     *
     * @return \EasyWeChat\Support\Collection
     */
    protected function parseResponse($response)
    {
        if ($response instanceof ResponseInterface) {
            $response = $response->getBody();
        }

        return new Collection((array) XML::parse($response));
    }

    /**
     * Wrap API.
     *
     * @param string $resource
     *
     * @return string
     */
    protected function wrapApi($resource)
    {
        return self::API_HOST.($this->sandboxEnabled ? '/sandboxnew' : '').$resource;
    }

    /**
     * Get sandbox sign key.
     *
     * @return string
     */
    protected function getSandboxSignKey()
    {
        if ($this->sandboxSignKey) {
            return $this->sandboxSignKey;
        }

        // Try to get sandbox_signkey from cache
        $cacheKey = 'sandbox_signkey.'.$this->merchant->merchant_id.$this->merchant->sub_merchant_id;

        /** @var \Doctrine\Common\Cache\Cache $cache */
        $cache = $this->getCache();

        $this->sandboxSignKey = $cache->fetch($cacheKey);

        if (!$this->sandboxSignKey) {
            // Try to acquire a new sandbox_signkey from WeChat
            $result = $this->request(self::API_SANDBOX_SIGN_KEY, []);

            if ($result->return_code === 'SUCCESS') {
                $cache->save($cacheKey, $result->sandbox_signkey, 24 * 3600);

                return $this->sandboxSignKey = $result->sandbox_signkey;
            }

            throw new Exception($result->return_msg);
        }

        return $this->sandboxSignKey;
    }

    /**
     * Return the cache manager.
     *
     * @return \Doctrine\Common\Cache\Cache
     */
    public function getCache()
    {
        return $this->cache ?: $this->cache = new FilesystemCache(sys_get_temp_dir());
    }
}


text:
legal docs for programmatic use

## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@losslessone_private/lodat-legal)
* [gitlab.com (source)](https://gitlab.com/losslessone/npm/lodat-legal)
* [github.com (source mirror)](https://github.com/losslessone/npm/lodat-legal)
* [docs (typedoc)](https://losslessone/npm.gitlab.io/lodat-legal/)

## Status for master
[![build status](https://gitlab.com/losslessone/npm/lodat-legal/badges/master/build.svg)](https://gitlab.com/losslessone/npm/lodat-legal/commits/master)
[![coverage report](https://gitlab.com/losslessone/npm/lodat-legal/badges/master/coverage.svg)](https://gitlab.com/losslessone/npm/lodat-legal/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@losslessone_private/lodat-legal.svg)](https://www.npmjs.com/package/@losslessone_private/lodat-legal)
[![Known Vulnerabilities](https://snyk.io/test/npm/@losslessone_private/lodat-legal/badge.svg)](https://snyk.io/test/npm/@losslessone_private/lodat-legal)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)

## Usage

```javascript
```

For exact usage refer to the [legal](https://www.npmjs.com/package/legal) package on npm

For further information read the linked docs at the top of this readme.

> UNLICENSED licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)

[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)


text:
import java.text.DecimalFormat;
import java.util.Scanner;

public class Fibonacci {
    private static long Fibo(int n) { // calculates nth fibonacci
    // number
        long result;
        if (n == 1)
            result = 0;
        else if (n == 2)
            result = 1;
        else
            result = Fibo(n - 1) + Fibo(n - 2);

        return result;
    }

    public static void main(String[] args) {
        Scanner mySc = new Scanner(System.in);

        System.out.println("Which Fibonacci number do you want? Enter 1, " +
                "2, ... :");
        int n = mySc.nextInt();

        DecimalFormat myForm = new DecimalFormat("###,###,###,###");
        System.out.println(n + "th Fibonacci number is: " + myForm.format
                (Fibo(n)) + ".");
    }
}


text: export * from './api';


text:
package com.iggroup.api.sample.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
@Slf4j
public class ApplicationConfiguration {

   @Bean
   public RestTemplate restTemplate() {
      HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
      requestFactory.setHttpClient(HttpClients.createDefault());
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.setRequestFactory(requestFactory);
      return restTemplate;
   }

   @Bean
   @Qualifier(value = "redirect.base.url")
   public String redirectUrl(Environment env) throws UnknownHostException {
      String redirectServerUrl = env.getProperty("redirect.server.url");
      String serverPort = env.getProperty("server.port");
      String contextPath = env.getProperty("server.context-path");
      String redirectBaseUrl =  (StringUtils.isNotBlank(redirectServerUrl) ? redirectServerUrl : "http://" + InetAddress.getLocalHost().getHostName() + ":" + serverPort) + contextPath;
      log.info("Server redirectBaseUrl={}", redirectBaseUrl);
      return redirectBaseUrl;
   }

}


text:
import {Headers} from 'j0';
export default function parseHeaders(rawHeaders) {
    const headers = new Headers();
    // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
    // https://tools.ietf.org/html/rfc7230#section-3.2
    const preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/, ' ');
    for (const line of preProcessedHeaders.split(/\r?\n/)) {
        const [key, ...parts] = line.split(':');
        if (key) {
            headers.append(key.trim(), parts.join(':').trim());
        }
    }
    return headers;
}


text:
"use strict"
var schedule = require('node-schedule');
var dateutils = require('./utils/time_utils.js');
var health_check = require('./health_check.js');
var firebase = require('firebase');
firebase.initializeApp({
  serviceAccount: "credentials.json",
  databaseURL: "https://sgdq-backend.firebaseio.com"
});
var ref = firebase.database().ref();
var gcloud = require('gcloud')({
  projectId: 'sgdq-backend',
  keyFilename: './credentials.json'
});

var bucket = gcloud.storage().bucket('sgdq-backend.appspot.com');

function doUpload(data) {
  var timestamp = dateutils.getTimeStamp();
  var timestamp_str = (new Date(timestamp)).toString();
  var file = bucket.file(timestamp_str + '.json');
  var latest = bucket.file('latest.json');

  var options = {
    metadata: { contentType: 'application/json'},
    // Should be public
    public: true
  };

  // Save new file to bucket
  file.save(JSON.stringify(data), options, function(err){
    if(err) console.log(err);
    else{
      console.log("[Storage Link] Upload successful.")
      // Delete old 'latest.json'
      latest.delete(function(err){
        if(err) console.log(err);
        else{
          console.log("[Storage Link] Deletion successful.")
          // Copy new upload to 'latest.json'
          file.copy('latest.json', function(err, copiedFile){
            if(err) console.log(err);
            else {
              copiedFile.makePublic();
              console.log("[Storage Link] Copy successful.")
            }
            // Only keep every 10th backup to prevent insanity
            if((new Date(timestamp)).getMinutes() % 10 != 0) {
              file.delete(function(err) { if(err) console.log(err); });
            }
          });
        }
      });
    }
  });
}

function onSchedule() {
  var timestamp = dateutils.getTimeStamp();
  console.log((new Date(timestamp)).toString() + " - Creating backup");
  ref.once("value", function(data){
    data = data.val();
    // Do file upload and then health check
    doUpload(data);
    health_check.check(data);
  });
}

console.log("*[Storage Link] Started.")
schedule.scheduleJob({second: (new Date()).getSeconds()}, function(){
  onSchedule();
});

if (require.main === module) {
  onSchedule();
}


text:
package org.neo4j.kernel.ha;

import org.neo4j.com.RequestContext;
import org.neo4j.com.Response;
import org.neo4j.kernel.ha.com.RequestContextFactory;
import org.neo4j.kernel.ha.com.master.Master;

public class SlavePropertyTokenCreator extends AbstractTokenCreator
{
    public SlavePropertyTokenCreator( Master master, RequestContextFactory requestContextFactory )
    {
        super( master, requestContextFactory );
    }

    @Override
    protected Response<Integer> create( Master master, RequestContext context, String name )
    {
        return master.createPropertyKey( context, name );
    }
}


text:
<CommandApplication name="demoApp">
	<Command name="help" class="com.icedeer.common.cmd.ext.HelpCommand" index="2"/>
	<Command name="hello" class="com.icedeer.common.cmd.demo.HelloCommand" index="1">
		<Option name="name" index="1" desc="You name" mandatory="true" hasValue="true"/>
		<Option name="country" index="2" desc="from which country" mandatory="false" hasValue="true">
			<Value defaut="true">Canada</Value>
			<Value>US</Value>
		</Option>
	</Command>
</CommandApplication>


text:
package org.apache.lucene.gdata.storage.lucenestorage.recover;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import junit.framework.TestCase;

import org.apache.lucene.gdata.data.ServerBaseEntry;
import org.apache.lucene.gdata.server.registry.GDataServerRegistry;
import org.apache.lucene.gdata.storage.StorageException;
import org.apache.lucene.gdata.storage.lucenestorage.StorageEntryWrapper;
import org.apache.lucene.gdata.storage.lucenestorage.StorageModifierStub;
import org.apache.lucene.gdata.storage.lucenestorage.StorageEntryWrapper.StorageOperation;
import org.apache.lucene.gdata.utils.ProvidedServiceStub;

import com.google.gdata.data.DateTime;

public class TestRecoverController extends TestCase {
    private RecoverController writeController;
    private RecoverController readController;
    private File recDir;
    private String feedId = "feedid";
    private String entryId = "entryId";

    protected void setUp() throws Exception {
        this.recDir = new File("unittest"+System.currentTimeMillis());
        if(!this.recDir.exists())
            this.recDir.mkdir();
        this.recDir.deleteOnExit();
        GDataServerRegistry.getRegistry().registerService(new ProvidedServiceStub());
        this.writeController = new RecoverController(this.recDir,false,true);
        this.readController = new RecoverController(this.recDir,true,true);

    }

    protected void tearDown() throws Exception {

        File[] files = this.recDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            files[i].delete();
        }
        this.recDir.delete();
      GDataServerRegistry.getRegistry().destroy();
    }

    /*
     * Test method for 'org.apache.lucene.gdata.storage.lucenestorage.recover.RecoverController.storageModified(StorageEntryWrapper)'
     */
    public void testStorageModified() throws IOException, RecoverException {
        this.writeController.initialize();
        ServerBaseEntry entry = new ServerBaseEntry();
        entry.setFeedId(this.feedId);
        entry.setId(entryId);
        entry.setUpdated(DateTime.now());
        entry.setServiceConfig(new ProvidedServiceStub());
        StorageEntryWrapper wrapper = new StorageEntryWrapper(entry,StorageOperation.INSERT);
        this.writeController.storageModified(wrapper);
        assertEquals(1,this.recDir.listFiles().length);
        this.writeController.destroy();
    }

    /*
     * Test method for 'org.apache.lucene.gdata.storage.lucenestorage.recover.RecoverController.recoverEntries(StorageModifier)'
     */
    public void testRecoverEntries() throws IOException, StorageException, RecoverException {
        testStorageModified();

        int length = this.recDir.listFiles().length;
        assertEquals(1,length);

        this.readController.initialize();
        try{
        this.readController.recoverEntries(new StorageModifierStub(null,null,null,0,0));
        }catch (Exception e) {
            fail("unexpected exception"+e.getMessage());
        }
        this.readController.destroy();
        assertEquals(1,this.recDir.listFiles().length);

        createCorruptedFile();
        this.readController.initialize();
        try{
        this.readController.recoverEntries(new StorageModifierStub(null,null,null,0,0));
        }catch (Exception e) {
            fail("unexpected exception"+e.getMessage());
        }
        this.readController.destroy();
        assertEquals(2,this.recDir.listFiles().length);
    }

    private void createCorruptedFile() throws IOException{
        File file = new File(this.recDir,"somefile.rec");
        file.deleteOnExit();
        FileWriter writer = new FileWriter(file);
        writer.write("someString\nSomeOtherString");
        writer.close();
    }

}


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))

begin
  require 'rails'
rescue LoadError
end

require 'bundler/setup'
Bundler.require

require 'database_cleaner'

# Simulate a gem providing a subclass of ActiveRecord::Base before the Railtie is loaded.
require 'fake_gem' if defined? ActiveRecord

if defined? Rails
  require 'fake_app/rails_app'

  require 'rspec/rails'
end
if defined? Sinatra
  require 'spec_helper_for_sinatra'
end

# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rr
end


text:
using System;
using System.IO;
using ZKWebStandard.Extensions;
using ZKWebStandard.Web;
using ZKWebStandard.Utils;

namespace ZKWeb.Web.ActionResults
{
    ///
    /// File result

    /// 文件结果, 此类已经过时, 请使用FileEntryResult

    ///
    [Obsolete("Please use FileEntryResult")]
    public class FileResult : IActionResult
    {
        ///
        /// File path

        /// 文件路径

        ///
        public string FilePath { get; set; }
        ///
        /// Cached modify time received from client

        /// 客户端缓存的内容的修改时间

        ///
        public DateTime? IfModifiedSince { get; set; }

        ///
        /// Initialize

        /// 初始化

        ///
        /// <param name="path">File path</param>
        /// <param name="ifModifiedSince">Cached modify time received from client</param>
        public FileResult(string path, DateTime? ifModifiedSince = null)
        {
            FilePath = path;
            IfModifiedSince = ifModifiedSince;
        }

        ///
        /// Write file to http response

        /// Return 304 If the file is not modified after the client caches it

        /// 写入文件到http回应

        /// 如果文件与客户端缓存的内容一致则返回304

        ///
        /// <param name="response">Http Reponse</param>
        public void WriteResponse(IHttpResponse response)
        {
            // Set last modified time
            var lastModified = File.GetLastWriteTimeUtc(FilePath).Truncate();
            response.SetLastModified(lastModified);
            // Set mime
            response.ContentType = MimeUtils.GetMimeType(FilePath);
            // If file not modified, return 304
            if (IfModifiedSince != null && IfModifiedSince == lastModified)
            {
                response.StatusCode = 304;
                return;
            }
            // Write file to http response
            response.StatusCode = 200;
            response.WriteFile(FilePath);
        }
    }
}


text:
"""
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its zigzag level order traversal as:
[
  [3],
  [20,9],
  [15,7]
]
"""

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def zigzagLevelOrder(self, root):
        ret = []
        if root is None:
            return ret
        queue = [root, None]
        res = []
        zig = False                     # Because we start from very root, so no reverse at that point
        while len(queue) > 0:
            node = queue.pop(0)
            if node is None:
                if zig:
                    ret.append(res[::-1])
                else:
                    ret.append(res[:])
                res = []
                if len(queue) == 0:     # Break here, otherwise will append another None
                    break
                zig = not zig
                queue.append(None)
            else:
                res.append(node.val)    # Remember this, need to do this in node, not node.left/right
                if node.left is not None:
                    queue.append(node.left)
                if node.right is not None:
                    queue.append(node.right)
        return ret


text:
package esride.opendatabridge.agolclient;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import esride.opendatabridge.httptransport.HTTPRequest;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * Class which implements the Generate Token Request.
 * See API details for a better parameter understanding here: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Generate_Token/02r3000000m5000000/
 * User: Markus Stecker, con terra GmbH
 * Date: 04.12.13
 * Time: 17:13
 */
public class AgolGenerateTokenRequest {

    private static Logger sLogger = Logger.getLogger(AgolGenerateTokenRequest.class);

    private static final String usernameParam = "username";
    private String usernameValue;

    private static final String passwdParam = "password";
    private String passwordValue;

    private static final String refererParam = "referer";
    private String refererValue;
    private static final String refererValueDefault = "http://www.esri.com";

    private static final String formatParam = "f";
    private static final String jsonFormatValueDefault = "json";

    private String url;

    public AgolGenerateTokenRequest(String pUsernameValue, String pPasswordValue, String pRefererValue, String pUrl) {
        if (sLogger.isDebugEnabled()) {
            sLogger.debug("Generate Token Request");
            sLogger.debug(usernameParam + ": " + pUsernameValue);
            sLogger.debug("password-Length: " + pPasswordValue.length());
            sLogger.debug(refererParam + ": " + pRefererValue);
            sLogger.debug("URL: " + pUrl);
        }

        if(pUsernameValue == null || pUsernameValue.trim().length() == 0){
            throw new IllegalArgumentException("missing username for token generation");
        }
        usernameValue = pUsernameValue;
        if(pPasswordValue == null || pPasswordValue.trim().length() == 0){
            throw new IllegalArgumentException("missing password for token generation");
        }
        passwordValue = pPasswordValue;

        if(pUrl == null || pUrl.trim().length() == 0){
            throw new IllegalArgumentException("missing url for token generation");
        }
        url = pUrl;
        if(pRefererValue == null){
            refererValue = refererValueDefault;
        }else{
            refererValue = pRefererValue;
        }
        refererValue = pRefererValue;
    }

    public AgolGenerateTokenResponse excReqWithJsonResp(HTTPRequest pHttpRequest, ObjectMapper pObjectMapper) throws IOException {
        HashMap<String, String> agolAttributes = new HashMap<String, String>();
        agolAttributes.put(formatParam, jsonFormatValueDefault);
        agolAttributes.put(usernameParam, usernameValue);
        agolAttributes.put(passwdParam, passwordValue);
        agolAttributes.put(refererParam, refererValue);

        InputStream entities = pHttpRequest.executePostRequest(url, agolAttributes, null);

        if (entities != null)
        {
            JsonNode rootNode = pObjectMapper.readTree(entities);
            JsonNode tokenNode = rootNode.get("token");
            if(tokenNode != null){
                String token = tokenNode.asText();
                Long tokenExpiresLong = rootNode.get("expires").asLong();
                Date resultdate = new Date(tokenExpiresLong);
                if (sLogger.isDebugEnabled()) {
                    sLogger.debug("Generate Token Response");
                    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
                    sLogger.debug("New token created. Expires at " + sdf.format(resultdate) + ".");
                }
                return new AgolGenerateTokenResponse(token, resultdate);
            }
            else{
                sLogger.error("No valid Token found in response: " + rootNode.toString());
                throw new IOException("No response from GenerateToken Request");

            }
        }else{
            throw new IOException("No response from GenerateToken Request");
        }
    }

}


text:
import React from 'react';

import Droppable from '../components/droppable';
import Keys from '../utils/keys';
import {UrlRegex} from '../utils';
require('isomorphic-fetch');

var UploadUrl = '';

class BlockImage extends React.Component {

  constructor(props) {
    super(props);
    this.handleImage = this.handleImage.bind(this);
    this.changeSubtext = this.changeSubtext.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }

  componentDidMount() {
    var content = this.props.content;
    if(!content || content.url === "") {
      React.findDOMNode(this.refs.img).focus();
    }
  }

  handleImage(files) {
    var UploadUrl = this.props.UploadUrl;
    var self = this;
    var file = files[0];
    if(file.type.indexOf("image/") !== 0) {
      alert("Provide a valid image file.");
      return;
    }
    var newContent = {};
    newContent.subtext = this.props.content.subtext;
    if(UploadUrl !== "") {
      var data = new FormData();
      data.append("image", file);
      fetch(UploadUrl, {
        method: 'POST',
        credentials: 'same-origin',
        body: data
      }).then(function(response) {
        if(response.status >= 200 && response.status < 300) {
          return response.json();
        } else {
          var error = new Error(response.statusText);
          error.response = response;
          throw error;
        }
      }).then(function(json) {
        if(json.type && json.type === "success") {
          if(self.props.onContentChanged) {
            newContent.url = json.message;
            self.props.onContentChanged(self.props.position, newContent);
          }
        } else {
          alert('Could not upload.');
        }
      }).catch(function(error) {
        console.error(error);
        alert('Error while uploading. Retry.');
      });
    } else if(this.props.onContentChanged){
      newContent.url = file.preview;
      this.props.onContentChanged(this.props.position, newContent);
    }
  }

  changeSubtext(e) {
    if(this.props.onContentChanged) {
      var newContent = {
        url: this.props.content.url,
        subtext: e.target.value
      };
      //console.log(newContent);
      this.props.onContentChanged(this.props.position, newContent);
    }
  }

  handleKeyPress(e) {
    if(e.which === Keys.ENTER) {
      if(UrlRegex.test(e.target.value)) {
        var newContent = {};
        newContent.subtext = this.props.content.subtext;
        newContent.url = e.target.value;
        if(this.props.onContentChanged) {
          this.props.onContentChanged(this.props.position, newContent);
        }
      } else {
        alert('Enter a valid URL.');
      }
      UrlRegex.lastIndex = 0;
    }
  }

  render() {
    var content = this.props.content;
    if(!content || content.url === "") {
      return (

          <input
            ref="img"
            type="text"
            placeholder="Paste URL of image and press enter"
            onKeyDown={this.handleKeyPress} />
          <Droppable
            onDrop={this.handleImage}>

{this.props.message}

          </Droppable>

      );
    } else {
      return (

          <input
            type="text"
            className="katap-image-subtext"
            placeholder="Image subtext"
            onChange={this.changeSubtext}
            value={content.subtext} />

      );
    }
  }
}

BlockImage.defaultProps = {
  UploadUrl: '',
  message: 'Or Drop image here or click to add.'
};

let Image = {
  Name: 'image',
  React: BlockImage,
  Icon: '',
  Empty: function() {
    return {
      url: '',
      subtext: ''
    };
  },
  Description: 'Image',
  isEmpty: function(content) {
    return (content.url === '');
  }
};

export default Image;