text:
using System;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Xml;
using Umbraco.Core._Legacy.PackageActions;
using Umbraco.Web.Composing;

namespace Umbraco.Web._Legacy.PackageActions
{
    ///
    /// This class implements the IPackageAction Interface, used to execute code when packages are installed.
    /// All IPackageActions only takes a PackageName and a XmlNode as input, and executes based on the data in the xmlnode.
    /// addStringToHtmlElement adds a string to specific HTML element in a specific template, and can either append or prepend it.
    /// It uses the action xml node to do this, exemple action xml node:
    /// <Action runat="install" alias="addStringToHtmlElement" templateAlias="news" htmlElementId="newsSection" position="end"><![CDATA[hello world!]]></action>
    /// The above will add the string "hello world!" to the first html element with the id "newsSection" in the template "news"
    ///
    public class addStringToHtmlElement : IPackageAction
    {
        #region IPackageAction Members

        ///
        /// Executes the specified package action.
        ///
        /// <param name="packageName">Name of the package.</param>
        /// <param name="xmlData">The XML data.</param>
        /// <example>
        ///     <Action runat="install" alias="addStringToHtmlElement" templateAlias="news" htmlElementId="newsSection" position="[beginning/end"><![CDATA[hello world!]]></action>
        /// </example>
        /// <returns>True if executed successfully</returns>
        public bool Execute(string packageName, XmlNode xmlData)
        {

            string templateAlias = xmlData.Attributes["templateAlias"].Value;
            string htmlElementId = xmlData.Attributes["htmlElementId"].Value;
            string position = xmlData.Attributes["position"].Value;
            string value = XmlHelper.GetNodeValue(xmlData);
            var tmp = Current.Services.FileService.GetTemplate(templateAlias);

            value = MasterPageHelper.EnsureMasterPageSyntax(templateAlias, value);

            _addStringToHtmlElement(tmp, value, htmlElementId, position);

            return true;
        }

        ///
        /// Undoes the addStringToHtml Execute() method, by removing the same string from the same template.
        ///
        /// <param name="packageName">Name of the package.</param>
        /// <param name="xmlData">The XML data.</param>
        /// <returns></returns>
        public bool Undo(string packageName, XmlNode xmlData)
        {
            string templateAlias = xmlData.Attributes["templateAlias"].Value;
            string htmlElementId = xmlData.Attributes["htmlElementId"].Value;
            string value = XmlHelper.GetNodeValue(xmlData);
            var tmp = Current.Services.FileService.GetTemplate(templateAlias);

            value = MasterPageHelper.EnsureMasterPageSyntax(templateAlias, value);

            _removeStringFromHtmlElement(tmp, value, htmlElementId);
            return true;
        }

        ///
        /// Action alias.
        ///
        /// <returns></returns>
        public string Alias()
        {
            return "addStringToHtmlElement";
        }

        private void _addStringToHtmlElement(ITemplate tmp, string value, string htmlElementId, string position)
        {
            bool hasAspNetContentBeginning = false;
            string design = "";
            string directive = "";

            if (tmp != null)
            {
                try
                {
                    XmlDocument templateXml = new XmlDocument();
                    templateXml.PreserveWhitespace = true;

                    //Make sure that directive is remove before hacked non html4 compatiple replacement action...
                    design = tmp.Content;

                    splitDesignAndDirective(ref design, ref directive);

                    //making sure that the template xml has a root node...
                    if (string.IsNullOrWhiteSpace(tmp.MasterTemplateAlias) == false)
                        templateXml.LoadXml(PackageHelper.ParseToValidXml(tmp, ref hasAspNetContentBeginning, "<root>" + design + "</root>", true));
                    else
                        templateXml.LoadXml(PackageHelper.ParseToValidXml(tmp, ref hasAspNetContentBeginning, design, true));

                    XmlNode xmlElement = templateXml.SelectSingleNode("//* [@id = '" + htmlElementId + "']");

                    if (xmlElement != null)
                    {

                        if (position == "beginning")
                        {
                            xmlElement.InnerXml = "\n" + PackageHelper.ParseToValidXml(tmp, ref hasAspNetContentBeginning, value, true) + "\n" + xmlElement.InnerXml;
                        }
                        else
                        {
                            xmlElement.InnerXml = xmlElement.InnerXml + "\n" + PackageHelper.ParseToValidXml(tmp, ref hasAspNetContentBeginning, value, true) + "\n";
                        }
                    }

                    tmp.Content = directive + "\n" + PackageHelper.ParseToValidXml(tmp, ref hasAspNetContentBeginning, templateXml.OuterXml, false);
                    Current.Services.FileService.SaveTemplate(tmp);
                }
                catch (Exception ex)
                {
                    Current.Logger.Error<addStringToHtmlElement>(ex, "An error occurred");
                }
            }
            else
            {
                Current.Logger.Debug<addStringToHtmlElement>("template not found");
            }
        }

        private void _removeStringFromHtmlElement(ITemplate tmp, string value, string htmlElementId)
        {
            bool hasAspNetContentBeginning = false;
            string design = "";
            string directive = "";

            if (tmp != null)
            {
                try
                {
                    XmlDocument templateXml = new XmlDocument();
                    templateXml.PreserveWhitespace = true;

                    //Make sure that directive is remove before hacked non html4 compatiple replacement action...
                    design = tmp.Content;
                    splitDesignAndDirective(ref design, ref directive);

                    //making sure that the template xml has a root node...
                    if (string.IsNullOrWhiteSpace(tmp.MasterTemplateAlias) == false)
                        templateXml.LoadXml(PackageHelper.ParseToValidXml(tmp, ref hasAspNetContentBeginning, "<root>" + design + "</root>", true));
                    else
                        templateXml.LoadXml(PackageHelper.ParseToValidXml(tmp, ref hasAspNetContentBeginning, design, true));

                    XmlNode xmlElement = templateXml.SelectSingleNode("//* [@id = '" + htmlElementId + "']");

                    if (xmlElement != null)
                    {
                        string repValue = PackageHelper.ParseToValidXml(tmp, ref hasAspNetContentBeginning, value, true);
                        xmlElement.InnerXml = xmlElement.InnerXml.Replace(repValue, "");
                    }

                    tmp.Content = directive + "\n" + PackageHelper.ParseToValidXml(tmp, ref hasAspNetContentBeginning, templateXml.OuterXml, false);
                    Current.Services.FileService.SaveTemplate(tmp);
                }
                catch (Exception ex)
                {
                    Current.Logger.Error<addStringToHtmlElement>(ex, "An error occurred");
                }
            }
            else
            {
                Current.Logger.Debug<addStringToHtmlElement>("template not found");
            }
        }

        private void splitDesignAndDirective(ref string design, ref string directive)
        {
            if (design.StartsWith("<%@"))
            {
                directive = design.Substring(0, design.IndexOf("%>") + 2).Trim(Environment.NewLine.ToCharArray());
                design = design.Substring(design.IndexOf("%>") + 3).Trim(Environment.NewLine.ToCharArray());
            }
        }

        #endregion

        public XmlNode SampleXml()
        {
            throw new NotImplementedException();
        }

    }
}


text:
//
//  ZTCommonUtils.m
//  Pods
//
//  Created by Adam on 2017/6/15.
//
//

#import "ZTCommonUtils.h"
#import <UIKit/UIDevice.h>
#import "SSZipArchive.h"

@implementation ZTCommonUtils

+ (NSTimeInterval)currentTimeIntervalDouble {

    NSDate *today = [NSDate dateWithTimeIntervalSinceNow:0];
    // 秒.毫秒 1442541004.2110679
    NSTimeInterval interval = [today timeIntervalSince1970];

    return interval;
}

+ (NSString *)currentTimeInterval {

    NSDate *today = [NSDate dateWithTimeIntervalSinceNow:0];
    // 秒.毫秒 1442541004.2110679
    NSTimeInterval interval = [today timeIntervalSince1970];
    NSString *dateInterval = [NSString stringWithFormat:@"%.0f", interval * 1000];

    return dateInterval;
}

+ (NSString *)getCurrentTime {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];

    return dateTime;
}

+ (NSString *)curDateString
{
    NSDate *curDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];

    return [dateFormatter stringFromDate:curDate];
}

+ (NSString *)currentDateStr:(NSString *)strSecs
{

    double secs = strSecs.doubleValue/1000;
    NSDate *today = [NSDate dateWithTimeIntervalSince1970:secs];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSString *dateString = [dateFormat stringFromDate:today];
    dateFormat = nil;

    return dateString;
}

#pragma mark - Param Dict
+ (NSMutableDictionary *)getParamDict:(NSMutableDictionary *)dataDict
{

    if (dataDict != nil) {

        [dataDict setObject:[ZTCommonUtils currentTimeInterval] forKey:@"time"];
    }

    NSMutableDictionary *commonDict = [NSMutableDictionary dictionary];
    [commonDict setObject:@"ios" forKey:@"plat"];
    [commonDict setObject:@"2" forKey:@"interVersion"];
    [dataDict setObject:commonDict forKey:@"common"];

    return dataDict;
}

+ (NSString *)dictToJsonString:(NSMutableDictionary *)dictionary
{
    NSString *backVal = nil;

    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    backVal = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    if (error) {
        NSLog(@"dic->%@",error);
    }

    return backVal;
}

#pragma mark - Common Method
+ (UIColor *)colorWithHexString:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

    if ([cString length] != 6) return  [UIColor grayColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];

    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

#pragma mark - 定宽高度自适应
+ (CGFloat)calcuViewHeight:(NSString *)content font:(UIFont *)font width:(CGFloat)width
{
    CGRect titleSize = [content boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:font} context:nil];

    return titleSize.size.height;
}

+ (CGFloat)calcuViewWidth:(NSString *)content font:(UIFont *)font
{

    // 计算宽度
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
    return [[[NSAttributedString alloc] initWithString:content attributes:attributes] size].width;
}

+ (BOOL)isExistDirName:(NSString *)dirName
{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:dirName
                                        isDirectory:&isDir];

    if(!(isDirExist && isDir))
    {

        return NO;
    }

    return YES;
}

+ (NSMutableArray *)allFilesAtPath:(NSString *)direString
{
    NSMutableArray *pathArray = [NSMutableArray array];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *tempArray = [fileManager contentsOfDirectoryAtPath:direString error:nil];

    for (NSString *fileName in tempArray) {

        BOOL flag = YES;
        NSString *fullPath = [direString stringByAppendingPathComponent:fileName];

        if ([fileManager fileExistsAtPath:fullPath isDirectory:&flag]) {
            if (!flag) {
                // ignore .DS_Store
                if (![[fileName substringToIndex:1] isEqualToString:@"."]) {
                    [pathArray addObject:fullPath];
                }
            } else {
                [pathArray addObject:[self allFilesAtPath:fullPath]];
            }
        }
    }

    return pathArray;
}

+ (BOOL)deleteFile:(NSString *)fileName
{
    if (fileName == nil) {
        return false;
    }

    NSError *error = nil;
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    if (fileManager != nil) {

        BOOL result = [fileManager removeItemAtPath:fileName error:&error];

        if (result != YES) {
            return false;
        }
        return true;
    }

    return false;
}

+ (void)doCopyFile:(NSString *)sourcePath targetPath:(NSString *)targetPath houseId:(NSString *)houseId
{
    // Create target path
    [[NSFileManager defaultManager] createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:NULL];

    // Copy .lf file
    NSError *copyError = nil;

    NSString *sourceFileName = [NSString stringWithFormat:@"%@/%@.lf", sourcePath, houseId];
    NSString *newFileName = [NSString stringWithFormat:@"%@/%@_1.lf", targetPath, houseId];

    if (![[NSFileManager defaultManager] copyItemAtPath:sourceFileName toPath:newFileName error:&copyError]) {
        DLog(@"Copy failure");
    }

}

+ (void)zipFileDir:(NSString *)zipPath sourcePath:(NSString *)sourcePath
{

    // Create
    [SSZipArchive createZipFileAtPath:zipPath withContentsOfDirectory:sourcePath];

    // Unzip
    // [SSZipArchive unzipFileAtPath:zipPath toDestination:unzipPath];
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0678])\\d{8}$";
    /**
     * 中国移动:China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通:China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信:China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    /**
     25     * 大陆地区固话及小灵通
     26     * 区号:010,020,021,022,023,024,025,027,028,029
     27     * 号码:七位或八位
     28     */
    //  NSString * PHS = @"^(0[0-9]{2})\\d{8}$|^(0[0-9]{3}(\\d{7,8}))$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];

    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+ (NSString *)commonMsg
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    // app build版本
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSLog(@"app名称: %@",app_Name);
    NSLog(@"app版本: %@",app_Version);
    NSLog(@"app build版本: %@",app_build);

    //手机序列号
    NSUUID *identifierUUID = [[UIDevice currentDevice] identifierForVendor];
    NSString* identifierNumber = [identifierUUID UUIDString];
    NSLog(@"手机序列号: %@",identifierNumber);
    //手机别名: 用户定义的名称
    NSString* userPhoneName = [[UIDevice currentDevice] name];
    NSLog(@"手机别名: %@", userPhoneName);
    //设备名称
    NSString* deviceName = [[UIDevice currentDevice] systemName];
    NSLog(@"设备名称: %@",deviceName);
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    NSLog(@"手机系统版本: %@", phoneVersion);
    //手机型号
    NSString* phoneModel = [[UIDevice currentDevice] model];
    NSLog(@"手机型号: %@",phoneModel );
    //地方型号  (国际化区域名称)
    NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];
    NSLog(@"国际化区域名称: %@",localPhoneModel );
    // 当前应用名称
    NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    NSLog(@"当前应用名称:%@",appCurName);
    // 当前应用软件版本  比如:1.0.1
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSLog(@"当前应用软件版本:%@",appCurVersion);
    // 当前应用版本号码 int类型
    NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSLog(@"当前应用版本号码:%@",appCurVersionNum);

    return nil;
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
  <DefaultLanguage xmlns="" code="zh-CN" />
  <App xmlns="" ProductID="{c77cac1b-4a63-48d7-8b07-c0340dcd6810}" Title="找厕所" RuntimeType="Silverlight" Version="0.7.1.4" Genre="apps.normal" Author="Eleven Van" Description="寻找公共厕所,解决在外上厕所麻烦的问题。" Publisher="Eleven Van" PublisherID="{100d4b69-ee97-4cba-8e59-15509f0050c9}">
    <IconPath IsRelative="true" IsResource="false">Assets\100x100.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_MEDIALIB_AUDIO" />
      <Capability Name="ID_CAP_SENSORS" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
      <Capability Name="ID_CAP_MAP" />
      <Capability Name="ID_CAP_LOCATION" />
      <Capability Name="ID_CAP_IDENTITY_DEVICE" />
      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
      <Capability Name="ID_CAP_IDENTITY_USER" />
    </Capabilities>
    <Tasks>
      <DefaultTask Name="_default" NavigationPage="MainPage.xaml" ActivationPolicy="Resume" />
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="ToiletToken" TaskName="_default">
        <TemplateFlip>
          <SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\159x159.png</SmallImageURI>
          <Count>0</Count>
          <BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\336x336.png</BackgroundImageURI>
          <Title>Toilet</Title>
          <BackContent>
          </BackContent>
          <BackBackgroundImageURI IsRelative="true" IsResource="false">
          </BackBackgroundImageURI>
          <BackTitle>
          </BackTitle>
          <DeviceLockImageURI IsRelative="true" IsResource="false">
          </DeviceLockImageURI>
          <HasLarge>false</HasLarge>
        </TemplateFlip>
      </PrimaryToken>
    </Tokens>
    <ScreenResolutions>
      <ScreenResolution Name="ID_RESOLUTION_WVGA" />
      <ScreenResolution Name="ID_RESOLUTION_WXGA" />
      <ScreenResolution Name="ID_RESOLUTION_HD720P" />
    </ScreenResolutions>
  </App>
</Deployment>


text:
var util = require('util');

var sprintf = require('./util/sprintf');

function DreadnotError(msg) {
  Error.call(this);
  Error.captureStackTrace(this, this.constructor);
  this.message = msg;
  this.name = 'DreadnotError';
  this.title = 'Error';
}

util.inherits(DreadnotError, Error);

function NotFoundError(msg) {
  DreadnotError.call(this, msg || 'Requested resource not found');
  this.name = 'NotFoundError';
  this.title = 'Not Found';
}

util.inherits(NotFoundError, DreadnotError);

function StackLockedError(deployment) {
  DreadnotError.call(this, sprintf('Stack locked for Deployment #%(name)s of %(stackName)s:%(region)s', deployment));
  this.name = 'StackLockedError';
  this.title = 'Stack Locked';
  this.deployment = deployment;
}

util.inherits(StackLockedError, DreadnotError);

exports.DreadnotError = DreadnotError;
exports.NotFoundError = NotFoundError;
exports.StackLockedError = StackLockedError;


text:
====================
### Indulge Yourself
** Agency theme based on [Agency bootstrap theme ](https://startbootstrap.com/template-overviews/agency/)**


text:
var smoosh = require('smoosh'),
    fs = require('fs');

smoosh.make('config/smoosh.json');

var copyright = fs.readFileSync('./src/copyright.js', 'utf8'),
    qwery = fs.readFileSync('./tmp/qwery.js', 'utf8'),
    qweryMin = fs.readFileSync('tmp/qwery.min.js', 'utf8');

fs.writeFileSync('./qwery.js', [copyright, qwery].join(''), 'utf8');
fs.writeFileSync('./qwery.min.js', [copyright, qweryMin].join(''), 'utf8');


text:
<?php

namespace People\AddressBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PeopleAddressBundle extends Bundle
{
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util" xmlns:sec="http://www.springframework.org/schema/security" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
  <util:list id="unicodeMappings">
    <bean class="com.attivio.platform.transformer.ingest.field.ReplacePatterns$RegexInfo">
      <property name="dotall" value="true"/>
      <property name="input" value="text"/>
      <property name="multiline" value="true"/>
      <property name="output" value="text"/>
      <property name="pattern" value="\uFFFD"/>
      <property name="replace" value=""/>
      <property name="replaceFirstOnly" value="false"/>
    </bean>
  </util:list>
</beans>


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:state_enabled="true" android:color="@color/address_pressed" />
    <item android:color="@color/address"/>
</selector>


text: echo "Successfully executed testinclude1.sh"


text:
$(function () {

    /*  Search Icons Function  */
    if ($('input#member-finder').length) {
        $('input#member-finder').val('').quicksearch('.member-entry');
    }

});


text:
.cm-s-default span.cm-keyword {color: #708;}
.cm-s-default span.cm-atom {color: #219;}
.cm-s-default span.cm-number {color: #164;}
.cm-s-default span.cm-def {color: #00f;}
.cm-s-default span.cm-variable {color: black;}
.cm-s-default span.cm-variable-2 {color: #05a;}
.cm-s-default span.cm-variable-3 {color: #0a5;}
.cm-s-default span.cm-property {color: black;}
.cm-s-default span.cm-operator {color: black;}
.cm-s-default span.cm-comment {color: #a50;}
.cm-s-default span.cm-string {color: #a11;}
.cm-s-default span.cm-string-2 {color: #f50;}
.cm-s-default span.cm-meta {color: #555;}
.cm-s-default span.cm-error {color: #f00;}
.cm-s-default span.cm-qualifier {color: #555;}
.cm-s-default span.cm-builtin {color: #30a;}
.cm-s-default span.cm-bracket {color: #cc7;}
.cm-s-default span.cm-tag {color: #170;}
.cm-s-default span.cm-attribute {color: #00c;}


text:
<?php

namespace M6Web\Bundle\FOSRestExtraBundle\EventListener;

use Doctrine\Common\Annotations\Reader;
use FOS\RestBundle\Request\ParamFetcherInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * This listener handles various setup tasks related to the query fetcher.
 *
 * - Checking the parameters vs request
 */
class ParamFetcherListener
{
    /** @var Reader */
    protected $reader;

    /** @var ParamFetcherInterface */
    protected $paramFetcher;

    /** @var int Error code to return for invalid input */
    protected $errorCode = 400;

    /** @var bool */
    protected $allowExtraParam = true;

    /** @var bool */
    protected $strict = false;

    public function __construct(Reader $reader, ParamFetcherInterface $paramFetcher)
    {
        $this->reader = $reader;
        $this->paramFetcher = $paramFetcher;
    }

    /**
     * @param bool $allow
     *
     * @return ParamFetcherListener
     */
    public function setAllowExtraParam($allow)
    {
        $this->allowExtraParam = $allow;

        return $this;
    }

    /**
     * @param bool $strict
     *
     * @return ParamFetcherListener
     */
    public function setStrict($strict)
    {
        $this->strict = $strict;

        return $this;
    }

    /**
     * Define HTTP status code returned on error
     *
     * @param int $code
     *
     * @return ParamFetcherListener
     */
    public function setErrorCode($code)
    {
        $this->errorCode = $code;

        return $this;
    }

    /**
     * Core controller handler.
     *
     * @throws HttpException
     */
    public function onKernelController(ControllerEvent $event): void
    {
        if ($event->isMasterRequest()) {
            $request = $event->getRequest();
            $paramFetcher = $this->paramFetcher;

            if ($request->attributes->has('paramFetcher')) {
                $paramFetcher = $request->attributes->get('paramFetcher');
            }

            $requestGetParams = $request->query->all();
            $requestPostParams = $request->request->all();

            // Check difference between the paramFetcher and the request
            foreach ([$requestGetParams, $requestPostParams] as $requestParams) {
                try {
                    $invalidParams = array_diff(
                        array_keys($requestParams),
                        array_keys($paramFetcher->all($this->strict))
                    );
                } catch (\RuntimeException $e) {
                    throw new HttpException($this->errorCode, $e->getMessage(), $e);
                }

                if (!empty($invalidParams) && $this->isExtraParametersCheckRequired($event)) {
                    $msg = sprintf(
                        "Invalid parameters '%s' for route '%s'",
                        implode(', ', $invalidParams),
                        $request->attributes->get('_route')
                    );

                    throw new HttpException($this->errorCode, $msg);
                }
            }
        }
    }

    protected function isExtraParametersCheckRequired(ControllerEvent $event): bool
    {
        $controller = $event->getController();

        if (is_callable($controller) && (is_object($controller) || is_string($controller)) && method_exists($controller, '__invoke')) {
            $controller = [$controller, '__invoke'];
        }

        if (is_array($controller)) {
            $annotation = $this->reader->getMethodAnnotation(
                new \ReflectionMethod($controller[0], $controller[1]),
                'M6Web\Bundle\FOSRestExtraBundle\Annotation\RestrictExtraParam'
            );

            if (!is_null($annotation)) {
                return (bool) $annotation->value;
            }
        }

        return !$this->allowExtraParam;
    }
}


text:
      {{ post.title }}

      {{ post.title }}

      {{ post.title }}

      {{ post.title }}

      {{ post.title }}

{{ post.category.name }}

{{ post.user.username }}

{{ post.submitted }}

{{ comment.text }}

{{ comment.user.username }}

{{ comment.submitted | DTSince }}

  <form ng-submit="new_comment_submit()">

      Comment

      <textarea name="title" ng-model="formData.text"></textarea>

    <button type="submit" class="button tiny">Submit</button>
  </form>


text:
import unittest
import glob
import os.path
import test.support
from test.support.script_helper import assert_python_failure

CRASHER_DIR = os.path.join(os.path.dirname(__file__), "crashers")
CRASHER_FILES = os.path.join(glob.escape(CRASHER_DIR), "*.py")

infinite_loops = ["infinite_loop_re.py", "nasty_eq_vs_dict.py"]

class CrasherTest(unittest.TestCase):

    @unittest.skip("these tests are too fragile")
    @test.support.cpython_only
    def test_crashers_crash(self):
        for fname in glob.glob(CRASHER_FILES):
            if os.path.basename(fname) in infinite_loops:
                continue
            # Some "crashers" only trigger an exception rather than a
            # segfault. Consider that an acceptable outcome.
            if test.support.verbose:
                print("Checking crasher:", fname)
            assert_python_failure(fname)

def tearDownModule():
    test.support.reap_children()

if __name__ == "__main__":
    unittest.main()


text:
#import <UIKit/UIKit.h>

typedef void(^ButtonClickedBlock)(void);
typedef void(^CountDownStartBlock)(void);
typedef void(^CountDownUnderwayBlock)(NSInteger restCountDownNum);
typedef void(^CountDownCompletionBlock)(void);

@interface CQCountDownButton : UIButton

/**
 构造方法

 @param duration 倒计时时间
 @param buttonClicked 按钮点击事件的回调
 @param countDownStart 倒计时开始时的回调
 @param countDownUnderway 倒计时进行中的回调(每秒一次)
 @param countDownCompletion 倒计时完成时的回调
 @return 倒计时button
 */
- (instancetype)initWithDuration:(NSInteger)duration
                   buttonClicked:(void(^)(void))buttonClicked
                  countDownStart:(void(^)(void))countDownStart
            countDownUnderway:(void(^)(NSInteger restCountDownNum))countDownUnderway
             countDownCompletion:(void(^)(void))countDownCompletion;

/** 开始倒计时 */
- (void)startCountDown;

@end


text:
<?php
return array(
    '{type} report' => '{type} Report',
    'other' => 'Other',
    'select all' => 'Select All',
    'submit' => 'OK',
    'empty' => '[Empty]',
    '{type} per {group}' => '{type} {group}',
    '{type} {group} per day' => '{type} {group}(Last 90 Days)',
    '{type} {group} per week' => '{type} {group} (Week)',
    '{type} {group} per month' => '{type} {group} (Month)',
    'bug per product' => 'Bug Product',
    'bug per module' => 'Bug Module',
    'bug per status' => 'Bug Status',
    'bug per priority' => 'Bug Priority',
    'bug per severity' => 'Bug Severity',
    'bug per created_by' => 'Bug Created By',
    'bug open per day' => 'Bug Created Date(Last 90 Days)',
    'bug open per week' => 'Bug Created Date(Week)',
    'bug open per month' => 'Bug Created Date(Month)',
    'bug per resolved_by' => 'Bug Resolved By',
    'bug per solution' => 'Bug Resolution',
    'bug resolve per day' => 'Bug Resolved Date(Last 90 Days)',
    'bug resolve per week' => 'Bug Resolved Date(Week)',
    'bug resolve per month' => 'Bug Resolved Date(Month)',
    'bug per closed_by' => 'Bug Closed By',
    'bug close per day' => 'Bug Closed Date(Last 90 Days)',
    'bug close per week' => 'Bug Closed Date(Week)',
    'bug close per month' => 'Bug Closed Date(Month)',
    'bug per assign_to' => 'Bug Assigned To',
    'bug actived per day' => 'Bug Reactivated Date(Last 90 Days)',
    'bug actived per week' => 'Bug Reactivated Date(Week)',
    'bug actived per month' => 'Bug Reactivated Date(Month)',
    'bug per live days' => 'Bug Lifecycle',
    'bug per history' => 'Bug Action Steps',
    '0 days' => '0 day',
    '1 days' => '1 day',
    '2 days' => '2 days',
    '3 days' => '3 days',
    '4 days' => '4 days',
    '5 days' => '5 days',
    '6 days' => '6 days',
    '7 days' => '7 days',
    '1-2 weeks' => '1-2 weeks',
    '2-4 weeks' => '2-4 weeks',
    '1-3 months' => '1-3 months',
    '3-6 months' => '3-6 months',
    'case per product' => 'Case Product',
    'case per module' => 'Case Module',
    'case per status' => 'Case Status',
    'case per priority' => 'Case Priority',
    'case per created_by' => 'Case Created By',
    'case open per day' => 'Case Created Date(Last 90 days)',
    'case open per week' => 'Case Created Date(Week)',
    'case open per month' => 'Case Created Date(Month)',
    'result per product' => 'Result Product',
    'result per module' => 'Result Module',
    'result per value' => 'Result Value',
    'result per status' => 'Result Status',
    'result per created_by' => 'Result Created By',
    'result open per day' => 'Result Created Date(Last 90 Days)',
    'result open per week' => 'Result Created Date(Week)',
    'result open per month' => 'Result Created Date(Month)',
);
?>


text:
#ifndef AliEventPoolManager_h
#define AliEventPoolManager_h

#include <vector>
#include <deque>
#include <Rtypes.h>
#include <TObjArray.h>
#include "AliLog.h"
#include <AliVParticle.h>

/// \class AliEventPoolManager
/// \brief Generic event mixing classes
///
/// Stores a buffer of tracks that updates continuously. The track type
/// contained by the pools can be anything inheriting from
/// TObject. Pools are updated based on maintaining a minimum fixed
/// number of tracks. Multiplicity/centrality and z-vertex bins must be
/// passed in at initialization. For example of implementation, see
/// $ALICE_ROOT/PWGCF/Correlations/DPhi/AliAnalysisTaskPhiCorrelations.cxx
///
/// \author A. Adare and C. Loizides

using std::deque;

class AliEventPool : public TObject
{
 public:
 AliEventPool()
   : fEvents(0),
    fNTracksInEvent(0),
    fEventIndex(0),
    fMixDepth(-1),
    fMultMin(-999),
    fMultMax(+999),
    fZvtxMin(-999),
    fZvtxMax(+999),
    fPsiMin(-999),
    fPsiMax(+999),
    fPtMin(-9999),
    fPtMax(+9999),
    fWasUpdated(0),
    fMultBinIndex(0),
    fZvtxBinIndex(0),
    fPsiBinIndex(0),
    fPtBinIndex(0),
    fDebug(0),
    fTargetTrackDepth(0),
    fFirstFilled(0),
    fLockFlag(0),
    fSaveFlag(0),
    fNTimes(0),
    fTargetFraction(1),
    fTargetEvents(0)  {;} // default constructor needed for correct saving

 AliEventPool(Int_t d)
   : fEvents(0),
    fNTracksInEvent(0),
    fEventIndex(0),
    fMixDepth(d),
    fMultMin(-999),
    fMultMax(+999),
    fZvtxMin(-999),
    fZvtxMax(+999),
    fPsiMin(-999),
    fPsiMax(+999),
    fPtMin(-9999),
    fPtMax(+9999),
    fWasUpdated(0),
    fMultBinIndex(0),
    fZvtxBinIndex(0),
    fPsiBinIndex(0),
    fPtBinIndex(0),
    fDebug(0),
    fTargetTrackDepth(0),
    fFirstFilled(0),
    fLockFlag(0),
    fSaveFlag(0),
    fNTimes(0),
    fTargetFraction(1),
    fTargetEvents(0)  {;}

 AliEventPool(Int_t d, Double_t multMin, Double_t multMax,
        Double_t zvtxMin, Double_t zvtxMax,
        Double_t psiMin=-999., Double_t psiMax=999.,
        Double_t ptMin=-9999., Double_t ptMax=9999.)
   : fEvents(0),
    fNTracksInEvent(0),
    fEventIndex(0),
    fMixDepth(d),
    fMultMin(multMin),
    fMultMax(multMax),
    fZvtxMin(zvtxMin),
    fZvtxMax(zvtxMax),
    fPsiMin(psiMin),
    fPsiMax(psiMax),
    fPtMin(ptMin),
    fPtMax(ptMax),
    fWasUpdated(0),
    fMultBinIndex(0),
    fZvtxBinIndex(0),
    fPsiBinIndex(0),
    fPtBinIndex(0),
    fDebug(0),
    fTargetTrackDepth(0),
    fFirstFilled(0),
    fLockFlag(0),
    fSaveFlag(0),
    fNTimes(0),
    fTargetFraction(1),
    fTargetEvents(0) {;}

  ~AliEventPool() {;}

  Bool_t      EventMatchesBin(Int_t mult,    Double_t zvtx, Double_t psi=0., Double_t pt=0.) const;
  Bool_t      EventMatchesBin(Double_t mult, Double_t zvtx, Double_t psi=0., Double_t pt=0.) const;
  Bool_t      IsReady()                    const { return IsReady(NTracksInPool(), GetCurrentNEvents()); }
  Bool_t      IsFirstReady()               const { return fFirstFilled;   }
  Int_t       GetNTimes()                  const { return fNTimes;        }
  Int_t       GetCurrentNEvents()          const { return fEvents.size(); }
  Int_t       GlobalEventIndex(Int_t j)    const;
  TObject    *GetRandomTrack()             const;
  TObjArray  *GetRandomEvent()             const;
  TObjArray  *GetEvent(Int_t i)            const;
  Int_t       MultBinIndex()               const { return fMultBinIndex; }
  Int_t       NTracksInEvent(Int_t iEvent) const;
  Int_t       NTracksInCurrentEvent()      const { return fNTracksInEvent.back(); }
  void        PrintInfo()                  const;
  Int_t       PsiBinIndex()                const { return fPsiBinIndex; }
  Int_t       PtBinIndex()                 const { return fPtBinIndex; }
  Int_t       NTracksInPool()              const;
  Bool_t      WasUpdated()                 const { return fWasUpdated; }
  Int_t       ZvtxBinIndex()               const { return fZvtxBinIndex; }
  void        SetDebug(Bool_t b)                 { fDebug = b; }
  void        SetTargetTrackDepth(Int_t d, Float_t fraction = 1.0) { fTargetTrackDepth = d; fTargetFraction = fraction; }
  void        SetTargetEvents(Int_t ev)          { fTargetEvents = ev; }
  void        SetMaxNbMixEvents(Int_t ev)        { fMixDepth = ev; }
  Int_t       SetEventMultRange(Int_t    multMin, Int_t multMax);
  Int_t       SetEventMultRange(Double_t multMin, Double_t multMax);
  Int_t       SetEventZvtxRange(Double_t zvtxMin, Double_t zvtxMax);
  Int_t       SetEventPsiRange(Double_t psiMin, Double_t psiMax);
  Int_t       SetEventPtRange(Double_t ptMin, Double_t ptMax);
  void        SetMultBinIndex(Int_t iM) { fMultBinIndex = iM; }
  void        SetZvtxBinIndex(Int_t iZ) { fZvtxBinIndex = iZ; }
  void        SetPsiBinIndex(Int_t iP) { fPsiBinIndex  = iP; }
  void        SetPtBinIndex(Int_t iPt) { fPtBinIndex = iPt; }
  void        SetLockFlag(Bool_t val) { fLockFlag = val; }
  Bool_t      GetLockFlag() { return fLockFlag; }
  void        SetSaveFlag(Bool_t val) { fSaveFlag = val; }
  Bool_t      GetSaveFlag() { return fSaveFlag; }
  Double_t    GetPtMin() { return fPtMin; }
  Double_t    GetPtMax() { return fPtMax; }
  Double_t    GetPsiMin() { return fPsiMin; }
  Double_t    GetPsiMax() { return fPsiMax; }
  Double_t    GetMultMin() { return fMultMin; }
  Double_t    GetMultMax() { return fMultMax; }
  Double_t    GetZvtxMin() { return fZvtxMin; }
  Double_t    GetZvtxMax() { return fZvtxMax; }

  Int_t       UpdatePool(TObjArray *trk);
  Long64_t    Merge(TCollection* hlist);
//  deque<TObjArray*> GetEvents() { return fEvents; }
  void        Clear(Option_t * /* option */ = "");

protected:
  Bool_t      IsReady(Int_t tracks, Int_t events) const { return ((tracks >= fTargetFraction * fTargetTrackDepth) || ((fTargetEvents > 0) && (events >= fTargetEvents)));}

  deque<TObjArray*>     fEvents;              ///< Holds TObjArrays of MyTracklets
  deque<int>            fNTracksInEvent;      ///< Tracks in event
  deque<int>            fEventIndex;          ///< Original event index
  Int_t                 fMixDepth;            ///< Number of evts. to mix with
  Double_t              fMultMin, fMultMax;   ///< Track multiplicity bin range
  Double_t              fZvtxMin, fZvtxMax;   ///< Event z-vertex bin range
  Double_t              fPsiMin, fPsiMax;     ///< Event plane angle (Psi) bin range
  Double_t              fPtMin, fPtMax;       ///< Particle pt bin range
  Bool_t                fWasUpdated;          ///< Evt. succesfully passed selection?
  Int_t                 fMultBinIndex;        ///< Multiplicity bin
  Int_t                 fZvtxBinIndex;        ///< Zvertex bin
  Int_t                 fPsiBinIndex;         ///< Event plane angle (Psi) bin
  Int_t                 fPtBinIndex;          ///< Particle pt bin
  Int_t                 fDebug;               ///< If 1 then debug on
  Int_t                 fTargetTrackDepth;    ///< Number of tracks, once full
  Bool_t                fFirstFilled;         ///< Init to false
  Bool_t                fLockFlag;            ///< if locked, no update is allowed. Useful for external pools
  Bool_t                fSaveFlag;            ///< flag whether to save the pool to the output file or not
  Int_t                 fNTimes;              ///< Number of times init. condition reached
  Float_t               fTargetFraction;      ///< fraction of fTargetTrackDepth at which pool is ready (default: 1.0)
  Int_t                 fTargetEvents;        ///< if non-zero: number of filled events after which pool is ready regardless of fTargetTrackDepth (default: 0)

  ClassDef(AliEventPool,4) // Event pool class
};

class AliEventPoolManager : public TObject
{
public:
  AliEventPoolManager()
    : fDebug(0),
    fNMultBins(0),
    fNZvtxBins(0),
    fNPsiBins(0),
    fNPtBins(0),
    fMultBins(),
    fZvtxBins(),
    fPsiBins(),
    fPtBins(),
    fEvPool(0),
    fTargetTrackDepth(0) {}
  AliEventPoolManager(Int_t maxEvts, Int_t minNTracks,
          Int_t nMultBins, Double_t *multbins,
          Int_t nZvtxBins, Double_t *zvtxbins);

  AliEventPoolManager(Int_t maxEvts, Int_t minNTracks,
          Int_t nMultBins, Double_t *multbins,
          Int_t nZvtxBins, Double_t *zvtxbins,
          Int_t nPsiBins, Double_t *psibins);

  AliEventPoolManager(Int_t maxEvts, Int_t minNTracks,
          Int_t nMultBins, Double_t *multbins,
          Int_t nZvtxBins, Double_t *zvtxbins,
          Int_t nPsiBins, Double_t *psibins,
          Int_t nPtBins, Double_t *ptbins);

  AliEventPoolManager(Int_t maxEvts, Int_t minNTracks, const char* binning);

  ~AliEventPoolManager() {;}
  Long64_t    Merge(TCollection* hlist);

  // First uses bin indices, second uses the variables themselves.
  AliEventPool *GetEventPool(Int_t iMult, Int_t iZvtx, Int_t iPsi=0, Int_t iPt=0) const;
  AliEventPool *GetEventPool(Int_t centVal, Double_t zvtxVal, Double_t psiVal=0., Int_t iPt=0) const;
  AliEventPool *GetEventPool(Double_t centVal, Double_t zvtxVal, Double_t psiVal=0., Int_t iPt=0) const;

  Int_t       InitEventPools(Int_t depth,
                Int_t nMultBins, Double_t *multbin,
                Int_t nZvtxBins, Double_t *zvtxbin,
                Int_t nPsiBins, Double_t *psibin,
                Int_t nPtBins, Double_t *ptbin);

  void        SetTargetTrackDepth(Int_t d) { fTargetTrackDepth = d;} // Same as for G.E.P. class
  Int_t       UpdatePools(TObjArray *trk);
  void        SetDebug(Bool_t b) { fDebug = b; }
  void        SetTargetValues(Int_t trackDepth, Float_t fraction, Int_t events);
  Int_t       GetNumberOfAllBins() {return fNPtBins*fNMultBins*fNZvtxBins*fNPsiBins;}
  Int_t       GetNumberOfPtBins() {return fNPtBins;}
  Int_t       GetNumberOfMultBins() {return fNMultBins;}
  Int_t       GetNumberOfZVtxBins() {return fNZvtxBins;}
  Int_t       GetNumberOfPsiBins() {return fNPsiBins;}

  void        Validate();
  void        ClearPools();
  void        ClearPools(Double_t minCent, Double_t maxCent,  Double_t minZvtx, Double_t maxZvtx, Double_t minPsi, Double_t maxPsi, Double_t minPt, Double_t maxPt);
  void        SetSaveFlag(Double_t minCent, Double_t maxCent,  Double_t minZvtx, Double_t maxZvtx, Double_t minPsi, Double_t maxPsi, Double_t minPt, Double_t maxPt);

 protected:
  Int_t      fDebug;                                    ///< If 1 then debug on
  Int_t      fNMultBins;                                ///< number mult bins
  Int_t      fNZvtxBins;                                ///< number vertex bins
  Int_t      fNPsiBins;                                 ///< number Event plane angle (Psi) bins
  Int_t      fNPtBins;                                  ///< number pt bins

  std::vector<Double_t> fMultBins;                      ///< mult bins
  std::vector<Double_t> fZvtxBins;                      ///< vertex bins
  std::vector<Double_t> fPsiBins;                       ///< Event plane angle (Psi) bins
  std::vector<Double_t> fPtBins;                        ///< pt bins

  std::vector<AliEventPool*> fEvPool;                   ///< pool in bins of [fNMultBin][fNZvtxBin][fNPsiBin][fNPtBins]
  Int_t      fTargetTrackDepth;                         ///< Required track size, same for all pools.

  Int_t       GetBinIndex(Int_t iMult, Int_t iZvtx, Int_t iPsi, Int_t iPt) const {return fNZvtxBins*fNPsiBins*fNPtBins*iMult + fNPsiBins*fNPtBins*iZvtx + fNPtBins*iPsi + iPt;}
  Double_t*   GetBinning(const char* configuration, const char* tag, Int_t& nBins) const;

  ClassDef(AliEventPoolManager,3)
};

#endif


text:
@interface GPAboutViewController : UIViewController
- (IBAction)backPressed:(id)sender;
@property (weak, nonatomic) IBOutlet UIWebView *webView;
- (IBAction)clearPressed:(id)sender;
- (IBAction)rateAppPressed:(id)sender;
- (IBAction)feedbackPressed:(id)sender;
- (IBAction)sharePressed:(id)sender;

@end


text:
package problems.medium;

import java.util.*;

/**
 * Why Did you create this class? what does it do?
 */
public class DailyTemperature {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(dailyTemperatures(new int[] {
                73, 74, 75, 71, 69, 72, 76, 73,
                })));
    }

    static int[] dailyTemperatures(int[] a) {
        if (a == null || a.length == 0) {
            return a;
        }
        TreeMap<Integer, TreeSet<Integer>> map = new TreeMap<>();
        for (int i = 0; i < a.length; i++) {
            if (!map.containsKey(a[i]))
                map.put(a[i], new TreeSet<>());
            map.get(a[i]).add(i);
        }
        int[] res = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            Integer k = 0;
            Map.Entry<Integer, TreeSet<Integer>> entry = null;
            int search = a[i];
            int min = Integer.MAX_VALUE;
            while ((entry = map.higherEntry(search)) != null) {
                k = entry.getValue().higher(i);
                if (k != null && k - i > 0) {
                    min = Math.min(min, k - i);
                }
                search = entry.getKey();
            }
            res[i] = min == Integer.MAX_VALUE ? 0 : min;
        }

        return res;
    }

    static class Pair implements Comparable {
        int index;
        int value;

        public Pair(int index, int value) {
            this.index = index;
            this.value = value;
        }

        @Override public int compareTo(Object o) {
            Pair pair = (Pair) o;
            int d = this.value - pair.value;
            if (d != 0)
                return d;
            return this.index - pair.index;
        }

        @Override public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || getClass() != o.getClass())
                return false;

            Pair pair = (Pair) o;

            if (index != pair.index)
                return false;
            return value == pair.value;
        }

        @Override public int hashCode() {
            int result = index;
            result = 31 * result + value;
            return result;
        }
    }
}


text:
"""Support for AVM FRITZ!SmartHome switch devices."""
from __future__ import annotations

from typing import Any

from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import FritzBoxEntity
from .const import CONF_COORDINATOR, DOMAIN as FRITZBOX_DOMAIN

async def async_setup_entry(
    hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
    """Set up the FRITZ!SmartHome switch from ConfigEntry."""
    coordinator = hass.data[FRITZBOX_DOMAIN][entry.entry_id][CONF_COORDINATOR]

    async_add_entities(
        [
            FritzboxSwitch(coordinator, ain)
            for ain, device in coordinator.data.items()
            if device.has_switch
        ]
    )

class FritzboxSwitch(FritzBoxEntity, SwitchEntity):
    """The switch class for FRITZ!SmartHome switches."""

    @property
    def is_on(self) -> bool:
        """Return true if the switch is on."""
        return self.device.switch_state  # type: ignore [no-any-return]

    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn the switch on."""
        await self.hass.async_add_executor_job(self.device.set_switch_state_on)
        await self.coordinator.async_refresh()

    async def async_turn_off(self, **kwargs: Any) -> None:
        """Turn the switch off."""
        await self.hass.async_add_executor_job(self.device.set_switch_state_off)
        await self.coordinator.async_refresh()


text:
/*
 * fill_edges.h - class used to represent a dynamic
 * set of fill edges of a graph.
 */

#ifndef CHORDALGSRC_FILL_EDGES_H_
#define CHORDALGSRC_FILL_EDGES_H_

#include <vector>

#include "ChordAlgSrc/graph.h"
#include "ChordAlgSrc/vertices.h"

namespace chordalg {

class FillEdges {
 public:
    FillEdges() = delete;
    FillEdges(const FillEdges&) = delete;
    void operator=(const FillEdges&) = delete;

    explicit FillEdges(const Graph*);

    const Vertices& N(Vertex) const;
    bool IsEdge(VertexPair) const;      // is in V(G_) or F_
    bool IsEdge(Vertex, Vertex) const;
    bool IsFillEdge(VertexPair) const;  // is in F_
    bool IsFillEdge(Vertex, Vertex) const;
    bool IsClique(const Vertices&) const;
    bool AddEdge(VertexPair);           // new edge?
    bool AddEdge(Vertex, Vertex);
    void RemoveEdge(VertexPair);
    void RemoveEdge(Vertex, Vertex);
    void Saturate(const Vertices&);

    const VertexSet& operator[](size_t) const;
    VertexSet& operator[](size_t);
    size_t fill_count() const;
    Weight fill_weight() const;
    // Returns amalgamation of neighborhoods_ and G_->neighborhoods_
    AdjacencyLists* FilledNbhds() const;

 private:
    const Graph* const G_;

    std::vector< VertexSet > fill_;
    size_t fill_count_;
    Weight fill_weight_;
    AdjacencyLists* neighborhoods_;
};  // FillEdges

}  // namespace chordalg

#endif  // CHORDALGSRC_FILL_EDGES_H_


text:
package org.fujion.chartjs.axis;

import org.fujion.annotation.Option;

/**
 * Options for linear radial axes.
 */
public class RadialAxisOptions extends BaseAxisOptions {

    /**
     * Angle line options.
     */
    @Option
    public final AngleLineOptions angleLines = new AngleLineOptions();

    /**
     * Whether to animate scaling the chart from the center.
     */
    @Option
    public Boolean animate;

    /**
     * If true, scale will include 0 if it is not already included.
     *
     * Default: false
     */
    @Option
    public Boolean beginAtZero;

    /**
     * Point label options.
     */
    @Option
    public final PointLabelOptions pointLabels = new PointLabelOptions();

    /**
     * Starting angle of the scale. In degrees, 0 is at top.
     * <p>
     * Default: 0
     */
    @Option
    public Double startAngle;

    /**
     * Tick configuration.
     */
    @Option
    public final RadialTickOptions ticks = new RadialTickOptions();

}


text:
@interface ARMAlertAction ()

@property (nonatomic) Block handler;
@property (nonatomic) ARMAlertActionStyle style;
@property (nonatomic) NSString * title;

@end

@implementation ARMAlertAction

+(instancetype)actionWithTitle:(NSString *)title style:(ARMAlertActionStyle)style handler:(Block)handler;
{
	ARMAlertAction * alertAction = [self new];

	alertAction.handler = handler;
	alertAction.style	= style;
	alertAction.title	= title;

	return alertAction;
}

-(UIAlertAction *)getUIAlertControllerAction
{
	UIAlertAction * alertAction =  [UIAlertAction actionWithTitle:self.title style:(UIAlertActionStyle)self.style handler:^(UIAlertAction *action) {
		if (self.handler) self.handler();
	}];

	alertAction.enabled = self.enabled;

	return alertAction;
}

@end


text:
package com.microsoft.azure.management.batchai.v2018_03_01.implementation;

import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl;
import com.microsoft.azure.management.batchai.v2018_03_01.Job;
import rx.Observable;
import com.microsoft.azure.management.batchai.v2018_03_01.JobCreateParameters;
import java.util.List;
import com.microsoft.azure.management.batchai.v2018_03_01.CaffeSettings;
import com.microsoft.azure.management.batchai.v2018_03_01.ChainerSettings;
import com.microsoft.azure.management.batchai.v2018_03_01.ResourceId;
import com.microsoft.azure.management.batchai.v2018_03_01.CNTKsettings;
import com.microsoft.azure.management.batchai.v2018_03_01.JobPropertiesConstraints;
import com.microsoft.azure.management.batchai.v2018_03_01.ContainerSettings;
import org.joda.time.DateTime;
import com.microsoft.azure.management.batchai.v2018_03_01.CustomToolkitSettings;
import com.microsoft.azure.management.batchai.v2018_03_01.EnvironmentVariable;
import com.microsoft.azure.management.batchai.v2018_03_01.JobPropertiesExecutionInfo;
import com.microsoft.azure.management.batchai.v2018_03_01.ExecutionState;
import com.microsoft.azure.management.batchai.v2018_03_01.InputDirectory;
import com.microsoft.azure.management.batchai.v2018_03_01.JobPreparation;
import com.microsoft.azure.management.batchai.v2018_03_01.MountVolumes;
import com.microsoft.azure.management.batchai.v2018_03_01.OutputDirectory;
import com.microsoft.azure.management.batchai.v2018_03_01.ProvisioningState;
import com.microsoft.azure.management.batchai.v2018_03_01.PyTorchSettings;
import com.microsoft.azure.management.batchai.v2018_03_01.EnvironmentVariableWithSecretValue;
import com.microsoft.azure.management.batchai.v2018_03_01.TensorFlowSettings;
import com.microsoft.azure.management.batchai.v2018_03_01.ToolType;
import com.microsoft.azure.management.batchai.v2018_03_01.Caffe2Settings;
import com.microsoft.azure.management.batchai.v2018_03_01.JobBasePropertiesConstraints;
import rx.functions.Func1;

class JobImpl extends GroupableResourceCoreImpl<Job, JobInner, JobImpl, BatchAIManager> implements Job, Job.Definition, Job.Update {
    private JobCreateParameters createOrUpdateParameter;
    JobImpl(String name, JobInner inner, BatchAIManager manager) {
        super(name, inner, manager);
        this.createOrUpdateParameter = new JobCreateParameters();
    }

    @Override
    public Observable<Job> createResourceAsync() {
        JobsInner client = this.manager().inner().jobs();
        this.createOrUpdateParameter.withLocation(inner().location());
        this.createOrUpdateParameter.withTags(inner().getTags());
        return client.createAsync(this.resourceGroupName(), this.name(), this.createOrUpdateParameter)
            .map(new Func1<JobInner, JobInner>() {
               @Override
               public JobInner call(JobInner resource) {
                   resetCreateUpdateParameters();
                   return resource;
               }
            })
            .map(innerToFluentMap(this));
    }

    @Override
    public Observable<Job> updateResourceAsync() {
        JobsInner client = this.manager().inner().jobs();
        return client.createAsync(this.resourceGroupName(), this.name(), this.createOrUpdateParameter)
            .map(new Func1<JobInner, JobInner>() {
               @Override
               public JobInner call(JobInner resource) {
                   resetCreateUpdateParameters();
                   return resource;
               }
            })
            .map(innerToFluentMap(this));
    }

    @Override
    protected Observable<JobInner> getInnerAsync() {
        JobsInner client = this.manager().inner().jobs();
        return client.getByResourceGroupAsync(this.resourceGroupName(), this.name());
    }

    @Override
    public boolean isInCreateMode() {
        return this.inner().id() == null;
    }

    private void resetCreateUpdateParameters() {
        this.createOrUpdateParameter = new JobCreateParameters();
    }

    @Override
    public CaffeSettings caffeSettings() {
        return this.inner().caffeSettings();
    }

    @Override
    public ChainerSettings chainerSettings() {
        return this.inner().chainerSettings();
    }

    @Override
    public ResourceId cluster() {
        return this.inner().cluster();
    }

    @Override
    public CNTKsettings cntkSettings() {
        return this.inner().cntkSettings();
    }

    @Override
    public JobPropertiesConstraints constraints() {
        return this.inner().constraints();
    }

    @Override
    public ContainerSettings containerSettings() {
        return this.inner().containerSettings();
    }

    @Override
    public DateTime creationTime() {
        return this.inner().creationTime();
    }

    @Override
    public CustomToolkitSettings customToolkitSettings() {
        return this.inner().customToolkitSettings();
    }

    @Override
    public List<EnvironmentVariable> environmentVariables() {
        return this.inner().environmentVariables();
    }

    @Override
    public JobPropertiesExecutionInfo executionInfo() {
        return this.inner().executionInfo();
    }

    @Override
    public ExecutionState executionState() {
        return this.inner().executionState();
    }

    @Override
    public DateTime executionStateTransitionTime() {
        return this.inner().executionStateTransitionTime();
    }

    @Override
    public String experimentName() {
        return this.inner().experimentName();
    }

    @Override
    public List<InputDirectory> inputDirectories() {
        return this.inner().inputDirectories();
    }

    @Override
    public String jobOutputDirectoryPathSegment() {
        return this.inner().jobOutputDirectoryPathSegment();
    }

    @Override
    public JobPreparation jobPreparation() {
        return this.inner().jobPreparation();
    }

    @Override
    public MountVolumes mountVolumes() {
        return this.inner().mountVolumes();
    }

    @Override
    public Integer nodeCount() {
        return this.inner().nodeCount();
    }

    @Override
    public List<OutputDirectory> outputDirectories() {
        return this.inner().outputDirectories();
    }

    @Override
    public Integer priority() {
        return this.inner().priority();
    }

    @Override
    public ProvisioningState provisioningState() {
        return this.inner().provisioningState();
    }

    @Override
    public DateTime provisioningStateTransitionTime() {
        return this.inner().provisioningStateTransitionTime();
    }

    @Override
    public PyTorchSettings pyTorchSettings() {
        return this.inner().pyTorchSettings();
    }

    @Override
    public List<EnvironmentVariableWithSecretValue> secrets() {
        return this.inner().secrets();
    }

    @Override
    public String stdOutErrPathPrefix() {
        return this.inner().stdOutErrPathPrefix();
    }

    @Override
    public TensorFlowSettings tensorFlowSettings() {
        return this.inner().tensorFlowSettings();
    }

    @Override
    public ToolType toolType() {
        return this.inner().toolType();
    }

    @Override
    public JobImpl withCluster(ResourceId cluster) {
        this.createOrUpdateParameter.withCluster(cluster);
        return this;
    }

    @Override
    public JobImpl withNodeCount(int nodeCount) {
        this.createOrUpdateParameter.withNodeCount(nodeCount);
        return this;
    }

    @Override
    public JobImpl withStdOutErrPathPrefix(String stdOutErrPathPrefix) {
        this.createOrUpdateParameter.withStdOutErrPathPrefix(stdOutErrPathPrefix);
        return this;
    }

    @Override
    public JobImpl withCaffe2Settings(Caffe2Settings caffe2Settings) {
        this.createOrUpdateParameter.withCaffe2Settings(caffe2Settings);
        return this;
    }

    @Override
    public JobImpl withCaffeSettings(CaffeSettings caffeSettings) {
        this.createOrUpdateParameter.withCaffeSettings(caffeSettings);
        return this;
    }

    @Override
    public JobImpl withChainerSettings(ChainerSettings chainerSettings) {
        this.createOrUpdateParameter.withChainerSettings(chainerSettings);
        return this;
    }

    @Override
    public JobImpl withCntkSettings(CNTKsettings cntkSettings) {
        this.createOrUpdateParameter.withCntkSettings(cntkSettings);
        return this;
    }

    @Override
    public JobImpl withConstraints(JobBasePropertiesConstraints constraints) {
        this.createOrUpdateParameter.withConstraints(constraints);
        return this;
    }

    @Override
    public JobImpl withContainerSettings(ContainerSettings containerSettings) {
        this.createOrUpdateParameter.withContainerSettings(containerSettings);
        return this;
    }

    @Override
    public JobImpl withCustomToolkitSettings(CustomToolkitSettings customToolkitSettings) {
        this.createOrUpdateParameter.withCustomToolkitSettings(customToolkitSettings);
        return this;
    }

    @Override
    public JobImpl withEnvironmentVariables(List<EnvironmentVariable> environmentVariables) {
        this.createOrUpdateParameter.withEnvironmentVariables(environmentVariables);
        return this;
    }

    @Override
    public JobImpl withExperimentName(String experimentName) {
        this.createOrUpdateParameter.withExperimentName(experimentName);
        return this;
    }

    @Override
    public JobImpl withInputDirectories(List<InputDirectory> inputDirectories) {
        this.createOrUpdateParameter.withInputDirectories(inputDirectories);
        return this;
    }

    @Override
    public JobImpl withJobPreparation(JobPreparation jobPreparation) {
        this.createOrUpdateParameter.withJobPreparation(jobPreparation);
        return this;
    }

    @Override
    public JobImpl withMountVolumes(MountVolumes mountVolumes) {
        this.createOrUpdateParameter.withMountVolumes(mountVolumes);
        return this;
    }

    @Override
    public JobImpl withOutputDirectories(List<OutputDirectory> outputDirectories) {
        this.createOrUpdateParameter.withOutputDirectories(outputDirectories);
        return this;
    }

    @Override
    public JobImpl withPriority(Integer priority) {
        this.createOrUpdateParameter.withPriority(priority);
        return this;
    }

    @Override
    public JobImpl withPyTorchSettings(PyTorchSettings pyTorchSettings) {
        this.createOrUpdateParameter.withPyTorchSettings(pyTorchSettings);
        return this;
    }

    @Override
    public JobImpl withSecrets(List<EnvironmentVariableWithSecretValue> secrets) {
        this.createOrUpdateParameter.withSecrets(secrets);
        return this;
    }

    @Override
    public JobImpl withTensorFlowSettings(TensorFlowSettings tensorFlowSettings) {
        this.createOrUpdateParameter.withTensorFlowSettings(tensorFlowSettings);
        return this;
    }

}


text:
package org.certificatetransparency.ctlog.comm;

import java.io.ByteArrayInputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.certificatetransparency.ctlog.CertificateInfo;
import org.certificatetransparency.ctlog.CertificateTransparencyException;
import org.certificatetransparency.ctlog.ParsedLogEntry;
import org.certificatetransparency.ctlog.ParsedLogEntryWithProof;
import org.certificatetransparency.ctlog.SignedTreeHead;
import org.certificatetransparency.ctlog.proto.Ct;
import org.certificatetransparency.ctlog.serialization.Deserializer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.protobuf.ByteString;

/**
 * A CT HTTP client. Abstracts away the json encoding necessary for the server.
 */
public class HttpLogClient {
  private static final String ADD_PRE_CHAIN_PATH = "add-pre-chain";
  private static final String ADD_CHAIN_PATH = "add-chain";
  private static final String GET_STH_PATH = "get-sth";
  private static final String GET_ROOTS_PATH = "get-roots";
  private static final String GET_ENTRIES = "get-entries";
  private static final String GET_STH_CONSISTENCY = "get-sth-consistency";
  private static final String GET_ENTRY_AND_PROOF = "get-entry-and-proof";

  private final String logUrl;
  private final HttpInvoker postInvoker;

  /**
   * New HttpLogClient.
   * @param logUrl CT Log's full URL, e.g. "http://ct.googleapis.com/pilot/ct/v1/"
   */
  public HttpLogClient(String logUrl) {
    this(logUrl, new HttpInvoker());
  }

  /**
   * For testing specify an HttpInvoker
   * @param logUrl URL of the log.
   * @param postInvoker HttpInvoker instance to use.
   */
  public HttpLogClient(String logUrl, HttpInvoker postInvoker) {
    this.logUrl = logUrl;
    this.postInvoker = postInvoker;
  }

  /**
   * JSON-encodes the list of certificates into a JSON object.
   * @param certs Certificates to encode.
   * @return A JSON object with one field, "chain", holding a JSON array of base64-encoded certs.
   */
  @SuppressWarnings("unchecked") // Because JSONObject, JSONArray extend raw types.
  JSONObject encodeCertificates(List<Certificate> certs) {
    JSONArray retObject = new JSONArray();

    try {
      for (Certificate cert : certs) {
        retObject.add(Base64.encodeBase64String(cert.getEncoded()));
      }
    } catch (CertificateEncodingException e) {
      throw new CertificateTransparencyException("Error encoding certificate", e);
    }

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("chain", retObject);
    return jsonObject;
  }

  /**
   * Parses the CT Log's json response into a proper proto.
   *
   * @param responseBody Response string to parse.
   * @return SCT filled from the JSON input.
   */
  static Ct.SignedCertificateTimestamp parseServerResponse(String responseBody) {
    if (responseBody == null) {
      return null;
    }

    JSONObject parsedResponse = (JSONObject) JSONValue.parse(responseBody);
    Ct.SignedCertificateTimestamp.Builder builder =
        Ct.SignedCertificateTimestamp.newBuilder();

    int numericVersion = ((Number) parsedResponse.get("sct_version")).intValue();
    Ct.Version version = Ct.Version.valueOf(numericVersion);
    if (version == null) {
      throw new IllegalArgumentException(String.format("Input JSON has an invalid version: %d",
          numericVersion));
    }
    builder.setVersion(version);
    Ct.LogID.Builder logIdBuilder = Ct.LogID.newBuilder();
    logIdBuilder.setKeyId(
        ByteString.copyFrom(Base64.decodeBase64((String) parsedResponse.get("id"))));
    builder.setId(logIdBuilder.build());
    builder.setTimestamp(((Number) parsedResponse.get("timestamp")).longValue());
    String extensions = (String) parsedResponse.get("extensions");
    if (!extensions.isEmpty()) {
      builder.setExtensions(ByteString.copyFrom(Base64.decodeBase64(extensions)));
    }

    String base64Signature = (String) parsedResponse.get("signature");
    builder.setSignature(
        Deserializer.parseDigitallySignedFromBinary(
            new ByteArrayInputStream(Base64.decodeBase64(base64Signature))));
    return builder.build();
  }

  /**
   * Adds a certificate to the log.
   * @param certificatesChain The certificate chain to add.
   * @return SignedCertificateTimestamp if the log added the chain successfully.
   */
  public Ct.SignedCertificateTimestamp addCertificate(List<Certificate> certificatesChain) {
    Preconditions.checkArgument(!certificatesChain.isEmpty(),
        "Must have at least one certificate to submit.");

    boolean isPreCertificate = CertificateInfo.isPreCertificate(certificatesChain.get(0));
    if (isPreCertificate &&
        CertificateInfo.isPreCertificateSigningCert(certificatesChain.get(1))) {
      Preconditions.checkArgument(
          certificatesChain.size() >= 3,
          "When signing a PreCertificate with a PreCertificate Signing Cert," +
              " the issuer certificate must follow.");
    }

    return addCertificate(certificatesChain, isPreCertificate);
  }

  private Ct.SignedCertificateTimestamp addCertificate(
      List<Certificate> certificatesChain, boolean isPreCertificate) {
    String jsonPayload = encodeCertificates(certificatesChain).toJSONString();
    String methodPath;
    if (isPreCertificate) {
      methodPath = ADD_PRE_CHAIN_PATH;
    } else {
      methodPath = ADD_CHAIN_PATH;
    }

    String response = postInvoker.makePostRequest(logUrl + methodPath, jsonPayload);
    return parseServerResponse(response);
  }

  /**
   * Retrieves Latest Signed Tree Head from the log.
   * The signature of the Signed Tree Head component is not verified.
   * @return latest STH
   */
  public SignedTreeHead getLogSTH() {
    String response = postInvoker.makeGetRequest(logUrl + GET_STH_PATH);
    return parseSTHResponse(response);
  }

  /**
   * Retrieves accepted Root Certificates.
   * @return a list of root certificates.
   */
  public List<Certificate> getLogRoots() {
    String response = postInvoker.makeGetRequest(logUrl + GET_ROOTS_PATH);

    return parseRootCertsResponse(response);
  }

  /**
   * Retrieve Entries from Log.
   * @param start 0-based index of first entry to retrieve, in decimal.
   * @param end 0-based index of last entry to retrieve, in decimal.
   * @return list of Log's entries.
   */
  public List<ParsedLogEntry> getLogEntries(long start, long end) {
    Preconditions.checkArgument(0 <= start && end >= start);

    List<NameValuePair> params = createParamsList("start", "end", Long.toString(start),
      Long.toString(end));

    String response = postInvoker.makeGetRequest(logUrl + GET_ENTRIES, params);
    return parseLogEntries(response);
  }

  /**
   * Retrieve Merkle Consistency Proof between Two Signed Tree Heads.
   * @param first The tree_size of the first tree, in decimal.
   * @param second The tree_size of the second tree, in decimal.
   * @return A list of base64 decoded Merkle Tree nodes serialized to ByteString objects.
   */
  public List<ByteString> getSTHConsistency(long first, long second) {
    Preconditions.checkArgument(0 <= first && second >= first);

    List<NameValuePair> params = createParamsList("first", "second", Long.toString(first),
      Long.toString(second));

    String response = postInvoker.makeGetRequest(logUrl + GET_STH_CONSISTENCY, params);
    return parseConsistencyProof(response);
  }

  /**
   * Retrieve Entry+Merkle Audit Proof from Log.
   * @param leaf_index The index of the desired entry.
   * @param tree_size The tree_size of the tree for which the proof is desired.
   * @return ParsedLog entry object with proof.
   */
  public ParsedLogEntryWithProof getLogEntryAndProof(long leafindex, long treeSize) {
    Preconditions.checkArgument(0 <= leafindex && treeSize >= leafindex);

    List<NameValuePair> params = createParamsList("leaf_index", "tree_size",
      Long.toString(leafindex), Long.toString(treeSize));

    String response = postInvoker.makeGetRequest(logUrl + GET_ENTRY_AND_PROOF, params);
    JSONObject entry = (JSONObject) JSONValue.parse(response);
    JSONArray auditPath = (JSONArray) entry.get("audit_path");

    return Deserializer.parseLogEntryWithProof(jsonToLogEntry.apply(entry), auditPath, leafindex,
      treeSize);
  }

  /**
   * Creates a list of NameValuePair objects.
   * @param firstParamName The first parameter name.
   * @param firstParamValue The first parameter value.
   * @param secondParamName The second parameter name.
   * @param secondParamValue The second parameter value.
   * @return A list of NameValuePair objects.
   */
  private List<NameValuePair> createParamsList(String firstParamName, String secondParamName,
    String firstParamValue, String secondParamValue) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(firstParamName, firstParamValue));
    params.add(new BasicNameValuePair(secondParamName, secondParamValue));
    return params;
  }

  /**
   * Parses CT log's response for "get-entries" into a list of {@link ParsedLogEntry} objects.
   * @param response Log response to pars.
   * @return list of Log's entries.
   */
  @SuppressWarnings("unchecked")
  private List<ParsedLogEntry> parseLogEntries(String response) {
    Preconditions.checkNotNull(response, "Log entries response from Log should not be null.");

    JSONObject responseJson = (JSONObject) JSONValue.parse(response);
    JSONArray arr = (JSONArray) responseJson.get("entries");
    return Lists.transform(arr, jsonToLogEntry);
  }

  private Function<JSONObject, ParsedLogEntry> jsonToLogEntry =
    new Function<JSONObject, ParsedLogEntry>() {
    @Override public ParsedLogEntry apply(JSONObject entry) {
      String leaf = (String) entry.get("leaf_input");
      String extra = (String) entry.get("extra_data");

      return Deserializer.parseLogEntry(
        new ByteArrayInputStream(Base64.decodeBase64(leaf)),
        new ByteArrayInputStream(Base64.decodeBase64(extra)));
      }
    };

  /**
   * Parses CT log's response for the "get-sth-consistency" request.
   * @param response JsonObject containing an array of Merkle Tree nodes.
   * @return A list of base64 decoded Merkle Tree nodes serialized to ByteString objects.
   */
  private List<ByteString> parseConsistencyProof(String response) {
    Preconditions.checkNotNull(response, "Merkle Consistency response should not be null.");

    JSONObject responseJson = (JSONObject) JSONValue.parse(response);
    JSONArray arr = (JSONArray) responseJson.get("consistency");

    List<ByteString> proof = new ArrayList<ByteString>();
    for(Object node: arr) {
      proof.add(ByteString.copyFrom(Base64.decodeBase64((String) node)));
    }
    return proof;
  }

  /**
   * Parses CT log's response for "get-sth" into a proto object.
   * @param sthResponse Log response to parse
   * @return a proto object of SignedTreeHead type.
   */
  SignedTreeHead parseSTHResponse(String sthResponse) {
    Preconditions.checkNotNull(
      sthResponse, "Sign Tree Head response from a CT log should not be null");

    JSONObject response = (JSONObject) JSONValue.parse(sthResponse);
    long treeSize = (Long) response.get("tree_size");
    long timestamp = (Long) response.get("timestamp");
    if (treeSize < 0 || timestamp < 0) {
      throw new CertificateTransparencyException(
        String.format("Bad response. Size of tree or timestamp cannot be a negative value. "
          + "Log Tree size: %d Timestamp: %d", treeSize, timestamp));
    }
    String base64Signature = (String) response.get("tree_head_signature");
    String sha256RootHash = (String) response.get("sha256_root_hash");

    SignedTreeHead sth = new SignedTreeHead(Ct.Version.V1);
    sth.treeSize = treeSize;
    sth.timestamp = timestamp;
    sth.sha256RootHash = Base64.decodeBase64(sha256RootHash);
    sth.signature = Deserializer.parseDigitallySignedFromBinary(new ByteArrayInputStream(Base64.decodeBase64(base64Signature)));

    if (sth.sha256RootHash.length != 32) {
       throw new CertificateTransparencyException(
         String.format("Bad response. The root hash of the Merkle Hash Tree must be 32 bytes. "
           + "The size of the root hash is %d", sth.sha256RootHash.length));
      }
    return sth;
  }

  /**
   * Parses the response from "get-roots" GET method.
   *
   * @param response JSONObject with certificates to parse.
   * @return a list of root certificates.
   */
  List<Certificate> parseRootCertsResponse(String response) {
    List<Certificate> certs = new ArrayList<>();

    JSONObject entries = (JSONObject) JSONValue.parse(response);
    JSONArray entriesArray = (JSONArray) entries.get("certificates");

    for(Object i: entriesArray) {
      // We happen to know that JSONArray contains strings.
      byte[] in = Base64.decodeBase64((String) i);
      try {
        certs.add(CertificateFactory.getInstance("X509").generateCertificate(
          new ByteArrayInputStream(in)));
      } catch (CertificateException e) {
        throw new CertificateTransparencyException(
          "Malformed data from a CT log have been received: " + e.getLocalizedMessage(), e);
      }
    }
    return certs;
  }
}


text:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;

namespace dotnetweb.web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);
            var loggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
            var env = host.Services.GetRequiredService<IHostingEnvironment>();
            ConfigureLogging(env, loggerFactory, host.Services);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    EnsureDataStorageIsReady(services);

                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred while migrating the database.");
                }
            }

            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();

        private static void EnsureDataStorageIsReady(IServiceProvider services)
        {
            CoreEFStartup.InitializeDatabaseAsync(services).Wait();

            SimpleContentEFStartup.InitializeDatabaseAsync(services).Wait();

            LoggingEFStartup.InitializeDatabaseAsync(services).Wait();
        }

        private static void ConfigureLogging(
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            IServiceProvider serviceProvider
            )
        {
            LogLevel minimumLevel;
            if (env.IsProduction())
            {
                minimumLevel = LogLevel.Warning;
            }
            else
            {
                minimumLevel = LogLevel.Information;
            }

            // a customizable filter for logging
            // add exclusions to remove noise in the logs
            var excludedLoggers = new List<string>
            {
                "Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware",
                "Microsoft.AspNetCore.Hosting.Internal.WebHost",
            };

            Func<string, LogLevel, bool> logFilter = (string loggerName, LogLevel logLevel) =>
            {
                if (logLevel < minimumLevel)
                {
                    return false;
                }

                if (excludedLoggers.Contains(loggerName))
                {
                    return false;
                }

                return true;
            };

            loggerFactory.AddDbLogger(serviceProvider, logFilter);
        }

    }

}


text:
package com.ait.lienzo.client.core.shape.json.validators;

import java.util.Set;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;

public class BehaviorMapValidator implements IAttributeTypeValidator
{
    public static BehaviorMapValidator INSTANCE = new BehaviorMapValidator();

    public BehaviorMapValidator()
    {
    }

    @Override
    public void validate(JSONValue jval, ValidationContext ctx) throws ValidationException
    {
        if (null == jval)
        {
            ctx.addBadTypeError("BoundingBox");

            return;
        }
        JSONObject jobj = jval.isObject();

        if (null == jobj)
        {
            ctx.addBadTypeError("BoundingBox");
        }
        else
        {
            Set<String> keys = jobj.keySet();

            if (keys.isEmpty())
            {
                ctx.addBadTypeError("BoundingBox no keys");

                return;
            }
            for (String ikey : keys)
            {
                if ((null == ikey) || (ikey.trim().isEmpty()))
                {
                    ctx.addBadTypeError("BoundingBox bad key");

                    return;
                }
                jval = jobj.get(ikey);

                if (null == jval)
                {
                    ctx.addBadTypeError("BoundingBox no array");

                    return;
                }
                JSONArray jarr = jval.isArray();

                if (null == jarr)
                {
                    ctx.addBadTypeError("BoundingBox not array");

                    return;
                }
                if (jarr.size() < 2)
                {
                    ctx.addBadArraySizeError(2, jarr.size());

                    return;
                }
                BoundingBoxArrayValidator.INSTANCE.validate(jarr, ctx);
            }
        }
    }
}