text:
using Microsoft.Extensions.Configuration;

namespace VstsDash
{
    public class AppSettings
    {
        public AppSettings(IConfiguration configuration)
        {
            AccessToken = configuration[nameof(AccessToken)];
            Account = configuration[nameof(Account)];
            DefaultProjectId = configuration[nameof(DefaultProjectId)];
            DefaultRepositoryId = configuration[nameof(DefaultRepositoryId)];
            DefaultTeamId = configuration[nameof(DefaultTeamId)];
        }

        public string AccessToken { get; }

        public string Account { get; }

        public string DefaultProjectId { get; }

        public string DefaultRepositoryId { get; }

        public string DefaultTeamId { get; }
    }
}


text:
FOUNDATION_EXPORT double ApexRecorderVersionNumber;

//! Project version string for ApexRecorder.
FOUNDATION_EXPORT const unsigned char ApexRecorderVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <ApexRecorder/PublicHeader.h>

redpajama_set_name: RedPajamaGithub


text:
@interface NTApiRequestBuilder () // private

@property (strong,nonatomic)    NSArray             *args;
@property (strong, nonatomic)   NTApiError          *error;
@property (strong,nonatomic)    NSString            *multipartBoundry;
@property (nonatomic)           NSString            *defaultHttpMethod;

-(BOOL)initializeMultipart;

@end

@implementation NSMutableData (NTApiClientHelper)

-(void)appendFormat:(NSString *)format, ...
{
    // A little helper to append formatted text to NSMutableData...

    va_list args;
    va_start(args, format);

    NSString *string = [[NSString alloc] initWithFormat:format arguments:args];

    NSData *data=[string dataUsingEncoding:NSUTF8StringEncoding];

    [self appendData:data];
}

@end

@implementation NTApiRequestBuilder

@synthesize args = mArgs;
@synthesize error = mError;
@synthesize multipartBoundry = mMulipartBoundry;

@synthesize baseUrl = mBaseUrl;
@synthesize headers = mHeaders;
@synthesize options = mOptions;
@synthesize httpMethod = mHttpMethod;
@synthesize timeout = mTimeout;
@synthesize cachePolicy = mCachePolicy;
@synthesize urlString = mUrlString;
@synthesize formString = mFormString;
@synthesize multipartData = mMulipartData;
@synthesize rawData = mRawData;
@synthesize defaultHttpMethod = mDefaltHttpMethod;

+(NSString *)urlEncode:(NSString *)string
{
    // based on: http://madebymany.com/blog/url-encoding-an-nsstring-on-ios

    return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                (__bridge CFStringRef)string,
                                                                                NULL,
                                                                                (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
}

static char NTBase64EncodingTable[64] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};

+(NSString *)base64Encode:(NSData *)data
{
    // from http://stackoverflow.com/questions/392464/any-base64-library-on-iphone-sdk

    unsigned long ixtext, lentext;
    long ctremaining;
    unsigned char input[3], output[4];
    short i, charsonline = 0, ctcopy;
    const unsigned char *raw;
    NSMutableString *result;

    lentext = [data length];
    if (lentext < 1)
        return @"";
    result = [NSMutableString stringWithCapacity: lentext];
    raw = [data bytes];
    ixtext = 0;

    while (true) {
        ctremaining = lentext - ixtext;
        if (ctremaining <= 0)
            break;
        for (i = 0; i < 3; i++) {
            unsigned long ix = ixtext + i;
            if (ix < lentext)
                input[i] = raw[ix];
            else
                input[i] = 0;
        }
        output[0] = (input[0] & 0xFC) >> 2;
        output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
        output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
        output[3] = input[2] & 0x3F;
        ctcopy = 4;
        switch (ctremaining) {
            case 1:
                ctcopy = 2;
                break;
            case 2:
                ctcopy = 3;
                break;
        }

        for (i = 0; i < ctcopy; i++)
            [result appendString: [NSString stringWithFormat: @"%c", NTBase64EncodingTable[output[i]]]];

        for (i = ctcopy; i < 4; i++)
            [result appendString: @"="];

        ixtext += 3;
        charsonline += 4;

        if ((data.length > 0) && (charsonline >= data.length))
            charsonline = 0;
    }
    return result;

}

-(id)initWithArgs:(NSArray *)args
{
    if ( (self=[super init]) )
    {
        self.args = args;

    }

    return self;
}

-(NSString *)multipartBoundry
{
    if ( !mMulipartBoundry )
        mMulipartBoundry = [NSString stringWithFormat:@">>>>%f<<<<", [NSDate timeIntervalSinceReferenceDate]];

    return mMulipartBoundry;
}

-(BOOL)addUrlValueWithName:(NSString *)name value:(NSString *)value
{
    if ( !value )
        return YES; // ignore nil values

    if ( self.urlString.length > 0 )
        [self.urlString appendString:@"&"];

    [self.urlString appendFormat:@"%@=%@", name, [NTApiRequestBuilder urlEncode:value]];

    return YES;
}

-(BOOL)addHeaderWithName:(NSString *)name value:(NSString *)value
{
    if ( !value )
        return YES; // ignore nil values

    [self.headers setObject:value forKey:name];

    return YES;
}

-(BOOL)addFormValueWithName:(NSString *)name value:(NSString *)value
{
    if ( !value )
        return YES; // ignore nil values

    if ( self.multipartData || self.rawData )
    {
        self.error = [NTApiError errorWithCode:NTApiErrorCodeError message:@"RequestBuilder: form data may not be combined with multipart or raw data"];

        return NO;
    }

    if ( !self.formString ) // initialize if this is the first form value
    {
        self.defaultHttpMethod = @"POST";
        self.formString = [NSMutableString new];
        [self addHeaderWithName:NTApiHeaderContentType value:@"application/x-www-form-urlencoded"];
    }
    else
        [self.formString appendString:@"&"];

    [self.formString appendFormat:@"%@=%@", name, [NTApiRequestBuilder urlEncode:value]];

    return YES;
}

-(BOOL)initializeMultipart
{
    if ( self.formString || self.rawData )
    {
        self.error = [NTApiError errorWithCode:NTApiErrorCodeError message:@"RequestBuilder: multipart data may not be combined with form or raw data"];

        return NO;
    }

    if ( !self.multipartData ) // initialize if this is the first multipart value.
    {
        self.defaultHttpMethod = @"POST";
        [self addHeaderWithName:NTApiHeaderContentType value:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.multipartBoundry]];

        self.multipartData = [NSMutableData new];

        [self.multipartData appendFormat:@"--%@\r\n", self.multipartBoundry];
    }

    return YES;
}

-(BOOL)addMultipartValueWithName:(NSString *)name value:(NSString *)value
{
    if ( !value )
        return YES; // ignore nil values

    if ( ![self initializeMultipart] )
        return NO;

    [self.multipartData appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", name];

    [self.multipartData appendFormat:@"\r\n"];
    [self.multipartData appendFormat:@"%@", value];
    [self.multipartData appendFormat:@"\r\n"];

    [self.multipartData appendFormat:@"--%@\r\n", self.multipartBoundry];

    return YES;
}

-(BOOL)addMultipartDataWithName:(NSString *)name data:(NSData *)data extension:(NSString *)extension
{
    if ( !data )
        return YES; // ignore nil values

    if ( ![self initializeMultipart] )
        return NO;

    [self.multipartData appendFormat:@"Content-Disposition: form-data; name=\"%@\"; attachment; filename=\"%@.%@\"\r\n", name, name, (extension) ? extension : @"bin"];

    [self.multipartData appendFormat:@"\r\n"];
    [self.multipartData appendData:data];
    [self.multipartData appendFormat:@"\r\n"];

    [self.multipartData appendFormat:@"--%@\r\n", self.multipartBoundry];

    return YES;
}

-(BOOL)addRawDataWithContentType:(NSString *)contentType data:(NSData *)data
{
    if ( !data )
        return YES; // ignore nil values

    if ( self.multipartData || self.formString )
    {
        self.error = [NTApiError errorWithCode:NTApiErrorCodeError message:@"RequestBuilder: raw data may not be combined with multipart or form data"];

        return NO;
    }

    if ( self.rawData )
    {
        self.error = [NTApiError errorWithCode:NTApiErrorCodeError message:@"RequestBuilder: raw data may only be defined once"];

        return NO;
    }

    self.defaultHttpMethod = @"POST";
    [self addHeaderWithName:NTApiHeaderContentType value:contentType];
    self.rawData = data;

    return YES;
}

-(BOOL)addOptionWithName:(NSString *)name value:(NSString *)value
{
    // note: nil values are not ignored here!

    [self.options setObject:(value) ? value : [NSNull null] forKey:name];

    return YES;
}

-(NSMutableURLRequest *)createRequest
{
    // first, initialize our state...

    self.error = nil; // set if we return nil
    self.multipartBoundry = nil; // will be created the first time it is accessed.

    self.baseUrl = nil;
    self.headers = [NSMutableDictionary new];
    self.options = [NSMutableDictionary new];
    self.httpMethod = nil;   // default - autodetect
    self.defaultHttpMethod = @"GET";
    self.timeout = 60;          // default to 60 seconds
    self.cachePolicy = NSURLRequestUseProtocolCachePolicy;  // default

    self.urlString = [NSMutableString new];

    self.formString = nil;
    self.multipartData = nil;
    self.rawData = nil;

    // Loop through each argument, applying it to ourselves...

    for(NTApiArg *arg in self.args)
    {
        if ( ![arg applyArgToBuilder:self] )
            return nil; // failed
    }

    // do some sanity checking...

    if ( !self.baseUrl )
    {
        self.error = [NTApiError errorWithCode:NTApiErrorCodeError message:@"RequestBuilder: baseUrl not set"];
        return nil;
    }

    // Now that we have applied all our arguments successfully, we can build the request...

    NSString *url = (self.urlString && self.urlString.length) ? [NSString stringWithFormat:@"%@?%@", self.baseUrl, self.urlString] : self.baseUrl;

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

    // create our data...

    if ( self.multipartData != nil )  // multipart data...
        [request setHTTPBody:self.multipartData];

    else if ( self.formString != nil ) // url encoded form data...
        [request setHTTPBody:[self.formString dataUsingEncoding:NSUTF8StringEncoding]];

    else if ( self.rawData != nil )
        [request setHTTPBody:self.rawData];
    else
        [request setHTTPBody:[@"" dataUsingEncoding:NSUTF8StringEncoding]]; // It's an empty request, but we can't leave it null

    // Set our method...

    request.HTTPMethod = (self.httpMethod) ? self.httpMethod : self.defaultHttpMethod;

    // Set timeout...

    request.timeoutInterval = (NSTimeInterval)self.timeout;

    // Set cachePolicy...

    request.cachePolicy = self.cachePolicy;

    // Set headers...

    [request setAllHTTPHeaderFields:self.headers];

    return request;
}

@end


text:
CREATE OR REPLACE FUNCTION openclinica_fdw.dm_create_dm_discrepancy_notes_all()
  RETURNS VOID AS
  $BODY$
    BEGIN
        EXECUTE $query$
    CREATE MATERIALIZED VIEW dm.discrepancy_notes_all AS
        SELECT
            dn_src.discrepancy_note_id,
            dn_src.study_name,
            dn_src.site_name,
            dn_src.subject_id,
            dn_src.event_name,
            dn_src.crf_parent_name,
            dn_src.crf_section_label,
            dn_src.item_description,
            dn_src.column_name,
            dn_src.parent_dn_id,
            dn_src.entity_type,
            dn_src.description,
            dn_src.detailed_notes,
            dn_src.date_created,
            dn_src.discrepancy_note_type,
            dn_src.resolution_status,
            dn_src.discrepancy_note_owner
        FROM
            (
                SELECT
                    DISTINCT ON (sua.discrepancy_note_id)
                    sua.discrepancy_note_id,
                    sua.study_name,
                    sua.site_name,
                    sua.subject_id,
                    sua.event_name,
                    sua.crf_parent_name,
                    sua.crf_section_label,
                    sua.item_description,
                    sua.column_name,
                    dn.parent_dn_id,
                    dn.entity_type,
                    dn.description,
                    dn.detailed_notes,
                    dn.date_created,
                    CASE
                    WHEN dn.discrepancy_note_type_id =
                         1 THEN $$Failed Validation Check$$ :: TEXT
                    WHEN dn.discrepancy_note_type_id =
                         2 THEN $$Annotation$$ :: TEXT
                    WHEN dn.discrepancy_note_type_id = 3 THEN $$Query$$ :: TEXT
                    WHEN dn.discrepancy_note_type_id =
                         4 THEN $$Reason for Change$$ :: TEXT
                    ELSE $$unhandled$$ :: TEXT
                    END :: TEXT                  AS discrepancy_note_type,
                    rs.name                      AS resolution_status,
                    ua.user_name                 AS discrepancy_note_owner
                FROM
                    (
                        (
                            (
                                (
                                    SELECT
                                        didm.discrepancy_note_id,
                                        didm.column_name,
                                        cd.study_name,
                                        cd.site_name,
                                        cd.subject_id,
                                        cd.event_name,
                                        cd.crf_parent_name,
                                        cd.crf_section_label,
                                        cd.item_description
                                    FROM
                                        openclinica_fdw.dn_item_data_map AS didm
                                        JOIN
                                        dm.clinicaldata AS cd
                                            ON cd.item_data_id =
                                               didm.item_data_id
                                    UNION ALL
                                    SELECT
                                        decm.discrepancy_note_id,
                                        decm.column_name,
                                        cd.study_name,
                                        cd.site_name,
                                        cd.subject_id,
                                        cd.event_name,
                                        cd.crf_parent_name,
                                        NULL :: TEXT AS crf_section_label,
                                        NULL :: TEXT AS item_description
                                    FROM
                                        openclinica_fdw.dn_event_crf_map AS decm
                                        JOIN
                                        dm.clinicaldata AS cd
                                            ON cd.event_crf_id =
                                               decm.event_crf_id
                                )
                                UNION ALL
                                SELECT
                                    dsem.discrepancy_note_id,
                                    dsem.column_name,
                                    cd.study_name,
                                    cd.site_name,
                                    cd.subject_id,
                                    cd.event_name,
                                    NULL :: TEXT AS crf_parent_name,
                                    NULL :: TEXT AS crf_section_label,
                                    NULL :: TEXT AS item_description
                                FROM
                                    openclinica_fdw.dn_study_event_map AS dsem
                                    JOIN
                                    dm.clinicaldata AS cd
                                        ON cd.study_event_id =
                                           dsem.study_event_id
                            )
                            UNION ALL
                            SELECT
                                dssm.discrepancy_note_id,
                                dssm.column_name,
                                cd.study_name,
                                cd.site_name,
                                cd.subject_id,
                                NULL :: TEXT AS event_name,
                                NULL :: TEXT AS crf_parent_name,
                                NULL :: TEXT AS crf_section_label,
                                NULL :: TEXT AS item_description
                            FROM
                                openclinica_fdw.dn_study_subject_map AS dssm
                                JOIN
                                dm.clinicaldata AS cd
                                    ON cd.study_subject_id =
                                       dssm.study_subject_id
                        )
                        UNION ALL
                        SELECT
                            dsm.discrepancy_note_id,
                            dsm.column_name,
                            cd.study_name,
                            cd.site_name,
                            cd.subject_id,
                            NULL :: TEXT AS event_name,
                            NULL :: TEXT AS crf_parent_name,
                            NULL :: TEXT AS crf_section_label,
                            NULL :: TEXT AS item_description
                        FROM
                            openclinica_fdw.dn_subject_map AS dsm
                            JOIN
                            dm.clinicaldata AS cd
                                ON cd.subject_id_seq = dsm.subject_id
                    ) AS sua
                    JOIN
                    openclinica_fdw.discrepancy_note AS dn
                        ON dn.discrepancy_note_id = sua.discrepancy_note_id
                    JOIN
                    openclinica_fdw.resolution_status AS rs
                        ON rs.resolution_status_id = dn.resolution_status_id
                    JOIN
                    openclinica_fdw.user_account AS ua
                        ON ua.user_id = dn.owner_id
            ) AS dn_src;
            $query$;
    END;
    $BODY$
LANGUAGE plpgsql VOLATILE;


text:
using System;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Soccer.Controllers;
using System.IO;

namespace Soccer.Test.Controllers
{
    [TestClass]
    public class TeamsControllerTest
    {
        // Helper to creeate a stream from a string
        public Stream CreateStream(string content)
        {
            return new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content));
        }

        [TestMethod]
        public void TestCreateController()
        {
            var ctrl = new TeamsController();
            Assert.AreNotSame(null, ctrl);
        }

        [TestMethod]
        public void TestIndex()
        {
            var ctrl = new TeamsController(CreateStream(""));
            var res = ctrl.Index();
            var data = ((JsonResult)res).Data.ToString();
            Assert.AreEqual("{ Success = True, Teams = System.Collections.Generic.List`1[Soccer.Models.Team], Smallest = Team: \tFor: 0\tAgainst: 0. Diff = 0 }", data);
            Assert.AreEqual(JsonRequestBehavior.AllowGet, ((JsonResult)res).JsonRequestBehavior);

            ctrl = new TeamsController(CreateStream(@"Team,P,W,L,D,F,-,A,Pts
                Arsenal,38,26,9,3,79,-,36,87
                Liverpool,38,24,8,6,67,-,30,80"));
            res = ctrl.Index();
            data = ((JsonResult)res).Data.ToString();
            Assert.AreEqual("{ Success = True, Teams = System.Collections.Generic.List`1[Soccer.Models.Team], Smallest = System.Collections.Generic.List`1[Soccer.Models.Team] }", data);
        }

    }
}


text:
<?php

namespace FOS\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class GroupFormType extends AbstractType
{
    private $class;

    /**
     * @param string $class The Group class name
     */
    public function __construct($class)
    {
        $this->class = $class;
    }

    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('name');
    }

    public function getDefaultOptions()
    {
        return array(
            'data_class' => $this->class,
            'intention'  => 'group',
        );
    }

    public function getName()
    {
        return 'fos_user_group';
    }
}


text:
/*
 * Pathfinder
 * Core application for storage and analysis of IT landscape data
 *
 * OpenAPI spec version: 5.0.813
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package net.leanix.api.common;

public class Pair {
    private String name = "";
    private String value = "";

    public Pair (String name, String value) {
        setName(name);
        setValue(value);
    }

    private void setName(String name) {
        if (!isValidString(name)) return;

        this.name = name;
    }

    private void setValue(String value) {
        if (!isValidString(value)) return;

        this.value = value;
    }

    public String getName() {
        return this.name;
    }

    public String getValue() {
        return this.value;
    }

    private boolean isValidString(String arg) {
        if (arg == null) return false;
        if (arg.trim().isEmpty()) return false;

        return true;
    }
}


text:
using System.Collections.Generic;

namespace GRA.Controllers.ViewModel.Shared
{
    public class PaginateViewModel
    {
        public int CurrentPage { get; set; }
        public int ItemCount { get; set; }
        public int ItemsPerPage { get; set; }

        public int? NextPage
        {
            get
            {
                if (this.CurrentPage < this.LastPage)
                {
                    return this.CurrentPage + 1;
                }
                return null;
            }
        }
        public int? PreviousPage
        {
            get
            {
                if (this.CurrentPage > 1)
                {
                    return this.CurrentPage - 1;
                }
                return null;
            }
        }
        public int? FirstPage
        {
            get
            {
                if (this.CurrentPage > 1)
                {
                    return 1;
                }
                return null;
            }
        }
        public int? LastPage
        {
            get
            {
                if (this.ItemCount > this.ItemsPerPage)
                {
                    int last = this.MaxPage;
                    if (this.CurrentPage != last)
                    {
                        return last;
                    }
                }
                return null;
            }
        }
        public int MaxPage
        {
            get
            {
                if (this.ItemsPerPage == 0)
                {
                    return 0;
                }
                int last = this.ItemCount / this.ItemsPerPage;
                if (this.ItemCount % this.ItemsPerPage > 0)
                {
                    last++;
                }
                return last;
            }
        }
    }
}


text:
from __future__ import absolute_import

import funcparserlib.parser as p

string = lambda x: x or ''
cat = ''.join

negative = p.maybe(p.a('-')) >> string
digits = p.oneplus(p.some(lambda char: char.isdigit())) >> cat
decimal_part = (p.maybe(p.a('.') + digits)) >> string >> cat
number = (negative + digits + decimal_part) >> cat >> float

addition = number + p.skip(p.a('+')) + number >> sum

expression = addition | number
expression = expression + p.finished

def calculate(text):
    return expression.parse(text)[0]


text:
package iht.controllers.application.exemptions.qualifyingBody

import iht.config.AppConfig
import iht.connector.{CachingConnector, IhtConnector}
import iht.controllers.application.EstateController
import iht.forms.ApplicationForms.qualifyingBodyNameForm
import iht.models._
import iht.models.application.ApplicationDetails
import iht.models.application.exemptions._
import iht.utils.CommonHelper
import iht.views.html.application.exemption.qualifyingBody.qualifying_body_name
import javax.inject.Inject
import play.api.mvc.{Call, MessagesControllerComponents, Request}
import uk.gov.hmrc.auth.core.AuthConnector
import uk.gov.hmrc.auth.core.retrieve.v2.Retrievals.{nino => ninoRetrieval}
import uk.gov.hmrc.play.bootstrap.frontend.controller.FrontendController

import scala.concurrent.Future

class QualifyingBodyNameControllerImpl @Inject()(val ihtConnector: IhtConnector,
                                                 val cachingConnector: CachingConnector,
                                                 val authConnector: AuthConnector,
                                                 val qualifyingBodyNameView: qualifying_body_name,
                                                 implicit val appConfig: AppConfig,
                                                 val cc: MessagesControllerComponents) extends FrontendController(cc) with QualifyingBodyNameController

trait QualifyingBodyNameController extends EstateController {

  lazy val submitUrl = CommonHelper.addFragmentIdentifier(routes.QualifyingBodyNameController.onSubmit, Some(appConfig.ExemptionsOtherNameID))

  def cancelUrl = routes.QualifyingBodyDetailsOverviewController.onPageLoad

  private def editCancelUrl(id: String) = routes.QualifyingBodyDetailsOverviewController.onEditPageLoad(id)

  private def editSubmitUrl(id: String) = {
    CommonHelper.addFragmentIdentifier(routes.QualifyingBodyNameController.onEditSubmit(id),
      Some(appConfig.ExemptionsOtherNameID))
  }

  def locationAfterSuccessfulSave(optionID: Option[String]) = CommonHelper.getOrException(
    optionID.map(id => routes.QualifyingBodyDetailsOverviewController.onEditPageLoad(id)))

  val updateApplicationDetails: (ApplicationDetails, Option[String], QualifyingBody) => (ApplicationDetails, Option[String]) =
    (appDetails, id, qualifyingBody) => {
      val seekID = id.getOrElse("")
      val qbList = appDetails.qualifyingBodies

      val updatedQBTuple: (Seq[QualifyingBody], String) = qbList.find(_.id.getOrElse("") equals seekID) match {
        case None =>
          id.fold {
            val nextID = nextId(qbList)
            (qbList :+ qualifyingBody.copy(id = Some(nextID)), nextID)
          } { reqId => throw new RuntimeException("Id " + reqId + " can not be found") }
        case Some(matchedQualifyingBody) =>
          val updatedQualifyingBody: QualifyingBody = matchedQualifyingBody.copy(name = qualifyingBody.name)
          (qbList.updated(qbList.indexOf(matchedQualifyingBody), updatedQualifyingBody), seekID)
      }
      (appDetails.copy(qualifyingBodies = updatedQBTuple._1), Some(updatedQBTuple._2))
    }
  val qualifyingBodyNameView: qualifying_body_name
  def onPageLoad = authorisedForIht {
    implicit request => {
      withRegistrationDetails { regDetails =>
        Future.successful(Ok(
          qualifyingBodyNameView(qualifyingBodyNameForm,
            regDetails,
            submitUrl,
            cancelUrl)))
      }
    }
  }

  def onEditPageLoad(id: String) = authorisedForIhtWithRetrievals(ninoRetrieval) { userNino =>
    implicit request => {
      estateElementOnEditPageLoadWithNavigation[QualifyingBody](qualifyingBodyNameForm,
        qualifyingBodyNameView.apply,
        retrieveQualifyingBodyDetailsOrExceptionIfInvalidID(id),
        editSubmitUrl(id),
        editCancelUrl(id),
        userNino)
    }
  }

  def onSubmit = authorisedForIhtWithRetrievals(ninoRetrieval) { userNino =>
    implicit request => {
      doSubmit(
        submitUrl = submitUrl,
        cancelUrl = cancelUrl,
        None,
        userNino)
    }
  }

  private def doSubmit(submitUrl: Call,
                       cancelUrl: Call,
                       charityId: Option[String],
                       userNino: Option[String])
                      (implicit request: Request[_]) = {
    estateElementOnSubmitWithIdAndNavigation[QualifyingBody](
      qualifyingBodyNameForm,
      qualifyingBodyNameView.apply,
      updateApplicationDetails,
      (_, updatedQualifyingBodyID) => locationAfterSuccessfulSave(updatedQualifyingBodyID),
      None,
      charityId,
      submitUrl,
      cancelUrl,
      userNino
    )
  }

  def onEditSubmit(id: String) = authorisedForIhtWithRetrievals(ninoRetrieval) { userNino =>
    implicit request => {
      doSubmit(
        submitUrl = editSubmitUrl(id),
        cancelUrl = editCancelUrl(id),
        charityId = Some(id),
        userNino)
    }
  }
}


text:
package org.apache.nifi.processors.evtx.parser.bxml;

import org.apache.nifi.processors.evtx.parser.BxmlNodeVisitor;
import org.apache.nifi.processors.evtx.parser.bxml.value.VariantTypeNode;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

public class RootNodeTest extends BxmlNodeTestBase {

    private String testString = "testString";
    private RootNode rootNode;

    @Override
    public void setup() throws IOException {
        super.setup();
        testBinaryReaderBuilder.put((byte) BxmlNode.END_OF_STREAM_TOKEN);
        testBinaryReaderBuilder.putDWord(1);

        testBinaryReaderBuilder.putWord(testString.length() + 1);
        testBinaryReaderBuilder.putWord(2);
        testBinaryReaderBuilder.putString(testString);
        testBinaryReaderBuilder.put((byte) 0);

        rootNode = new RootNode(testBinaryReaderBuilder.build(), chunkHeader, parent);
    }

    @Test
    public void testInit() {
        List<BxmlNode> children = rootNode.getChildren();
        assertEquals(1, children.size());
        assertTrue(children.get(0) instanceof EndOfStreamNode);

        List<VariantTypeNode> substitutions = rootNode.getSubstitutions();
        assertEquals(1, substitutions.size());
        assertEquals(testString, substitutions.get(0).getValue());
    }

    @Test
    public void testVisitor() throws IOException {
        BxmlNodeVisitor mock = mock(BxmlNodeVisitor.class);
        rootNode.accept(mock);
        verify(mock).visit(rootNode);
        verifyNoMoreInteractions(mock);
    }
}


text:
@interface Fun : NSObject
@property (nonatomic, strong) NSString* name;
@end


text:
Learn words meanings

    bundle:
      <select (change)="selectWordBundle($event.target.value)">
        <option *ngFor="let wordBundle of learnService.wordBundles" [value]="wordBundle.id">{{wordBundle.name}}</option>
      </select>

    learning type:
      <select (change)="selectWordKnowledgeTestType($event.target.value)">
        <option *ngFor="let selectOption of learnService.wordKnowledgeTestTypes" [value]="selectOption.value">{{selectOption.label}}</option>
      </select>

{{learnService.activeWord.word}}

{{learnService.activeWord.meaning}}

{{learnService.activeWord.word}}

{{learnService.activeWord.meaning}}

{{learnService.activeWord.meaning}}

{{learnService.activeWord.word}}

        <button id="know-button" (click)="doKnow()">Know</button>
        <button id="do-not-know-button" (click)="doNotKnow()">Do not know</button>

        <button id="self-check-correct" (click)="selfCheckCorrect()">Right</button>
        <button id="self-check-wrong" (click)="selfCheckWrong()">Wrong</button>

        <button id="next-word" (click)="nextWord()">Ok</button>


text:
package org.abysm.onionzip;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class App {
    public static void main(String[] args) throws IOException {
        CommandLineParser parser = new DefaultParser();

        Options options = new Options();
        options.addOption("c", "charset", true, "charset of filenames in the archive (detected if not given)");
        options.addOption("h", "help", false, "print this message");
        options.addOption("l", "list", false, "list contents of archive");
        options.addOption("s", "supported-charsets", false, "list supported charsets");

        try {
            CommandLine cmd = parser.parse(options, args);

            if (cmd.hasOption("supported-charsets")) {
                for (String charsetName : Charset.availableCharsets().keySet()) {
                    System.out.println(charsetName);
                }
                return;
            }

            if (cmd.hasOption("help") || cmd.getArgs().length != 1) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("onionzip [OPTIONS] ZIP_FILE", options);
                return;
            }

            String zipFilename = cmd.getArgs()[0];
            ZipFileExtractHelper zipFileHandler = new ZipFileExtractHelper(zipFilename);

            if (cmd.hasOption("charset")) {
                zipFileHandler.setEncoding(cmd.getOptionValue("charset"));
            } else {
                zipFileHandler.setEncodingByDetection();
                System.err.format("Detected charset: %s\n", zipFileHandler.getEncoding());
            }

            if (cmd.hasOption("list")) {
                zipFileHandler.listZipArchiveEntries();
            } else {
                zipFileHandler.extractZipArchiveEntries();
            }
        } catch (ParseException e) {
            System.err.println(e.getMessage());
        }
    }
}


text:
#include "../platform/platform.h"
#include "../utilities/kaa_mem.h"

#ifdef KAA_TRACE_MEMORY_ALLOCATIONS

#if KAA_LOG_LEVEL_TRACE_ENABLED
static kaa_logger_t * logger_ = NULL;
#endif

void *kaa_trace_memory_allocs_malloc(size_t s, const char *file, int line) {
#if KAA_LOG_LEVEL_TRACE_ENABLED
    void *ptr = __KAA_MALLOC(s);
    if (logger_)
        kaa_log_write(logger_, file, line, KAA_LOG_LEVEL_TRACE, KAA_ERR_NONE, "Allocated (using malloc) %d bytes at {%p}", s, ptr);
    return ptr;
#else
    return malloc(s);
#endif
}

void *kaa_trace_memory_allocs_calloc(size_t n, size_t s, const char *file, int line) {
#if KAA_LOG_LEVEL_TRACE_ENABLED
    void *ptr = __KAA_CALLOC(n, s);
    if (logger_)
        kaa_log_write(logger_, file, line, KAA_LOG_LEVEL_TRACE, KAA_ERR_NONE, "Allocated (using calloc) %u blocks of %u bytes (total %u) at {%p}", n, s, n*s, ptr);
    return ptr;
#else
    return calloc(n, s);
#endif
}

void kaa_trace_memory_allocs_free(void * p, const char *file, int line)
{
#if KAA_LOG_LEVEL_TRACE_ENABLED
    if (logger_)
        kaa_log_write(logger_, file, line, KAA_LOG_LEVEL_TRACE, KAA_ERR_NONE, "Going to deallocate memory at {%p}", p);
#endif
    __KAA_FREE(p);
}

void kaa_trace_memory_allocs_set_logger(kaa_logger_t *logger)
{
#if KAA_LOG_LEVEL_TRACE_ENABLED
    logger_ = logger;
#endif
}

#endif


text:
https://github.com/politza/pdf-tools

```
brew install poppler automake
export PKG_CONFIG_PATH=/usr/local/Cellar/zlib/1.2.8/lib/pkgconfig:/usr/local/lib/pkgconfig:/opt/X11/lib/pkgconfig
```

```
$ cd /path/to/pdf-tools
$ make install-server-deps # optional
$ make -s
```


text:
use serde_json::Value;

pub enum Message {
    Join,
}

use self::Message::*;

impl Message {
    pub fn build(&self, stage_id: i32) -> Value {
        match *self {
            Join => {
                let identifier = json!({
                    "channel": "ColoredDeployLogChannel",
                    "stage_id": stage_id,
                    "color": "",
                });

                json!({
                    "command": "subscribe",
                    "identifier": identifier.to_string(),
                })
            }
        }
    }
}


text:
namespace blink {

// This class parses a multipart message which is supplied (possible in chunks)
// to MultipartParser::appendData which parses the data and passes resulting
// part header fields and data to Client.
//
// - MultipartParser::appendData does not accept base64, quoted-printable nor
//   otherwise transfer encoded multipart message parts (no-op transfer
//   encodings "binary", "7bit" and "8bit" are OK).
// - If MultipartParser::cancel() is called, Client's methods will not be
//   called anymore.
class CORE_EXPORT MultipartParser final
    : public GarbageCollected<MultipartParser> {
 public:
  // Client recieves parsed part header fields and data.
  class CORE_EXPORT Client : public GarbageCollectedMixin {
   public:
    virtual ~Client() = default;
    // The method is called whenever header fields of a part are parsed.
    virtual void PartHeaderFieldsInMultipartReceived(
        const HTTPHeaderMap& header_fields) = 0;
    // The method is called whenever some data of a part is parsed which
    // can happen zero or more times per each part. It always holds that
    // |size| > 0.
    virtual void PartDataInMultipartReceived(const char* bytes, size_t) = 0;
    // The method is called whenever all data of a complete part is parsed.
    virtual void PartDataInMultipartFullyReceived() = 0;
    void Trace(Visitor* visitor) override {}
  };

  MultipartParser(Vector<char> boundary, Client*);
  bool AppendData(const char* bytes, size_t);
  void Cancel();
  bool Finish();

  bool IsCancelled() const { return state_ == State::kCancelled; }

  void Trace(Visitor*);

 private:
  class Matcher {
    DISALLOW_NEW();

   public:
    Matcher();
    Matcher(const char* data, size_t num_matched_bytes, size_t);

    bool Match(char value) {
      DCHECK_LT(num_matched_bytes_, size_);
      if (value != data_[num_matched_bytes_])
        return false;
      ++num_matched_bytes_;
      return true;
    }
    bool Match(const char* first, const char* last);
    bool IsMatchComplete() const { return num_matched_bytes_ == size_; }
    size_t NumMatchedBytes() const { return num_matched_bytes_; }
    void SetNumMatchedBytes(size_t);

    const char* Data() const { return data_; }

   private:
    const char* data_ = nullptr;
    size_t num_matched_bytes_ = 0u;
    size_t size_ = 0u;
  };

  Matcher CloseDelimiterSuffixMatcher() const;
  Matcher DelimiterMatcher(size_t num_already_matched_bytes = 0u) const;
  Matcher DelimiterSuffixMatcher() const;

  void ParseDataAndDelimiter(const char** bytes_pointer, const char* bytes_end);
  void ParseDelimiter(const char** bytes_pointer, const char* bytes_end);
  bool ParseHeaderFields(const char** bytes_pointer,
                         const char* bytes_end,
                         HTTPHeaderMap* header_fields);
  void ParseTransportPadding(const char** bytes_pointer,
                             const char* bytes_end) const;

  Matcher matcher_;
  Vector<char> buffered_header_bytes_;
  Member<Client> client_;
  Vector<char> delimiter_;

  enum class State {
    kParsingPreamble,
    kParsingDelimiterSuffix,
    kParsingPartHeaderFields,
    kParsingPartOctets,
    kParsingDelimiterOrCloseDelimiterSuffix,
    kParsingCloseDelimiterSuffix,
    kParsingEpilogue,
    kCancelled,
    kFinished
  } state_;

  DISALLOW_COPY_AND_ASSIGN(MultipartParser);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_MULTIPART_PARSER_H_


text:
package com.android.email.mail.store.imap;

import static com.android.email.mail.store.imap.ImapTestUtils.*;

import com.android.email.mail.store.imap.ImapElement;
import com.android.email.mail.store.imap.ImapList;
import com.android.email.mail.store.imap.ImapSimpleString;
import com.android.email.mail.store.imap.ImapString;

import android.test.suitebuilder.annotation.SmallTest;

import junit.framework.TestCase;

@SmallTest
public class ImapListTest extends TestCase {

    /**
     * Test for small functions.  (isList, isString, isEmpty and size)
     */
    public void testBasics() {
        ImapList list = new ImapList();

        assertTrue(list.isList());
        assertFalse(list.isString());

        assertTrue(list.isEmpty());
        assertEquals(0, list.size());

        list.add(STRING_1);
        assertFalse(list.isEmpty());
        assertEquals(1, list.size());

        list.add(STRING_2);
        assertEquals(2, list.size());

        list.add(LIST_1);
        assertEquals(3, list.size());
    }

    /**
     * Test for {@link ImapList#EMPTY}.
     */
    public void testEmpty() {
        assertTrue(ImapList.EMPTY.isEmpty());
    }

    public void testIs() {
        final ImapString ABC = new ImapSimpleString("AbC");
        ImapList list = buildList(ImapList.EMPTY, ABC, LIST_1, ImapString.EMPTY);

        assertFalse(list.is(0, "abc"));
        assertFalse(list.is(1, "ab"));
        assertTrue (list.is(1, "abc"));
        assertFalse(list.is(2, "abc"));
        assertFalse(list.is(3, "abc"));
        assertFalse(list.is(4, "abc"));

        assertFalse(list.is(0, "ab", false));
        assertFalse(list.is(1, "ab", false));
        assertTrue (list.is(1, "abc", false));
        assertFalse(list.is(2, "ab", false));
        assertFalse(list.is(3, "ab", false));
        assertFalse(list.is(4, "ab", false));

        assertFalse(list.is(0, "ab", true));
        assertTrue (list.is(1, "ab", true));
        assertTrue (list.is(1, "abc", true));
        assertFalse(list.is(2, "ab", true));
        assertFalse(list.is(3, "ab", true));
        assertFalse(list.is(4, "ab", true));

        // Make sure null is okay
        assertFalse(list.is(0, null, false));

        // Make sure won't crash with empty list
        assertFalse(ImapList.EMPTY.is(0, "abc"));
    }

    public void testGetElementOrNone() {
        ImapList list = buildList(ImapList.EMPTY, STRING_1, LIST_1, ImapString.EMPTY);

        assertElement(ImapList.EMPTY,   list.getElementOrNone(0));
        assertElement(STRING_1,         list.getElementOrNone(1));
        assertElement(LIST_1,           list.getElementOrNone(2));
        assertElement(ImapString.EMPTY, list.getElementOrNone(3));
        assertElement(ImapElement.NONE, list.getElementOrNone(4)); // Out of index.

        // Make sure won't crash with empty list
        assertElement(ImapElement.NONE, ImapList.EMPTY.getElementOrNone(0));
    }

    public void testGetListOrEmpty() {
        ImapList list = buildList(ImapList.EMPTY, STRING_1, LIST_1, ImapString.EMPTY);

        assertElement(ImapList.EMPTY, list.getListOrEmpty(0));
        assertElement(ImapList.EMPTY, list.getListOrEmpty(1));
        assertElement(LIST_1,         list.getListOrEmpty(2));
        assertElement(ImapList.EMPTY, list.getListOrEmpty(3));
        assertElement(ImapList.EMPTY, list.getListOrEmpty(4)); // Out of index.

        // Make sure won't crash with empty list
        assertElement(ImapList.EMPTY, ImapList.EMPTY.getListOrEmpty(0));
    }

    public void testGetStringOrEmpty() {
        ImapList list = buildList(ImapList.EMPTY, STRING_1, LIST_1, ImapString.EMPTY);

        assertElement(ImapString.EMPTY, list.getStringOrEmpty(0));
        assertElement(STRING_1,         list.getStringOrEmpty(1));
        assertElement(ImapString.EMPTY, list.getStringOrEmpty(2));
        assertElement(ImapString.EMPTY, list.getStringOrEmpty(3));
        assertElement(ImapString.EMPTY, list.getStringOrEmpty(4)); // Out of index.

        // Make sure won't crash with empty list
        assertElement(ImapString.EMPTY, ImapList.EMPTY.getStringOrEmpty(0));
    }

    public void testGetKeyedElementOrNull() {
        final ImapString K1 = new ImapSimpleString("aBCd");
        final ImapString K2 = new ImapSimpleString("Def");
        final ImapString K3 = new ImapSimpleString("abC");

        ImapList list = buildList(
                K1, STRING_1,
                K2, K3,
                K3, STRING_2);

        assertElement(null,     list.getKeyedElementOrNull("ab", false));
        assertElement(STRING_1, list.getKeyedElementOrNull("abcd", false));
        assertElement(K3,       list.getKeyedElementOrNull("def", false));
        assertElement(STRING_2, list.getKeyedElementOrNull("abc", false));

        assertElement(STRING_1, list.getKeyedElementOrNull("ab", true));
        assertElement(STRING_1, list.getKeyedElementOrNull("abcd", true));
        assertElement(K3,       list.getKeyedElementOrNull("def", true));
        assertElement(STRING_1, list.getKeyedElementOrNull("abc", true));

        // Make sure null is okay
        assertElement(null, list.getKeyedElementOrNull(null, false));

        // Make sure won't crash with empty list
        assertNull(ImapList.EMPTY.getKeyedElementOrNull("ab", false));

        // Shouldn't crash with a list with an odd number of elements.
        assertElement(null, buildList(K1).getKeyedElementOrNull("abcd", false));
    }

    public void getKeyedListOrEmpty() {
        final ImapString K1 = new ImapSimpleString("Key");
        ImapList list = buildList(K1, LIST_1);

        assertElement(LIST_1,         list.getKeyedListOrEmpty("key", false));
        assertElement(LIST_1,         list.getKeyedListOrEmpty("key", true));
        assertElement(ImapList.EMPTY, list.getKeyedListOrEmpty("ke", false));
        assertElement(LIST_1,         list.getKeyedListOrEmpty("ke", true));

        assertElement(ImapList.EMPTY, list.getKeyedListOrEmpty("ke"));
        assertElement(LIST_1,         list.getKeyedListOrEmpty("key"));
    }

    public void getKeyedStringOrEmpty() {
        final ImapString K1 = new ImapSimpleString("Key");
        ImapList list = buildList(K1, STRING_1);

        assertElement(STRING_1,         list.getKeyedListOrEmpty("key", false));
        assertElement(STRING_1,         list.getKeyedListOrEmpty("key", true));
        assertElement(ImapString.EMPTY, list.getKeyedListOrEmpty("ke", false));
        assertElement(STRING_1,         list.getKeyedListOrEmpty("ke", true));

        assertElement(ImapString.EMPTY, list.getKeyedListOrEmpty("ke"));
        assertElement(STRING_1,         list.getKeyedListOrEmpty("key"));
    }

    public void testContains() {
        final ImapString K1 = new ImapSimpleString("aBCd");
        final ImapString K2 = new ImapSimpleString("Def");
        final ImapString K3 = new ImapSimpleString("abC");

        ImapList list = buildList(K1, K2, K3);

        assertTrue(list.contains("abc"));
        assertTrue(list.contains("abcd"));
        assertTrue(list.contains("def"));
        assertFalse(list.contains(""));
        assertFalse(list.contains("a"));
        assertFalse(list.contains(null));

        // Make sure null is okay
        assertFalse(list.contains(null));

        // Make sure won't crash with empty list
        assertFalse(ImapList.EMPTY.contains(null));
    }

    public void testFlatten() {
        assertEquals("[]", ImapList.EMPTY.flatten());
        assertEquals("[aBc]", buildList(STRING_1).flatten());
        assertEquals("[[]]", buildList(ImapList.EMPTY).flatten());
        assertEquals("[aBc,[,X y z],aBc]",
                buildList(STRING_1, buildList(ImapString.EMPTY, STRING_2), STRING_1).flatten());
    }
}


text:
# iPhoneX 适配

safe area

## UIViewController

```objc

/* Custom container UIViewController subclasses can use this property to add to the overlay
 that UIViewController calculates for the safeAreaInsets for contained view controllers.
 */
@property(nonatomic) UIEdgeInsets additionalSafeAreaInsets API_AVAILABLE(ios(11.0), tvos(11.0));
// These objects may be used as layout items in the NSLayoutConstraint API
@property(nonatomic,readonly,strong) id<UILayoutSupport> topLayoutGuide API_DEPRECATED_WITH_REPLACEMENT("-[UIView safeAreaLayoutGuide]", ios(7.0,11.0), tvos(7.0,11.0));
@property(nonatomic,readonly,strong) id<UILayoutSupport> bottomLayoutGuide API_DEPRECATED_WITH_REPLACEMENT("-[UIView safeAreaLayoutGuide]", ios(7.0,11.0), tvos(7.0,11.0));

- (void)viewSafeAreaInsetsDidChange NS_REQUIRES_SUPER API_AVAILABLE(ios(11.0), tvos(11.0));

```

## UIView

```objc
@property (nonatomic) BOOL insetsLayoutMarginsFromSafeArea API_AVAILABLE(ios(11.0),tvos(11.0));  // Default: YES
@property (nonatomic,readonly) UIEdgeInsets safeAreaInsets
@property(nonatomic,readonly,strong) UILayoutGuide *safeAreaLayoutGuide

- (void)safeAreaInsetsDidChange
```

## react native

初始化 和 `safeAreaInsetsDidChange` 的时候,

1. 设置 `statusBar` height 和 paddingTop,适配 top。

```
paddingTop = safeArea.top。
height += paddingTop
```

2. 设置 `tabBar` height 和 paddingBottom,适配 bottom。

```
paddingBottom = safeArea.bottom
height += paddingBottom
```

3. `scrollview` 及所有子类,例如 `flatList` `listView`,设置  `contentInset` 或 `scrollIndicatorInsets` 属性,适配 bottom

```
scrollview.contentInset = {0, 0, safeArea.bottom, 0}
```

或

```
scrollview.scrollIndicatorInsets = {top: 0, left: 0, bottom: safeArea.bottom, right: 0}
```

两个效果是一样的,原生调用的同样的代码

4. `webview` 设置 `contentInset`

```
webview.contentInset = {top: 0, left: 0, bottom: safeArea.bottom, right: 0}
```

## References

* [Human Interface Guidelines - iPhoneX](https://developer.apple.com/ios/human-interface-guidelines/overview/iphone-x/)
* [Positioning Content Relative to the Safe Area](https://developer.apple.com/documentation/uikit/uiview/positioning_content_relative_to_the_safe_area)
* [iOS 指纹识别常见问题汇总](http://www.jianshu.com/p/d44b7d85e0a6)


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

	<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
	<title></title>
	<meta name="generator" content="LibreOffice 4.4.5.2 (Linux)"/>
	<meta name="created" content="2006-09-16T00:00:00"/>
	<meta name="changed" content="2015-09-15T00:20:24"/>
	<meta name="AppVersion" content="14.0300"/>
	<meta name="DocSecurity" content="0"/>
	<meta name="HyperlinksChanged" content="false"/>
	<meta name="LinksUpToDate" content="false"/>
	<meta name="ScaleCrop" content="false"/>
	<meta name="ShareDoc" content="false"/>

	<colgroup width="104"></colgroup>
	<colgroup width="192"></colgroup>
	<colgroup width="137"></colgroup>
	<colgroup width="236"></colgroup>
	<colgroup width="152"></colgroup>

		State
		Theater Name
		City
		Show Times
		Online Tickets

		California

		Towne3 Cinemas
		San Jose
		Full Schedule from 9/16
		www.towne3.com

		Simi Valley Cinemas
		SimiValley
		9/19: 10:00 PM
		www.eknazar.com

		Georgia

		Aakash Cinemas
		Rosewell
		Schedule from 9/17
		www.aakashcinemas.com

		Illinois

		Movie Max (BIG Cinemas)
		Niles
		Full Schedule from 9/16
		www.moviemax.com

		Michigan

		Cinemark Movies 16
		Warren
		Full Schedule from 9/17
		www.cinemark.com

		New Jersey

		Columbia Park 12
		North Bergen
		Full Schedule from 9/17
		www.fandango.com

		Ohio

		Screen at Continent
		Columbus
		Schedule from 9/17
		www.screen8.net

		Texas

		Regal Macarthur Market Place
		Irving
		Full Schedule from 9/17
		www.fandango.com

		Cinemark Movies 16
		San Antonio
		Full Schedule from 9/17
		www.cinemark.com

		Virginia

		DC Cinemas
		Falls Church
		Full Schedule from 9/16
		www.dccinemas.com

		Washington

		Roxy Cinema
		Renton
		Schedule from 9/18


text:
clients = {
    "statsd": ("pghoard.monitoring.statsd", "StatsClient"),
    "pushgateway": ("pghoard.monitoring.pushgateway", "PushgatewayClient"),
    "prometheus": ("pghoard.monitoring.prometheus", "PrometheusClient"),
}


text:
extern VALUE cMysql2Statement;

typedef struct {
  VALUE client;
  MYSQL_STMT *stmt;
  int refcount;
} mysql_stmt_wrapper;

void init_mysql2_statement();
void decr_mysql2_stmt(mysql_stmt_wrapper *stmt_wrapper);

VALUE rb_mysql_stmt_new(VALUE rb_client, VALUE sql);
VALUE rb_raise_mysql2_stmt_error2(MYSQL_STMT *stmt
#ifdef HAVE_RUBY_ENCODING_H
  , rb_encoding* conn_enc
#endif
  );

#endif


text:
use crate::real_std::{
    fmt, fs,
    path::PathBuf,
    pin::Pin,
    sync::{Arc, Mutex},
};

use {
    collect_mac::collect,
    futures::{
        future::{self, BoxFuture},
        prelude::*,
        ready,
        task::{self, Poll},
    },
    http::{
        header::{HeaderMap, HeaderName, HeaderValue},
        StatusCode,
    },
    hyper::{body::Bytes, Server},
    pin_project_lite::pin_project,
};

use crate::base::types::{ArcType, Type};

use crate::{
    vm::{
        self,
        api::{
            generic, Collect, Eff, Function, Getable, OpaqueValue, PushAsRef, Pushable, VmType,
            WithVM, IO,
        },
        thread::{ActiveThread, RootedThread, Thread},
        ExternModule, Variants,
    },
    Error,
};

macro_rules! try_future {
    ($e:expr) => {
        try_future!($e, Box::pin)
    };
    ($e:expr, $f:expr) => {
        match $e {
            Ok(x) => x,
            Err(err) => return $f(::futures::future::err(err.into())),
        }
    };
}

pub struct HttpEffect;
impl VmType for HttpEffect {
    type Type = Self;
    fn make_type(vm: &Thread) -> ArcType {
        let r = generic::R::make_type(vm);
        Type::app(
            vm.find_type_info("std.http.types.HttpEffect")
                .map(|alias| alias.into_type())
                .unwrap_or_else(|_| Type::hole()),
            collect![r],
        )
    }
}

pub type EffectHandler<T> = Eff<HttpEffect, T>;

pub struct Headers(HeaderMap);

impl VmType for Headers {
    type Type = Vec<(String, Vec<u8>)>;

    fn make_type(vm: &Thread) -> ArcType {
        Vec::<(String, Vec<u8>)>::make_type(vm)
    }
}

impl<'vm> Pushable<'vm> for Headers {
    fn vm_push(self, context: &mut ActiveThread<'vm>) -> vm::Result<()> {
        Collect::new(
            self.0
                .iter()
                .map(|(name, value)| (name.as_str(), value.as_bytes())),
        )
        .vm_push(context)
    }
}

impl<'vm, 'value> Getable<'vm, 'value> for Headers {
    impl_getable_simple!();

    fn from_value(vm: &'vm Thread, value: Variants<'value>) -> Self {
        Headers(
            Collect::from_value(vm, value)
                // TODO Error somehow on invalid headers
                .filter_map(|(name, value): (&str, &[u8])| {
                    match (
                        HeaderName::from_bytes(name.as_bytes()),
                        HeaderValue::from_bytes(value),
                    ) {
                        (Ok(name), Ok(value)) => Some((name, value)),
                        _ => None,
                    }
                })
                .collect(),
        )
    }
}

// By implementing `Userdata` on `Body` it can be automatically pushed and retrieved from gluon
// threads
#[derive(Userdata, Trace, VmType, Clone)]
#[gluon(vm_type = "std.http.types.Body")]
#[gluon(crate_name = "::vm")]
#[gluon_userdata(clone)]
#[gluon_trace(skip)]
// Representation of a http body that is in the prograss of being read
pub struct Body(
    Arc<Mutex<Pin<Box<dyn Stream<Item = Result<PushAsRef<Bytes, [u8]>, vm::Error>> + Send>>>>,
);

// Types implementing `Userdata` requires a `std::fmt::Debug` implementation so it can be displayed
impl fmt::Debug for Body {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "hyper::Body")
    }
}

// Since `Body` implements `Userdata` gluon will automatically marshal the gluon representation
// into `&Body` argument
fn read_chunk(body: &Body) -> impl Future<Output = IO<Option<PushAsRef<Bytes, [u8]>>>> {
    use futures::future::poll_fn;

    let body = body.0.clone();
    poll_fn(move |cx| {
        let mut stream = body.lock().unwrap();
        Poll::Ready(IO::Value(
            if let Some(result) = ready!(stream.as_mut().poll_next(cx)) {
                match result {
                    Ok(chunk) => Some(chunk),
                    Err(err) => return IO::Exception(err.to_string()).into(),
                }
            } else {
                None
            },
        ))
    })
}

// A http body that is being written
#[derive(Userdata, Trace, VmType, Clone)]
#[gluon(vm_type = "std.http.types.ResponseBody")]
#[gluon(crate_name = "::vm")]
#[gluon_userdata(clone)]
#[gluon_trace(skip)]
pub struct ResponseBody(Arc<Mutex<Option<hyper::body::Sender>>>);

impl fmt::Debug for ResponseBody {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "ResponseBody")
    }
}

fn write_response(response: &ResponseBody, bytes: &[u8]) -> impl Future<Output = IO<()>> {
    use futures::future::poll_fn;

    // Turn `bytes´ into a `Bytes` which can be sent to the http body
    let mut unsent_chunk = Some(bytes.to_owned().into());
    let response = response.0.clone();
    poll_fn(move |cx| {
        info!("Starting response send");
        let mut sender = response.lock().unwrap();
        let sender = sender
            .as_mut()
            .expect("Sender has been dropped while still in use");
        let chunk = unsent_chunk
            .take()
            .expect("Attempt to poll after chunk is sent");
        match sender.poll_ready(cx) {
            Poll::Pending => {
                unsent_chunk = Some(chunk);
                return Poll::Pending;
            }
            Poll::Ready(Ok(_)) => (),
            Poll::Ready(Err(err)) => {
                info!("Could not send http response {}", err);
                return IO::Exception(err.to_string()).into();
            }
        }
        match sender.try_send_data(chunk) {
            Ok(()) => Poll::Ready(IO::Value(())),
            Err(chunk) => {
                unsent_chunk = Some(chunk);
                IO::Exception("Could not send http response".into()).into()
            }
        }
    })
}

#[derive(Debug, Userdata, Trace, VmType, Clone)]
#[gluon(vm_type = "std.http.types.Uri")]
#[gluon(crate_name = "::vm")]
#[gluon_trace(skip)]
#[gluon_userdata(clone)]
struct Uri(http::Uri);

// Next we define some record types which are marshalled to and from gluon. These have equivalent
// definitions in http_types.glu
field_decl! { http, method, uri, status, body, request, response, headers }

type Request = record_type! {
    method => String,
    uri => Uri,
    body => Body
};

pub type Response = record_type! {
    status => u16,
    headers => Headers
};

type HttpState = record_type! {
    request => Request,
    response => ResponseBody
};

#[derive(Getable, VmType)]
#[gluon(crate_name = "::vm")]
struct Settings {
    port: u16,
    tls_cert: Option<PathBuf>,
}

fn listen(
    settings: Settings,
    WithVM { vm, value }: WithVM<OpaqueValue<RootedThread, EffectHandler<Response>>>,
) -> impl Future<Output = IO<()>> + Send + 'static {
    let vm = vm.root_thread();
    listen_(settings, vm, value).map(IO::from)
}

async fn listen_(
    settings: Settings,
    thread: RootedThread,
    handler: OpaqueValue<RootedThread, EffectHandler<Response>>,
) -> vm::Result<()> {
    let thread = match thread.new_thread() {
        Ok(thread) => thread,
        Err(err) => return Err(err),
    };

    impl tower_service::Service<hyper::Request<hyper::Body>> for Handler {
        type Response = hyper::Response<hyper::Body>;
        type Error = Error;
        type Future = BoxFuture<'static, Result<http::Response<hyper::Body>, Error>>;

        fn poll_ready(&mut self, _cx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
            Ok(()).into()
        }

        fn call(&mut self, request: hyper::Request<hyper::Body>) -> Self::Future {
            let (parts, body) = request.into_parts();
            self.handle(parts.method, parts.uri, body)
        }
    }

    let addr = format!("0.0.0.0:{}", settings.port).parse().unwrap();

    let listener = Handler::new(&thread, handler);

    if let Some(cert_path) = &settings.tls_cert {
        let identity = fs::read(cert_path).map_err(|err| {
            vm::Error::Message(format!(
                "Unable to open certificate `{}`: {}",
                cert_path.display(),
                err
            ))
        })?;

        let identity = native_tls::Identity::from_pkcs12(&identity, "")
            .map_err(|err| vm::Error::Message(err.to_string()))?;
        let acceptor = tokio_native_tls::TlsAcceptor::from(
            native_tls::TlsAcceptor::new(identity)
                .map_err(|err| vm::Error::Message(err.to_string()))?,
        );

        let http = hyper::server::conn::Http::new();

        let tcp_listener = tokio::net::TcpListener::bind(&addr)
            .map_err(|err| vm::Error::Message(err.to_string()))
            .await?;
        let incoming = tokio_stream::wrappers::TcpListenerStream::new(tcp_listener)
            .err_into()
            .and_then(|stream| {
                acceptor.accept(stream).map_err(|err| {
                    info!("Unable to accept TLS connection: {}", err);
                    Box::new(err) as Box<dyn ::std::error::Error + Send + Sync>
                })
            });

        pin_project! {
            struct Acceptor<S> {
                #[pin]
                incoming: S,
            }
        }
        impl<S, T, E> hyper::server::accept::Accept for Acceptor<S>
        where
            S: Stream<Item = Result<T, E>>,
        {
            type Conn = T;
            type Error = E;
            fn poll_accept(
                self: Pin<&mut Self>,
                cx: &mut task::Context<'_>,
            ) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
                self.project().incoming.poll_next(cx)
            }
        }

        return hyper::server::Builder::new(Acceptor { incoming }, http)
            .serve(hyper::service::make_service_fn(move |_| {
                future::ready(Ok::<_, hyper::Error>(listener.clone()))
            }))
            .map_err(|err| vm::Error::from(format!("Server error: {}", err)))
            .await;
    }

    Server::bind(&addr)
        .serve(hyper::service::make_service_fn(move |_| {
            future::ready(Ok::<_, hyper::Error>(listener.clone()))
        }))
        .map_err(|err| vm::Error::from(format!("Server error: {}", err)))
        .map_ok(|_| ())
        .await
}

type ListenFn = fn(OpaqueValue<RootedThread, EffectHandler<Response>>, HttpState) -> IO<Response>;

#[derive(Clone)]
pub struct Handler {
    handle: Function<RootedThread, ListenFn>,
    handler: OpaqueValue<RootedThread, EffectHandler<Response>>,
}

impl Handler {
    pub fn new(
        thread: &Thread,
        handler: OpaqueValue<RootedThread, EffectHandler<Response>>,
    ) -> Self {
        // Retrieve the `handle` function from the http module which we use to evaluate values of type
        // `EffectHandler Response`
        let handle: Function<RootedThread, ListenFn> = thread
            .get_global("std.http.handle")
            .unwrap_or_else(|err| panic!("{}", err));
        Self { handle, handler }
    }

    pub fn handle<E>(
        &mut self,
        method: http::Method,
        uri: http::Uri,
        body: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
    ) -> BoxFuture<'static, crate::Result<hyper::Response<hyper::Body>>>
    where
        E: fmt::Display + Send + 'static,
    {
        let child_thread = try_future!(self.handle.vm().new_thread());
        let mut handle = try_future!(self.handle.re_root(child_thread));

        let gluon_request = record_no_decl! {
            method => method.as_str().to_owned(),
            uri => Uri(uri),
            // Since `Body` implements `Userdata` it can be directly pushed to gluon
            body => Body(Arc::new(Mutex::new(Box::pin(
                body
                    .map_err(|err| vm::Error::Message(format!("{}", err)))
                    // `PushAsRef` makes the `body` parameter act as a `&[u8]` which means it is
                    // marshalled to `Array Byte` in gluon
                    .map_ok(PushAsRef::<_, [u8]>::new)
            ))))
        };
        let (response_sender, response_body) = hyper::Body::channel();
        let response_sender = Arc::new(Mutex::new(Some(response_sender)));
        let http_state = record_no_decl! {
            request => gluon_request,
            response => ResponseBody(response_sender.clone())
        };

        let handler = self.handler.clone();
        Box::pin(async move {
            handle
                .call_async(handler, http_state)
                .map(move |result| match result {
                    Ok(value) => {
                        match value {
                            IO::Value(record_p! { status, headers }) => {
                                // Drop the sender to so that it the receiver stops waiting for
                                // more chunks
                                *response_sender.lock().unwrap() = None;

                                let status = StatusCode::from_u16(status)
                                    .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                                let mut response = http::Response::builder()
                                    .status(status)
                                    .body(response_body)
                                    .unwrap();
                                *response.headers_mut() = headers.0;
                                Ok(response)
                            }
                            IO::Exception(err) => {
                                info!("{}", err);
                                Ok(http::Response::builder()
                                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                                    .body("".into())
                                    .unwrap())
                            }
                        }
                    }
                    Err(err) => {
                        info!("{}", err);
                        Ok(http::Response::builder()
                            .status(StatusCode::INTERNAL_SERVER_ERROR)
                            .body("".into())
                            .unwrap())
                    }
                })
                .await
        })
    }
}

// To let the `http_types` module refer to `Body` and `ResponseBody` we register these types in a
// separate function which is called before loading `http_types`
pub fn load_types(vm: &Thread) -> vm::Result<ExternModule> {
    vm.register_type::<Body>("std.http.types.Body", &[])?;
    vm.register_type::<ResponseBody>("std.http.types.ResponseBody", &[])?;
    vm.register_type::<Uri>("std.http.types.Uri", &[])?;

    ExternModule::new(
        vm,
        record! {
            // Define the types so that they can be used from gluon
            type std::http::types::Body => Body,
            type std::http::types::ResponseBody => ResponseBody,
            type std::http::types::Uri => Uri,
            type std::http::Method => String,
            type std::http::StatusCode => u16,
            type std::http::Request => Request,
            type std::http::Response => Response,
            type std::http::Headers => Headers,
            type std::http::HttpState => HttpState
        },
    )
}

macro_rules! uri_binds {
    ($($id: ident)*) => {
        record!{
            $(
                $id => primitive!(1, concat!("std.http.prim.uri.", stringify!($id)), |u: &Uri| (u.0).$id())
            ),*
        }
    }
}

mod std {
    pub(crate) mod http {
        pub(crate) use crate::std_lib::http as prim;
    }
}

pub fn load(vm: &Thread) -> vm::Result<ExternModule> {
    ExternModule::new(
        vm,
        record! {
            listen => primitive!(2, async fn std::http::prim::listen),
            read_chunk => primitive!(1, async fn std::http::prim::read_chunk),
            write_response => primitive!(2, async fn std::http::prim::write_response),
            port => primitive!(1, "std.http.prim.uri.port", |u: &Uri| (u.0).port().map(|p| p.as_u16())),
            uri => uri_binds!(path host query to_string)
        },
    )
}


text:
<?php

namespace TreeHouse\IoBundle\Tests\Scrape\Crawler\Log;

use TreeHouse\IoBundle\Scrape\Crawler\Log\RedisRequestLogger;

class RedisRequestLoggerTest extends AbstractRequestLoggerTest
{
    /**
     * @inheritdoc
     */
    protected function getLogger()
    {
        if (!extension_loaded('redis')) {
            $this->markTestSkipped('Redis extension not loaded');
        }

        $redis = new \Redis();

        if (false === $redis->connect('localhost', 6379, 1)) {
            $this->markTestSkipped('Could not connect to Redis server');
        }

        $redis->flushDB();

        return new RedisRequestLogger($redis);
    }
}


text:
module Amazing
  def amazing?
    true
  end
end

class RubyLanguage

end

ruby_language = RubyLanguage.new
ruby_language.extend Amazing
puts ruby_language.amazing?
ruby_language2 = RubyLanguage.new
puts ruby_language2.amazing? #Error


text:
'use strict';

angular
	.module('ngFoundation.rangeSlider', [])

	.provider('$rangeSlider', function () {
		var $rangeSliderProvider = this;

		this.defaults = {
			start: 0,
			end: 100,
			step: 1,
			initial: null,
			vertical: false,
			onChange: function () {}
		};

		this.$get = function ($rootScope, $window, $fd, $q, $timeout) {
			function $RangeSliderFactory ($element, options) {
				var $rangeSlider = {};

				options = $rangeSlider.$options = angular.extend({}, $rangeSliderProvider.defaults, options);
				$rangeSlider.$options.$scope = $rangeSlider.$options.$scope || $rootScope.$new();
				$rangeSlider.$element = $element;
				$rangeSlider.$handle = null;
				$rangeSlider.$segment = null;

				$rangeSlider.$setHandle = function ($handle) {
					$rangeSlider.$handle = $handle;
				};

				$rangeSlider.onTouchstart = function (event) {};

				$rangeSlider.onTouchmove = function (event) {
					var scrollOffset = 0;

					if(!event.pageY) {
						scrollOffset = $window.scrollY;
					}

					$rangeSlider.applyPosition((event.pageY
					|| event.originalEvent.clientY
					|| event.originalEvent.touches[0].clientY ||
					event.currentPoint.y) + scrollOffset, $rangeSlider.$handle);
				};

				$rangeSlider.$setSegment = function (element) {
					$rangeSlider.$segment = element;
				};

				$rangeSlider.onTouchend = function (event) {};

				$rangeSlider.$setUi = function (value, position) {
					var barO = position.barO,
					barL = position.barL,
					handleO = position.handleO,
					handleL = position.handleL;

					var segment = $rangeSlider.$segment,
					normalizedPercentage = $rangeSlider.$normalizedPercentage(value, options.start, options.end),
					handleOffset = normalizedPercentage * (barL - handleL) - 1,
					progressBarLength = normalizedPercentage * 100;

					if($fd.rtl && !options.vertical) {
						handleOffset = -handleOffset;
					}

					handleOffset = options.vertical ? -handleOffset + barL - handleL + 1 : handleOffset;
					$rangeSlider.$setTranslate($rangeSlider.$handle, handleOffset);

					if(options.vertical) {
						segment.css('height', progressBarLength + '%');
					} else {
						segment.css('width', progressBarLength + '%');
					}
				};

				$rangeSlider.$normalizedPercentage = function (value, start, end) {
					return Math.min(1, (value - start) / (end - start));
				};

		    $rangeSlider.$normalizedValue = function(val, start, end, step) {
		      var range = end - start,
		          point = val*range,
		          mod = (point-(point%step)) / step,
		          rem = point % step,
		          round = ( rem >= step*0.5 ? step : 0);
		      return (mod*step + round) + start;
		    };

		    $rangeSlider.$setTranslate = function (el, offset) {
		      if (options.vertical) {
		        angular.element(el).css('-webkit-transform', 'translateY('+offset+'px)')
		          .css('-moz-transform', 'translateY('+offset+'px)')
		          .css('-ms-transform', 'translateY('+offset+'px)')
		          .css('-o-transform', 'translateY('+offset+'px)')
		          .css('transform', 'translateY('+offset+'px)');
		      } else {
		        angular.element(el).css('-webkit-transform', 'translateX('+offset+'px)')
		          .css('-moz-transform', 'translateX('+offset+'px)')
		          .css('-ms-transform', 'translateX('+offset+'px)')
		          .css('-o-transform', 'translateX('+offset+'px)')
		          .css('transform', 'translateX('+offset+'px)');
		      }
		    };

		    $rangeSlider.applyPosition = function (cursorX, handle) {
		    	$rangeSlider.$applyPosition(cursorX, handle);
		    };

		    $rangeSlider.$limitTo = function (val, min, max) {
		    	return Math.min(Math.max(val, min), max);
		    };

				$rangeSlider.$applyPosition = function (cursorX, handle) {
					var barOffset = $element.offset(),
					handleOffset = handle.offset(),
					barO, barL, handleO, handleL;

					if(options.vertical) {
						barO = barOffset.top;
						barL = $element.outerHeight();
						handleO = handleOffset.top;
						handleL = handle.outerHeight();
					} else {
						barO = barOffset.left;
						barL = $element.outerWidth();
						handleO = handleOffset.left;
						handleL = handle.outerWidth();
					}

					if($fd.rtl && !options.vertical) {
						pct = $rangeSlider.$limitTo(((barO + barL - cursorX) / barL), 0, 1);
					} else {
						pct = $rangeSlider.$limitTo(((cursorX - barO) / barL), 0, 1);
					}

					pct = options.vertical ? 1 - pct : pct;

					var norm = $rangeSlider.$normalizedValue(pct, options.start, options.end, options.step);

					var position = {
						barO: barO,
						barL: barL,
						handleO: handleO,
						handleL: handleL
					};

					$rangeSlider.$setUi(norm, position);
				};

				return $rangeSlider;
			}

			return $RangeSliderFactory;
		};
	})

	.controller('RangeSliderController', function ($scope, $element, $attrs, $rangeSlider) {
		var rangeSlider = this.$rangeSlider = $rangeSlider($element, {});

		this.onTouchstart = function (event) {
			rangeSlider.onTouchstart(event);
		};

		this.onTouchmove = function (event) {
			rangeSlider.onTouchmove(event);
		};

		this.onTouchend = function (event) {
			rangeSlider.onTouchend(event);
		};
	})

	.directive('rangeSlider', function () {
		return {
			templateUrl: 'range-slider/range-slider.tpl.html',
			require: '?ngModel',
			controller: 'RangeSliderController',
			link: function (scope, element, attrs, ngModel) {
			}
		};
	})

	.directive('rangeSliderActiveSegment', function () {
		return {
			restrict: 'C',
			require: '?^rangeSlider',
			link: function preLink (scope, element, attrs, rangeSlider) {
				if(!rangeSlider) return;

				rangeSlider.$rangeSlider.$setSegment(element);
			}
		};
	})

	.directive('rangeSliderHandle', function () {
		return {
			restrict: 'C',
			require: '?^rangeSlider',
			link: function preLink (scope, element, attrs, rangeSlider) {
				if(!rangeSlider) return;

				rangeSlider.$rangeSlider.$setHandle(element);

				element.bind('mousedown pointerdown touchmove', rangeSlider.onTouchmove);
				element.bind('mousemove pointermove touchstart', rangeSlider.onTouchstart);
				element.bind('mouseup pointerup touchend', rangeSlider.onTouchend);
			}
		};
	});


text:
+++ src/System.Security.Cryptography.OpenSsl/src/SR.cs	2016-05-21 17:08:24.590347000 -0400
@@ -0,0 +1,198 @@
+using System;
+using System.Resources;
+
+namespace FxResources.System.Security.Cryptography.OpenSsl
+{
+    internal static class SR
+    {
+
+    }
+}
+
+namespace System
+{
+    internal static class SR
+    {
+        private static ResourceManager s_resourceManager;
+
+        private const String s_resourcesName = "FxResources.System.Security.Cryptography.OpenSsl.SR";
+
+	internal static string Cryptography_CurveNotSupported
+        {
+            get
+            {
+                return SR.GetResourceString("Cryptography_CurveNotSupported", null);
+            }
+        }
+
+	internal static string Cryptography_InvalidKeySize
+        {
+            get
+            {
+                return SR.GetResourceString("Cryptography_InvalidKeySize", null);
+            }
+        }
+
+        internal static String Cryptography_UnsupportedEcKeyAlgorithm
+        {
+            get
+            {
+                return SR.GetResourceString("Cryptography_UnsupportedEcKeyAlgorithm", null);
+            }
+        }
+
+		internal static String Arg_CryptographyException
+        {
+            get
+            {
+                return SR.GetResourceString("Arg_CryptographyException", null);
+            }
+        }
+
+		internal static String Cryptography_OpenInvalidHandle
+        {
+            get
+            {
+                return SR.GetResourceString("Cryptography_OpenInvalidHandle", null);
+            }
+        }
+
+		internal static String Cryptography_UnknownHashAlgorithm
+        {
+            get
+            {
+                return SR.GetResourceString("Cryptography_UnknownHashAlgorithm", null);
+            }
+        }
+
+		internal static String Argument_InvalidOidValue
+        {
+            get
+            {
+                return SR.GetResourceString("Argument_InvalidOidValue", null);
+            }
+        }
+
+		internal static String Cryptography_Invalid_IA5String
+        {
+            get
+            {
+                return SR.GetResourceString("Cryptography_Invalid_IA5String", null);
+            }
+        }
+
+		internal static String Cryptography_CSP_NoPrivateKey
+        {
+            get
+            {
+                return SR.GetResourceString("Cryptography_CSP_NoPrivateKey", null);
+            }
+        }
+
+		internal static String Argument_InvalidValue
+        {
+            get
+            {
+                return SR.GetResourceString("Argument_InvalidValue", null);
+            }
+        }
+
+		internal static String Cryptography_InvalidPaddingMode
+        {
+            get
+            {
+                return SR.GetResourceString("Cryptography_InvalidPaddingMode", null);
+            }
+        }
+
+		internal static String Cryptography_HashAlgorithmNameNullOrEmpty
+        {
+            get
+            {
+                return SR.GetResourceString("Cryptography_HashAlgorithmNameNullOrEmpty", null);
+            }
+        }
+
+        private static ResourceManager ResourceManager
+        {
+            get
+            {
+                if (SR.s_resourceManager == null)
+                {
+                    SR.s_resourceManager = new ResourceManager(SR.ResourceType);
+                }
+                return SR.s_resourceManager;
+            }
+        }
+
+        internal static Type ResourceType
+        {
+            get
+            {
+                return typeof(FxResources.System.Security.Cryptography.OpenSsl.SR);
+            }
+        }
+
+        internal static String Format(String resourceFormat, params Object[] args)
+        {
+            if (args == null)
+            {
+                return resourceFormat;
+            }
+            if (!SR.UsingResourceKeys())
+            {
+                return String.Format(resourceFormat, args);
+            }
+            return String.Concat(resourceFormat, String.Join(", ", args));
+        }
+
+        internal static String Format(String resourceFormat, Object p1)
+        {
+            if (!SR.UsingResourceKeys())
+            {
+                return String.Format(resourceFormat, p1);
+            }
+            return String.Join(", ", new Object[] { resourceFormat, p1 });
+        }
+
+        internal static String Format(String resourceFormat, Object p1, Object p2)
+        {
+            if (!SR.UsingResourceKeys())
+            {
+                return String.Format(resourceFormat, p1, p2);
+            }
+            return String.Join(", ", new Object[] { resourceFormat, p1, p2 });
+        }
+
+        internal static String Format(String resourceFormat, Object p1, Object p2, Object p3)
+        {
+            if (!SR.UsingResourceKeys())
+            {
+                return String.Format(resourceFormat, p1, p2, p3);
+            }
+            return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 });
+        }
+
+        internal static String GetResourceString(String resourceKey, String defaultString)
+        {
+            String str = null;
+            try
+            {
+                str = SR.ResourceManager.GetString(resourceKey);
+            }
+            catch (MissingManifestResourceException missingManifestResourceException)
+            {
+            }
+            if (defaultString != null && resourceKey.Equals(str))
+            {
+                return defaultString;
+            }
+            return str;
+        }
+
+        private static Boolean UsingResourceKeys()
+        {
+            return false;
+        }
+    }
+}


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "weblayer/browser/browser_main_parts_impl.h"

#include "base/base_switches.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/json/json_reader.h"
#include "base/run_loop.h"
#include "base/task/current_thread.h"
#include "base/task/task_traits.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "cc/base/switches.h"
#include "components/captive_portal/core/buildflags.h"
#include "components/performance_manager/embedder/graph_features.h"
#include "components/performance_manager/embedder/performance_manager_lifetime.h"
#include "components/prefs/pref_service.h"
#include "components/startup_metric_utils/browser/startup_metric_utils.h"
#include "components/subresource_filter/content/browser/ruleset_service.h"
#include "components/translate/core/browser/translate_download_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/page_visibility_state.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/url_constants.h"
#include "ui/base/resource/resource_bundle.h"
#include "weblayer/browser/accept_languages_service_factory.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/cookie_settings_factory.h"
#include "weblayer/browser/feature_list_creator.h"
#include "weblayer/browser/heavy_ad_service_factory.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/i18n_util.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_link_manager_factory.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h"
#include "weblayer/browser/origin_trials_factory.h"
#include "weblayer/browser/permissions/weblayer_permissions_client.h"
#include "weblayer/browser/stateful_ssl_host_state_delegate_factory.h"
#include "weblayer/browser/subresource_filter_profile_context_factory.h"
#include "weblayer/browser/translate_ranker_factory.h"
#include "weblayer/browser/web_data_service_factory.h"
#include "weblayer/browser/webui/web_ui_controller_factory.h"
#include "weblayer/grit/weblayer_resources.h"
#include "weblayer/public/main.h"

#if BUILDFLAG(IS_ANDROID)
#include "base/command_line.h"
#include "components/crash/content/browser/child_exit_observer_android.h"
#include "components/crash/content/browser/child_process_crash_observer_android.h"
#include "components/crash/core/common/crash_key.h"
#include "components/javascript_dialogs/android/app_modal_dialog_view_android.h"  // nogncheck
#include "components/javascript_dialogs/app_modal_dialog_manager.h"  // nogncheck
#include "components/metrics/metrics_service.h"
#include "components/variations/synthetic_trials_active_group_id_provider.h"
#include "components/variations/variations_ids_provider.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "weblayer/browser/android/metrics/uma_utils.h"
#include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
#include "weblayer/browser/java/jni/MojoInterfaceRegistrar_jni.h"
#include "weblayer/browser/media/local_presentation_manager_factory.h"
#include "weblayer/browser/media/media_router_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_metrics_collector_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_navigation_observer_manager_factory.h"
#include "weblayer/browser/site_engagement/site_engagement_service_factory.h"
#include "weblayer/browser/webapps/weblayer_webapps_client.h"
#include "weblayer/browser/weblayer_factory_impl_android.h"
#include "weblayer/common/features.h"
#endif

// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
// complete.
#if defined(USE_AURA) && (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
#include "ui/base/ime/init/input_method_initializer.h"
#endif

#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
#include "weblayer/browser/captive_portal_service_factory.h"
#endif

namespace weblayer {

namespace {

// Indexes and publishes the subresource filter ruleset data from resources in
// the resource bundle.
void PublishSubresourceFilterRulesetFromResourceBundle() {
  // First obtain the version of the ruleset data from the manifest.
  std::string ruleset_manifest_string =
      ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
          IDR_SUBRESOURCE_FILTER_UNINDEXED_RULESET_MANIFEST_JSON);
  auto ruleset_manifest = base::JSONReader::Read(ruleset_manifest_string);
  DCHECK(ruleset_manifest);
  std::string* content_version = ruleset_manifest->FindStringKey("version");

  // Instruct the RulesetService to obtain the unindexed ruleset data from the
  // ResourceBundle and give it the version of that data.
  auto* ruleset_service =
      BrowserProcess::GetInstance()->subresource_filter_ruleset_service();
  subresource_filter::UnindexedRulesetInfo ruleset_info;
  ruleset_info.resource_id = IDR_SUBRESOURCE_FILTER_UNINDEXED_RULESET;
  ruleset_info.content_version = *content_version;
  ruleset_service->IndexAndStoreAndPublishRulesetIfNeeded(ruleset_info);
}

// Instantiates all weblayer KeyedService factories, which is
// especially important for services that should be created at profile
// creation time as compared to lazily on first access.
void EnsureBrowserContextKeyedServiceFactoriesBuilt() {
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
  CaptivePortalServiceFactory::GetInstance();
#endif
  HeavyAdServiceFactory::GetInstance();
  HostContentSettingsMapFactory::GetInstance();
  StatefulSSLHostStateDelegateFactory::GetInstance();
  CookieSettingsFactory::GetInstance();
  AcceptLanguagesServiceFactory::GetInstance();
  TranslateRankerFactory::GetInstance();
  NoStatePrefetchLinkManagerFactory::GetInstance();
  NoStatePrefetchManagerFactory::GetInstance();
  SubresourceFilterProfileContextFactory::GetInstance();
  OriginTrialsFactory::GetInstance();
#if BUILDFLAG(IS_ANDROID)
  SiteEngagementServiceFactory::GetInstance();
  SafeBrowsingMetricsCollectorFactory::GetInstance();
  SafeBrowsingNavigationObserverManagerFactory::GetInstance();
  if (MediaRouterFactory::IsFeatureEnabled()) {
    LocalPresentationManagerFactory::GetInstance();
    MediaRouterFactory::GetInstance();
  }
#endif
  WebDataServiceFactory::GetInstance();
}

void StopMessageLoop(base::OnceClosure quit_closure) {
  for (auto it = content::RenderProcessHost::AllHostsIterator(); !it.IsAtEnd();
       it.Advance()) {
    it.GetCurrentValue()->DisableRefCounts();
  }

  std::move(quit_closure).Run();
}

}  // namespace

BrowserMainPartsImpl::BrowserMainPartsImpl(
    MainParams* params,
    std::unique_ptr<PrefService> local_state)
    : params_(params), local_state_(std::move(local_state)) {}

BrowserMainPartsImpl::~BrowserMainPartsImpl() = default;

int BrowserMainPartsImpl::PreCreateThreads() {
  // Make sure permissions client has been set.
  WebLayerPermissionsClient::GetInstance();
#if BUILDFLAG(IS_ANDROID)
  // The ChildExitObserver needs to be created before any child process is
  // created because it needs to be notified during process creation.
  child_exit_observer_ = std::make_unique<crash_reporter::ChildExitObserver>();
  child_exit_observer_->RegisterClient(
      std::make_unique<crash_reporter::ChildProcessCrashObserver>());

  crash_reporter::InitializeCrashKeys();

  // WebLayer initializes the MetricsService once consent is determined.
  // Determining consent is async and potentially slow. VariationsIdsProvider
  // is responsible for updating the X-Client-Data header.
  // SyntheticTrialsActiveGroupIdProvider is responsible for updating the
  // variations crash keys. To ensure the header and crash keys are always
  // provided, they are registered now.
  //
  // Chrome registers these providers from PreCreateThreads() as well.
  auto* synthetic_trial_registry = WebLayerMetricsServiceClient::GetInstance()
                                       ->GetMetricsService()
                                       ->GetSyntheticTrialRegistry();
  synthetic_trial_registry->AddSyntheticTrialObserver(
      variations::VariationsIdsProvider::GetInstance());
  synthetic_trial_registry->AddSyntheticTrialObserver(
      variations::SyntheticTrialsActiveGroupIdProvider::GetInstance());
#endif

  return content::RESULT_CODE_NORMAL_EXIT;
}

int BrowserMainPartsImpl::PreEarlyInitialization() {
  browser_process_ = std::make_unique<BrowserProcess>(std::move(local_state_));

// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
// complete.
#if defined(USE_AURA) && (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
  ui::InitializeInputMethodForTesting();
#endif
#if BUILDFLAG(IS_ANDROID)
  net::NetworkChangeNotifier::SetFactory(
      new net::NetworkChangeNotifierFactoryAndroid());

  WebLayerWebappsClient::Create();
#endif

  return content::RESULT_CODE_NORMAL_EXIT;
}

void BrowserMainPartsImpl::PostCreateThreads() {
  performance_manager_lifetime_ =
      std::make_unique<performance_manager::PerformanceManagerLifetime>(
          performance_manager::GraphFeatures::WithMinimal()
              // Reports performance-related UMA/UKM.
              .EnableMetricsCollector(),
          base::DoNothing());

  translate::TranslateDownloadManager* download_manager =
      translate::TranslateDownloadManager::GetInstance();
  download_manager->set_url_loader_factory(
      BrowserProcess::GetInstance()->GetSharedURLLoaderFactory());
  download_manager->set_application_locale(i18n::GetApplicationLocale());
}

int BrowserMainPartsImpl::PreMainMessageLoopRun() {
  FeatureListCreator::GetInstance()->PerformPreMainMessageLoopStartup();

  // It's necessary to have a complete dependency graph of
  // BrowserContextKeyedServices before calling out to the delegate (which
  // will potentially create a profile), so that a profile creation message is
  // properly dispatched to the factories that want to create their services
  // at profile creation time.
  EnsureBrowserContextKeyedServiceFactoriesBuilt();

  params_->delegate->PreMainMessageLoopRun();

  content::WebUIControllerFactory::RegisterFactory(
      WebUIControllerFactory::GetInstance());

  BrowserProcess::GetInstance()->PreMainMessageLoopRun();

  // Publish the ruleset data. On the vast majority of runs this will
  // effectively be a no-op as the version of the data changes at most once per
  // release. Nonetheless, post it as a best-effort task to take it off the
  // critical path of startup. Note that best-effort tasks are guaranteed to
  // execute within a reasonable delay (assuming of course that the app isn't
  // shut down first).
  content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
      ->PostTask(
          FROM_HERE,
          base::BindOnce(&PublishSubresourceFilterRulesetFromResourceBundle));

#if BUILDFLAG(IS_ANDROID)
  // On Android, retrieve the application start time from Java and record it. On
  // other platforms, the application start time was already recorded in the
  // constructor of ContentMainDelegateImpl.
  startup_metric_utils::RecordApplicationStartTime(GetApplicationStartTime());
#endif  // BUILDFLAG(IS_ANDROID)
  // Record the time at which the main message loop starts. Must be recorded
  // after application start time (see startup_metric_utils.h).
  startup_metric_utils::RecordBrowserMainMessageLoopStart(
      base::TimeTicks::Now(), /* is_first_run */ false);

#if BUILDFLAG(IS_ANDROID)
  memory_metrics_logger_ = std::make_unique<metrics::MemoryMetricsLogger>();

  // Set the global singleton app modal dialog factory.
  javascript_dialogs::AppModalDialogManager::GetInstance()
      ->SetNativeDialogFactory(base::BindRepeating(
          [](javascript_dialogs::AppModalDialogController* controller)
              -> javascript_dialogs::AppModalDialogView* {
            return new javascript_dialogs::AppModalDialogViewAndroid(
                base::android::AttachCurrentThread(), controller,
                controller->web_contents()->GetTopLevelNativeWindow());
          }));

  Java_MojoInterfaceRegistrar_registerMojoInterfaces(
      base::android::AttachCurrentThread());
#endif

  return content::RESULT_CODE_NORMAL_EXIT;
}

void BrowserMainPartsImpl::WillRunMainMessageLoop(
    std::unique_ptr<base::RunLoop>& run_loop) {
  // Wrap the method that stops the message loop so we can do other shutdown
  // cleanup inside content.
  params_->delegate->SetMainMessageLoopQuitClosure(
      base::BindOnce(StopMessageLoop, run_loop->QuitClosure()));
}

void BrowserMainPartsImpl::OnFirstIdle() {
  startup_metric_utils::RecordBrowserMainLoopFirstIdle(base::TimeTicks::Now());
}

void BrowserMainPartsImpl::PostMainMessageLoopRun() {
  params_->delegate->PostMainMessageLoopRun();
  browser_process_->StartTearDown();

  performance_manager_lifetime_.reset();
}

}  // namespace weblayer


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Secken.ServerSdk.DemoSix</title>
    <script src="/static/js/jquery/1.11.2/jquery.min.js"></script>
    <script src="/static/js/push.js"></script>
</head>
<body style="background-color: #02C4FC;">
    <img src="" id="qr_img" style="width: 658px; height: 493px; border: 0px; position: absolute; top: 50%; left: 50%; margin-top: -246px; margin-left: -329px;">
</body>
</html>