text:
package com.google.cloud.spanner.admin.database.v1;

import static com.google.cloud.spanner.admin.database.v1.PagedResponseWrappers.ListDatabasesPagedResponse;

import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.ApiException;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.common.collect.Lists;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.longrunning.Operation;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import com.google.protobuf.GeneratedMessageV3;
import com.google.spanner.admin.database.v1.CreateDatabaseRequest;
import com.google.spanner.admin.database.v1.Database;
import com.google.spanner.admin.database.v1.DatabaseName;
import com.google.spanner.admin.database.v1.DropDatabaseRequest;
import com.google.spanner.admin.database.v1.GetDatabaseDdlRequest;
import com.google.spanner.admin.database.v1.GetDatabaseDdlResponse;
import com.google.spanner.admin.database.v1.GetDatabaseRequest;
import com.google.spanner.admin.database.v1.InstanceName;
import com.google.spanner.admin.database.v1.ListDatabasesRequest;
import com.google.spanner.admin.database.v1.ListDatabasesResponse;
import com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

@javax.annotation.Generated("by GAPIC")
public class DatabaseAdminClientTest {
  private static MockDatabaseAdmin mockDatabaseAdmin;
  private static MockServiceHelper serviceHelper;
  private DatabaseAdminClient client;

  @BeforeClass
  public static void startStaticServer() {
    mockDatabaseAdmin = new MockDatabaseAdmin();
    serviceHelper =
        new MockServiceHelper("in-process-1", Arrays.<MockGrpcService>asList(mockDatabaseAdmin));
    serviceHelper.start();
  }

  @AfterClass
  public static void stopServer() {
    serviceHelper.stop();
  }

  @Before
  public void setUp() throws IOException {
    serviceHelper.reset();
    DatabaseAdminSettings settings =
        DatabaseAdminSettings.defaultBuilder()
            .setChannelProvider(serviceHelper.createChannelProvider())
            .setCredentialsProvider(new NoCredentialsProvider())
            .build();
    client = DatabaseAdminClient.create(settings);
  }

  @After
  public void tearDown() throws Exception {
    client.close();
  }

  @Test
  @SuppressWarnings("all")
  public void listDatabasesTest() {
    String nextPageToken = "";
    Database databasesElement = Database.newBuilder().build();
    List<Database> databases = Arrays.asList(databasesElement);
    ListDatabasesResponse expectedResponse =
        ListDatabasesResponse.newBuilder()
            .setNextPageToken(nextPageToken)
            .addAllDatabases(databases)
            .build();
    mockDatabaseAdmin.addResponse(expectedResponse);

    InstanceName parent = InstanceName.create("[PROJECT]", "[INSTANCE]");

    ListDatabasesPagedResponse pagedListResponse = client.listDatabases(parent);

    List<Database> resources = Lists.newArrayList(pagedListResponse.iterateAll());
    Assert.assertEquals(1, resources.size());
    Assert.assertEquals(expectedResponse.getDatabasesList().get(0), resources.get(0));

    List<GeneratedMessageV3> actualRequests = mockDatabaseAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    ListDatabasesRequest actualRequest = (ListDatabasesRequest) actualRequests.get(0);

    Assert.assertEquals(parent, actualRequest.getParentAsInstanceName());
  }

  @Test
  @SuppressWarnings("all")
  public void listDatabasesExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockDatabaseAdmin.addException(exception);

    try {
      InstanceName parent = InstanceName.create("[PROJECT]", "[INSTANCE]");

      client.listDatabases(parent);
      Assert.fail("No exception raised");
    } catch (ApiException e) {
      Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
    }
  }

  @Test
  @SuppressWarnings("all")
  public void createDatabaseTest() throws Exception {
    String name = "name3373707";
    Database expectedResponse = Database.newBuilder().setName(name).build();
    Operation resultOperation =
        Operation.newBuilder()
            .setName("createDatabaseTest")
            .setDone(true)
            .setResponse(Any.pack(expectedResponse))
            .build();
    mockDatabaseAdmin.addResponse(resultOperation);

    InstanceName parent = InstanceName.create("[PROJECT]", "[INSTANCE]");
    String createStatement = "createStatement552974828";

    Database actualResponse = client.createDatabaseAsync(parent, createStatement).get();
    Assert.assertEquals(expectedResponse, actualResponse);

    List<GeneratedMessageV3> actualRequests = mockDatabaseAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    CreateDatabaseRequest actualRequest = (CreateDatabaseRequest) actualRequests.get(0);

    Assert.assertEquals(parent, actualRequest.getParentAsInstanceName());
    Assert.assertEquals(createStatement, actualRequest.getCreateStatement());
  }

  @Test
  @SuppressWarnings("all")
  public void createDatabaseExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockDatabaseAdmin.addException(exception);

    try {
      InstanceName parent = InstanceName.create("[PROJECT]", "[INSTANCE]");
      String createStatement = "createStatement552974828";

      client.createDatabaseAsync(parent, createStatement).get();
      Assert.fail("No exception raised");
    } catch (ExecutionException e) {
      Assert.assertEquals(ApiException.class, e.getCause().getClass());
      ApiException apiException = (ApiException) e.getCause();
      Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), apiException.getStatusCode());
    }
  }

  @Test
  @SuppressWarnings("all")
  public void getDatabaseTest() {
    String name2 = "name2-1052831874";
    Database expectedResponse = Database.newBuilder().setName(name2).build();
    mockDatabaseAdmin.addResponse(expectedResponse);

    DatabaseName name = DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]");

    Database actualResponse = client.getDatabase(name);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<GeneratedMessageV3> actualRequests = mockDatabaseAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    GetDatabaseRequest actualRequest = (GetDatabaseRequest) actualRequests.get(0);

    Assert.assertEquals(name, actualRequest.getNameAsDatabaseName());
  }

  @Test
  @SuppressWarnings("all")
  public void getDatabaseExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockDatabaseAdmin.addException(exception);

    try {
      DatabaseName name = DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]");

      client.getDatabase(name);
      Assert.fail("No exception raised");
    } catch (ApiException e) {
      Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
    }
  }

  @Test
  @SuppressWarnings("all")
  public void updateDatabaseDdlTest() throws Exception {
    Empty expectedResponse = Empty.newBuilder().build();
    Operation resultOperation =
        Operation.newBuilder()
            .setName("updateDatabaseDdlTest")
            .setDone(true)
            .setResponse(Any.pack(expectedResponse))
            .build();
    mockDatabaseAdmin.addResponse(resultOperation);

    DatabaseName database = DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]");
    List<String> statements = new ArrayList<>();

    Empty actualResponse = client.updateDatabaseDdlAsync(database, statements).get();
    Assert.assertEquals(expectedResponse, actualResponse);

    List<GeneratedMessageV3> actualRequests = mockDatabaseAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    UpdateDatabaseDdlRequest actualRequest = (UpdateDatabaseDdlRequest) actualRequests.get(0);

    Assert.assertEquals(database, actualRequest.getDatabaseAsDatabaseName());
    Assert.assertEquals(statements, actualRequest.getStatementsList());
  }

  @Test
  @SuppressWarnings("all")
  public void updateDatabaseDdlExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockDatabaseAdmin.addException(exception);

    try {
      DatabaseName database = DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]");
      List<String> statements = new ArrayList<>();

      client.updateDatabaseDdlAsync(database, statements).get();
      Assert.fail("No exception raised");
    } catch (ExecutionException e) {
      Assert.assertEquals(ApiException.class, e.getCause().getClass());
      ApiException apiException = (ApiException) e.getCause();
      Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), apiException.getStatusCode());
    }
  }

  @Test
  @SuppressWarnings("all")
  public void dropDatabaseTest() {
    Empty expectedResponse = Empty.newBuilder().build();
    mockDatabaseAdmin.addResponse(expectedResponse);

    DatabaseName database = DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]");

    client.dropDatabase(database);

    List<GeneratedMessageV3> actualRequests = mockDatabaseAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    DropDatabaseRequest actualRequest = (DropDatabaseRequest) actualRequests.get(0);

    Assert.assertEquals(database, actualRequest.getDatabaseAsDatabaseName());
  }

  @Test
  @SuppressWarnings("all")
  public void dropDatabaseExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockDatabaseAdmin.addException(exception);

    try {
      DatabaseName database = DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]");

      client.dropDatabase(database);
      Assert.fail("No exception raised");
    } catch (ApiException e) {
      Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
    }
  }

  @Test
  @SuppressWarnings("all")
  public void getDatabaseDdlTest() {
    GetDatabaseDdlResponse expectedResponse = GetDatabaseDdlResponse.newBuilder().build();
    mockDatabaseAdmin.addResponse(expectedResponse);

    DatabaseName database = DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]");

    GetDatabaseDdlResponse actualResponse = client.getDatabaseDdl(database);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<GeneratedMessageV3> actualRequests = mockDatabaseAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    GetDatabaseDdlRequest actualRequest = (GetDatabaseDdlRequest) actualRequests.get(0);

    Assert.assertEquals(database, actualRequest.getDatabaseAsDatabaseName());
  }

  @Test
  @SuppressWarnings("all")
  public void getDatabaseDdlExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockDatabaseAdmin.addException(exception);

    try {
      DatabaseName database = DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]");

      client.getDatabaseDdl(database);
      Assert.fail("No exception raised");
    } catch (ApiException e) {
      Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
    }
  }

  @Test
  @SuppressWarnings("all")
  public void setIamPolicyTest() {
    int version = 351608024;
    ByteString etag = ByteString.copyFromUtf8("21");
    Policy expectedResponse = Policy.newBuilder().setVersion(version).setEtag(etag).build();
    mockDatabaseAdmin.addResponse(expectedResponse);

    String formattedResource =
        DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString();
    Policy policy = Policy.newBuilder().build();

    Policy actualResponse = client.setIamPolicy(formattedResource, policy);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<GeneratedMessageV3> actualRequests = mockDatabaseAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    SetIamPolicyRequest actualRequest = (SetIamPolicyRequest) actualRequests.get(0);

    Assert.assertEquals(formattedResource, actualRequest.getResource());
    Assert.assertEquals(policy, actualRequest.getPolicy());
  }

  @Test
  @SuppressWarnings("all")
  public void setIamPolicyExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockDatabaseAdmin.addException(exception);

    try {
      String formattedResource =
          DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString();
      Policy policy = Policy.newBuilder().build();

      client.setIamPolicy(formattedResource, policy);
      Assert.fail("No exception raised");
    } catch (ApiException e) {
      Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
    }
  }

  @Test
  @SuppressWarnings("all")
  public void getIamPolicyTest() {
    int version = 351608024;
    ByteString etag = ByteString.copyFromUtf8("21");
    Policy expectedResponse = Policy.newBuilder().setVersion(version).setEtag(etag).build();
    mockDatabaseAdmin.addResponse(expectedResponse);

    String formattedResource =
        DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString();

    Policy actualResponse = client.getIamPolicy(formattedResource);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<GeneratedMessageV3> actualRequests = mockDatabaseAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    GetIamPolicyRequest actualRequest = (GetIamPolicyRequest) actualRequests.get(0);

    Assert.assertEquals(formattedResource, actualRequest.getResource());
  }

  @Test
  @SuppressWarnings("all")
  public void getIamPolicyExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockDatabaseAdmin.addException(exception);

    try {
      String formattedResource =
          DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString();

      client.getIamPolicy(formattedResource);
      Assert.fail("No exception raised");
    } catch (ApiException e) {
      Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
    }
  }

  @Test
  @SuppressWarnings("all")
  public void testIamPermissionsTest() {
    TestIamPermissionsResponse expectedResponse = TestIamPermissionsResponse.newBuilder().build();
    mockDatabaseAdmin.addResponse(expectedResponse);

    String formattedResource =
        DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString();
    List<String> permissions = new ArrayList<>();

    TestIamPermissionsResponse actualResponse =
        client.testIamPermissions(formattedResource, permissions);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<GeneratedMessageV3> actualRequests = mockDatabaseAdmin.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    TestIamPermissionsRequest actualRequest = (TestIamPermissionsRequest) actualRequests.get(0);

    Assert.assertEquals(formattedResource, actualRequest.getResource());
    Assert.assertEquals(permissions, actualRequest.getPermissionsList());
  }

  @Test
  @SuppressWarnings("all")
  public void testIamPermissionsExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
    mockDatabaseAdmin.addException(exception);

    try {
      String formattedResource =
          DatabaseName.create("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString();
      List<String> permissions = new ArrayList<>();

      client.testIamPermissions(formattedResource, permissions);
      Assert.fail("No exception raised");
    } catch (ApiException e) {
      Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
    }
  }
}


text:
cask 'dispcalgui' do
  version :latest
  sha256 :no_check

  url 'http://dispcalgui.hoech.net/download/dispcalGUI.dmg'
  name 'dispcalGUI'
  homepage 'https://dispcalgui.hoech.net'
  license :gpl

  app 'dispcalGUI.app'
end

redpajama_set_name: RedPajamaGithub


text:
package alluxio.exception;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Precondition messages used across Alluxio.
 *
 * Note: To minimize merge conflicts, please sort alphabetically in this section.
 */
@ThreadSafe
public enum PreconditionMessage {
  ASYNC_JOURNAL_WRITER_NULL("AsyncJournalWriter cannot be null"),
  COMMAND_LINE_LINEAGE_ONLY("Only command line jobs are supported by createLineage"),
  EMPTY_FILE_INFO_LIST_FOR_PERMISSION_CHECK(
      "The passed-in file info list can not be empty when checking permission"),
  ERR_BLOCK_INDEX("Current block index exceeds max index"),
  ERR_BLOCK_REMAINING("The current block still has space left, no need to get new block"),
  ERR_BUFFER_STATE("Buffer length: %s, offset: %s, len: %s"),
  ERR_CLOSED_BLOCK_IN_STREAM("Cannot do operations on a closed BlockInStream"),
  ERR_CLOSED_BLOCK_OUT_STREAM("Cannot do operations on a closed BlockOutStream"),
  ERR_CLOSED_UNDER_FILE_SYSTEM_FILE_OUT_STREAM(
      "Cannot do operations on a closed UnderFileSystemFileOutStream"),
  ERR_END_OF_BLOCK("Cannot write past end of block"),
  ERR_READ_BUFFER_NULL("Read buffer cannot be null"),
  ERR_PUT_EMPTY_KEY("Cannot put an empty buffer as a key"),
  ERR_PUT_EMPTY_VALUE("Cannot put an empty buffer as a value"),
  ERR_PUT_NULL_KEY("Cannot put a null key"),
  ERR_PUT_NULL_VALUE("Cannot put a null value"),
  ERR_SEEK_NEGATIVE("Seek position is negative: %s"),
  ERR_SEEK_PAST_END_OF_BLOCK("Seek position past end of block: %s"),
  ERR_SEEK_PAST_END_OF_FILE("Seek position past end of file: %s"),
  ERR_SET_STATE_UNPERSIST("Cannot set the state of a file to not-persisted"),
  ERR_TIER_QUOTA_BLANK("Tier capacity configuration should not be blank"),
  ERR_UFS_MANAGER_OPERATION_INVALID_SESSION("Attempted to %s ufs file with invalid session id."),
  ERR_UFS_MANAGER_FAILED_TO_REMOVE_AGENT(
      "Failed to remove agent %d from ufs manager's internal state."),
  ERR_UNEXPECTED_EOF("Reached EOF unexpectedly."),
  ERR_WRITE_BUFFER_NULL("Cannot write a null input buffer"),
  FILE_TO_PERSIST_MUST_BE_COMPLETE("File being persisted must be complete"),
  FILE_WRITE_LOCATION_POLICY_UNSPECIFIED("The location policy is not specified"),
  GCS_BUCKET_MUST_BE_SET("The %s system property must be set to use the GCSUnderStorageCluster"),
  INODE_TREE_UNINITIALIZED_IS_ROOT_ID("Cannot call isRootId() before initializeRoot()"),
  MUST_SET_PINNED("The pinned flag must be set"),
  MUST_SET_TTL("The TTL value must be set"),
  MUST_SET_PERSISTED("The persisted value must be set"),
  MUST_SET_OWNER("The owner must be set"),
  MUST_SET_GROUP("The group must be set"),
  MUST_SET_MODE("The mode must be set"),
  PERMISSION_GROUP_IS_NULL("Group cannot be null when constructing Permission"),
  PERMISSION_MODE_IS_NULL("Mode cannot be null when constructing Permission"),
  PERMISSION_OWNER_IS_NULL("Owner cannot be null when constructing Permission"),
  PERSIST_ONLY_FOR_FILE("Only files can be persisted"),
  PROTOCOL_NULL_WHEN_CONNECTED(
      "The client protocol should never be null when the client is connected"),
  REMOTE_CLIENT_BUT_LOCAL_HOSTNAME(
      "Acquire Remote Worker Client cannot not be called with local hostname"),
  S3_BUCKET_MUST_BE_SET("The %s system property must be set to use the S3UnderStorageCluster"),
  TTL_ONLY_FOR_FILE("TTL can only be set for files"),
  URI_HOST_NULL("URI hostname must not be null"),
  URI_PORT_NULL("URI port must not be null"),
  URI_KEY_VALUE_STORE_NULL("URI of key-value store must not be null"),

  // SEMICOLON! minimize merge conflicts by putting it on its own line
  ;

  private final String mMessage;

  PreconditionMessage(String message) {
    mMessage = message;
  }

  @Override
  public String toString() {
    return mMessage;
  }
}


text:
require 'rubygems'
require 'ostruct'

require 'sinatra' unless defined?(Sinatra)

configure do
  SiteConfig = OpenStruct.new(
    :title => 'UVA Library Geoportal',
    :description => '',
    :geonetwork_url => 'http://gis.lib.virginia.edu',
    :geonetwork_port => ':8080',
    :geonetwork_mount => 'geonetwork',
    :geoserver_url => 'http://gis.lib.virginia.edu:8080/geoserver',
    :library_catalog => 'http://search.lib.virginia.edu/catalog/'
  )

  # Load modules
  $LOAD_PATH.unshift("#{File.dirname(__FILE__)}/lib/")
  Dir.glob("#{File.dirname(__FILE__)}/lib/*.rb") {|lib| require File.basename(lib, '.*') }
end

configure :development do

end

configure :production do

end


text:
The following packages are included in WinPython-32bit v3.8.1.0dot .

### Tools

Name | Version | Description
-----|---------|------------

### Python packages

Name | Version | Description
-----|---------|------------
[Python](http://www.python.org/) | 3.8.1 | Python programming language with standard library
[pip](https://pypi.org/project/pip) | 19.3.1 | A tool for installing and managing Python packages
[setuptools](https://pypi.org/project/setuptools) | 42.0.2 | Download, build, install, upgrade, and uninstall Python packages - easily
[sqlite_bro](https://pypi.org/project/sqlite_bro) | 0.9.1 | a graphic SQLite Client in 1 Python file
[wheel](https://pypi.org/project/wheel) | 0.33.6 | A built-package format for Python.
[winpython](http://winpython.github.io/) | 2.2.20191222 | WinPython distribution tools, including WPPM (package manager)


text:
require 'spec_helper'

RSpec.describe ComposedValidations::OrStringJoiner do
  subject { described_class.new(*strings) }
  context "when there's two strings" do
    let(:strings) { ["one", "two"] }
    it "should join with or" do
      expect(subject.to_s).to eq "one or two"
    end
  end
  context "when there's three strings" do
    let(:strings) { ["one", "two", "three"] }
    it "should join with a comma and or" do
      expect(subject.to_s).to eq "one, two or three"
    end
  end
  context "when there's four strings" do
    let(:strings) { ["one", "two", "three", "four"] }
    it "should join nicely" do
      expect(subject.to_s).to eq "one, two, three or four"
    end
  end
end


text:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Effects;

namespace Esthar.UI
{
    public static class ValidationHelper
    {
        private static readonly DropShadowEffect InvalidEffect = new DropShadowEffect { Color = Colors.Red, BlurRadius = 5, ShadowDepth = 1 };

        public static void SetInvalid(FrameworkElement element, ValidationResult result)
        {
            if (result.IsValid)
            {
                element.Effect = null;
                element.ToolTip = null;
            }
            else
            {
                element.Effect = InvalidEffect;
                element.ToolTip = new ToolTip { Content = result.ErrorContent };
            }
        }
    }
}


text:
<!DOCTYPE html>
<title>drag & drop - microdata for selection surrounding nested non-property items</title>

0123456789

Use your pointing device to select the text substring "12345678" above, drag the selection upwards to the pink box,
then back to the blue box, and release it.

Enable JavaScript and reload


text:
declare const observableSymbol: symbol;
export default observableSymbol;

declare global {
  export interface SymbolConstructor {
    readonly observable: symbol;
  }
}

export interface Symbol {
  readonly [Symbol.observable]: symbol;
}


text:
require 'ostruct'

module Psych
  module Inherit
    module File
      class Parser
        def load_file(file)
          parse_file(file).to_ruby
        end

        def parse_file(file)
          parse(::File.read(file))
        rescue StandardError => e
          # STDOUT.puts "Error while reading file #{file}: #{e}"
          raise e
        end

        def parse(content)
          parser = Psych::Parser.new(File::Handler.new(self))
          parser.parse(content).handler.document
        end
      end
    end
  end
end


text:
{-# LANGUAGE Rank2Types, GADTs #-}
{-# LANGUAGE CPP #-}
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
-------------------------------------------------------------------------------------------
-- |
-- Copyright 	: 2008-2013 Edward Kmett
-- License	: BSD
--
-- Maintainer	: Edward Kmett <ekmett@gmail.com>
-- Stability	: experimental
-- Portability	: rank 2 types
--
-- * Right Kan Extensions
-------------------------------------------------------------------------------------------
module Data.Functor.Kan.Ran
  (
    Ran(..)
  , toRan, fromRan
  , gran
  , composeRan, decomposeRan
  , adjointToRan, ranToAdjoint
  , composedAdjointToRan, ranToComposedAdjoint
  , repToRan, ranToRep
  , composedRepToRan, ranToComposedRep
  ) where

import Data.Functor.Adjunction
import Data.Functor.Composition
import Data.Functor.Identity
import Data.Functor.Rep

-- | The right Kan extension of a 'Functor' h along a 'Functor' g.
--
-- We can define a right Kan extension in several ways. The definition here is obtained by reading off
-- the definition in of a right Kan extension in terms of an End, but we can derive an equivalent definition
-- from the universal property.
--
-- Given a 'Functor' @h : C -> D@ and a 'Functor' @g : C -> C'@, we want to extend @h@ /back/ along @g@
-- to give @Ran g h : C' -> C@, such that the natural transformation @'gran' :: Ran g h (g a) -> h a@ exists.
--
-- In some sense this is trying to approximate the inverse of @g@ by using one of
-- its adjoints, because if the adjoint and the inverse both exist, they match!
--
-- > Hask -h-> Hask
-- >   |       +
-- >   g      /
-- >   |    Ran g h
-- >   v    /
-- > Hask -'
--
-- The Right Kan extension is unique (up to isomorphism) by taking this as its universal property.
--
-- That is to say given any @K : C' -> C@ such that we have a natural transformation from @k.g@ to @h@
-- @(forall x. k (g x) -> h x)@ there exists a canonical natural transformation from @k@ to @Ran g h@.
-- @(forall x. k x -> Ran g h x)@.
--
-- We could literally read this off as a valid Rank-3 definition for 'Ran':
--
-- @
-- data Ran' g h a = forall z. 'Functor' z => Ran' (forall x. z (g x) -> h x) (z a)
-- @
--
-- This definition is isomorphic the simpler Rank-2 definition we use below as witnessed by the
--
-- @
-- ranIso1 :: Ran g f x -> Ran' g f x
-- ranIso1 (Ran e) = Ran' e id
-- @
--
-- @
-- ranIso2 :: Ran' g f x -> Ran g f x
-- ranIso2 (Ran' h z) = Ran $ \\k -> h (k \<$\> z)
-- @
--
-- @
-- ranIso2 (ranIso1 (Ran e)) ≡ -- by definition
-- ranIso2 (Ran' e id) ≡       -- by definition
-- Ran $ \\k -> e (k \<$\> id)    -- by definition
-- Ran $ \\k -> e (k . id)      -- f . id = f
-- Ran $ \\k -> e k             -- eta reduction
-- Ran e
-- @
--
-- The other direction is left as an exercise for the reader.
newtype Ran g h a = Ran { runRan :: forall b. (a -> g b) -> h b }

instance Functor (Ran g h) where
  fmap f m = Ran (\k -> runRan m (k . f))
  {-# INLINE fmap #-}

-- | The universal property of a right Kan extension.
toRan :: Functor k => (forall a. k (g a) -> h a) -> k b -> Ran g h b
toRan s t = Ran (s . flip fmap t)
{-# INLINE toRan #-}

-- | 'toRan' and 'fromRan' witness a higher kinded adjunction. from @(`'Compose'` g)@ to @'Ran' g@
--
-- @
-- 'toRan' . 'fromRan' ≡ 'id'
-- 'fromRan' . 'toRan' ≡ 'id'
-- @
fromRan :: (forall a. k a -> Ran g h a) -> k (g b) -> h b
fromRan s = flip runRan id . s
{-# INLINE fromRan #-}

-- |
-- @
-- 'composeRan' . 'decomposeRan' ≡ 'id'
-- 'decomposeRan' . 'composeRan' ≡ 'id'
-- @
composeRan :: Composition compose => Ran f (Ran g h) a -> Ran (compose f g) h a
composeRan r = Ran (\f -> runRan (runRan r (decompose . f)) id)
{-# INLINE composeRan #-}

decomposeRan :: (Composition compose, Functor f) => Ran (compose f g) h a -> Ran f (Ran g h) a
decomposeRan r = Ran (\f -> Ran (\g -> runRan r (compose . fmap g . f)))
{-# INLINE decomposeRan #-}

-- |
--
-- @
-- 'adjointToRan' . 'ranToAdjoint' ≡ 'id'
-- 'ranToAdjoint' . 'adjointToRan' ≡ 'id'
-- @
adjointToRan :: Adjunction f g => f a -> Ran g Identity a
adjointToRan f = Ran (\a -> Identity $ rightAdjunct a f)
{-# INLINE adjointToRan #-}

ranToAdjoint :: Adjunction f g => Ran g Identity a -> f a
ranToAdjoint r = runIdentity (runRan r unit)
{-# INLINE ranToAdjoint #-}

-- |
--
-- @
-- 'composedAdjointToRan' . 'ranToComposedAdjoint' ≡ 'id'
-- 'ranToComposedAdjoint' . 'composedAdjointToRan' ≡ 'id'
-- @
ranToComposedAdjoint :: Adjunction f g => Ran g h a -> h (f a)
ranToComposedAdjoint r = runRan r unit
{-# INLINE ranToComposedAdjoint #-}

composedAdjointToRan :: (Adjunction f g, Functor h) => h (f a) -> Ran g h a
composedAdjointToRan f = Ran (\a -> fmap (rightAdjunct a) f)
{-# INLINE composedAdjointToRan #-}

-- | This is the natural transformation that defines a Right Kan extension.
gran :: Ran g h (g a) -> h a
gran (Ran f) = f id
{-# INLINE gran #-}

repToRan :: Representable u => Rep u -> a -> Ran u Identity a
repToRan e a = Ran $ \k -> Identity $ index (k a) e
{-# INLINE repToRan #-}

ranToRep :: Representable u => Ran u Identity a -> (Rep u, a)
ranToRep (Ran f) = runIdentity $ f (\a -> tabulate $ \e -> (e, a))
{-# INLINE ranToRep #-}

ranToComposedRep :: Representable u => Ran u h a -> h (Rep u, a)
ranToComposedRep (Ran f) = f (\a -> tabulate $ \e -> (e, a))
{-# INLINE ranToComposedRep #-}

composedRepToRan :: (Representable u, Functor h) => h (Rep u, a) -> Ran u h a
composedRepToRan hfa = Ran $ \k -> fmap (\(e, a) -> index (k a) e) hfa
{-# INLINE composedRepToRan #-}


text:
<?php

namespace Symfony\Component\Workflow\Event;

class CompletedEvent extends Event
{
}


text:
package com.ing.baker.il.petrinet

import com.ing.baker.petrinet.api.Identifiable

object Transition {

  implicit val identifiable: Identifiable[Transition] = p => p.id
}

trait Transition {

  def id: Long
  def label: String
}


text:
package de.darwinspl.feature.graphical.editor.template.svg;

import java.util.List;

/**
 * Data container for a feature to use with freemarker to generate a svg file from a feature model
 * @author Gil Engel
 *
 */
public class DwFeatureModelSVGFeatureDataObject {
	private String name;

	private int x;

	private int y;

	private int width;

	private int height;

	private int versionAreaWidth;

	private int versionAreaHeight;

	private int modifier;

	private List<DwFeatureModelSVGAttributeDataObject> attributes;

	private List<DwFeatureModelSVGFeatureDataObject> children;

	private DwFeatureModelSVGVersionDataObject rootVersion;

	public String getName() {
		return name;
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public int getVersionAreaWidth() {
		return versionAreaWidth;
	}

	public int getVersionAreaHeight() {
		return versionAreaHeight;
	}

	public int getModifier() {
		return modifier;
	}

	public List<DwFeatureModelSVGAttributeDataObject> getAttributes() {
		return attributes;
	}

	public List<DwFeatureModelSVGFeatureDataObject> getChildren() {
		return children;
	}

	public DwFeatureModelSVGVersionDataObject getRootVersion() {
		return rootVersion;
	}

	public DwFeatureModelSVGFeatureDataObject(String name, int x, int y, int width, int height, int versionAreaWidth,
			int versionAreaHeight, int modifier, List<DwFeatureModelSVGAttributeDataObject> attributes,
			List<DwFeatureModelSVGFeatureDataObject> children, DwFeatureModelSVGVersionDataObject rootVersion) {
		super();
		this.name = name;
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.versionAreaWidth = versionAreaWidth;
		this.versionAreaHeight = versionAreaHeight;
		this.modifier = modifier;
		this.attributes = attributes;
		this.children = children;
		this.rootVersion = rootVersion;
	}
}


text:
package net.lacolaco.smileessence.command.status;

import android.app.Activity;
import android.content.Intent;

import net.lacolaco.smileessence.R;
import net.lacolaco.smileessence.twitter.util.TwitterUtils;
import net.lacolaco.smileessence.util.IntentUtils;

import twitter4j.Status;

public class StatusCommandShare extends StatusCommand {

    // --------------------------- CONSTRUCTORS ---------------------------

    public StatusCommandShare(Activity activity, Status status) {
        super(R.id.key_command_status_share, activity, status);
    }

    // --------------------- GETTER / SETTER METHODS ---------------------

    @Override
    public String getText() {
        return getActivity().getString(R.string.command_status_share);
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    // -------------------------- OTHER METHODS --------------------------

    @Override
    public boolean execute() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, TwitterUtils.getStatusSummary(getOriginalStatus()));
        IntentUtils.startActivityIfFound(getActivity(), intent);
        return true;
    }
}


text:
// Headers
#include "lmt_reader.h"
#include "lmt_chunks.h"
#include "reader_struct.h"

// Read MapInfo.

#define LCF_CHUNK_SUFFIX LMT_Reader
#define LCF_CURRENT_STRUCT MapInfo

LCF_STRUCT_FIELDS_BEGIN()
	LCF_STRUCT_TYPED_FIELD(std::string, name),
	LCF_STRUCT_TYPED_FIELD(int32_t, parent_map),
	LCF_STRUCT_TYPED_FIELD(int32_t, indentation),
	LCF_STRUCT_TYPED_FIELD(int32_t, type),
	LCF_STRUCT_TYPED_FIELD(int32_t, scrollbar_x),
	LCF_STRUCT_TYPED_FIELD(int32_t, scrollbar_y),
	LCF_STRUCT_TYPED_FIELD(bool, expanded_node),
	LCF_STRUCT_TYPED_FIELD(int32_t, music_type),
	LCF_STRUCT_TYPED_FIELD(RPG::Music, music),
	LCF_STRUCT_TYPED_FIELD(int32_t, background_type),
	LCF_STRUCT_TYPED_FIELD(std::string, background_name),
	LCF_STRUCT_TYPED_FIELD(int32_t, teleport),
	LCF_STRUCT_TYPED_FIELD(int32_t, escape),
	LCF_STRUCT_TYPED_FIELD(int32_t, save),
	LCF_STRUCT_TYPED_FIELD(std::vector<RPG::Encounter>, encounters),
	LCF_STRUCT_TYPED_FIELD(int32_t, encounter_steps),
	LCF_STRUCT_TYPED_FIELD(RPG::Rect, area_rect),
LCF_STRUCT_FIELDS_END()

#undef LCF_CURRENT_STRUCT
#undef LCF_CHUNK_SUFFIX


text:
<?php
 defined('BASEPATH') OR exit('No direct script access allowed');

 class Newsphoto_model extends PIXOLO_Model
 {
 	public $_table = 'newsphotos';

 		 //Write functions here
 	public function getallimagesofnews($id)
	{
		$query=$this->db->query("SELECT `newsphotos`.`id` AS `photoid`,`newsphotos`.`photo` AS `photo` FROM `newsphotos`
			INNER JOIN `news`
			ON `newsphotos`.`newsid`=`news`.`id`
			WHERE `news`.`id`='$id' ")->result();

		return $query;
	}

 }

 ?>


text:
==========================
Concept Formation Examples
==========================

Cobweb Predict Mushroom Edibility (`source <cobweb_predict_mushroom.py>`_)::

    python -c "from concept_formation.examples.cobweb_predict_mushroom import run_demo; run_demo()"

Cobweb Cluster Mushroom Data (`source <cobweb_cluster_mushroom.py>`_)::

    python -c "from concept_formation.examples.cobweb_cluster_mushroom import run_demo; run_demo()"

Cobweb/3 Predict Iris Class (`source <cobweb3_predict_iris.py>`_)::

    python -c "from concept_formation.examples.cobweb3_predict_iris import run_demo; run_demo()"

Cobweb/3 Cluster Iris Data (`source <cobweb3_cluster_iris.py>`_)::

    python -c "from concept_formation.examples.cobweb3_cluster_iris import run_demo; run_demo()"

Trestle Predict RumbleBlocks Tower Success (`source <trestle_predict_rumbleblocks.py>`_)::

    python -c "from concept_formation.examples.trestle_predict_rumbleblocks import run_demo; run_demo()"

Cobweb/3 Cluster RumbleBlocks Tower Data (`source <trestle_cluster_rumbleblocks.py>`_)::

    python -c "from concept_formation.examples.trestle_cluster_rumbleblocks import run_demo; run_demo()"


text:
package org.newdawn.slick.openal;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;

import org.lwjgl.BufferUtils;
import org.lwjgl.Sys;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL10;
import org.lwjgl.openal.OpenALException;
import org.newdawn.slick.util.Log;
import org.newdawn.slick.util.ResourceLoader;

/**
 * Responsible for holding and playing the sounds used in the game.
 *
 * @author Kevin Glass
 * @author Rockstar setVolume cleanup
 */
public class SoundStore {

	/** The single instance of this class */
	private static SoundStore store = new SoundStore();

	/** True if sound effects are turned on */
	private boolean sounds;
	/** True if music is turned on */
	private boolean music;
	/** True if sound initialisation succeeded */
	private boolean soundWorks;
	/** The number of sound sources enabled - default 8 */
	private int sourceCount;
	/** The map of references to IDs of previously loaded sounds */
	private HashMap loaded = new HashMap();
	/** The ID of the buffer containing the music currently being played */
	private int currentMusic = -1;
	/** The OpenGL AL sound sources in use */
	private IntBuffer sources;
	/** The next source to be used for sound effects */
	private int nextSource;
	/** True if the sound system has been initialise */
	private boolean inited = false;
	/** The MODSound to be updated */
	private MODSound mod;
	/** The stream to be updated */
	private OpenALStreamPlayer stream;

	/** The global music volume setting */
	private float musicVolume = 1.0f;
	/** The global sound fx volume setting */
	private float soundVolume = 1.0f;
	/** The volume given for the last current music */
	private float lastCurrentMusicVolume = 1.0f;

	/** True if the music is paused */
	private boolean paused;
	/** True if we're returning deferred versions of resources */
	private boolean deferred;

	/** The buffer used to set the velocity of a source */
    private FloatBuffer sourceVel = BufferUtils.createFloatBuffer(3).put(new float[] { 0.0f, 0.0f, 0.0f });
    /** The buffer used to set the position of a source */
    private FloatBuffer sourcePos = BufferUtils.createFloatBuffer(3);

    /** The maximum number of sources */
    private int maxSources = 64;

	/**
	 * Create a new sound store
	 */
	private SoundStore() {
	}

	/**
	 * Deletes any sources and clears out the sound store contents
	 */
	public void clear() {
		if (sources!=null && AL.isCreated()) {
			for (int i=0;i<sourceCount;i++) {
				int src = sources.get(i);
				AL10.alSourcei(src, AL10.AL_BUFFER, 0);
				AL10.alSourceStop(src);
				AL10.alDeleteSources(src);
			}
		}
		store = new SoundStore();
	}

	/**
	 * Disable use of the Sound Store (must be called before init)
	 */
	public void disable() {
		inited = true;
	}

    /**
     * True if we should only record the request to load in the intention
     * of loading the sound later
     *
     * @param deferred True if the we should load a token
     */
    public void setDeferredLoading(boolean deferred) {
    	this.deferred = deferred;
    }

    /**
     * Check if we're using deferred loading
     *
     * @return True if we're loading deferred sounds
     */
    public boolean isDeferredLoading() {
    	return deferred;
    }

	/**
	 * Inidicate whether music should be playing
	 *
	 * @param music True if music should be played
	 */
	public void setMusicOn(boolean music) {
		if (soundWorks) {
			this.music = music;
			if (music) {
				restartLoop();
				setMusicVolume(musicVolume);
			} else {
				pauseLoop();
			}
		}
	}

	/**
	 * Check if music should currently be playing
	 *
	 * @return True if music is currently playing
	 */
	public boolean isMusicOn() {
		return music;
	}

	/**
	 * Set the music volume
	 *
	 * @param volume The volume for music
	 */
	public void setMusicVolume(float volume) {
		if (volume < 0) {
			volume = 0;
		}
		if (volume > 1) {
			volume = 1;
		}

		musicVolume = volume;
		if (soundWorks) {
			AL10.alSourcef(sources.get(0), AL10.AL_GAIN, lastCurrentMusicVolume * musicVolume);
		}
	}

	/**
	 * Get the volume scalar of the music that is currently playing.
	 *
	 * @return The volume of the music currently playing
	 */
	public float getCurrentMusicVolume() {
		return lastCurrentMusicVolume;
	}

	/**
	 * Set the music volume of the current playing music. Does NOT affect the global volume
	 *
	 * @param volume The volume for the current playing music
	 */
	public void setCurrentMusicVolume(float volume) {
		if (volume < 0) {
			volume = 0;
		}
		if (volume > 1) {
			volume = 1;
		}

		if (soundWorks) {
			lastCurrentMusicVolume = volume;
			AL10.alSourcef(sources.get(0), AL10.AL_GAIN, lastCurrentMusicVolume * musicVolume);
		}
	}

	/**
	 * Set the sound volume
	 *
	 * @param volume The volume for sound fx
	 */
	public void setSoundVolume(float volume) {
		if (volume < 0) {
			volume = 0;
		}
		soundVolume = volume;
	}

	/**
	 * Check if sound works at all
	 *
	 * @return True if sound works at all
	 */
	public boolean soundWorks() {
		return soundWorks;
	}

	/**
	 * Check if music is currently enabled
	 *
	 * @return True if music is currently enabled
	 */
	public boolean musicOn() {
		return music;
	}

	/**
	 * Get the volume for sounds
	 *
	 * @return The volume for sounds
	 */
	public float getSoundVolume() {
		return soundVolume;
	}

	/**
	 * Get the volume for music
	 *
	 * @return The volume for music
	 */
	public float getMusicVolume() {
		return musicVolume;
	}

	/**
	 * Get the ID of a given source
	 *
	 * @param index The ID of a given source
	 * @return The ID of the given source
	 */
	public int getSource(int index) {
		if (!soundWorks) {
			return -1;
		}
		if (index < 0) {
			return -1;
		}
		return sources.get(index);
	}

	/**
	 * Indicate whether sound effects should be played
	 *
	 * @param sounds True if sound effects should be played
	 */
	public void setSoundsOn(boolean sounds) {
		if (soundWorks) {
			this.sounds = sounds;
		}
	}

	/**
	 * Check if sound effects are currently enabled
	 *
	 * @return True if sound effects are currently enabled
	 */
	public boolean soundsOn() {
		return sounds;
	}

	/**
	 * Set the maximum number of concurrent sound effects that will be
	 * attempted
	 *
	 * @param max The maximum number of sound effects/music to mix
	 */
	public void setMaxSources(int max) {
		this.maxSources = max;
	}

	/**
	 * Initialise the sound effects stored. This must be called
	 * before anything else will work
	 */
	public void init() {
		if (inited) {
			return;
		}
		Log.info("Initialising sounds..");
		inited = true;

		AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
				try {
					AL.create();
					soundWorks = true;
					sounds = true;
					music = true;
					Log.info("- Sound works");
				} catch (Exception e) {
					Log.error("Sound initialisation failure.");
					Log.error(e);
					soundWorks = false;
					sounds = false;
					music = false;
				}

				return null;
            }});

		if (soundWorks) {
			sourceCount = 0;
			sources = BufferUtils.createIntBuffer(maxSources);
			while (AL10.alGetError() == AL10.AL_NO_ERROR) {
				IntBuffer temp = BufferUtils.createIntBuffer(1);

				try {
					AL10.alGenSources(temp);

					if (AL10.alGetError() == AL10.AL_NO_ERROR) {
						sourceCount++;
						sources.put(temp.get(0));
						if (sourceCount > maxSources-1) {
							break;
						}
					}
				} catch (OpenALException e) {
					// expected at the end
					break;
				}
			}
			Log.info("- "+sourceCount+" OpenAL source available");

			if (AL10.alGetError() != AL10.AL_NO_ERROR) {
				sounds = false;
				music = false;
				soundWorks = false;
				Log.error("- AL init failed");
			} else {
				FloatBuffer listenerOri = BufferUtils.createFloatBuffer(6).put(
						new float[] { 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f });
				FloatBuffer listenerVel = BufferUtils.createFloatBuffer(3).put(
						new float[] { 0.0f, 0.0f, 0.0f });
				FloatBuffer listenerPos = BufferUtils.createFloatBuffer(3).put(
						new float[] { 0.0f, 0.0f, 0.0f });
				listenerPos.flip();
				listenerVel.flip();
				listenerOri.flip();
				AL10.alListener(AL10.AL_POSITION, listenerPos);
				AL10.alListener(AL10.AL_VELOCITY, listenerVel);
				AL10.alListener(AL10.AL_ORIENTATION, listenerOri);

				Log.info("- Sounds source generated");
			}
		}
	}

	/**
	 * Stop a particular sound source
	 *
	 * @param index The index of the source to stop
	 */
	void stopSource(int index) {
		AL10.alSourceStop(sources.get(index));
	}

	/**
	 * Play the specified buffer as a sound effect with the specified
	 * pitch and gain.
	 *
	 * @param buffer The ID of the buffer to play
	 * @param pitch The pitch to play at
	 * @param gain The gain to play at
	 * @param loop True if the sound should loop
	 * @return source The source that will be used
	 */
	int playAsSound(int buffer,float pitch,float gain,boolean loop) {
		return playAsSoundAt(buffer, pitch, gain, loop, 0, 0, 0);
	}

	/**
	 * Play the specified buffer as a sound effect with the specified
	 * pitch and gain.
	 *
	 * @param buffer The ID of the buffer to play
	 * @param pitch The pitch to play at
	 * @param gain The gain to play at
	 * @param loop True if the sound should loop
	 * @param x The x position to play the sound from
	 * @param y The y position to play the sound from
	 * @param z The z position to play the sound from
	 * @return source The source that will be used
	 */
	int playAsSoundAt(int buffer,float pitch,float gain,boolean loop,float x, float y, float z) {
		gain *= soundVolume;
		if (gain == 0) {
			gain = 0.001f;
		}
		if (soundWorks) {
			if (sounds) {
				int nextSource = findFreeSource();
				if (nextSource == -1) {
					return -1;
				}

				AL10.alSourceStop(sources.get(nextSource));

				AL10.alSourcei(sources.get(nextSource), AL10.AL_BUFFER, buffer);
				AL10.alSourcef(sources.get(nextSource), AL10.AL_PITCH, pitch);
				AL10.alSourcef(sources.get(nextSource), AL10.AL_GAIN, gain);
			    AL10.alSourcei(sources.get(nextSource), AL10.AL_LOOPING, loop ? AL10.AL_TRUE : AL10.AL_FALSE);

			    sourcePos.clear();
			    sourceVel.clear();
				sourceVel.put(new float[] { 0, 0, 0 });
				sourcePos.put(new float[] { x, y, z });
			    sourcePos.flip();
			    sourceVel.flip();
			    AL10.alSource(sources.get(nextSource), AL10.AL_POSITION, sourcePos);
    			AL10.alSource(sources.get(nextSource), AL10.AL_VELOCITY, sourceVel);

				AL10.alSourcePlay(sources.get(nextSource));

				return nextSource;
			}
		}

		return -1;
	}
	/**
	 * Check if a particular source is playing
	 *
	 * @param index The index of the source to check
	 * @return True if the source is playing
	 */
	boolean isPlaying(int index) {
		int state = AL10.alGetSourcei(sources.get(index), AL10.AL_SOURCE_STATE);

		return (state == AL10.AL_PLAYING);
	}

	/**
	 * Check if a particle source is paused
	 * @param index the index of the source
	 * @return true if the source is playing
	 */
	boolean isPaused(int index) {
		int state = AL10.alGetSourcei(sources.get(index), AL10.AL_SOURCE_STATE);
		return (state == AL10.AL_PAUSED);
	}

	/**
	 * Find a free sound source
	 *
	 * @return The index of the free sound source
	 */
	private int findFreeSource() {
		for (int i=1;i<sourceCount;i++) {
			int state = AL10.alGetSourcei(sources.get(i), AL10.AL_SOURCE_STATE);

			if ((state != AL10.AL_PLAYING) && (state != AL10.AL_PAUSED)) {
				return i;
			}
		}

		return -1;
	}

	/**
	 * Play the specified buffer as music (i.e. use the music channel)
	 *
	 * @param buffer The buffer to be played
	 * @param pitch The pitch to play the music at
	 * @param gain The gaing to play the music at
	 * @param loop True if we should loop the music
	 */
	void playAsMusic(int buffer,float pitch,float gain, boolean loop) {
		paused = false;
		gain *= musicVolume;
		if (gain == 0) {
			gain = 0.001f;
		}

		setMOD(null);

		if (soundWorks) {
			if (currentMusic != -1) {
				AL10.alSourceStop(sources.get(0));
			}

			getMusicSource();

			AL10.alSourcef(sources.get(0), AL10.AL_GAIN, gain);
			AL10.alSourcei(sources.get(0), AL10.AL_BUFFER, buffer);
			AL10.alSourcef(sources.get(0), AL10.AL_PITCH, pitch);
		    AL10.alSourcei(sources.get(0), AL10.AL_LOOPING, loop ? AL10.AL_TRUE : AL10.AL_FALSE);

			currentMusic = sources.get(0);

			if (!music) {
				pauseLoop();
			} else {
				AL10.alSourcePlay(sources.get(0));
			}
		}
	}

	/**
	 * Get the OpenAL source used for music
	 *
	 * @return The open al source used for music
	 */
	private int getMusicSource() {
		return sources.get(0);
	}

	/**
	 * Set the pitch at which the current music is being played
	 *
	 * @param pitch The pitch at which the current music is being played
	 */
	public void setMusicPitch(float pitch) {
		if (soundWorks) {
			AL10.alSourcef(sources.get(0), AL10.AL_PITCH, pitch);
		}
	}

	/**
	 * Pause the music loop that is currently playing
	 */
	public void pauseLoop() {
		if ((soundWorks) && (currentMusic != -1)){
			paused = true;
			AL10.alSourcePause(currentMusic);
		}
	}

	/**
	 * Restart the music loop that is currently paused
	 */
	public void restartLoop() {
		if ((music) && (soundWorks) && (currentMusic != -1)){
			paused = false;
			AL10.alSourcePlay(currentMusic);
		}
	}

	/**
	 * Check if the supplied player is currently being polled by this
	 * sound store.
	 *
	 * @param player The player to check
	 * @return True if this player is currently in use by this sound store
	 */
	boolean isPlaying(OpenALStreamPlayer player) {
		return stream == player;
	}

	/**
	 * Get a MOD sound (mod/xm etc)
	 *
	 * @param ref The refernece to the mod to load
	 * @return The sound for play back
	 * @throws IOException Indicates a failure to read the data
	 */
	public Audio getMOD(String ref) throws IOException {
		return getMOD(ref, ResourceLoader.getResourceAsStream(ref));
	}

	/**
	 * Get a MOD sound (mod/xm etc)
	 *
	 * @param in The stream to the MOD to load
	 * @return The sound for play back
	 * @throws IOException Indicates a failure to read the data
	 */
	public Audio getMOD(InputStream in) throws IOException {
		return getMOD(in.toString(), in);
	}

	/**
	 * Get a MOD sound (mod/xm etc)
	 *
	 * @param ref The stream to the MOD to load
	 * @param in The stream to the MOD to load
	 * @return The sound for play back
	 * @throws IOException Indicates a failure to read the data
	 */
	public Audio getMOD(String ref, InputStream in) throws IOException {
		if (!soundWorks) {
			return new NullAudio();
		}
		if (!inited) {
			throw new RuntimeException("Can't load sounds until SoundStore is init(). Use the container init() method.");
		}
		if (deferred) {
			return new DeferredSound(ref, in, DeferredSound.MOD);
		}

		return new MODSound(this, in);
	}

	/**
	 * Get the Sound based on a specified AIF file
	 *
	 * @param ref The reference to the AIF file in the classpath
	 * @return The Sound read from the AIF file
	 * @throws IOException Indicates a failure to load the AIF
	 */
	public Audio getAIF(String ref) throws IOException {
		return getAIF(ref, ResourceLoader.getResourceAsStream(ref));
	}

	/**
	 * Get the Sound based on a specified AIF file
	 *
	 * @param in The stream to the MOD to load
	 * @return The Sound read from the AIF file
	 * @throws IOException Indicates a failure to load the AIF
	 */
	public Audio getAIF(InputStream in) throws IOException {
		return getAIF(in.toString(), in);
	}

	/**
	 * Get the Sound based on a specified AIF file
	 *
	 * @param ref The reference to the AIF file in the classpath
	 * @param in The stream to the AIF to load
	 * @return The Sound read from the AIF file
	 * @throws IOException Indicates a failure to load the AIF
	 */
	public Audio getAIF(String ref, InputStream in) throws IOException {
		in = new BufferedInputStream(in);

		if (!soundWorks) {
			return new NullAudio();
		}
		if (!inited) {
			throw new RuntimeException("Can't load sounds until SoundStore is init(). Use the container init() method.");
		}
		if (deferred) {
			return new DeferredSound(ref, in, DeferredSound.AIF);
		}

		int buffer = -1;

		if (loaded.get(ref) != null) {
			buffer = ((Integer) loaded.get(ref)).intValue();
		} else {
			try {
				IntBuffer buf = BufferUtils.createIntBuffer(1);

				AiffData data = AiffData.create(in);
				AL10.alGenBuffers(buf);
				AL10.alBufferData(buf.get(0), data.format, data.data, data.samplerate);

				loaded.put(ref,new Integer(buf.get(0)));
				buffer = buf.get(0);
			} catch (Exception e) {
				Log.error(e);
				IOException x = new IOException("Failed to load: "+ref);
				x.initCause(e);

				throw x;
			}
		}

		if (buffer == -1) {
			throw new IOException("Unable to load: "+ref);
		}

		return new AudioImpl(this, buffer);
	}

	/**
	 * Get the Sound based on a specified WAV file
	 *
	 * @param ref The reference to the WAV file in the classpath
	 * @return The Sound read from the WAV file
	 * @throws IOException Indicates a failure to load the WAV
	 */
	public Audio getWAV(String ref) throws IOException {
		return getWAV(ref, ResourceLoader.getResourceAsStream(ref));
	}

	/**
	 * Get the Sound based on a specified WAV file
	 *
	 * @param in The stream to the WAV to load
	 * @return The Sound read from the WAV file
	 * @throws IOException Indicates a failure to load the WAV
	 */
	public Audio getWAV(InputStream in) throws IOException {
		return getWAV(in.toString(), in);
	}

	/**
	 * Get the Sound based on a specified WAV file
	 *
	 * @param ref The reference to the WAV file in the classpath
	 * @param in The stream to the WAV to load
	 * @return The Sound read from the WAV file
	 * @throws IOException Indicates a failure to load the WAV
	 */
	public Audio getWAV(String ref, InputStream in) throws IOException {
		if (!soundWorks) {
			return new NullAudio();
		}
		if (!inited) {
			throw new RuntimeException("Can't load sounds until SoundStore is init(). Use the container init() method.");
		}
		if (deferred) {
			return new DeferredSound(ref, in, DeferredSound.WAV);
		}

		int buffer = -1;

		if (loaded.get(ref) != null) {
			buffer = ((Integer) loaded.get(ref)).intValue();
		} else {
			try {
				IntBuffer buf = BufferUtils.createIntBuffer(1);

				WaveData data = WaveData.create(in);
				AL10.alGenBuffers(buf);
				AL10.alBufferData(buf.get(0), data.format, data.data, data.samplerate);

				loaded.put(ref,new Integer(buf.get(0)));
				buffer = buf.get(0);
			} catch (Exception e) {
				Log.error(e);
				IOException x = new IOException("Failed to load: "+ref);
				x.initCause(e);

				throw x;
			}
		}

		if (buffer == -1) {
			throw new IOException("Unable to load: "+ref);
		}

		return new AudioImpl(this, buffer);
	}

	/**
	 * Get the Sound based on a specified OGG file
	 *
	 * @param ref The reference to the OGG file in the classpath
	 * @return The Sound read from the OGG file
	 * @throws IOException Indicates a failure to load the OGG
	 */
	public Audio getOggStream(String ref) throws IOException {
		if (!soundWorks) {
			return new NullAudio();
		}

		setMOD(null);
		setStream(null);

		if (currentMusic != -1) {
			AL10.alSourceStop(sources.get(0));
		}

		getMusicSource();
		currentMusic = sources.get(0);

		return new StreamSound(new OpenALStreamPlayer(currentMusic, ref));
	}

	/**
	 * Get the Sound based on a specified OGG file
	 *
	 * @param ref The reference to the OGG file in the classpath
	 * @return The Sound read from the OGG file
	 * @throws IOException Indicates a failure to load the OGG
	 */
	public Audio getOggStream(URL ref) throws IOException {
		if (!soundWorks) {
			return new NullAudio();
		}

		setMOD(null);
		setStream(null);

		if (currentMusic != -1) {
			AL10.alSourceStop(sources.get(0));
		}

		getMusicSource();
		currentMusic = sources.get(0);

		return new StreamSound(new OpenALStreamPlayer(currentMusic, ref));
	}

	/**
	 * Get the Sound based on a specified OGG file
	 *
	 * @param ref The reference to the OGG file in the classpath
	 * @return The Sound read from the OGG file
	 * @throws IOException Indicates a failure to load the OGG
	 */
	public Audio getOgg(String ref) throws IOException {
		return getOgg(ref, ResourceLoader.getResourceAsStream(ref));
	}

	/**
	 * Get the Sound based on a specified OGG file
	 *
	 * @param in The stream to the OGG to load
	 * @return The Sound read from the OGG file
	 * @throws IOException Indicates a failure to load the OGG
	 */
	public Audio getOgg(InputStream in) throws IOException {
		return getOgg(in.toString(), in);
	}

	/**
	 * Get the Sound based on a specified OGG file
	 *
	 * @param ref The reference to the OGG file in the classpath
	 * @param in The stream to the OGG to load
	 * @return The Sound read from the OGG file
	 * @throws IOException Indicates a failure to load the OGG
	 */
	public Audio getOgg(String ref, InputStream in) throws IOException {
		if (!soundWorks) {
			return new NullAudio();
		}
		if (!inited) {
			throw new RuntimeException("Can't load sounds until SoundStore is init(). Use the container init() method.");
		}
		if (deferred) {
			return new DeferredSound(ref, in, DeferredSound.OGG);
		}

		int buffer = -1;

		if (loaded.get(ref) != null) {
			buffer = ((Integer) loaded.get(ref)).intValue();
		} else {
			try {
				IntBuffer buf = BufferUtils.createIntBuffer(1);

				OggDecoder decoder = new OggDecoder();
				OggData ogg = decoder.getData(in);

				AL10.alGenBuffers(buf);
				AL10.alBufferData(buf.get(0), ogg.channels > 1 ? AL10.AL_FORMAT_STEREO16 : AL10.AL_FORMAT_MONO16, ogg.data, ogg.rate);

				loaded.put(ref,new Integer(buf.get(0)));

				buffer = buf.get(0);
			} catch (Exception e) {
				Log.error(e);
				Sys.alert("Error","Failed to load: "+ref+" - "+e.getMessage());
				throw new IOException("Unable to load: "+ref);
			}
		}

		if (buffer == -1) {
			throw new IOException("Unable to load: "+ref);
		}

		return new AudioImpl(this, buffer);
	}

	/**
	 * Set the mod thats being streamed if any
	 *
	 * @param sound The mod being streamed
	 */
	void setMOD(MODSound sound) {
		if (!soundWorks) {
			return;
		}

		currentMusic = sources.get(0);
		stopSource(0);

		this.mod = sound;
		if (sound != null) {
			this.stream = null;
		}
		paused = false;
	}

	/**
	 * Set the stream being played
	 *
	 * @param stream The stream being streamed
	 */
	void setStream(OpenALStreamPlayer stream) {
		if (!soundWorks) {
			return;
		}

		currentMusic = sources.get(0);
		this.stream = stream;
		if (stream != null) {
			this.mod = null;
		}
		paused = false;
	}

	/**
	 * Poll the streaming system
	 *
	 * @param delta The amount of time passed since last poll (in milliseconds)
	 */
	public void poll(int delta) {
		if (!soundWorks) {
			return;
		}
		if (paused) {
			return;
		}

		if (music) {
			if (mod != null) {
				try {
					mod.poll();
				} catch (OpenALException e) {
					Log.error("Error with OpenGL MOD Player on this this platform");
					Log.error(e);
					mod = null;
				}
			}
			if (stream != null) {
				try {
					stream.update();
				} catch (OpenALException e) {
					Log.error("Error with OpenGL Streaming Player on this this platform");
					Log.error(e);
					mod = null;
				}
			}
		}
	}

	/**
	 * Check if the music is currently playing
	 *
	 * @return True if the music is playing
	 */
	public boolean isMusicPlaying()
	{
		if (!soundWorks) {
			return false;
		}

		int state = AL10.alGetSourcei(sources.get(0), AL10.AL_SOURCE_STATE);
		return ((state == AL10.AL_PLAYING) || (state == AL10.AL_PAUSED));
	}

	/**
	 * Get the single instance of this class
	 *
	 * @return The single instnace of this class
	 */
	public static SoundStore get() {
		return store;
	}

	/**
	 * Stop a playing sound identified by the ID returned from playing. This utility method
	 * should only be used when needing to stop sound effects that may have been played
	 * more than once and need to be explicitly stopped.
	 *
	 * @param id The ID of the underlying OpenAL source as returned from playAsSoundEffect
	 */
	public void stopSoundEffect(int id) {
		AL10.alSourceStop(id);
	}

	/**
	 * Retrieve the number of OpenAL sound sources that have been
	 * determined at initialisation.
	 *
	 * @return The number of sources available
	 */
	public int getSourceCount() {
		return sourceCount;
	}
}


text:
"""Contains a model definition for AlexNet.

This work was first described in:
  ImageNet Classification with Deep Convolutional Neural Networks
  Alex Krizhevsky, Ilya Sutskever and Geoffrey E. Hinton

and later refined in:
  One weird trick for parallelizing convolutional neural networks
  Alex Krizhevsky, 2014

Here we provide the implementation proposed in "One weird trick" and not
"ImageNet Classification", as per the paper, the LRN layers have been removed.

Usage:
  with slim.arg_scope(alexnet.alexnet_v2_arg_scope()):
    outputs, end_points = alexnet.alexnet_v2(inputs)

@@alexnet_v2
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

slim = tf.contrib.slim
trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev)

def alexnet_v2_arg_scope(weight_decay=0.0005):
  with slim.arg_scope([slim.conv2d, slim.fully_connected],
                      activation_fn=tf.nn.relu,
                      biases_initializer=tf.constant_initializer(0.1),
                      weights_regularizer=slim.l2_regularizer(weight_decay)):
    with slim.arg_scope([slim.conv2d], padding='SAME'):
      with slim.arg_scope([slim.max_pool2d], padding='VALID') as arg_sc:
        return arg_sc

def alexnet_v2(inputs,
               num_classes=1000,
               is_training=True,
               dropout_keep_prob=0.5,
               spatial_squeeze=True,
               scope='alexnet_v2'):
  """AlexNet version 2.

  Described in: http://arxiv.org/pdf/1404.5997v2.pdf
  Parameters from:
  github.com/akrizhevsky/cuda-convnet2/blob/master/layers/
  layers-imagenet-1gpu.cfg

  Note: All the fully_connected layers have been transformed to conv2d layers.
        To use in classification mode, resize input to 224x224. To use in fully
        convolutional mode, set spatial_squeeze to false.
        The LRN layers have been removed and change the initializers from
        random_normal_initializer to xavier_initializer.

  Args:
    inputs: a tensor of size [batch_size, height, width, channels].
    num_classes: number of predicted classes.
    is_training: whether or not the model is being trained.
    dropout_keep_prob: the probability that activations are kept in the dropout
      layers during training.
    spatial_squeeze: whether or not should squeeze the spatial dimensions of the
      outputs. Useful to remove unnecessary dimensions for classification.
    scope: Optional scope for the variables.

  Returns:
    the last op containing the log predictions and end_points dict.
  """
  with tf.variable_scope(scope, 'alexnet_v2', [inputs]) as sc:
    end_points_collection = sc.original_name_scope + '_end_points'
    # Collect outputs for conv2d, fully_connected and max_pool2d.
    with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d],
                        outputs_collections=[end_points_collection]):
      net = slim.conv2d(inputs, 64, [11, 11], 4, padding='VALID',
                        scope='conv1')
      net = slim.max_pool2d(net, [3, 3], 2, scope='pool1')
      net = slim.conv2d(net, 192, [5, 5], scope='conv2')
      net = slim.max_pool2d(net, [3, 3], 2, scope='pool2')
      net = slim.conv2d(net, 384, [3, 3], scope='conv3')
      net = slim.conv2d(net, 384, [3, 3], scope='conv4')
      net = slim.conv2d(net, 256, [3, 3], scope='conv5')
      net = slim.max_pool2d(net, [3, 3], 2, scope='pool5')

      # Use conv2d instead of fully_connected layers.
      with slim.arg_scope([slim.conv2d],
                          weights_initializer=trunc_normal(0.005),
                          biases_initializer=tf.constant_initializer(0.1)):
        net = slim.conv2d(net, 4096, [5, 5], padding='VALID',
                          scope='fc6')
        net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
                           scope='dropout6')
        net = slim.conv2d(net, 4096, [1, 1], scope='fc7')
        net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
                           scope='dropout7')
        net = slim.conv2d(net, num_classes, [1, 1],
                          activation_fn=None,
                          normalizer_fn=None,
                          biases_initializer=tf.zeros_initializer,
                          scope='fc8')

      # Convert end_points_collection into a end_point dict.
      end_points = slim.utils.convert_collection_to_dict(end_points_collection)
      if spatial_squeeze:
        net = tf.squeeze(net, [1, 2], name='fc8/squeezed')
        end_points[sc.name + '/fc8'] = net
      return net, end_points
alexnet_v2.default_image_size = 224


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

#include "chrome/browser/new_tab_page/modules/photos/photos_service.h"

#include <memory>
#include <utility>

#include "base/hash/hash.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "chrome/browser/ui/hats/hats_service.h"
#include "chrome/browser/ui/hats/hats_service_factory.h"
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/search/ntp_features.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h"
#include "components/signin/public/identity_manager/scope_set.h"
#include "components/variations/net/variations_http_headers.h"
#include "content/public/browser/web_contents.h"
#include "google_apis/gaia/gaia_constants.h"
#include "net/base/load_flags.h"
#include "services/network/public/cpp/resource_request.h"
#include "ui/base/l10n/l10n_util.h"

namespace {
// Maximum accepted size of an API response. 1MB.
constexpr int kMaxResponseSize = 1024 * 1024;
const int kMaxPersonalizedMessageLength = 20;
const char server_url[] =
    "https://photosfirstparty-pa.googleapis.com/v1/ntp/memories:read";
constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation =
    net::DefineNetworkTrafficAnnotation("photos_service", R"(
      semantics {
        sender: "Photos Service"
        description:
          "The Photos Service requests Memories from "
          "the Google Photos API. The response will be displayed in NTP's "
          "Photos Module."
        trigger:
          "Each time a user navigates to the NTP while "
          "the Photos module is enabled and the user is "
          "signed in."
        data:
          "OAuth2 access token."
        destination: GOOGLE_OWNED_SERVICE
      }
      policy {
        cookies_allowed: NO
        setting:
          "Users can control this feature by (1) selecting "
          "a non-Google default search engine in Chrome "
          "settings under 'Search Engine', (2) signing out, "
          "or (3) disabling the Drive module."
        chrome_policy {
          DefaultSearchProviderEnabled {
            policy_options {mode: MANDATORY}
            DefaultSearchProviderEnabled: false
          }
          BrowserSignin {
            policy_options {mode: MANDATORY}
            BrowserSignin: 0
          }
          NTPCardsVisible {
            NTPCardsVisible: false
          }
        }
      })");
constexpr char kMemoryTemplate[] = R"(
  {
    "memoryMediaKey": "key%d",
    "title": {
      "header": "%d years ago",
      "subheader": ""
    },
    "coverMediaKey": "coverKey%d",
    "coverDatUrl": "https://lh3.googleusercontent.com/proxy/CyeQrfWvSkJ-4wjGmm1zVIP4XZKL4oAjywWcPh8lhrwtizOY4kGsDtVa3nk984qJB5q2-r7aInfG25UFjfwyu7QEraqepTlbsDdKX1yeenhh7EGeAR2Hp1QcbO24C7WyU8bLPx8o_2HA-opm6cqZ8f4ehEXCxMEbR79A44jcWpacTLfYERPGeVrljo2vAl2LyFMHrA"
  })";
}  // namespace

// static
const char PhotosService::kLastDismissedTimePrefName[] =
    "NewTabPage.Photos.LastDimissedTime";
const char PhotosService::kOptInAcknowledgedPrefName[] =
    "NewTabPage.Photos.OptInAcknowledged";
const char PhotosService::kLastMemoryOpenTimePrefName[] =
    "NewTabPage.Photos.LastMemoryOpenTime";
const char PhotosService::kSoftOptOutCountPrefName[] =
    "NewTabPage.Photos.SoftOptOutCount";
const char PhotosService::kLastSoftOptedOutTimePrefName[] =
    "NewTabPage.Photos.LastSoftOptedoutTime";

// static
const base::TimeDelta PhotosService::kDismissDuration = base::Days(1);
const base::TimeDelta PhotosService::kSoftOptOutDuration = base::Days(2);
const int PhotosService::kMaxSoftOptOuts = 1;
const char kRecentHighlightsTitle[] = "recent highlights";
const char kNYearsAgoSubstring[] = "years ago";

PhotosService::PhotosService(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    signin::IdentityManager* identity_manager,
    PrefService* pref_service)
    : url_loader_factory_(std::move(url_loader_factory)),
      identity_manager_(identity_manager),
      pref_service_(pref_service) {
  identity_manager_->AddObserver(this);
}

PhotosService::~PhotosService() {
  identity_manager_->RemoveObserver(this);
}

// static
void PhotosService::RegisterProfilePrefs(PrefRegistrySimple* registry) {
  registry->RegisterTimePref(kLastDismissedTimePrefName, base::Time());
  registry->RegisterBooleanPref(kOptInAcknowledgedPrefName, false);
  registry->RegisterTimePref(kLastMemoryOpenTimePrefName, base::Time());
  registry->RegisterTimePref(kLastSoftOptedOutTimePrefName, base::Time());
  registry->RegisterIntegerPref(kSoftOptOutCountPrefName, 0);
}

void PhotosService::OnPrimaryAccountChanged(
    const signin::PrimaryAccountChangeEvent& event) {
  // If the primary account has changed, clear opt-in pref.
  if (event.GetCurrentState().primary_account !=
          event.GetPreviousState().primary_account &&
      pref_service_->HasPrefPath(kOptInAcknowledgedPrefName)) {
    pref_service_->ClearPref(kOptInAcknowledgedPrefName);
  }
}

void PhotosService::GetMemories(GetMemoriesCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  callbacks_.push_back(std::move(callback));
  if (callbacks_.size() > 1) {
    return;
  }

  // Bail if module is still dismissed or user soft opted out.
  if (IsModuleSoftOptedOut() ||
      (!base::FeatureList::IsEnabled(ntp_features::kNtpModulesRedesigned) &&
       !pref_service_->GetTime(kLastDismissedTimePrefName).is_null() &&
       base::Time::Now() - pref_service_->GetTime(kLastDismissedTimePrefName) <
           kDismissDuration)) {
    for (auto& callback : callbacks_) {
      std::move(callback).Run(std::vector<photos::mojom::MemoryPtr>());
    }
    callbacks_.clear();
    return;
  }

  // Skip fetch and jump straight to data parsing when serving fake data.
  std::string fake_data_choice = base::GetFieldTrialParamValueByFeature(
      ntp_features::kNtpPhotosModule, ntp_features::kNtpPhotosModuleDataParam);
  if (fake_data_choice != "") {
    std::string fake_response = "{\"memory\": [";
    int num_memory;
    base::StringToInt(fake_data_choice, &num_memory);
    for (int i = 0; i < num_memory; i++) {
      std::string memory = base::StringPrintf(kMemoryTemplate, i, i + 2, i);
      if (i + 1 < num_memory) {
        memory += ", ";
      }
      fake_response += memory;
    }
    fake_response += "]}";

    data_decoder::DataDecoder::ParseJsonIsolated(
        fake_response, base::BindOnce(&PhotosService::OnJsonParsed,
                                      weak_factory_.GetWeakPtr(), ""));
    return;
  }

  signin::ScopeSet scopes;
  scopes.insert(GaiaConstants::kPhotosModuleOAuth2Scope);
  scopes.insert(GaiaConstants::kPhotosModuleImageOAuth2Scope);
  token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>(
      "ntp_photos_module", identity_manager_, scopes,
      base::BindOnce(&PhotosService::OnTokenReceived,
                     weak_factory_.GetWeakPtr()),
      signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate,
      signin::ConsentLevel::kSignin);
}

void PhotosService::DismissModule() {
  pref_service_->SetTime(kLastDismissedTimePrefName, base::Time::Now());
}

void PhotosService::RestoreModule() {
  pref_service_->SetTime(kLastDismissedTimePrefName, base::Time());
  if (base::FeatureList::IsEnabled(ntp_features::kNtpPhotosModuleSoftOptOut)) {
    pref_service_->SetTime(kLastSoftOptedOutTimePrefName, base::Time());
    pref_service_->SetInteger(
        kSoftOptOutCountPrefName,
        pref_service_->GetInteger(kSoftOptOutCountPrefName) - 1);
  }
}

bool PhotosService::IsModuleSoftOptedOut() {
  return base::FeatureList::IsEnabled(
             ntp_features::kNtpPhotosModuleSoftOptOut) &&
         !pref_service_->GetTime(kLastSoftOptedOutTimePrefName).is_null() &&
         base::Time::Now() -
                 pref_service_->GetTime(kLastSoftOptedOutTimePrefName) <
             kSoftOptOutDuration;
}

bool PhotosService::ShouldShowOptInScreen() {
  return !pref_service_->GetBoolean(kOptInAcknowledgedPrefName);
}

bool PhotosService::ShouldShowSoftOptOutButton() {
  return base::FeatureList::IsEnabled(
             ntp_features::kNtpPhotosModuleSoftOptOut) &&
         pref_service_->GetInteger(kSoftOptOutCountPrefName) < kMaxSoftOptOuts;
}

void PhotosService::SoftOptOut() {
  pref_service_->SetTime(kLastSoftOptedOutTimePrefName, base::Time::Now());
  pref_service_->SetInteger(
      kSoftOptOutCountPrefName,
      pref_service_->GetInteger(kSoftOptOutCountPrefName) + 1);
}

void PhotosService::OnUserOptIn(bool accept,
                                content::WebContents* web_contents,
                                Profile* profile) {
  pref_service_->SetBoolean(kOptInAcknowledgedPrefName, accept);

  // Trigger a HaTS survey when user opts-out.
  if (!accept && web_contents && profile) {
    HatsService* hats_service = HatsServiceFactory::GetForProfile(
        profile, /*create_if_necessary=*/true);
    CHECK(hats_service);
    hats_service->LaunchDelayedSurveyForWebContents(
        kHatsSurveyTriggerNtpPhotosModuleOptOut, web_contents, 0);
  }
}

void PhotosService::OnMemoryOpen() {
  pref_service_->SetTime(kLastMemoryOpenTimePrefName, base::Time::Now());
}

std::string PhotosService::GetOptInTitleText(
    std::vector<photos::mojom::MemoryPtr> memories) {
  std::string customTitleChoiceString = base::GetFieldTrialParamValueByFeature(
      ntp_features::kNtpPhotosModuleCustomizedOptInTitle,
      ntp_features::kNtpPhotosModuleOptInTitleParam);
  int customTitle = -1;

  if (customTitleChoiceString != "") {
    base::StringToInt(customTitleChoiceString, &customTitle);
  }

  if (customTitle == static_cast<int>(OptInCardTitle::kOptInRHTitle)) {
    return l10n_util::GetStringUTF8(
        IDS_NTP_MODULES_PHOTOS_MEMORIES_RH_WELCOME_TITLE);
  }

  if (customTitle == static_cast<int>(OptInCardTitle::kOptInFavoritesTitle)) {
    return l10n_util::GetStringUTF8(
        IDS_NTP_MODULES_PHOTOS_MEMORIES_FAVORITE_PEOPLE_WELCOME_TITLE);
  }

  if (customTitle == static_cast<int>(OptInCardTitle::kOptInpersonalizedTitle)) {
    return ConstructPersonalizedString(std::move(memories));
  }

  if (customTitle == static_cast<int>(OptInCardTitle::kOptInTripsTitle)) {
    return l10n_util::GetStringUTF8(
        IDS_NTP_MODULES_PHOTOS_MEMORIES_TRIPS_WELCOME_TITLE);
  }

  return l10n_util::GetStringUTF8(
      IDS_NTP_MODULES_PHOTOS_MEMORIES_WELCOME_TITLE);
}

std::string PhotosService::ConstructPersonalizedString(
    std::vector<photos::mojom::MemoryPtr> memories) {
  std::string personalizedTitle;
  bool recentHighlightsPresent = false;
  for (photos::mojom::MemoryPtr& memory : memories) {
    // TODO(crbug/1297769): Fetch memory type from BE to filter RH and NYA
    // memories. Ignore the recent highlights memory but mark
    // recentHighlightsPresent to true.
    if (base::EqualsCaseInsensitiveASCII(memory->title,
                                         kRecentHighlightsTitle)) {
      recentHighlightsPresent = true;
      continue;
    }

    // Memory is a suitable candidate if the memory is not "N Years Ago" memory
    // and its length is < 20.
    // TODO(crbug/1297769): Fetch memory type from BE to filter RH and NYA
    // memories.
    if (!base::EndsWith(memory->title, kNYearsAgoSubstring,
                        base::CompareCase::INSENSITIVE_ASCII) &&
        memory->title.length() <= kMaxPersonalizedMessageLength) {
      personalizedTitle = memory->title;
      break;
    }
  }

  // If no suitable memory is found return default title or title emphasizing
  // recent highlights depending on the presence of Recent Highlights memory.
  if (personalizedTitle.empty()) {
    return recentHighlightsPresent
               ? l10n_util::GetStringUTF8(
                     IDS_NTP_MODULES_PHOTOS_MEMORIES_RH_WELCOME_TITLE)
               : l10n_util::GetStringUTF8(
                     IDS_NTP_MODULES_PHOTOS_MEMORIES_WELCOME_TITLE);
  }

  return l10n_util::GetStringFUTF8(
      IDS_NTP_MODULES_PHOTOS_MEMORIES_PERSONALIZED_WELCOME_TITLE_TEMPLATE,
      base::ASCIIToUTF16(personalizedTitle));
}

void PhotosService::OnTokenReceived(GoogleServiceAuthError error,
                                    signin::AccessTokenInfo token_info) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  token_fetcher_.reset();
  if (error.state() != GoogleServiceAuthError::NONE) {
    for (auto& callback : callbacks_) {
      std::move(callback).Run(std::vector<photos::mojom::MemoryPtr>());
    }
    callbacks_.clear();
    return;
  }

  std::string cache_bust_param = "";
  if (!pref_service_->GetTime(kLastMemoryOpenTimePrefName).is_null()) {
    cache_bust_param =
        "?lastViewed=" +
        base::NumberToString(
            pref_service_->GetTime(kLastMemoryOpenTimePrefName).ToTimeT());
  }

  auto resource_request = std::make_unique<network::ResourceRequest>();
  resource_request->method = "GET";
  resource_request->url = GURL(server_url + cache_bust_param);
  // Cookies should not be allowed.
  resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  resource_request->headers.SetHeader(net::HttpRequestHeaders::kContentType,
                                      "application/json");
  resource_request->headers.SetHeader(net::HttpRequestHeaders::kAuthorization,
                                      "Bearer " + token_info.token);
  variations::AppendVariationsHeaderUnknownSignedIn(
      resource_request->url,
      /* Modules are only shown in non-incognito. */
      variations::InIncognito::kNo, resource_request.get());

  if (url_loader_) {
    return;
  }
  url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
                                                 kTrafficAnnotation);
  url_loader_->SetRetryOptions(0, network::SimpleURLLoader::RETRY_NEVER);
  url_loader_->DownloadToString(
      url_loader_factory_.get(),
      base::BindOnce(&PhotosService::OnJsonReceived, weak_factory_.GetWeakPtr(),
                     token_info.token),
      kMaxResponseSize);
}

void PhotosService::OnJsonReceived(
    const std::string& token,
    const std::unique_ptr<std::string> response_body) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  const int net_error = url_loader_->NetError();
  bool loaded_from_cache = url_loader_->LoadedFromCache();
  url_loader_.reset();

  if (!loaded_from_cache) {
    base::UmaHistogramSparse("NewTabPage.Modules.DataRequest",
                             base::PersistentHash("photos"));
  }

  if (net_error != net::OK || !response_body) {
    base::UmaHistogramEnumeration("NewTabPage.Photos.DataRequest",
                                  RequestResult::kError);
    for (auto& callback : callbacks_) {
      std::move(callback).Run(std::vector<photos::mojom::MemoryPtr>());
    }
    callbacks_.clear();
    return;
  }

  if (loaded_from_cache) {
    base::UmaHistogramEnumeration("NewTabPage.Photos.DataRequest",
                                  RequestResult::kCached);
  } else {
    base::UmaHistogramEnumeration("NewTabPage.Photos.DataRequest",
                                  RequestResult::kSuccess);
  }

  data_decoder::DataDecoder::ParseJsonIsolated(
      *response_body, base::BindOnce(&PhotosService::OnJsonParsed,
                                     weak_factory_.GetWeakPtr(), token));
}

void PhotosService::OnJsonParsed(
    const std::string& token,
    data_decoder::DataDecoder::ValueOrError result) {
  if (!result.value) {
    for (auto& callback : callbacks_) {
      std::move(callback).Run(std::vector<photos::mojom::MemoryPtr>());
    }
    callbacks_.clear();
    return;
  }

  auto* memories = result.value->FindListPath("memory");
  if (!memories) {
    base::UmaHistogramCustomCounts("NewTabPage.Photos.DataResponseCount", 0, 0,
                                   10, 11);
    for (auto& callback : callbacks_) {
      std::move(callback).Run(std::vector<photos::mojom::MemoryPtr>());
    }
    callbacks_.clear();
    return;
  }
  std::vector<photos::mojom::MemoryPtr> memory_list;

  base::UmaHistogramCustomCounts("NewTabPage.Photos.DataResponseCount",
                                 memories->GetListDeprecated().size(), 0, 10,
                                 11);
  for (const auto& memory : memories->GetListDeprecated()) {
    auto* title = memory.FindStringPath("title.header");
    auto* memory_id = memory.FindStringPath("memoryMediaKey");
    auto* cover_id = memory.FindStringPath("coverMediaKey");
    auto* cover_url = memory.FindStringPath("coverUrl");
    auto* cover_dat_url = memory.FindStringPath("coverDatUrl");
    if (!title || !memory_id || !cover_id || (!cover_url && !cover_dat_url)) {
      continue;
    }
    auto mojo_memory = photos::mojom::Memory::New();
    mojo_memory->id = *memory_id;
    mojo_memory->title = *title;
    mojo_memory->item_url =
        GURL("https://photos.google.com/memory/featured/" + *memory_id +
             "/photo/" + *cover_id + "?referrer=CHROME_NTP");
    if (cover_url) {
      mojo_memory->cover_url = GURL(*cover_url + "?access_token=" + token);
    } else if (cover_dat_url) {
      mojo_memory->cover_url = GURL(*cover_dat_url);
    }

    memory_list.push_back(std::move(mojo_memory));
  }

  for (auto& callback : callbacks_) {
    std::move(callback).Run(mojo::Clone(memory_list));
  }
  callbacks_.clear();
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Linnaea 43:323. 1882

#### Original name
null

### Remarks
null


text:
package org.apache.geode.internal.cache;

import org.apache.geode.internal.cache.lru.LRUEntry;

/**
 * Abstract implementation class of RegionEntry interface. This adds LRU support behaviour
 *
 * @since GemFire 3.5.1
 *
 *
 */
public abstract class AbstractLRURegionEntry extends AbstractRegionEntry implements LRUEntry {
  protected AbstractLRURegionEntry(RegionEntryContext context, Object value) {
    super(context, value);
  }

  /////////////////////////////////////////////////////////////////////
  ////////////////////////// instance methods /////////////////////////
  /////////////////////////////////////////////////////////////////////

  // Do not add any instance fields to this class.
  // Instead add them to the LRU section of LeafRegionEntry.cpp.
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/BeeFrameworkExample.iml" filepath="$PROJECT_DIR$/BeeFrameworkExample.iml" />
    </modules>
  </component>
</project>


text:
<?php

namespace Addons\Controller;

//hook
class BaseController{

    public function __construct(){
    }

    public function doIndex()
    {
        view();
    }

}


text:
"""TODO(tsitsulin): add headers, tests, and improve style."""
import os

from absl import app
from absl import flags
from sklearn.metrics import normalized_mutual_info_score
import tensorflow.compat.v2 as tf

from graph_embedding.dmon.models.gcn_modularity import gcn_modularity
from graph_embedding.dmon.utilities.graph import load_kipf_data
from graph_embedding.dmon.utilities.graph import load_npz_to_sparse_graph
from graph_embedding.dmon.utilities.graph import normalize_graph
from graph_embedding.dmon.utilities.graph import scipy_to_tf
from graph_embedding.dmon.utilities.metrics import conductance
from graph_embedding.dmon.utilities.metrics import modularity
from graph_embedding.dmon.utilities.metrics import precision
from graph_embedding.dmon.utilities.metrics import recall

tf.compat.v1.enable_v2_behavior()

FLAGS = flags.FLAGS

flags.DEFINE_string('graph_path', None, 'Input graph path')
flags.DEFINE_string('output_path', None, 'Output results path')
flags.DEFINE_string('architecture', None, 'Network architecture')
flags.DEFINE_string('load_strategy', 'schur', 'Graph format')
flags.DEFINE_string('postfix', '', 'File postfix')
flags.DEFINE_float(
    'orthogonality_regularization',
    1,
    'Orthogonality regularization parameter',
    lower_bound=0)
flags.DEFINE_float(
    'cluster_size_regularization',
    1,
    'Cluster size regularization parameter',
    lower_bound=0)
flags.DEFINE_float(
    'dropout_rate',
    0,
    'Orthogonality regularization parameter',
    lower_bound=0,
    upper_bound=1)
flags.DEFINE_integer('n_clusters', 16, 'Number of clusters', lower_bound=0)
flags.DEFINE_integer('n_epochs', 1000, 'Number of epochs', lower_bound=0)
flags.DEFINE_float('learning_rate', 0.001, 'Learning rate', lower_bound=0)

def format_filename():
  graph_name = os.path.split(FLAGS.graph_path)[1]
  architecture_str = FLAGS.architecture.strip('[]')
  return (f'{FLAGS.output_path}/{graph_name}-'
          f'nclusters-{FLAGS.n_clusters}-'
          f'architecture-{architecture_str}-'
          f'ortho-{FLAGS.orthogonality_regularization}-'
          f'clustersize-{FLAGS.cluster_size_regularization}-'
          f'dropout-{FLAGS.dropout_rate}-'
          f'lr-{FLAGS.learning_rate}-'
          f'epochs-{FLAGS.n_epochs}'
          f'postfix-{FLAGS.postfix}'
          '.txt')

def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')
  print('Starting', format_filename())
  if FLAGS.load_strategy == 'schur':
    adjacency, features, labels, label_mask = load_npz_to_sparse_graph(
        FLAGS.graph_path)
  elif FLAGS.load_strategy == 'kipf':
    adjacency, features, labels, label_mask = load_kipf_data(
        *os.path.split(FLAGS.graph_path))
  else:
    raise Exception('Unknown loading strategy!')
  n_nodes = adjacency.shape[0]
  feature_size = features.shape[1]
  architecture = [int(x) for x in FLAGS.architecture.strip('[]').split('_')]
  architecture.append(FLAGS.n_clusters)
  graph_clean = scipy_to_tf(adjacency)
  graph_clean_normalized = scipy_to_tf(
      normalize_graph(adjacency.copy(), normalized=True))

  input_features = tf.keras.layers.Input(shape=(feature_size,))
  input_graph = tf.keras.layers.Input((n_nodes,), sparse=True)
  input_adjacency = tf.keras.layers.Input((n_nodes,), sparse=True)

  model = gcn_modularity(
      [input_features, input_graph, input_adjacency],
      architecture,
      dropout_rate=FLAGS.dropout_rate,
      orthogonality_regularization=FLAGS.orthogonality_regularization,
      cluster_size_regularization=FLAGS.cluster_size_regularization)

  def grad(model, inputs):
    with tf.GradientTape() as tape:
      _ = model(inputs, training=True)
      loss_value = sum(model.losses)
    return model.losses, tape.gradient(loss_value, model.trainable_variables)

  optimizer = tf.keras.optimizers.Adam(FLAGS.learning_rate)
  model.compile(optimizer, None)

  for epoch in range(FLAGS.n_epochs):
    loss_values, grads = grad(model,
                              [features, graph_clean_normalized, graph_clean])
    optimizer.apply_gradients(zip(grads, model.trainable_variables))
    print(f'epoch {epoch}, losses: ' +
          ' '.join([f'{loss_value.numpy():.4f}' for loss_value in loss_values]))

  _, assignments = model([features, graph_clean_normalized, graph_clean],
                         training=False)
  assignments = assignments.numpy()
  clusters = assignments.argmax(axis=1)
  print('Conductance:', conductance(adjacency, clusters))
  print('Modularity:', modularity(adjacency, clusters))
  print(
      'NMI:',
      normalized_mutual_info_score(
          labels, clusters[label_mask], average_method='arithmetic'))
  print('Precision:', precision(labels, clusters[label_mask]))
  print('Recall:', recall(labels, clusters[label_mask]))
  with open(format_filename(), 'w') as out_file:
    print('Conductance:', conductance(adjacency, clusters), file=out_file)
    print('Modularity:', modularity(adjacency, clusters), file=out_file)
    print(
        'NMI:',
        normalized_mutual_info_score(
            labels, clusters[label_mask], average_method='arithmetic'),
        file=out_file)
    print('Precision:', precision(labels, clusters[label_mask]), file=out_file)
    print('Recall:', recall(labels, clusters[label_mask]), file=out_file)

if __name__ == '__main__':
  app.run(main)


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using GroupDocs.Viewer.Options;

namespace GroupDocs.Viewer.Examples.CSharp.AdvancedUsage.Rendering.RenderingOptionsByDocumentType.RenderingWebDocuments
{
    /// <summary>
    /// This example demonstrates how to render CHM document into HTML, JPG, PNG, PDF.
    /// </summary>
    public class RenderingChmFiles
    {
        public static void Run()
        {
            string outputDirectory = Utils.GetOutputDirectoryPath();
            string pageFilePathFormat = Path.Combine(outputDirectory, "chm_result_{0}.html");

            // TO HTML
            using (Viewer viewer = new Viewer(TestFiles.SAMPLE_CHM))
            {
                HtmlViewOptions options = HtmlViewOptions.ForEmbeddedResources(pageFilePathFormat);
                options.RenderToSinglePage = true; // Enable it if you want to convert all CHM content to single page

                //viewer.View(options,1,2,3); // Convert only 1,2,3 pages
                 viewer.View(options); // Convert all pages
            }

            // TO JPG
            pageFilePathFormat = Path.Combine(outputDirectory, "chm_result_{0}.jpg");

            using (Viewer viewer = new Viewer(TestFiles.SAMPLE_CHM))
            {
                JpgViewOptions options = new JpgViewOptions(pageFilePathFormat);

                viewer.View(options,1,2,3); // Convert only 1,2,3 pages
                //viewer.View(options); // Convert all pages
            }

            // TO PNG
            pageFilePathFormat = Path.Combine(outputDirectory, "chm_result_{0}.png");

            using (Viewer viewer = new Viewer(TestFiles.SAMPLE_CHM))
            {
                PngViewOptions options = new PngViewOptions(pageFilePathFormat);

                viewer.View(options,1,2,3); // Convert only 1,2,3 pages
                //viewer.View(options); // Convert all pages
            }

            // TO PDF
            pageFilePathFormat = Path.Combine(outputDirectory, "chm_result.pdf");

            using (Viewer viewer = new Viewer(TestFiles.SAMPLE_CHM))
            {
                PdfViewOptions options = new PdfViewOptions(pageFilePathFormat);

                viewer.View(options); // Convert all pages
            }

            Console.WriteLine($"\nSource document rendered successfully.\nCheck output in {outputDirectory}.");
        }
    }
}