text:
module Bio
  module Ucsc
    # The BigWig class interacts with bigWig files
    class BigBed
      require 'bio/ucsc/binding'
      # bigWig file name
      attr_accessor :filename
      # pointer to bbiFile
      attr_accessor :bbi_file
      # convenience method to create a new BigBed and open it.
      def self.open(*args)
        self.new(*args).open
      end
      # Returns a new BigBed.
      def initialize(f=nil, opts={})
        @filename = f
        return self
      end
      # opens the file
      def open
        raise ArgumentError, "filename undefined" unless filename
        raise NameError, "#{filename} not found" unless File.exist?(filename)
        raise LoadError, "#{filename} bad format" unless Binding::bigBedFileCheckSigs(filename)
        Binding::udcSetDefaultDir Binding::udcDefaultDir
        @bbi_file = Binding::bigBedFileOpen(filename)
        return self
      end
      # closes the file
      def close
        if bbi_file
          bbi_ptr= FFI::MemoryPointer.new(:pointer)
          bbi_ptr.write_pointer(bbi_file)
          Binding::bbiFileClose(bbi_ptr)
        end
        @bbi_file = nil
      end

      def count
        Binding::bigBedItemCount(bbi_file)
      end

      # retrieves intervals from the bigBed for the given range.
      # - chrom  => Sequence name for summary
      # - start  => Start of range (0 based)
      # - stop  => End of range
      # hash Options:
      # * :count  => Max number of items to return (0 for all)
      def interval(chrom, start, stop, opts={})
        count = opts[:count]||0
        # create the local memory pool
        lm = FFI::Pointer.new(Binding::lmInit(0))
        # Get the first interval
        bb_interval = Binding::bigBedIntervalQuery(bbi_file, chrom, start, stop, count, lm)
        # copy data to ruby array
        a = []
        bbi = Binding::BigBedInterval.new(bb_interval)
        a << bbi
        while bbi = bbi.next
          a << bbi
        end
        # Clear C memory
        Binding::LmPointerHelper.release(lm)
        return a
      end

    end
  end
end


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

001
022
023package com.restfb;
024
025import static com.restfb.util.StringUtils.isBlank;
026import static com.restfb.util.StringUtils.trimToEmpty;
027import static java.lang.String.format;
028
029import java.io.IOException;
030
031/**
032 * Specifies how a class that sends {@code HTTP} requests to the Facebook API endpoint must operate.
033 *
034 * @author <a href="http://restfb.com">Mark Allen</a>
035 */
036public interface WebRequestor {
037  /**
038   * Encapsulates an HTTP response body and status code.
039   *
040   * @author <a href="http://restfb.com">Mark Allen</a>
041   */
042  public static class Response {
043    /**
044     * HTTP response status code (e.g. 200).
045     */
046    private Integer statusCode;
047
048    /**
049     * HTTP response body as text.
050     */
051    private String body;
052
053    /**
054     * Creates a response with the given HTTP status code and response body as text.
055     *
056     * @param statusCode
057     *          The HTTP status code of the response.
058     * @param body
059     *          The response body as text.
060     */
061    public Response(Integer statusCode, String body) {
062      this.statusCode = statusCode;
063      this.body = trimToEmpty(body);
064    }
065
066    /**
067     * Gets the HTTP status code.
068     *
069     * @return The HTTP status code.
070     */
071    public Integer getStatusCode() {
072      return statusCode;
073    }
074
075    /**
076     * Gets the HTTP response body as text.
077     *
078     * @return The HTTP response body as text.
079     */
080    public String getBody() {
081      return body;
082    }
083
084    /**
085     * @see java.lang.Object#toString()
086     */
087    @Override
088    public String toString() {
089      if (isBlank(getBody()))
090        return format("HTTP status code %d and an empty response body.", getStatusCode());
091      return format("HTTP status code %d and response body: %s", getStatusCode(), getBody());
092    }
093  }
094
095  /**
096   * Given a Facebook API endpoint URL, execute a {@code GET} against it.
097   *
098   * @param url
099   *          The URL to make a {@code GET} request for, including URL parameters.
100   * @return HTTP response data.
101   * @throws IOException
102   *           If an error occurs while performing the {@code GET} operation.
103   * @since 1.5
104   */
105  Response executeGet(String url) throws IOException;
106
107  /**
108   * Given a Facebook API endpoint URL and parameter string, execute a {@code POST} to the endpoint URL.
109   *
110   * @param url
111   *          The URL to {@code POST} to.
112   * @param parameters
113   *          The parameters to be {@code POST}ed.
114   * @return HTTP response data.
115   * @throws IOException
116   *           If an error occurs while performing the {@code POST}.
117   */
118  Response executePost(String url, String parameters) throws IOException;
119
120  /**
121   * Given a Facebook API endpoint URL and parameter string, execute a {@code POST} to the endpoint URL.
122   *
123   * @param url
124   *          The URL to {@code POST} to.
125   * @param parameters
126   *          The parameters to be {@code POST}ed.
127   * @param binaryAttachments
128   *          Optional binary attachments to be included in the {@code POST} body (e.g. photos and videos).
129   * @return HTTP response data.
130   * @throws IOException
131   *           If an error occurs while performing the {@code POST}.
132   */
133  Response executePost(String url, String parameters, BinaryAttachment... binaryAttachments) throws IOException;
134}

redpajama_set_name: RedPajamaGithub


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var name_list_service_1 = require('../shared/name-list/name-list.service');
var HomeComponent = (function () {
    function HomeComponent(nameListService) {
        this.nameListService = nameListService;
        this.newName = '';
        this.names = [];
    }
    HomeComponent.prototype.ngOnInit = function () {
        this.getNames();
    };
    HomeComponent.prototype.getNames = function () {
        var _this = this;
        this.nameListService.get()
            .subscribe(function (names) { return _this.names = names; }, function (error) { return _this.errorMessage = error; });
    };
    HomeComponent.prototype.addName = function () {
        this.names.push(this.newName);
        this.newName = '';
        return false;
    };
    HomeComponent = __decorate([
        core_1.Component({
            moduleId: module.id,
            selector: 'sd-home',
            template: "
Howdy! Here's a list of awesome computer scientists. Do you know any others? Add to the list yourself.
  <form (submit)=\"addName()\">   <input [(ngModel)]=\"newName\" name=\"newName\" placeholder=\"Awesome Computer Scientist\">   <button type=\"submit\">Add</button> </form>

{{name}}

",
            styles: [":host{display:block;padding:0 16px}input{width:250px}ul{list-style-type:none;padding:0 0 0 8px}"],
        }),
        __metadata('design:paramtypes', [name_list_service_1.NameListService])
    ], HomeComponent);
    return HomeComponent;
}());
exports.HomeComponent = HomeComponent;


text:
import { StandardEditorProps } from '@grafana/data';
import { DiagramPanelControllerProps } from 'DiagramController';
import React from 'react';

export const SupportEditor: React.FC<StandardEditorProps<boolean, any, DiagramPanelControllerProps>> = ({}) => {
  const openSupportPage = () => {
    window.open('https://github.com/jdbranham/grafana-diagram/issues', '_github');
  };

  const openSponsorPage = () => {
    window.open('https://github.com/sponsors/jdbranham', '_github');
  };

  const openPatreonPage = () => {
    window.open('https://patreon.com/savantly', '_patreon');
  };

  return (

          <button className="btn btn-secondary gf-form-input" onClick={openSupportPage}>
             Community Support
          </button>

          <button className="btn btn-primary gf-form-input" onClick={openSponsorPage}>
             Sponsors
          </button>

          <button className="btn btn-primary gf-form-input" onClick={openPatreonPage}>
             Vote for features
          </button>

  );
};


text:
package com.eagle.programmar.COBOL.Statements;

import com.eagle.programmar.COBOL.COBOL_AbstractStatement;
import com.eagle.programmar.COBOL.Symbols.COBOL_Identifier_Reference;
import com.eagle.programmar.COBOL.Terminals.COBOL_Keyword;
import com.eagle.programmar.COBOL.Terminals.COBOL_KeywordChoice;
import com.eagle.tokens.TokenList;
import com.eagle.tokens.TokenSequence;
import com.eagle.tokens.punctuation.PunctuationComma;

public class COBOL_OpenStatement extends COBOL_AbstractStatement
{
	public @DOC("rlpsopen.htm") COBOL_Keyword OPEN = new COBOL_Keyword("OPEN");
	public COBOL_KeywordChoice inputOutput = new COBOL_KeywordChoice("I-O", "INPUT", "OUTPUT", "EXTEND");
	public TokenList<COBOL_OpenFileList> fileList;

	public static class COBOL_OpenFileList extends TokenSequence
	{
		public @OPT PunctuationComma comma;
		public COBOL_Identifier_Reference file;
	}
}


text:
REM Release automation script for Windows builds.  This should be run
REM after the Linux build has created the staging repository and
REM selected the BoringSSL revision.  Must be run from the top-level
REM conscrypt directory, which should be synced to the appropriate
REM release branch.

@echo off
setlocal

if "%2"=="" (
    echo Usage: %0 ^<boringssl revision^> ^<repository ID^>
    exit /B
)

REM TODO(flooey): The BoringSSL directory needs to be at ../boringssl
pushd ..\boringssl

if "%JAVA_HOME%"=="" (
    for /F "usebackq delims==" %%i in (`where java`) do set JAVA_HOME=%%~dpi
)
set JAVA_HOME=%JAVA_HOME:\bin\=%

if "%BORINGSSL_HOME%"=="" (set BORINGSSL_HOME=%cd%)

git checkout master
git pull
git checkout %1

pushd .
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" x86
popd
cd build32
ninja
cd ..

pushd .
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" x86_amd64
popd
cd build64
ninja

popd

call gradlew conscrypt-openjdk:build
call gradlew conscrypt-openjdk:publish -Dorg.gradle.parallel=false -PrepositoryId=%2


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

#include "chromeos/utils/pdf_conversion.h"

#include <fstream>
#include <string>
#include <vector>

#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_unittest_util.h"
#include "ui/gfx/image/image_util.h"

namespace chromeos {

namespace {

// Returns a manually generated JPG image with specified width and height in
// pixels.
std::vector<uint8_t> CreateJpg(int width, int height) {
  gfx::Image original = gfx::test::CreateImage(width, height);
  std::vector<uint8_t> jpg_buffer;
  if (!gfx::JPEG1xEncodedDataFromImage(original, 80, &jpg_buffer)) {
    return {};
  }
  return jpg_buffer;
}

}  // namespace

using ConvertToPdfTest = testing::Test;

// Test that JPG image can be converted to pdf file successfully.
TEST_F(ConvertToPdfTest, ToFileNoDpi) {
  std::vector<std::string> images;
  std::vector<uint8_t> bytes = CreateJpg(100, 100);
  images.push_back(std::string(bytes.begin(), bytes.end()));

  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  auto output_path = temp_dir.GetPath().Append("temp.pdf");

  EXPECT_TRUE(ConvertJpgImagesToPdf(images, output_path,
                                    /*rotate_alternate_pages=*/false,
                                    /*dpi=*/absl::nullopt));
  EXPECT_TRUE(base::PathExists(output_path));

  int64_t file_size;
  EXPECT_TRUE(base::GetFileSize(output_path, &file_size));

  // Smallest PDF should be at least 20 bytes.
  EXPECT_GT(file_size, 20u);
}

// Test that JPG image can be converted to pdf file successfully when scanner
// DPI is specified. Higher DPI results in larger pixel counts, but should
// result in the same PDF page size.
TEST_F(ConvertToPdfTest, ToFileWithDpi) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  // Generate and process 100 DPI image.
  std::vector<std::string> images_100;
  std::vector<uint8_t> bytes_100 = CreateJpg(100, 100);
  images_100.push_back(std::string(bytes_100.begin(), bytes_100.end()));
  auto output_path_100 = temp_dir.GetPath().Append("temp_100.pdf");
  EXPECT_TRUE(ConvertJpgImagesToPdf(images_100, output_path_100,
                                    /*rotate_alternate_pages=*/false,
                                    /*dpi=*/100));
  EXPECT_TRUE(base::PathExists(output_path_100));

  // Generate and process 200 DPI image.
  std::vector<std::string> images_200;
  std::vector<uint8_t> bytes_200 = CreateJpg(200, 200);
  images_200.push_back(std::string(bytes_200.begin(), bytes_200.end()));
  auto output_path_200 = temp_dir.GetPath().Append("temp_200.pdf");
  EXPECT_TRUE(ConvertJpgImagesToPdf(images_200, output_path_200,
                                    /*rotate_alternate_pages=*/false,
                                    /*dpi=*/200));
  EXPECT_TRUE(base::PathExists(output_path_200));

  // Generate and process 300 DPI image.
  std::vector<std::string> images_300;
  std::vector<uint8_t> bytes_300 = CreateJpg(300, 300);
  images_300.push_back(std::string(bytes_300.begin(), bytes_300.end()));
  auto output_path_300 = temp_dir.GetPath().Append("temp_300.pdf");
  EXPECT_TRUE(ConvertJpgImagesToPdf(images_300, output_path_300,
                                    /*rotate_alternate_pages=*/false,
                                    /*dpi=*/300));
  EXPECT_TRUE(base::PathExists(output_path_300));

  // Each file should increase in size as DPI increases.
  int64_t file_size_100;
  int64_t file_size_200;
  int64_t file_size_300;
  EXPECT_TRUE(base::GetFileSize(output_path_100, &file_size_100));
  EXPECT_TRUE(base::GetFileSize(output_path_200, &file_size_200));
  EXPECT_TRUE(base::GetFileSize(output_path_300, &file_size_300));
  EXPECT_GT(file_size_200, file_size_100);
  EXPECT_GT(file_size_300, file_size_200);

  // Verify that the media box is the same size across PDFs.
  const char kMediaBoxString[] = "[0 0 72 72]";
  std::string file_contents;

  EXPECT_TRUE(base::ReadFileToString(output_path_100, &file_contents));
  EXPECT_THAT(file_contents, testing::HasSubstr(kMediaBoxString));

  EXPECT_TRUE(base::ReadFileToString(output_path_200, &file_contents));
  EXPECT_THAT(file_contents, testing::HasSubstr(kMediaBoxString));

  EXPECT_TRUE(base::ReadFileToString(output_path_300, &file_contents));
  EXPECT_THAT(file_contents, testing::HasSubstr(kMediaBoxString));
}

// Test that JPG images can be converted to pdf and saved to vector
// successfully.
TEST_F(ConvertToPdfTest, ToVector) {
  std::vector<uint8_t> pdf_buffer;
  std::vector<uint8_t> buffer_1 = CreateJpg(1, 1);
  ASSERT_FALSE(buffer_1.empty());

  std::vector<std::vector<uint8_t>> jpg_buffers{buffer_1};
  EXPECT_TRUE(ConvertJpgImagesToPdf(jpg_buffers, &pdf_buffer));

  // Smallest PDF should be at least 20 bytes.
  size_t size_1 = pdf_buffer.size();
  EXPECT_GT(size_1, 20u);

  jpg_buffers.push_back(CreateJpg(200, 200));
  jpg_buffers.push_back(CreateJpg(300, 300));
  EXPECT_TRUE(ConvertJpgImagesToPdf(jpg_buffers, &pdf_buffer));
  EXPECT_GT(pdf_buffer.size(), size_1);
}

// Test that passing empty vectors should fail and print error messages.
TEST_F(ConvertToPdfTest, ToVectorEmpty) {
  std::vector<uint8_t> pdf_buffer;
  std::vector<uint8_t> buffer_empty;
  ASSERT_TRUE(buffer_empty.empty());

  std::vector<std::vector<uint8_t>> jpg_buffers{buffer_empty};
  EXPECT_FALSE(ConvertJpgImagesToPdf(jpg_buffers, &pdf_buffer));
}

}  // namespace chromeos


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.security.models;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;

/** Resource collection API of Tasks. */
public interface Tasks {
    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of security task recommendations as paginated response with {@link PagedIterable}.
     */
    PagedIterable<SecurityTask> list();

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param filter OData filter. Optional.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of security task recommendations as paginated response with {@link PagedIterable}.
     */
    PagedIterable<SecurityTask> list(String filter, Context context);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of security task recommendations as paginated response with {@link PagedIterable}.
     */
    PagedIterable<SecurityTask> listByHomeRegion(String ascLocation);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param filter OData filter. Optional.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of security task recommendations as paginated response with {@link PagedIterable}.
     */
    PagedIterable<SecurityTask> listByHomeRegion(String ascLocation, String filter, Context context);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param taskName Name of the task object, will be a GUID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return security task that we recommend to do in order to strengthen security along with {@link Response}.
     */
    Response<SecurityTask> getSubscriptionLevelTaskWithResponse(String ascLocation, String taskName, Context context);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param taskName Name of the task object, will be a GUID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return security task that we recommend to do in order to strengthen security.
     */
    SecurityTask getSubscriptionLevelTask(String ascLocation, String taskName);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param taskName Name of the task object, will be a GUID.
     * @param taskUpdateActionType Type of the action to do on the task.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    Response<Void> updateSubscriptionLevelTaskStateWithResponse(
        String ascLocation, String taskName, TaskUpdateActionType taskUpdateActionType, Context context);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param taskName Name of the task object, will be a GUID.
     * @param taskUpdateActionType Type of the action to do on the task.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void updateSubscriptionLevelTaskState(
        String ascLocation, String taskName, TaskUpdateActionType taskUpdateActionType);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of security task recommendations as paginated response with {@link PagedIterable}.
     */
    PagedIterable<SecurityTask> listByResourceGroup(String resourceGroupName, String ascLocation);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param filter OData filter. Optional.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of security task recommendations as paginated response with {@link PagedIterable}.
     */
    PagedIterable<SecurityTask> listByResourceGroup(
        String resourceGroupName, String ascLocation, String filter, Context context);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param taskName Name of the task object, will be a GUID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return security task that we recommend to do in order to strengthen security along with {@link Response}.
     */
    Response<SecurityTask> getResourceGroupLevelTaskWithResponse(
        String resourceGroupName, String ascLocation, String taskName, Context context);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param taskName Name of the task object, will be a GUID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return security task that we recommend to do in order to strengthen security.
     */
    SecurityTask getResourceGroupLevelTask(String resourceGroupName, String ascLocation, String taskName);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param taskName Name of the task object, will be a GUID.
     * @param taskUpdateActionType Type of the action to do on the task.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    Response<Void> updateResourceGroupLevelTaskStateWithResponse(
        String resourceGroupName,
        String ascLocation,
        String taskName,
        TaskUpdateActionType taskUpdateActionType,
        Context context);

    /**
     * Recommended tasks that will help improve the security of the subscription proactively.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get
     *     locations.
     * @param taskName Name of the task object, will be a GUID.
     * @param taskUpdateActionType Type of the action to do on the task.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void updateResourceGroupLevelTaskState(
        String resourceGroupName, String ascLocation, String taskName, TaskUpdateActionType taskUpdateActionType);
}


text:
package org.elasticsearch.xpack.analytics.rate;

import org.apache.lucene.index.LeafReaderContext;
import org.elasticsearch.common.Rounding;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.CardinalityUpperBound;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.aggregations.support.ValuesSourceRegistry;
import org.elasticsearch.search.internal.SearchContext;

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

class RateAggregatorFactory extends ValuesSourceAggregatorFactory {

    private final Rounding.DateTimeUnit rateUnit;

    RateAggregatorFactory(
        String name,
        ValuesSourceConfig config,
        Rounding.DateTimeUnit rateUnit,
        QueryShardContext queryShardContext,
        AggregatorFactory parent,
        AggregatorFactories.Builder subFactoriesBuilder,
        Map<String, Object> metadata
    ) throws IOException {
        super(name, config, queryShardContext, parent, subFactoriesBuilder, metadata);
        this.rateUnit = rateUnit;
    }

    static void registerAggregators(ValuesSourceRegistry.Builder builder) {
        builder.register(
            RateAggregationBuilder.REGISTRY_KEY,
            List.of(CoreValuesSourceType.NUMERIC, CoreValuesSourceType.BOOLEAN),
            RateAggregator::new,
            true
        );
    }

    @Override
    protected Aggregator createUnmapped(SearchContext searchContext, Aggregator parent, Map<String, Object> metadata) throws IOException {
        return new RateAggregator(name, config, rateUnit, searchContext, parent, metadata) {
            @Override
            public LeafBucketCollector getLeafCollector(LeafReaderContext ctx, LeafBucketCollector sub) {
                return LeafBucketCollector.NO_OP_COLLECTOR;
            }
        };
    }

    @Override
    protected Aggregator doCreateInternal(
        SearchContext searchContext,
        Aggregator parent,
        CardinalityUpperBound bucketCardinality,
        Map<String, Object> metadata
    ) throws IOException {
        return queryShardContext.getValuesSourceRegistry()
            .getAggregator(RateAggregationBuilder.REGISTRY_KEY, config)
            .build(name, config, rateUnit, searchContext, parent, metadata);
    }
}


text:
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Attiny = require('attiny-common');
var MODULE_ID = 0x08;
var TINY44_SIGNATURE = 0x9207;
var FIRMWARE_FILE = __dirname + '/firmware/src/ambient-attx4.hex';

// Max 10 (16 bit) data chunks
var AMBIENT_BUF_SIZE = 10 * 2;
var AMBIENT_SINGLE_BYTE = 1 * 2;
var MAX_AMBIENT_VALUE = 1024;

// Confirmation Signals
var PACKET_CONF = 0x55;
var ACK_CONF = 0x33;
var FIN_CONF = 0x16;

var LIGHT_CMD = 2;
var SOUND_CMD = 3;
var LIGHT_TRIGGER_CMD = 4;
var SOUND_TRIGGER_CMD = 5;
var FETCH_TRIGGER_CMD = 6;

// These should be updated with each firmware release
var FIRMWARE_VERSION = 0x03;
var CRC = 0x1eb5;

function Ambient(hardware, callback) {

  // Create a new instance of an attiny
  this.attiny = new Attiny(hardware);

  // Global connected. We may use this in the future
  this.connected = false;

  this.lightTriggerLevel = null;

  this.soundTriggerLevel = null;

  // milliSeconds between reads
  this.pollingFrequency = 500;
  this.lightPolling = false;
  this.soundPolling = false;
  this.pollInterval = undefined;

  var self = this;

  // Store our firmware checking and updating options
  var firmwareOptions = {
    firmwareFile : FIRMWARE_FILE,
    firmwareVersion : FIRMWARE_VERSION,
    moduleID : MODULE_ID,
    signature : TINY44_SIGNATURE,
    crc : CRC,
  }
  // Make sure we can communicate with the module
  self.attiny.initialize(firmwareOptions, function(err) {
    if (err) {
      // Emit the error
      self.emit('error', err);

      // Call the callback with an error
      if (callback) {
        callback(err);
      }

      return;
    }
    else {

      self.connected = true;

      // If someone starts listening
      self.on('newListener', function(event) {
        // and there weren't listeners before
        if (!self.listeners(event).length)
        {
          // start retrieving data for this type of buffer
          self._setListening(true, event);
        }
      });

      // if someone stops listening
      self.on('removeListener', function(event)
      {
        // and there are none left
        if (!self.listeners(event).length)
        {
          // stop retrieving data
          self._setListening(false, event);
        }
      });

      setImmediate(function () {
        // Emit a ready event
        self.emit('ready');
        // Start listening for IRQ interrupts
        self.irqwatcher = self._fetchTriggerValues.bind(self);
        self.attiny.setIRQCallback(self.irqwatcher);

      });

      if (callback) {
        callback(null, self);
      }
    }
  });
}

// We want the ability to emit events
util.inherits(Ambient, EventEmitter);

Ambient.prototype._fetchTriggerValues = function() {

  var self = this;

  // cmd, cmd_echo, light_val (16 bits), sound_val (16 bits)
  var packet = new Buffer([FETCH_TRIGGER_CMD, 0x00, 0x00, 0x00, 0x00, 0x00]);

  // transceive the command
  self.attiny.transceive(packet, function spiComplete(err, response) {
    if (self.attiny._validateResponse(response, [PACKET_CONF, FETCH_TRIGGER_CMD]))
    {
      // make a buffer with the cmd and cmd_echo spliced out
      var data = new Buffer(response.slice(2, response.length));
      // Read values
      var lightTriggerValue = self._normalizeValue(data.readUInt16BE(0));
      var soundTriggerValue = self._normalizeValue(data.readUInt16BE(2));

      if (lightTriggerValue && self.lightTriggerLevel)
      {
        self.emit('light-trigger', lightTriggerValue);
      }
      if (soundTriggerValue && self.soundTriggerLevel)
      {
        self.emit('sound-trigger', soundTriggerValue);
      }

      setImmediate(function() {
        self.irqwatcher = self._fetchTriggerValues.bind(self);
        self.attiny.setIRQCallback(self.irqwatcher);
      });
    }
    else
    {
      console.warn("Warning... Invalid trigger values fetched...");
    }
  });
};

Ambient.prototype._getSingleDatum = function(command, callback) {

  // Read the buffer but only 1 16-bit wordbyte
  this._readBuffer(command, AMBIENT_SINGLE_BYTE, callback);
};

Ambient.prototype._normalizeBuffer = function(buf) {
  var numUInt16 = buf.length/2;
  var ret = new Array(numUInt16);

  for (var i = 0; i < numUInt16; i++) {
    ret[i] = this._normalizeValue(buf.readUInt16BE(i*2));
  }

  return ret;
};

Ambient.prototype._normalizeValue = function(value) {
  return (value/MAX_AMBIENT_VALUE);
};

Ambient.prototype._pollBuffers = function(cb) {
  var self = this;

  if (!self.connected) {
    self._establishCommunication(5, function(err) {
      if (err) {
        self.emit('error', new Error("Can't communicate with Ambient module..."));
      }
    });
  }
  if (self.lightPolling)
  {
    self.getLightBuffer(cb);
  }
  if (self.soundPolling)
  {
    self.getSoundBuffer(cb);
  }
};

Ambient.prototype._readBuffer = function(command, readLen, callback) {

  var self = this;

  // Create a packet with header, data bytes (16 bits) and stop byte
  var header = new Buffer([command, readLen/2, 0x00]);

  var bytes = new Buffer(readLen);
  bytes.fill(0);

  var stop = new Buffer(1);
  stop.writeUInt8(FIN_CONF, 0);

  var packet = Buffer.concat([header, bytes, stop]);

  // Synchronously transceive command to read
  self.attiny.transceive(packet, function spiComplete(err, data) {
    // If the response is valid
    if (self.attiny._validateResponse(data, [PACKET_CONF, command, readLen/2]) &&
      data[data.length-1] === FIN_CONF) {

      data = self._normalizeBuffer(data.slice(header.length, data.length-1));

      if (data.length === 1) {
        data = data[0];
      }

      var event = (command == LIGHT_CMD ? "light" : "sound");

      self.emit(event, data);

      // Return data
      if (callback) {
        callback(null, data);
      }

      return data;
    }
    else {

      var err = new Error("Invalid response from Ambient module");

      if (callback) {
        callback(err);
      }
    }
  });
};

Ambient.prototype._setListening = function(enable, event) {
  var self = this;
  if (event === "light") {
    this.lightPolling = enable;
  } else if (event === "sound") {
    this.soundPolling = enable;
  } else {
    return;
  }

  // if the other buffer is not already polling
  if (event === "light" && !this.soundPolling ||
      event === "sound" && !this.lightPolling) {

    function pollBuffers() {
      self._pollBuffers(function(){
        self._pollTimeout = setTimeout(pollBuffers, self.pollingFrequency);
      });
    }

    if (enable && !self._pollTimeout) {
      // if we want to enable polling & there isn't already a poll
      pollBuffers();
    } else if (!enable && self._pollTimeout) {
      // stop polling
      clearTimeout(self._pollTimeout);
      self._pollTimeout = null;
      if(this.irqwatcher) {
        this.attiny.irq.removeListener('high', this.irqwatcher);
      }
    }
  }
};

Ambient.prototype.disable = function () {
  this._setListening(false, 'light');
  this._setListening(false, 'sound');
};

Ambient.prototype._setTrigger = function(triggerCmd, triggerVal, callback) {

  var self = this;

  // Make the packet
  triggerVal = Math.ceil(triggerVal * MAX_AMBIENT_VALUE);

  var dataBuffer = new Buffer(2);
  dataBuffer.writeUInt16BE(triggerVal, 0);

  var packet = new Buffer([triggerCmd, dataBuffer.readUInt8(0), dataBuffer.readUInt8(1), 0x00]);

  // Send it over SPI
  self.attiny.transceive(packet, function spiComplete(err, data) {
    // If it's a valud response
    if (self.attiny._validateResponse(data, [PACKET_CONF, triggerCmd, dataBuffer.readUInt8(0), dataBuffer.readUInt8(1)]))
    {

      // Get the event title
      var event = (triggerCmd == LIGHT_TRIGGER_CMD ? "light-trigger-set" : "sound-trigger-set");

      // Store the trigger value locally
      if (triggerCmd == LIGHT_TRIGGER_CMD)
      {
        self.lightTriggerLevel = triggerVal;
      }
      else
      {
        self.soundTriggerLevel = triggerVal;
      }

      // Emit the event
      self.emit(event, triggerVal / MAX_AMBIENT_VALUE);
      // Return data
      if (callback) {
        callback(null, triggerVal / MAX_AMBIENT_VALUE);
      }
      // Return the value
      return triggerVal;
    }
    else
    {
      if (callback) {
        callback(new Error("Invalid response from Ambient module for trigger set."));
      }
    }
  });
};

// Clears trigger listener for light trigger
Ambient.prototype.clearLightTrigger = function(callback) {
  this.setLightTrigger(0, callback);
};

// Gets trigger listener for sound trigger
Ambient.prototype.clearSoundTrigger = function(callback) {
  this.setSoundTrigger(0, callback);
};

// Gets the last 20 light readings
Ambient.prototype.getLightBuffer = function(callback) {
  this._readBuffer(LIGHT_CMD, AMBIENT_BUF_SIZE, callback);
};

// Gets a single data point of light level
Ambient.prototype.getLightLevel = function(callback) {
  // Grab a single data point
  this._getSingleDatum(LIGHT_CMD, callback);
};

// Gets the last 20 sound readings
Ambient.prototype.getSoundBuffer = function(callback) {
  this._readBuffer(SOUND_CMD, AMBIENT_BUF_SIZE, callback);
};

// Gets a single data point of sound level
Ambient.prototype.getSoundLevel = function(callback) {
    // Grab a single data point
  this._getSingleDatum(SOUND_CMD, callback);
};

// Sets a trigger to emit a 'light-trigger' event when triggerVal is reached
Ambient.prototype.setLightTrigger = function(triggerVal, callback) {
  this._setTrigger(LIGHT_TRIGGER_CMD, triggerVal, callback);
};

// Sets a trigger to emit a 'sound-trigger' event when triggerVal is reached
Ambient.prototype.setSoundTrigger = function(triggerVal, callback) {
  this._setTrigger(SOUND_TRIGGER_CMD, triggerVal, callback);
};

function use (hardware, callback) {
  if(!hardware) {
    console.warn(new Error('Improperly specified Tessel port.'));
  }
  return new Ambient(hardware, callback);
}

exports.Ambient = Ambient;
exports.use = use;


text:
namespace Apache.Ignite.Core.Impl.Portable
{
    using Apache.Ignite.Core.Portable;

    /// <summary>
    /// Serializer for system types that can create instances directly from a stream and does not support handles.
    /// </summary>
    internal interface IPortableSystemTypeSerializer : IPortableSerializer
    {
        /// <summary>
        /// Reads the instance from a reader.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns>Deserialized instance.</returns>
        object ReadInstance(PortableReaderImpl reader);
    }
}


text:
Yeoman generator that scaffolds out a front-end mobile web app

[![NPM version](https://img.shields.io/npm/v/generator-jhw-webapp.svg?style=flat)](https://www.npmjs.com/package/generator-jhw-webapp)
[![Node version](https://img.shields.io/node/v/generator-jhw-webapp.svg?style=flat)](https://www.npmjs.com/package/generator-jhw-webapp)
[![NPM Downloads](https://img.shields.io/npm/dm/generator-jhw-webapp.svg)](https://www.npmjs.com/package/generator-jhw-webapp)

[![NPM](https://nodei.co/npm/generator-jhw-webapp.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/generator-jhw-webapp)
[![NPM](https://nodei.co/npm-dl/generator-jhw-webapp.png)](https://nodei.co/npm-dl/generator-jhw-webapp/)

---

## Install
```bash
$ npm install -g generator-jhw-webapp
```

## Usage
Run it with [yo](https://github.com/yeoman/yo)
```bash
$ yo jhw-webapp
```

## License
[![License](https://img.shields.io/npm/l/generator-jhw-webapp.svg?style=flat)](https://github.com/jhw-dev/generator-jhw-webapp)


text:
#include <fstream>
#include <iostream>
#include <json-c/json.h>
#include <forward_list>
#include <algorithm>
#include <memory>

#include "filesystem.h"
#include "filetrans.h"
#include "http.h"
#include "jsonentry.h"
#include "log.h"

namespace by {
bool MapToString(const MemTable &mem,char **ptr) {
  char buf[2];
  buf[1] = '\n';
  std::string str;
  for(auto iter = mem.begin();iter != mem.end();++iter) {
    str.append(iter->first);
    assert(iter->second <= 0xff);
    buf[0] = static_cast<char>(iter->second);
    str.insert(str.size(),buf,2);
  }
  *ptr = (char *)malloc(sizeof(char)*(str.size()+1));
  memcpy(*ptr,str.data(),str.size());
  if(*ptr == NULL)
    return false;

  (*ptr)[str.size()] = '\0';
  return true;
}

void StringToMap(MemTable &mem,char **ptr) {
  std::string str = *ptr;
  size_t first = 0;
  size_t found = str.find_first_of('\n');
  while (found != std::string::npos) {
    mem[str.substr(first, found-1-first)] = static_cast<FileOperation>(str[found - 1]);
    first = found + 1;
    found = str.find_first_of('\n', found + 1);
  }
}

std::string ExtractPath(const std::string& p) {
  std::string path = p;
  if(!path.compare(0,kRemoteRoot.size(),kRemoteRoot))
    path = p.substr(kRemoteRoot.size());
  else if(!path.compare(0,kLocalRoot.size(),kLocalRoot))
    path =  p.substr(kLocalRoot.size());

  std::size_t found = 0;
  std::size_t pos;
  while (found!=std::string::npos) {
    pos = path.find_first_of("/\\",found);
    if(pos > path.size())
      break;
    if(pos - found != 0) {
      path[pos] = '/';
    } else {
      path.erase(path.begin()+pos);
      continue;
    }
    found  = pos + 1;
  }
  found = path.find_last_of("/\\");
  if(found == path.size()-1)
    path.erase(path.begin()+found);
  return path;
}

bool IsMd5Match(const std::string& path,const std::string& md5,const JsonEntry& jobj) {
  std::string rmd5 = jobj["md5"].Value<std::string>();
  if(md5!=rmd5) {
    return false;
  } else {
    std::string rpath = jobj["path"].Value<std::string>();
    std::string p1 = ExtractPath(path);
    std::string p2 = ExtractPath(rpath);
    if(p1 != p2)
      return false;
    else
      return true;
  }
}

bool IsExists(const std::string& path,const JsonEntry& jobj) {
  std::string rpath = jobj["path"].Value<std::string>();
  std::string p1 = ExtractPath(path);
  std::string p2 = ExtractPath(rpath);
  if(p2 == p1)
    return true;
  else
    return false;
}

void FileTrans::AddToMemTable(FileOperation flag,const std::string& path) {
  if(flag != kPass)
    mem_table_.insert(std::pair<std::string,FileOperation>(path,flag));
}

void FileTrans::SynOperation() {
  FileOperation flag;
  std::string path;
  for(auto iter = mem_table_.begin();iter != mem_table_.end();++iter) {
    path = iter->first;
    flag = iter->second;
    switch(flag) {
      case kPass :
        printf("pass\n");
        break;

      case kDownloads :
        printf("download...");
        DownloadFile(path);
        break;

      case kRemoteDelete :
        printf("remote deleting...");
        DeleteFile(path);
        break;

      case kLocalDelete :
        printf("local deleting...");
        fs_->DeleteDir(path);
        break;

      case kUploads :
        printf("uploading...");
        UploadFile(path);
        break;

      default: break;
    }

  }
}

FileTrans::FileTrans(const std::string&  access_token) :
            access_token_(access_token) ,
            markf_(kMarkfile),
            fs_(NULL),
            log_(NULL) {}

FileTrans::~FileTrans() {
  delete log_;
  delete fs_;
}

JsonEntry::list FileTrans::FileInfo(const std::string& sub_dir) {
  std::string filelist_url = kDPcsURL      +
                   "?method=list"
                    "&access_token=" + access_token_ +
                    "&path="         + kRemoteRoot  + sub_dir;

  JsonEntry resp = JsonEntry::Parse(HttpGet(filelist_url));
  JsonEntry::list filelist = resp["list"].Value<JsonEntry::list>();
  return filelist;
}

void FileTrans::Downloads(const std::string& p) {
  std::string sub_dir = "";
  if(p != kLocalRoot)
    sub_dir = p.substr(kLocalRoot.size());
  if(!fs_->IsExist(p))
    fs_->CreatDir(p);
  JsonEntry::list remote_flist = FileInfo(sub_dir);
  if(remote_flist.empty()) {
    printf("%s is empty.\n",p.c_str());
    return;
  }
  for (auto iter = remote_flist.begin(); iter != remote_flist.end(); ++iter) {
    if (IsDir(*iter)) {
      std::string local_path = p + '/' + FileFromPath(ParseFileName(*iter));
      Downloads(local_path);
    }
    else {
      DownloadFile(ParseFileName(*iter));
    }
  }
}

void FileTrans::DownloadFile(const std::string& download_file) {
  std::string path = download_file;
  if(path.compare(0,kRemoteRoot.size(),kRemoteRoot)) {
    path = kRemoteRoot + '/' + path;
  }
  std::string file = path.substr(kRemoteRoot.size());
  std::string url = kDPcsURL      +
                   "?method=download"
                    "&access_token=" + access_token_ +
                    "&path="         + kRemoteRoot  +
                    "/"              + file;
  std::string local_path = kLocalRoot + file;
  std::ofstream mfile(local_path, std::ios::out | std::ios::binary);
  HttpGetFile(url, &mfile);
}

void FileTrans::Uploads(const std::string& p) {
  std::forward_list<JsonEntry> local_flist;
  fs_->GetChild(local_flist,p);
  for (auto iter = local_flist.begin(); iter != local_flist.end(); ++iter) {
    std::string path = ParseFileName(*iter);
    bool isdir = fs_->IsLocalDir(path);
    if(isdir) {
      Uploads(path);
    } else {
      UploadFile(path);
    }
  }
}

void FileTrans::UploadFile(const std::string& path) {
  std::ifstream ifile(path.c_str());
  std::string file_contents(
      (std::istreambuf_iterator<char>(ifile)),
      (std::istreambuf_iterator<char>()));
  std::string remote_path  = ExtractPath(path);
  std::string post = kCPcsURL +
                     "?method=upload"
                     "&access_token=" + access_token_ +
                     "&path="         + kRemoteRoot  + '/' + remote_path +
                     "&ondup=overwrite";
  Put(post, file_contents);
}

void FileTrans::DeleteFile(const std::string& path) {
  std::string remote_path  = ExtractPath(path);
  std::string post =  kPcsURL +
                     "?method=delete"
                     "&access_token=" + access_token_ +
                     "&path="         + kRemoteRoot + '/' +remote_path;
  HttpGet(post);
}

void FileTrans::Drive(const std::string &p) {
  File* lfile;
  char *buf = NULL;
  bool is_ok;
  if(fs_->IsExist("Mybaidu/log_history")){
    is_ok = fs_->NewFile(&lfile,"log_history",-1);
    if(!is_ok)
      return;

    log_ = new log::LogFile(lfile);
    is_ok = log_->LogReader(&buf);
    if(!is_ok)
      return;
    StringToMap(mem_table_,&buf);
    SynOperation();
    lfile->Close();
    mem_table_.clear();
    delete buf;
    delete log_;
    fs_->DeleteFile("Mybaidu/log_history");
  }
  Sync(p);
  std::cout << mem_table_.size() << std::endl;
  for (auto it = mem_table_.begin();it != mem_table_.end();++it) {
    std::cout << it->first << "=>" <<it->second << std::endl;
  }
  if(!mem_table_.empty()) {
    if(!MapToString(mem_table_,&buf)) {
      throw std::runtime_error("memory alloc error!");
    }
    is_ok = fs_->NewFile(&lfile,"log_history",1);
    if(!is_ok)
      return;

    log_ = new log::LogFile(lfile);
    is_ok = log_->LogWriter(buf);
    lfile->Close();
    delete buf;
    if(!is_ok)
      return;
    SynOperation();
    fs_->DeleteFile("Mybaidu/log_history");
  }
  std::ofstream ofile(kMarkfile);
}

void FileTrans::Sync(const std::string& p) {
  if(p.empty()) {
    printf("Please input path name.");
    return;
  }
  using namespace std::placeholders;
  FileOperation op_flag;
  std::string sub_dir = "";
  if(!fs_->IsExist(kMarkfile))
    std::ofstream ofile(kMarkfile);

  if(!fs_->IsExist(p)) {
    if(!fs_->CreatDir(p)){
      printf("Pathname invalid.");
      return;
    }
    Downloads(p);
    std::ofstream ofile(kMarkfile);
    return;
  }

  if(p != kLocalRoot)
    sub_dir = p.substr(kLocalRoot.size());

  JsonEntry::list remote_flist = FileInfo(sub_dir);
  std::forward_list<JsonEntry> local_flist;
  fs_->GetChild(local_flist,p);
  for (auto iter = local_flist.begin(); iter != local_flist.end(); ++iter) {
    std::string path = ParseFileName(*iter);
    bool isdir = fs_->IsLocalDir(path);
    if(isdir) {
      auto file = find_if(remote_flist.begin(),remote_flist.end(),std::bind(IsExists,path,_1));
      if(file == remote_flist.end()) {
        op_flag = LocalMtimeCmp(path);
        AddToMemTable(op_flag,path);
      }
      if(op_flag == kRemoteDelete || op_flag == kLocalDelete)
        continue;
      remote_flist.remove(*file);
      std::string local_path = p + '/' + FileFromPath(path);
      Sync(local_path);
    } else {
      LocalUpdate(*iter,remote_flist);
    }
  }
  if(!remote_flist.empty()){
    FileOperation op_flag;
    for(auto iter = remote_flist.begin(); iter != remote_flist.end(); ++iter) {
      std::string remote_path = ParseFileName(*iter);
      op_flag = RemoteMtimeCmp(*iter);
      AddToMemTable(op_flag,remote_path);
    }
  }

}

FileOperation FileTrans::RemoteMtimeCmp(const JsonEntry& json) {
  FileOperation op_flag;
  unsigned int mtime = fs_->LastWriteTime(kMarkfile);
  if(mtime < ParseFilemTime(json))
    op_flag = kDownloads;
  else
    op_flag = kRemoteDelete;
  return op_flag;
}

FileOperation FileTrans::LocalMtimeCmp(const std::string& path) {
  FileOperation op_flag;
  auto mtime = fs_->LastWriteTime(kMarkfile);
  auto ptime = fs_->LastWriteTime(path);
  if(mtime <= ptime)
    op_flag = kUploads;
  else
    op_flag = kLocalDelete;
  return op_flag;
}

void FileTrans::LocalUpdate(const JsonEntry& jobj,JsonEntry::list& flist) {
  using namespace std::placeholders;

  std::string path = jobj["path"].Value<std::string>();
  FileOperation op_flag;
  auto file = find_if(flist.begin(),flist.end(),std::bind(IsExists,path,_1));
  if(file == flist.end()) {
    op_flag = LocalMtimeCmp(path);
  } else {
    std::ifstream ifile(path.c_str(), std::ios::binary | std::ios::out);
    std::string md5 = MD5(ifile.rdbuf());
    auto remote_file = find_if(flist.begin(),flist.end(),std::bind(IsMd5Match,path,md5,_1));
    if(remote_file == flist.end()) {
      auto remote_time = (*file)["mtime"].Value<unsigned int>();
      unsigned int local_time = fs_->LastWriteTime(path);
      if(remote_time < local_time)
        op_flag = kUploads;
      else
        op_flag = kDownloads;
    } else {
      op_flag = kPass;
    }
    flist.remove(*file);
  }
  AddToMemTable(op_flag,path);
}

}  // namespace by


text:
console.log("passed args");

if (42 != process.argv[2]) {
    throw new Error("Invalid args");
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lycoperdon constellatum var. groenlandicum Henn.

### Remarks
null


text:
<pnc-header>
  <pnc-header-title>Projects</pnc-header-title>
  <pnc-header-buttons>
    <button type="button" ui-sref="project.create" class="btn btn-lg btn-default" data-toggle="tooltip"
            title="Create Project">
       Create
    </button>
  </pnc-header-buttons>
</pnc-header>

    <pnc-search-field page="listCtrl.projects" text="projects"></pnc-search-field>

      Name
      Description

        {{ project.name }}
        {{ project.description }}

    <pnc-pager class="pull-right" page="listCtrl.projects"></pnc-pager>


text:
import logging
from itertools import chain
import time

from django import forms
from django.db.models import Q

from aggregator import spiders
from .models import Language, Website

# Get an instance of a logger
logger = logging.getLogger(__name__)

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

class SearchForm(forms.Form):
    """
	translations,target_language,source_language,website,domain,terms,last_updated
	ordinateur,fr,en,iate,Pharmaceutical industry,computer,"[datetime.date(2016, 11, 18)]"
	"""
    keywords_charfield_attrs = forms.TextInput(attrs={'size':50,
                                                      'placeholder':"Search for term"})
    keywords = forms.CharField(max_length=100,
                               widget=keywords_charfield_attrs
                               )
    source_language = forms.ModelChoiceField(Language.objects.all().order_by('code2d'),
                                             label="From",
                                             label_suffix=": ",
                                             empty_label="Source language"
                                             )
    target_language = forms.ModelChoiceField(Language.objects.all().order_by('code2d'),
                                             label="To",
                                             label_suffix=": ",
                                             empty_label="Target language"
                                             )
    def get_all_websites(self):
        '''
        Check first that the form is valid (should never be called if the form is not valid)
        returns an empty Queryset if the form is not valid

        In a normal situation, returns the merged list of all the websites using the language pair selected

        Example : Termium is EN/FR/ES/PT only, don't include it when searching in DE, IT etc...

        '''
        if self.is_valid():
            q_source_language = Q(languages=self.cleaned_data['source_language'])
            q_target_language = Q(languages=self.cleaned_data['target_language'])
            website_list = Website.objects.filter(q_source_language).filter(q_target_language).distinct().order_by('id')
            return website_list
        else:
            return Website.objects.none()

    def get_search_parameters(self):

        if self.is_valid():
            return {'keywords': self.cleaned_data['keywords'],
                'source_language': self.cleaned_data['source_language'],
                'target_language': self.cleaned_data['target_language']}
        else:
            return {'keywords': 'Form is not valid',
                'source_language': '',
                'target_language': ''}

    def get_spider(self, Website):

        search_parameters = self.get_search_parameters()

        # todo test dict performance versus elif switch-like statement
        return {'iate': spiders.IateSpider(**search_parameters),
                'proz': spiders.ProzSpider(**search_parameters),
                'termium': spiders.TermiumSpider(**search_parameters)}[Website.name.lower()]

    def get_records(self, websites):

        spiders_list = []
        for website in websites:
            # for each website, check if search is already in db
            # search_parameters = self.get_search_parameters()
            # search, is_new_search = Search.get_or_create(keywords=self.cleaned_data['keywords'])
            # if (is_new_search):
                # spider = self.get_spider(website)
                # spiders_list.append(spider.parse())
            # else:
                # return results from db as a generator
            spider = self.get_spider(website)
            spiders_list.append(spider.parse())

        return chain.from_iterable(spiders_list)

    def delay(self):

        for i in range(5):
            time.sleep(0.1)

    def get_records_with_delay(self, websites):

        spiders_list = []
        for website in websites:
            spider = self.get_spider(website)
            spiders_list.append(spider.parse())
            spiders_list.append(self.delay())

        return chain.from_iterable(spiders_list)


text:
package language.functions;

public class ConditionalThunk extends Thunk{

	private final Thunk cond;
	private final Thunk then;
	private final Thunk els;

	public ConditionalThunk(Thunk cond, Thunk then, Thunk els){
		this.cond = cond; this.then = then; this.els = els;
	}

	@Override
	protected Object eval() {
		boolean b = (Boolean) cond.exec();
		if(b){
			return then.exec();
		}else{
			return els.exec();
		}
	}

}


text:
package ru.stqa.pft.gge.model;

import com.google.gson.annotations.Expose;

/**
 * Created by manuhin on 16.08.2016.
 */
public class DbConnect {
  @Expose
  private String dbserver;

  @Expose
  private String port;

  @Expose
  private String sid;

  @Expose
  private String user;

  @Expose
  private String password;

  public String getPassword() {
    return password;
  }

  public String getDbserver() {
    return dbserver;
  }

  public String getPort() {
    return port;
  }

  public String getSid() {
    return sid;
  }

  public String getUser() {
    return user;
  }

  public DbConnect withPassword(String password) {
    this.password = password;
    return this;
  }

  public DbConnect withDbserver(String dbserver) {
    this.dbserver = dbserver;
    return this;
  }

  public DbConnect withPort(String port) {
    this.port = port;
    return this;
  }

  public DbConnect withSid(String sid) {
    this.sid = sid;
    return this;
  }

  public DbConnect withUser(String user) {
    this.user = user;
    return this;
  }
}


text:
package org.osgi.util.function;

import static java.util.Objects.requireNonNull;

import org.osgi.annotation.versioning.ConsumerType;

/**
 * A function that accepts a single argument and produces a result.
 *

 * This is a functional interface and can be used as the assignment target for a
 * lambda expression or method reference.
 *
 * @param <T> The type of the function input.
 * @param <R> The type of the function output.
 * @ThreadSafe
 * @author $Id$
 */
@ConsumerType
@FunctionalInterface
public interface Function<T, R> {
	/**
	 * Applies this function to the specified argument.
	 *
	 * @param t The input to this function.
	 * @return The output of this function.
	 * @throws Exception An exception thrown by the method.
	 */
	R apply(T t) throws Exception;

	/**
	 * Compose the specified {@code Function} to be called on the value returned
	 * by this {@code Function}.
	 *
	 * @param <S> The type of the value supplied by the specified
	 *            {@code Function}.
	 * @param after The {@code Function} to be called on the value returned by
	 *            this {@code Function}. Must not be {@code null}.
	 * @return A {@code Function} composed of this {@code Function} and the
	 *         specified {@code Function}.
	 */
	default <S> Function<T,S> andThen(Function< ? super R, ? extends S> after) {
		requireNonNull(after);
		return t -> after.apply(apply(t));
	}

	/**
	 * Compose the specified {@code Function} to be called to supply a value to
	 * be consumed by this {@code Function}.
	 *
	 * @param <S> The type of the value consumed the specified {@code Function}.
	 * @param before The {@code Function} to be called to supply a value to be
	 *            consumed by this {@code Function}. Must not be {@code null}.
	 * @return A {@code Function} composed of this {@code Function} and the
	 *         specified {@code Function}.
	 */
	default <S> Function<S,R> compose(
			Function< ? super S, ? extends T> before) {
		requireNonNull(before);
		return s -> apply(before.apply(s));
	}

	/**
	 * Returns a {@code java.util.function.Function} which wraps the specified
	 * {@code Function} and throws any thrown exceptions.
	 *

	 * The returned {@code java.util.function.Function} will throw any exception
	 * thrown by the wrapped {@code Function}.
	 *
	 * @param <T> The type of the function input.
	 * @param <R> The type of the function output.
	 * @param wrapped The {@code Function} to wrap. Must not be {@code null}.
	 * @return A {@code java.util.function.Function} which wraps the specified
	 *         {@code Function}.
	 */
	static <T, R> java.util.function.Function<T,R> asJavaFunction(
			Function<T,R> wrapped) {
		requireNonNull(wrapped);
		return t -> {
			try {
				return wrapped.apply(t);
			} catch (Exception e) {
				throw Exceptions.throwUnchecked(e);
			}
		};
	}

	/**
	 * Returns a {@code java.util.function.Function} which wraps the specified
	 * {@code Function} and the specified value.
	 *

	 * If the the specified {@code Function} throws an {@code Exception}, the
	 * the specified value is returned.
	 *
	 * @param <T> The type of the function input.
	 * @param <R> The type of the function output.
	 * @param wrapped The {@code Function} to wrap. Must not be {@code null}.
	 * @param orElse The value to return if the specified {@code Function}
	 *            throws an {@code Exception}.
	 * @return A {@code java.util.function.Function} which wraps the specified
	 *         {@code Function} and the specified value.
	 */
	static <T, R> java.util.function.Function<T,R> asJavaFunctionOrElse(
			Function<T,R> wrapped, R orElse) {
		requireNonNull(wrapped);
		return t -> {
			try {
				return wrapped.apply(t);
			} catch (Exception e) {
				return orElse;
			}
		};
	}

	/**
	 * Returns a {@code java.util.function.Function} which wraps the specified
	 * {@code Function} and the specified {@code java.util.function.Supplier}.
	 *

	 * If the the specified {@code Function} throws an {@code Exception}, the
	 * value returned by the specified {@code java.util.function.Supplier} is
	 * returned.
	 *
	 * @param <T> The type of the function input.
	 * @param <R> The type of the function output.
	 * @param wrapped The {@code Function} to wrap. Must not be {@code null}.
	 * @param orElseGet The {@code java.util.function.Supplier} to call for a
	 *            return value if the specified {@code Function} throws an
	 *            {@code Exception}.
	 * @return A {@code java.util.function.Function} which wraps the specified
	 *         {@code Function} and the specified
	 *         {@code java.util.function.Supplier}.
	 */
	static <T, R> java.util.function.Function<T,R> asJavaFunctionOrElseGet(
			Function<T,R> wrapped,
			java.util.function.Supplier< ? extends R> orElseGet) {
		requireNonNull(wrapped);
		return t -> {
			try {
				return wrapped.apply(t);
			} catch (Exception e) {
				return orElseGet.get();
			}
		};
	}

	/**
	 * Returns a {@code Function} which wraps the specified
	 * {@code java.util.function.Function}.
	 *
	 * @param <T> The type of the function input.
	 * @param <R> The type of the function output.
	 * @param wrapped The {@code java.util.function.Function} to wrap. Must not
	 *            be {@code null}.
	 * @return A {@code Function} which wraps the specified
	 *         {@code java.util.function.Function}.
	 */
	static <T, R> Function<T,R> asFunction(
			java.util.function.Function<T,R> wrapped) {
		requireNonNull(wrapped);
		return wrapped::apply;
	}
}


text:
namespace AIFH_Vol2.Core.Error
{
    /// <summary>
    /// An error calculation metric calculates the difference between two vector sets.  One vector set will be the ideal
    /// expected output from a Machine Learning Algorithm.  The other vector set is the actual output.  Training a
    /// Machine Learning Algorithm typically involves minimizing this error.
    ///
    /// Error calculation metrics are very similar to distance metrics.  However, an error calculation metric operates over
    /// a set of vectors, whereas a distance metric operates over just two vectors.
    /// </summary>
    public interface IErrorCalculation
    {
        /// <summary>
        /// Called to update for each number that should be checked.
        /// </summary>
        /// <param name="actual">The actual number.</param>
        /// <param name="ideal">The ideal number.</param>
        /// <param name="significance">The significance, 0 none, 1.0 full.</param>
        void UpdateError(double[] actual, double[] ideal, double significance);

        /// <summary>
        /// Update the error with single values.s
        /// </summary>
        /// <param name="actual">The actual value.</param>
        /// <param name="ideal">The ideal value.</param>
        void UpdateError(double actual, double ideal);

        /// <summary>
        /// Calculate the error with MSE.
        /// </summary>
        /// <returns>The current error for the neural network.</returns>
        double Calculate();

        /// <summary>
        /// Clear the error calculation and start over.
        /// </summary>
        void Clear();

        /// <summary>
        /// The total size of the set (vector size times number of vectors).
        /// </summary>
        int SetSize { get; }

        /// <summary>
        /// Create a new instance of this object.
        /// </summary>
        /// <returns>A new instance of this object.</returns>
        IErrorCalculation Create();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/EC2UserIdGroupPairUnmarshaller.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/EC2UserIdGroupPairUnmarshaller</TokenIdentifier>
			<Abstract type="html">User Id Group Pair Unmarshaller</Abstract>
			<DeclaredIn>EC2UserIdGroupPairUnmarshaller.h</DeclaredIn>

			<NodeRef refid="818"/>
		</Token>

	</File>
</Tokens>


text:
#include <aws/resourcegroupstaggingapi/model/ResourceTagMapping.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace ResourceGroupsTaggingAPI
{
namespace Model
{

ResourceTagMapping::ResourceTagMapping() :
    m_resourceARNHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

ResourceTagMapping::ResourceTagMapping(const JsonValue& jsonValue) :
    m_resourceARNHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
  *this = jsonValue;
}

ResourceTagMapping& ResourceTagMapping::operator =(const JsonValue& jsonValue)
{
  if(jsonValue.ValueExists("ResourceARN"))
  {
    m_resourceARN = jsonValue.GetString("ResourceARN");

    m_resourceARNHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Tags"))
  {
    Array<JsonValue> tagsJsonList = jsonValue.GetArray("Tags");
    for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
    {
      m_tags.push_back(tagsJsonList[tagsIndex].AsObject());
    }
    m_tagsHasBeenSet = true;
  }

  return *this;
}

JsonValue ResourceTagMapping::Jsonize() const
{
  JsonValue payload;

  if(m_resourceARNHasBeenSet)
  {
   payload.WithString("ResourceARN", m_resourceARN);

  }

  if(m_tagsHasBeenSet)
  {
   Array<JsonValue> tagsJsonList(m_tags.size());
   for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
   {
     tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize());
   }
   payload.WithArray("Tags", std::move(tagsJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace ResourceGroupsTaggingAPI
} // namespace Aws


text:
module Language.Interpreter.StdLib
  ( addStdLib
  ) where

import           Language.Interpreter.StdLib.BlockHandling
                                                ( addBlockHandlingStdLib )
import           Language.Interpreter.StdLib.ColourOps
                                                ( addColourStdLib )
import           Language.Interpreter.StdLib.Materials
                                                ( addMaterialStdLib )
import           Language.Interpreter.StdLib.Maths
                                                ( addMathStdLib )
import           Language.Interpreter.StdLib.MatrixOps
                                                ( addMatrixStdLib )
import           Language.Interpreter.StdLib.PostEffects
                                                ( addPostEffectsStdLib )
import           Language.Interpreter.StdLib.Shapes
                                                ( addShapesStdLib )
import           Language.Interpreter.StdLib.Util
                                                ( addUtilStdLib )

import           Language.Interpreter.Types     ( InterpreterProcess )

addStdLib :: InterpreterProcess ()
addStdLib = do
  addMathStdLib
  addMaterialStdLib
  addShapesStdLib
  addMatrixStdLib
  addColourStdLib
  addPostEffectsStdLib
  addBlockHandlingStdLib
  addUtilStdLib


text:
<?xml version="1.0" encoding="UTF-8"?>
<problems>
  <problem>
    <file>light_idea_test_case</file>
    <problem_class>Unused library</problem_class>
    <description>Unused library 'JUnit'</description>
  </problem>

</problems>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2017 Capital One Services, LLC and Bitwise, Inc.
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 -->

<?NLS TYPE="org.eclipse.help.toc"?>

<toc label="GIT- How to check out existing Hydrograph project" link_to="xml/How To Steps/howToSteps.xml#GitChkOutExstProj">
   <topic href="html/How To Steps/Git_How_to_check_out_existing_Hydrograph_proj_from_Git.html" label="GIT- How to check out existing Hydrograph project">
   </topic>

</toc>


text:
namespace CommandPipeline.Infrastructure.Pipeline
{
    public interface IMessageHandlerPipeline
    {
        IMessageHandlerPipeline Register<TCommand>() where TCommand : INonParameterizedCommand;

        void Handle();
    }
}


text:
package org.xml.sax;

import java.io.IOException;
import java.io.Reader;
import java.io.InputStream;

/**
 * A single input source for an XML entity.
 *
 *
This class allows a SAX application to encapsulate information
 * about an input source in a single object, which may include
 * a public identifier, a system identifier, a byte stream (possibly
 * with a specified encoding), and/or a character stream.

 *
 *
There are two places that the application can deliver an
 * input source to the parser: as the argument to the Parser.parse
 * method, or as the return value of the EntityResolver.resolveEntity
 * method.

 *
 *
The SAX parser will use the InputSource object to determine how
 * to read XML input.  If there is a character stream available, the
 * parser will read that stream directly, disregarding any text
 * encoding declaration found in that stream.
 * If there is no character stream, but there is
 * a byte stream, the parser will use that byte stream, using the
 * encoding specified in the InputSource or else (if no encoding is
 * specified) autodetecting the character encoding using an algorithm
 * such as the one in the XML specification.  If neither a character
 * stream nor a
 * byte stream is available, the parser will attempt to open a URI
 * connection to the resource identified by the system
 * identifier.

 *
 *
An InputSource object belongs to the application: the SAX parser
 * shall never modify it in any way (it may modify a copy if
 * necessary).  However, standard processing of both byte and
 * character streams is to close them on as part of end-of-parse cleanup,
 * so applications should not attempt to re-use such streams after they
 * have been handed to a parser.

 *
 * @since 1.4, SAX 1.0
 * @author David Megginson
 * @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource)
 * @see org.xml.sax.EntityResolver#resolveEntity
 * @see java.io.InputStream
 * @see java.io.Reader
 */
public class InputSource {

    /**
     * Zero-argument default constructor.
     *
     * @see #setPublicId
     * @see #setSystemId
     * @see #setByteStream
     * @see #setCharacterStream
     * @see #setEncoding
     */
    public InputSource ()
    {
    }

    /**
     * Create a new input source with a system identifier.
     *
     *
Applications may use setPublicId to include a
     * public identifier as well, or setEncoding to specify
     * the character encoding, if known.

     *
     *
If the system identifier is a URL, it must be fully
     * resolved (it may not be a relative URL).

     *
     * @param systemId The system identifier (URI).
     * @see #setPublicId
     * @see #setSystemId
     * @see #setByteStream
     * @see #setEncoding
     * @see #setCharacterStream
     */
    public InputSource (String systemId)
    {
        setSystemId(systemId);
    }

    /**
     * Create a new input source with a byte stream.
     *
     *
Application writers should use setSystemId() to provide a base
     * for resolving relative URIs, may use setPublicId to include a
     * public identifier, and may use setEncoding to specify the object's
     * character encoding.

     *
     * @param byteStream The raw byte stream containing the document.
     * @see #setPublicId
     * @see #setSystemId
     * @see #setEncoding
     * @see #setByteStream
     * @see #setCharacterStream
     */
    public InputSource (InputStream byteStream)
    {
        setByteStream(byteStream);
    }

    /**
     * Create a new input source with a character stream.
     *
     *
Application writers should use setSystemId() to provide a base
     * for resolving relative URIs, and may use setPublicId to include a
     * public identifier.

     *
     *
The character stream shall not include a byte order mark.

     *
     * @param characterStream the character stream
     * @see #setPublicId
     * @see #setSystemId
     * @see #setByteStream
     * @see #setCharacterStream
     */
    public InputSource (Reader characterStream)
    {
        setCharacterStream(characterStream);
    }

    /**
     * Set the public identifier for this input source.
     *
     *
The public identifier is always optional: if the application
     * writer includes one, it will be provided as part of the
     * location information.

     *
     * @param publicId The public identifier as a string.
     * @see #getPublicId
     * @see org.xml.sax.Locator#getPublicId
     * @see org.xml.sax.SAXParseException#getPublicId
     */
    public void setPublicId (String publicId)
    {
        this.publicId = publicId;
    }

    /**
     * Get the public identifier for this input source.
     *
     * @return The public identifier, or null if none was supplied.
     * @see #setPublicId
     */
    public String getPublicId ()
    {
        return publicId;
    }

    /**
     * Set the system identifier for this input source.
     *
     *
The system identifier is optional if there is a byte stream
     * or a character stream, but it is still useful to provide one,
     * since the application can use it to resolve relative URIs
     * and can include it in error messages and warnings (the parser
     * will attempt to open a connection to the URI only if
     * there is no byte stream or character stream specified).

     *
     *
If the application knows the character encoding of the
     * object pointed to by the system identifier, it can register
     * the encoding using the setEncoding method.

     *
     *
If the system identifier is a URL, it must be fully
     * resolved (it may not be a relative URL).

     *
     * @param systemId The system identifier as a string.
     * @see #setEncoding
     * @see #getSystemId
     * @see org.xml.sax.Locator#getSystemId
     * @see org.xml.sax.SAXParseException#getSystemId
     */
    public void setSystemId (String systemId)
    {
        this.systemId = systemId;
    }

    /**
     * Get the system identifier for this input source.
     *
     *
The getEncoding method will return the character encoding
     * of the object pointed to, or null if unknown.

     *
     *
If the system ID is a URL, it will be fully resolved.

     *
     * @return The system identifier, or null if none was supplied.
     * @see #setSystemId
     * @see #getEncoding
     */
    public String getSystemId ()
    {
        return systemId;
    }

    /**
     * Set the byte stream for this input source.
     *
     *
The SAX parser will ignore this if there is also a character
     * stream specified, but it will use a byte stream in preference
     * to opening a URI connection itself.

     *
     *
If the application knows the character encoding of the
     * byte stream, it should set it with the setEncoding method.

     *
     * @param byteStream A byte stream containing an XML document or
     *        other entity.
     * @see #setEncoding
     * @see #getByteStream
     * @see #getEncoding
     * @see java.io.InputStream
     */
    public void setByteStream (InputStream byteStream)
    {
        this.byteStream = byteStream;
    }

    /**
     * Get the byte stream for this input source.
     *
     *
The getEncoding method will return the character
     * encoding for this byte stream, or null if unknown.

     *
     * @return The byte stream, or null if none was supplied.
     * @see #getEncoding
     * @see #setByteStream
     */
    public InputStream getByteStream ()
    {
        return byteStream;
    }

    /**
     * Set the character encoding, if known.
     *
     *
The encoding must be a string acceptable for an
     * XML encoding declaration (see section 4.3.3 of the XML 1.0
     * recommendation).

     *
     *
This method has no effect when the application provides a
     * character stream.

     *
     * @param encoding A string describing the character encoding.
     * @see #setSystemId
     * @see #setByteStream
     * @see #getEncoding
     */
    public void setEncoding (String encoding)
    {
        this.encoding = encoding;
    }

    /**
     * Get the character encoding for a byte stream or URI.
     * This value will be ignored when the application provides a
     * character stream.
     *
     * @return The encoding, or null if none was supplied.
     * @see #setByteStream
     * @see #getSystemId
     * @see #getByteStream
     */
    public String getEncoding ()
    {
        return encoding;
    }

    /**
     * Set the character stream for this input source.
     *
     *
If there is a character stream specified, the SAX parser
     * will ignore any byte stream and will not attempt to open
     * a URI connection to the system identifier.

     *
     * @param characterStream The character stream containing the
     *        XML document or other entity.
     * @see #getCharacterStream
     * @see java.io.Reader
     */
    public void setCharacterStream (Reader characterStream)
    {
        this.characterStream = characterStream;
    }

    /**
     * Get the character stream for this input source.
     *
     * @return The character stream, or null if none was supplied.
     * @see #setCharacterStream
     */
    public Reader getCharacterStream ()
    {
        return characterStream;
    }

    /**
     * Indicates whether the {@code InputSource} object is empty. Empty is
     * defined as follows:
     *

     *
All of the input sources, including the public identifier, system
     * identifier, byte stream, and character stream, are {@code null}.
     *

     *
The public identifier and system identifier are  {@code null}, and
     * byte and character stream are either  {@code null} or contain no byte
     * or character.
     *

     * Note that this method will reset the byte stream if it is provided, or
     * the character stream if the byte stream is not provided.
     *

     *

     *

     * In case of error while checking the byte or character stream, the method
     * will return false to allow the XML processor to handle the error.
     *
     * @return true if the {@code InputSource} object is empty, false otherwise
     */
    public boolean isEmpty() {
        return (publicId == null && systemId == null && isStreamEmpty());
    }

    private boolean isStreamEmpty() {
        boolean empty = true;
        try {
            if (byteStream != null) {
                byteStream.reset();
                int bytesRead = byteStream.available();
                if (bytesRead > 0) {
                    return false;
                }
            }

            if (characterStream != null) {
                characterStream.reset();
                int c = characterStream.read();
                characterStream.reset();
                if (c != -1) {
                    return false;
                }
            }
        } catch (IOException ex) {
            //in case of error, return false
            return false;
        }

        return empty;
    }
    ////////////////////////////////////////////////////////////////////
    // Internal state.
    ////////////////////////////////////////////////////////////////////

    private String publicId;
    private String systemId;
    private InputStream byteStream;
    private String encoding;
    private Reader characterStream;

}

// end of InputSource.java


text:
package org.guvnor.structure.client.editors.fileexplorer;

import org.guvnor.structure.client.resources.i18n.CommonConstants;
import org.uberfire.backend.vfs.Path;
import org.uberfire.ext.widgets.core.client.tree.FSTreeItem;

import static org.uberfire.commons.validation.PortablePreconditions.checkNotNull;

class FileExplorerItem {

    private CommonConstants constants = CommonConstants.INSTANCE;

    private final FSTreeItem parent;

    FileExplorerItem(final FSTreeItem treeItem) {
        this.parent = checkNotNull("parent",
                                   treeItem);
    }

    public void addDirectory(final Path child) {
        checkCleanupLoading();

        final FSTreeItem newDirectory = parent.addItem(FSTreeItem.FSType.FOLDER,
                                                       child.getFileName());
        newDirectory.addItem(FSTreeItem.FSType.LOADING,
                             constants.Loading());
        newDirectory.setUserObject(child);
    }

    public void addFile(final Path child) {
        checkCleanupLoading();

        final FSTreeItem newFile = parent.addItem(FSTreeItem.FSType.ITEM,
                                                  child.getFileName());
        newFile.setUserObject(child);
    }

    private void checkCleanupLoading() {
        if (parent.getChild(0) != null && parent.getChild(0).getUserObject() == null) {
            parent.getChild(0).remove();
        }
    }
}


text:
using ColossalFramework.Math;
using UnityEngine;
using Boformer.Redirection;
using ColossalFramework;

namespace WG_BalancedPopMod
{
    [TargetType(typeof(IndustrialExtractorAI))]
    class IndustrialExtractorAIMod : IndustrialExtractorAI
    {
        private const int EXTRACT_LEVEL = 0; // Extracting is always level 1 (To make it easier to code)

        /// <summary>
        ///
        /// </summary>
        /// <param name="r"></param>
        /// <param name="width"></param>
        /// <param name="length"></param>
        /// <param name="level0"></param>
        /// <param name="level1"></param>
        /// <param name="level2"></param>
        /// <param name="level3"></param>
        [RedirectMethod(true)]
        public override void CalculateWorkplaceCount(ItemClass.Level level, Randomizer r, int width, int length, out int level0, out int level1, out int level2, out int level3)
        {
            BuildingInfo item = this.m_info;

            PrefabEmployStruct output;
            // If not seen prefab, calculate
            if (!DataStore.prefabWorkerVisit.TryGetValue(item.gameObject.GetHashCode(), out output))
            {
                int[] array = getArray(item, EXTRACT_LEVEL);
                AI_Utils.CalculateprefabWorkerVisit(width, length, ref item, 3, ref array, out output);
                DataStore.prefabWorkerVisit.Add(item.gameObject.GetHashCode(), output);
            }

            level0 = output.level0;
            level1 = output.level1;
            level2 = output.level2;
            level3 = output.level3;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="r"></param>
        /// <param name="productionRate"></param>
        /// <param name="electricityConsumption"></param>
        /// <param name="waterConsumption"></param>
        /// <param name="sewageAccumulation"></param>
        /// <param name="garbageAccumulation"></param>
        /// <param name="incomeAccumulation"></param>
        [RedirectMethod(true)]
        public override void GetConsumptionRates(ItemClass.Level level, Randomizer r, int productionRate, out int electricityConsumption, out int waterConsumption, out int sewageAccumulation, out int garbageAccumulation, out int incomeAccumulation, out int mailAccumulation)
        {
            ulong seed = r.seed;
            ItemClass item = this.m_info.m_class;
            int[] array = getArray(this.m_info, EXTRACT_LEVEL);

            electricityConsumption = array[DataStore.POWER];
            waterConsumption = array[DataStore.WATER];
            sewageAccumulation = array[DataStore.SEWAGE];
            garbageAccumulation = array[DataStore.GARBAGE];
            mailAccumulation = array[DataStore.MAIL];

            int landVal = AI_Utils.GetLandValueIncomeComponent(r.seed);
            incomeAccumulation = array[DataStore.INCOME] + landVal;

            electricityConsumption = Mathf.Max(100, productionRate * electricityConsumption) / 100;
            waterConsumption = Mathf.Max(100, productionRate * waterConsumption) / 100;
            sewageAccumulation = Mathf.Max(100, productionRate * sewageAccumulation) / 100;
            garbageAccumulation = Mathf.Max(100, productionRate * garbageAccumulation) / 100;
            incomeAccumulation = productionRate * incomeAccumulation;
            mailAccumulation = Mathf.Max(100, productionRate * mailAccumulation) / 100;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="productionRate"></param>
        /// <param name="cityPlanningPolicies"></param>
        /// <param name="groundPollution"></param>
        /// <param name="noisePollution"></param>
        [RedirectMethod(true)]
        public override void GetPollutionRates(ItemClass.Level level, int productionRate, DistrictPolicies.CityPlanning cityPlanningPolicies, out int groundPollution, out int noisePollution)
        {
            groundPollution = 0;
            noisePollution = 0;
            int[] array = getArray(this.m_info, EXTRACT_LEVEL);

            groundPollution = (productionRate * array[DataStore.GROUND_POLLUTION]) / 100;
            noisePollution = (productionRate * array[DataStore.NOISE_POLLUTION]) / 100;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="r"></param>
        /// <param name="width"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        [RedirectMethod(true)]
        public override int CalculateProductionCapacity(ItemClass.Level level, Randomizer r, int width, int length)
        {
            int[] array = getArray(this.m_info, EXTRACT_LEVEL);
            return Mathf.Max(100, width * length * array[DataStore.PRODUCTION]) / 100;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="item"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        private int[] getArray(BuildingInfo item, int level)
        {
            int[][] array = DataStore.industry;

            try
            {
                switch (item.m_class.m_subService)
                {
                    case ItemClass.SubService.IndustrialOre:
                        array = DataStore.industry_ore;
                        break;

                    case ItemClass.SubService.IndustrialForestry:
                        array = DataStore.industry_forest;
                        break;

                    case ItemClass.SubService.IndustrialFarming:
                        array = DataStore.industry_farm;
                        break;

                    case ItemClass.SubService.IndustrialOil:
                        array = DataStore.industry_oil;
                        break;

                    case ItemClass.SubService.IndustrialGeneric:  // Deliberate fall through
                    default:
                        break;
                }

                return array[level];
            }
            catch (System.Exception)
            {
                string error = item.gameObject.name + " attempted to be use " + item.m_class.m_subService.ToString() + " with level " + level + ". Returning as level 0.";
                Debugging.writeDebugToFile(error);
                return array[0];
            }
        } // end getArray
    }
}


text:
extern crate log;
extern crate futures;
extern crate tokio_core as tokio;
extern crate tokio_service as service;
extern crate tokio_proto as proto;
extern crate env_logger;
extern crate vastatrix;
#[macro_use]
extern crate clap;

use tokio::reactor::Core;
use std::net::SocketAddr;
use clap::{App, Arg};
use std::io::{self, BufRead};

fn main() {
    env_logger::init().unwrap_or(());

    let mut core = Core::new().unwrap();

    let matches = App::new("chain-repl-test")
        .arg(Arg::with_name("head").short("h").takes_value(true))
        .arg(Arg::with_name("tail").short("t").takes_value(true))
        .get_matches();

    let head_addr = value_t!(matches, "head", SocketAddr).unwrap_or_else(|e| e.exit());
    let tail_addr = value_t!(matches, "tail", SocketAddr).unwrap_or_else(|e| e.exit());

    let client = vastatrix::ThickClient::new(core.handle(), &head_addr, &tail_addr);

    let stdin = io::stdin();
    for l in stdin.lock().lines().map(|l| l.expect("read-line")) {
        let f = client.log_item(l.into_bytes());
        let wpos = core.run(f).expect("run write");
        println!("Produce: {:?}", wpos);
    }
}


text:
@class NSMutableArray, NSString;

@interface CRRequest : NSObject
{
    int _requestType;
    NSObject *_payload;
    NSString *_baseURL;
    NSString *_endpoint;
    NSMutableArray *_parts;
}

@property(retain) NSMutableArray *parts; // @synthesize parts=_parts;
@property(copy) NSString *endpoint; // @synthesize endpoint=_endpoint;
@property(copy) NSString *baseURL; // @synthesize baseURL=_baseURL;
@property(retain) NSObject *payload; // @synthesize payload=_payload;
- (void).cxx_destruct;
- (id)buildPOSTRequest;
- (id)buildMultipartRequest;
- (id)buildURIEncodedRequest;
- (id)buildJSONRequest;
- (id)getURLRequest;
- (void)addPart:(id)arg1;
- (id)initWithBaseURL:(id)arg1 andEndPoint:(id)arg2 andRequestType:(int)arg3;

@end


text:
<?php
error_reporting(E_ALL ^ E_NOTICE);
  require_once("mostra-alerta.php"); ?>

	<meta charset="utf-8">
	<title>Minha Loja</title>
	<link href="css/bootstrap.css" rel="stylesheet">
	<link href="css/loja.css" rel="stylesheet">

				Minha Loja

Adiciona Produto

Produtos

Contato

		    <?php  mostraAlerta("success"); ?>
		    <?php mostraAlerta("danger"); ?>


text:
@interface NSURL (GQURLUtilities)

- (NSString *)gq_dispatchURLString;

- (BOOL)gq_isSameToURL:(NSURL *)aURL;

- (NSDictionary *)gq_queryDictionary;

@end


text:
package io.cereebro.snitch.detect.annotation;

import java.util.Set;

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import io.cereebro.core.Component;
import io.cereebro.core.Consumer;
import io.cereebro.core.Relationship;
import io.cereebro.snitch.detect.annotation.ConsumerHintAnnotationRelationshipDetector;
import io.cereebro.snitch.detect.annotation.DependencyHintAnnotationRelationshipDetector;
import io.cereebro.snitch.detect.annotation.RelationshipHintsAnnotationRelationshipDetector;
import io.cereebro.snitch.detect.annotation.RelationshipHintsConsumersTest.RelationshipHintsConsumerTestConfig;
import io.cereebro.snitch.detect.annotation.test.RelationshipHintsWithConsumersClass;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = RelationshipHintsConsumerTestConfig.class)
public class RelationshipHintsConsumersTest {

    private static final Relationship[] EXPECTED_RELATIONSHIPS = new Relationship[] {
            Consumer.by(Component.of("firstConsumer", "firstType")),
            Consumer.by(Component.of("secondConsumer", "secondType")) };

    @Autowired
    private RelationshipHintsAnnotationRelationshipDetector detector;

    @Test
    public void testTheSize() {
        Set<Relationship> rels = detector.detect();
        Assertions.assertThat(rels).isNotEmpty();
        Assertions.assertThat(rels).hasSize(2);
    }

    @Test
    public void testTheContents() {
        Set<Relationship> actual = detector.detect();
        for (Relationship r : actual) {
            Assertions.assertThat(r).isExactlyInstanceOf(Consumer.class);
        }
        Assertions.assertThat(actual).containsExactlyInAnyOrder(EXPECTED_RELATIONSHIPS);
    }

    @Configuration
    public static class RelationshipHintsConsumerTestConfig {

        @Bean
        public RelationshipHintsAnnotationRelationshipDetector detector() {
            return new RelationshipHintsAnnotationRelationshipDetector(
                    new DependencyHintAnnotationRelationshipDetector(),
                    new ConsumerHintAnnotationRelationshipDetector());
        }

        @Bean
        public RelationshipHintsWithConsumersClass relationsWithConsumers() {
            return new RelationshipHintsWithConsumersClass();
        }

    }

}


text:
import { browser, element, by, logging } from 'protractor';

describe('Inputs and Outputs', () => {

  beforeEach(() => browser.get(''));

   // helper function used to test what's logged to the console
  async function logChecker(contents: string) {
    const logs = await browser
      .manage()
      .logs()
      .get(logging.Type.BROWSER);
    const messages = logs.filter(({ message }) => message.indexOf(contents) !== -1);
    expect(messages.length).toBeGreaterThan(0);
  }

  it('should have title Inputs and Outputs', async () => {
    const title = element.all(by.css('h1')).get(0);
    expect(await title.getText()).toEqual('Inputs and Outputs');
  });

  it('should add 123 to the parent list', async () => {
    const addToParentButton = element.all(by.css('button')).get(0);
    const addToListInput = element.all(by.css('input')).get(0);
    const addedItem = element.all(by.css('li')).get(4);
    await addToListInput.sendKeys('123');
    await addToParentButton.click();
    expect(await addedItem.getText()).toEqual('123');
  });

  it('should delete item', async () => {
    const deleteButton = element.all(by.css('button')).get(1);
    const contents = 'Child';
    await deleteButton.click();
    await logChecker(contents);
  });

  it('should log buy the item', async () => {
    const buyButton = element.all(by.css('button')).get(2);
    const contents = 'Child';
    await buyButton.click();
    await logChecker(contents);
  });

  it('should save item for later', async () => {
    const saveButton = element.all(by.css('button')).get(3);
    const contents = 'Child';
    await saveButton.click();
    await logChecker(contents);
  });

  it('should add item to wishlist', async () => {
    const addToParentButton = element.all(by.css('button')).get(4);
    const addedItem = element.all(by.css('li')).get(6);
    await addToParentButton.click();
    expect(await addedItem.getText()).toEqual('Television');
  });

});