text:
using System.Collections.Generic;
using Xunit;

//
// About the "desktopQuirk"
//
//   On the desktop CLR, GetRuntimeProperties() and GetRuntimeEvents() behave inconsistently from the other
//   GetRuntime*() apis in that they suppress hidden instance properties and events from base classes.
//
//   On .NET Native, the GetRuntime*() apis all behave consistently (i.e. the results include hidden instance
//   members from base classes.)
//

namespace System.Reflection.Extensions.Tests
{
    public class RuntimeReflectionExtensionsTestsWithQuirks
    {
        [Fact]
        public void GetRuntimeProperties()
        {
            var types = GetTypes();

            Assert.Throws<ArgumentNullException>(() =>
            {
                RuntimeReflectionExtensions.GetRuntimeProperties(null);
            });

            List<String> properties = new List<String>();

            foreach (TypeInfo type in types)
            {
                if (!type.Namespace.Equals("PropertyDefinitions", StringComparison.Ordinal))
                    continue;

                properties.Clear();
                properties.AddRange((IEnumerable<String>)type.GetDeclaredField("DeclaredPropertyNames").GetValue(null));
                properties.AddRange((IEnumerable<String>)type.GetDeclaredField("InheritedPropertyNames").GetValue(null));

                Assert.All(type.AsType().GetRuntimeProperties(), p => Assert.True(properties.Remove(p.Name)));
                Assert.Empty(properties);
            }
        }

        [Fact]
        public void GetRuntimeEvents()
        {
            var types = GetTypes();

            Assert.Throws<ArgumentNullException>(() =>
            {
                RuntimeReflectionExtensions.GetRuntimeEvents(null);
            });

            List<String> events = new List<String>();

            foreach (TypeInfo type in types)
            {
                if (!type.Namespace.Equals("EventDefinitions", StringComparison.Ordinal))
                    continue;

                if (type.IsInterface)
                    continue;

                events.Clear();
                events.AddRange((IEnumerable<String>)type.GetDeclaredField("DeclaredEvents").GetValue(null));
                events.AddRange((IEnumerable<String>)type.GetDeclaredField("InheritedEvents").GetValue(null));

                Assert.All(type.AsType().GetRuntimeEvents(), e => Assert.True(events.Remove(e.Name)));
                Assert.Empty(events);
            }
        }

        private static TypeInfo[] GetTypes()
        {
            Assembly asm = typeof(PropertyDefinitions.BaseClass).GetTypeInfo().Assembly;
            var list = new List<TypeInfo>();
            foreach (var t in asm.DefinedTypes)
            {
                if (t.Namespace == null) continue; // These are classes in the global namespace; not under test
                list.Add(t);
            }
            return list.ToArray();
        }
    }
}


text:
import org.omg.PortableInterceptor.INACTIVE;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Liuxz on 2017/1/24.
 */

public class Leet39CombinationSum {
    int[] candidates;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.candidates = candidates;
        List<List<Integer>> result = new ArrayList<>();
        loop(result, new ArrayList<Integer>(), 0,target);
        System.out.println(result);
        return result;
    }

    private void loop(List<List<Integer>> all, List<Integer> backup, int cur,int target){
        if (target <=0){
            return;
        }else{
            for (int i = cur ;i < candidates.length; i++){
                target = target - candidates[i];
                backup.add(candidates[i]);
                if (target == 0){
                    all.add(new ArrayList<Integer>(backup));
                }
                loop(all, backup, i,target);
                backup.remove(backup.size()-1);
                target = target + candidates[i];
            }
        }
    }

    public static void main (String[] args){
        Leet39CombinationSum x = new Leet39CombinationSum();
        x.combinationSum(new int[]{2,3,6,7}, 7);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apereo.portal.events.aggr.tabrender;

import org.apereo.portal.events.aggr.BaseAggregation;
import org.apereo.portal.events.aggr.TimedAggregationStatistics;
import org.apereo.portal.events.aggr.tabs.AggregatedTabMapping;

/**
 * Tracks tab render stats, all times are in nanoseconds.
 *
 */
public interface TabRenderAggregation
        extends BaseAggregation<TabRenderAggregationKey, TabRenderAggregationDiscriminator>,
                TimedAggregationStatistics {

    /** @return Number of times the tab was rendered */
    int getRenderCount();

    /** @return The name of the tab */
    AggregatedTabMapping getTabMapping();
}


text:
<component name="ArtifactManager">
  <artifact type="jar" name="writer:jar">
    <output-path>$PROJECT_DIR$/out/artifacts/writer_jar</output-path>
    <root id="archive" name="writer.jar">
      <element id="module-output" name="writer" />
    </root>
  </artifact>
</component>


text:
<resources>
    <string name="app_name">Google Direction Library Demo</string>
    <string name="simple_direction">Simple Direction</string>
    <string name="transit_direction">Transit Direction</string>
    <string name="alternative_direction">Alternative Direction</string>
    <string name="waypoints_direction">Waypoints Direction</string>
    <string name="request_direction">Request Direction</string>
    <string name="success_with_status">Success with status : %1$s</string>
    <string name="direction_requesting">Direction Requesting...</string>
</resources>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>server.logic.routing package — Runamic Server 1.0 documentation</title>

    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="server.static package" href="server.static.html" />
    <link rel="prev" title="server.logic.projection package" href="server.logic.projection.html" />

  <link rel="stylesheet" href="_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

server.logic.routing package¶

Submodules¶

server.logic.routing.compress module¶

server.logic.routing.compress.decode(string)¶

Decodes the string generated by encode back into an integer

server.logic.routing.compress.encode(integer)¶

Encodes an (very large) integer into a string.

server.logic.routing.compress.from_string(graph, string)¶

Creates a rod from a graph and tag.

server.logic.routing.compress.into_string(graph, rod)¶

Transforms a list of indices into a tag.

server.logic.routing.config module¶

class server.logic.routing.config.RoutingConfig¶

Bases: server.logic.routing.config.RoutingConfig

The class containing all possible config options for routing.

Keep it up to date with server.config.DEFAULT_ROUTING_CONFIG

server.logic.routing.config.from_dict(default, dictionary)¶

Generates a routing configuration from a dictionary

server.logic.routing.directions module¶

class server.logic.routing.directions.Direction¶

Bases: server.logic.routing.directions.Direction

Class for serializing into the direction type

static from_index(graph, index, c)¶

class server.logic.routing.directions.DirectionDict¶

Bases: object

server.logic.routing.directions.get_direction(node_angle, threshold, left, right)¶

Return right or left depending on the angle

Function args:
node_angle – list of three points forming an angle.
threshold – minimum (-maximum) value of the sine of the angle

in order to count

left, right – return values in case of success

server.logic.routing.directions.into_directions(graph, nodelist, dirdict)¶

Annotate a nodelist with directions

Returns: list of coordinates with direction metadata.

server.logic.routing.poison module¶

server.logic.routing.poison.poison_graph(graph, venomous_path, config)¶

Poisons a graph

Function args:
graph – the graph
venomous_path – the path from which the poison originates
config – routing configuration

server.logic.routing.ratings module¶

server.logic.routing.ratings.add_rating_list(graph, edges, rating)¶

Adds a rating to an edge in the database. If an edge does not exist, it is created.

Function args:
graph – the graph
edges – the edges which will get a rating
rating – the score which is passed

server.logic.routing.routing module¶

This file implements the Lightning Rod algorithm for route generation

The algorithm consists of three steps:

A "rod" is generated, a shortest path between the starting node and a random
node at a set distance.

Various routes are generated from the starting node towards the rod. When
they collide, the path formed by the lower part of the rod and the generated
path is tested on length. If the length satisfies the total length constraint,
it is added to the list of possible results.

The best path, using other cost metrics, is selected.

server.logic.routing.routing.annotate_rod(rod, graph, distance_fn)¶

Returns a dictionary with information about distances from the rod to the starting node.

server.logic.routing.routing.close_rod(graph, start_node, rod, routing_config, alt_rod=None)¶

Generates a closed route given a rod

server.logic.routing.routing.generate_rod(graph, start_node, routing_config)¶

Generates a random rod.

server.logic.routing.tests module¶

class server.logic.routing.tests.TestEncodeDecode(methodName='runTest')¶

Bases: django.test.testcases.TestCase

Test whether encoding or decoding actually works

test_encode_decode()¶

class server.logic.routing.tests.TestPoison(methodName='runTest')¶

Bases: django.test.testcases.TestCase

Test whether poisoning doesn't change the graph

poison()¶

class server.logic.routing.tests.TestUtil(methodName='runTest')¶

Bases: django.test.testcases.TestCase

Test whether the ground and unground functions work

test_ground_unground()¶

server.logic.routing.util module¶

class server.logic.routing.util.RandomChooser¶

Bases: object

Deprecated

pop()¶

push(weight, item)¶

server.logic.routing.util.ground(visited_node_dict, end_node)¶

'grounds' a rod: it returns a list of nodes given a dict of nodes pointing to their precessor.

For example:
{2 : 1, 3 : 2, 5 : 3}, 5 -> [1, 2, 3, 5]

server.logic.routing.util.unground(visited_nodes)¶

Performs the inverse 'grounding' operation

Module contents¶

Table Of Contents

server.logic.routing package

Submodules

server.logic.routing.compress module

server.logic.routing.config module

server.logic.routing.directions module

server.logic.routing.poison module

server.logic.routing.ratings module

server.logic.routing.routing module

server.logic.routing.tests module

server.logic.routing.util module

Module contents

Related Topics

Documentation overview

server

server package

server.logic package

Previous: server.logic.projection package

Next: server.static package

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2017, Groep16.

      |
      Powered by Sphinx 1.6.1
      & Alabaster 0.7.10

      |
      Page source


text:
import os

PARENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
CITIES_FILE = os.path.join(PARENT_DIR, 'indexer', 'cities', 'clean_cities.csv')
NUMBEO_DIR = os.path.join(PARENT_DIR, 'data', 'numbeo')
GLASSDOOR_DIR = os.path.join(PARENT_DIR, 'data', 'glassdoor')


text:
require "Macaroni.IO.GeneratedFileWriter"
require "Macaroni.IO.Path"

Path = Macaroni.IO.Path

function checkArgs(args, name, description)
    if args[name] == nil then
        msg = 'Missing argument "' .. name;
        if description ~= nil then
            msg = msg .. " Description:" .. description;
        end
        error(msg)
    end
end

function Generate(library, sources, outputPath)
end

function Build(library, sources, outputPath, installPath, extraArgs)
    -- Creates a Visual C++ project.
    local proj = ProjectFileWriter.new(extraArgs, library, sources, outputPath)
    proj:WriteFile()
end

ProjectFileWriter = {

    new = function(args, library, sources, outputPath)
        if args == nil then error("Must include extraArgs.") end
        checkArgs(args, "ProjectFile",
                  "The path to put the generated project file.");
        checkArgs(args, "ProjectGUID");
        checkArgs(args, "RootNamespace");
        if args.Name == nil then
            args.Name = library.Name
        end
        checkArgs(args, "AdditionalIncludePaths");
        checkArgs(args, "AdditionalLibraryPaths");
        checkArgs(args, "SourcePaths");
        if args.AdditionalIncludePaths == nil then
            args.AdditionalIncludePaths = {}
        end
        if args.AdditionalLibraryPaths == nil then
            args.AdditionalLibraryPaths = {}
        end
        if args.AdditionalSourcePaths == nil then
            args.AdditionalSourcePaths = {}
        end
        if args.SourceExcludePatterns == nil then
            args.SourceExcludePatterns = {}
        end
        if args.Configurations == nil then
            args.Configurations = {
                {
                  Name="Debug|Win32",
                  Configuration="Debug",
                  Platform="Win32",
                  --PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
                 }
            };
        end
        args.library = library
        args.sources = {}
        for i, v in ipairs(args.SourcePaths) do
            args.sources[#args.sources + 1] = Path.New(v)
        end
        for i, v in ipairs(args.AdditionalSourcePaths) do
            args.sources[#args.sources + 1] = Path.New(v)
        end
        args.outputPath = outputPath
        self = args
        self.writer =  Path.New(self.ProjectFile):CreateFile()
        setmetatable(self, {["__index"]=ProjectFileWriter});
        return self
    end,

    -- function librarySourcePath(d)
    --     local success, path = pcall(d.FindInstallPath, d);
    --     if (success and path ~= nil) then
    --         local pathText = path.AbsolutePathForceSlash;
    --         local sourceFolder = path:NewPathForceSlash('Cpp');
    --         if (sourceFolder.Exists) then
    --             return sourceFolder;
    --         end
    --     end
    --     return nil;
    -- end,

    WriteFile = function(self)
        self:writeBegin();
        self:writeConfigurations();
        self.writer:Write([[
      <PropertyGroup Label="Globals">
        <ProjectGuid>{]] .. self.ProjectGUID .. [[}</ProjectGuid>
        <Keyword>Win32Proj</Keyword>
        <RootNamespace>]] .. self.RootNamespace .. [[</RootNamespace>
      </PropertyGroup>

        ]])

        self.writer:Write([[
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <WholeProgramOptimization>true</WholeProgramOptimization>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <LinkIncremental>true</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
  ]]);

    self.writer:Write([[
    <PropertyGroup>
        <LinkIncremental>true</LinkIncremental>
        <IncludePath>]]);

    -- for i, source in ipairs(self.sources) do
    --     self.writer:Write('"' .. source.AbsolutePath .. '";')
    -- end
    -- self.writer:Write('"' .. self.outputPath.AbsolutePath .. '";')
    self.writer:Write([[$(IncludePath)</IncludePath>
      </PropertyGroup>
    ]])

    self.writer:Write([[
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <ClCompile>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <AdditionalIncludeDirectories>]]);

    for i, source in ipairs(self.sources) do
        self.writer:Write('"' .. source.AbsolutePath .. '";')
    end
    self.writer:Write('"' .. self.outputPath.AbsolutePath .. '";')
    for i, dir in ipairs(self.AdditionalIncludePaths) do
        self.writer:Write('"' .. Path.New(dir).AbsolutePath .. '";')
    end

      self.writer:Write([[%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
      <AdditionalLibraryDirectories>]]);

      for i, dir in ipairs(self.AdditionalLibraryPaths) do
          self.writer:Write('"' .. Path.New(dir).AbsolutePath .. '";')
      end

      self.writer:Write([[%(AdditionalLibraryDirectories)
      </AdditionalLibraryDirectories>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <Optimization>MaxSpeed</Optimization>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
    </Link>
  </ItemDefinitionGroup>
  <ItemGroup>
    <None Include="ReadMe.txt" />
  </ItemGroup>
  ]]);
        self:writeFiles();
        self.writer:Write([[
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
        ]]);

        -- TODO: References?

--        self:writeFiles();

        self:writeEnd();
    end,

    writeBegin = function(self)
        self.writer:Write([[
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      ]]);
    end,

    writeConfiguration = function(self, config)
        self.writer:Write([[
            <ProjectConfiguration Include="]] .. config.Name .. [[">
              <Configuration>]] .. config.Configuration .. [[</Configuration>
              <Platform>]] .. config.Platform .. [[</Platform>
            </ProjectConfiguration>
        ]]);
    end,

    writeConfigurations = function(self)
        self.writer:Write([[
            <ItemGroup Label="ProjectConfigurations">
            ]]);
        for i, v in ipairs(self.Configurations) do
            self:writeConfiguration(v);
        end
        self.writer:Write([[
            </ItemGroup>
        ]]);
    end,

    filePathExclude = function(self, fp)
      -- Returns true if the given file path should be excluded.
      for i, v in ipairs(self.SourceExcludePatterns) do
          if string.sub(fp.AbsolutePath, - string.len(v)) == v then
              return true
          end
      end
      return false
    end,

    writeFiles = function(self)
        local writeDirFiles = function(elementName, src, regex)
            local filePaths = src:GetPaths(regex)
            for i = 1, #filePaths do
                local fp = filePaths[i];
                if not self:filePathExclude(fp) then
                  if elementName == "None" then
                      self.writer:Write([[<None Include="]] ..
                          fp.AbsolutePath ..
                          [[">
                            <FileType>Document</FileType>
                          </None>]])
                  else
                      self.writer:Write([[<]] .. elementName ..[[ Include="]])
                      self.writer:Write(fp.AbsolutePath .. [[" />]] .. '\n')
                  end
                end
            end
        end

        self.writer:Write([[<ItemGroup>]]);
        for i, v in ipairs(self.sources) do
            writeDirFiles("None", v, [[\.(mcpp)?$]])
        end
        self.writer:Write([[</ItemGroup>]]);

        self.writer:Write([[<ItemGroup>]]);
        for i, v in ipairs(self.sources) do
            writeDirFiles("ClCompile", v, [[\.(c|cc|cpp)?$]])
        end
        writeDirFiles("ClCompile", self.outputPath, [[\.(c|cpp)?$]])
        self.writer:Write([[</ItemGroup>]]);

        self.writer:Write([[<ItemGroup>]]);
        for i, v in ipairs(self.sources) do
            writeDirFiles("ClInclude", v, [[\.(h|hpp)?$]])
        end
        writeDirFiles("ClInclude", self.outputPath, [[\.(h|hpp)?$]])
        self.writer:Write([[</ItemGroup>]]);
    end,

    writeEnd = function(self)
        self.writer:Write("\n" .. [[
        </Project>
        ]]);
        self.writer:Close();
    end,

    writeIncludeDirectories = function(self, seperator)
        local rtn = ""
        for i, v in ipairs(self.sources) do
            rtn = rtn .. v.AbsolutePath .. seperator
        end
        rtn = rtn .. self.outputPath.AbsolutePath .. seperator
        for i, v in ipairs(self.library.Dependencies) do
            local dir = guessIncludeLocation(v)
            if dir ~= nil then
                rtn = rtn .. dir .. seperator
            end
        end
        return rtn;
    end,

    writeLibraryDirectories = function(self, seperator)
        rtn = ""
        for i, v in ipairs(self.sources) do
            rtn = rtn .. v.AbsolutePath .. seperator
        end
        rtn = rtn .. self.outputPath.AbsolutePath .. seperator
        for i, v in ipairs(self.library.Dependencies) do
            local dir = guessBoostBuildLibraryLocation(v)
            if dir ~= nil then
                rtn = rtn .. dir .. seperator
            end
        end
        return rtn;
    end,

    writePlatforms = function(self)
        self.writer:Write("<Platforms>")
        for i, n in ipairs(self.PlatformNames) do
            self.writer:Write('<Platform Name="' .. n .. '" />')
        end
        self.writer:Write("</Platforms>")
    end,
};

function guessIncludeLocation(d)
    -- Given a dependency library, estimates where the included source is.
    local success, path = pcall(d.FindInstallPath, d);
    if (success and path ~= nil) then
        local pathText = path.AbsolutePathForceSlash;
        local includeDir = path:NewPathForceSlash('Cpp');
        if (includeDir.Exists) then
            return includeDir.AbsolutePath;
        end
    end
    return nil;
end

function guessBoostBuildLibraryLocation(d)
    -- Given a dependency library, estimates where Boost Build might have stored
    -- its library files.
    -- Clearly this is an insane hack, because a better solution would have to
    -- solve for the multitude of possible configurations in a C++ project
    -- and where they all might live.
    local success, path = pcall(d.FindInstallPath, d);
    if (success and path ~= nil) then
        local pathText = path.AbsolutePathForceSlash;
        -- local link_static = "Cpp/bin/msvc-9.0/debug/link-static"
        local libDir = path:NewPathForceSlash('Cpp/bin/msvc-9.0/debug/threading-multi');
        if (libDir.Exists) then
            return libDir.AbsolutePath;
        end
    end
    return nil;
end


text:
/**
 *
  Package: MAG - VistA Imaging
  WARNING: Per VHA Directive 2004-038, this routine should not be modified.
  Date Created: Oct 16, 2008
  Site Name:  Washington OI Field Office, Silver Spring, MD
  Developer:  VHAISWWERFEJ
  Description:

        ;; +--------------------------------------------------------------------+
        ;; Property of the US Government.
        ;; No permission to copy or redistribute this software is given.
        ;; Use of unreleased versions of this software requires the user
        ;;  to execute a written test agreement with the VistA Imaging
        ;;  Development Office of the Department of Veterans Affairs,
        ;;  telephone (301) 734-0100.
        ;;
        ;; The Food and Drug Administration classifies this software as
        ;; a Class II medical device.  As such, it may not be changed
        ;; in any way.  Modifications to this software may result in an
        ;; adulterated medical device under 21CFR820, the use of which
        ;; is considered to be a violation of US Federal Statutes.
        ;; +--------------------------------------------------------------------+

 */
package gov.va.med.imaging.exchange;

import gov.va.med.imaging.exchange.enums.ImageFormat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

import junit.framework.TestCase;

/**
 * Unit testing for the FileTypeIdentifierStream. This test looks in the image folder of the test
 * resources and identifies each image in the folder.  Then based on the file extension given to the
 * file determines if the file was identified correctly. This means that files in this folder need
 * non-standard file extensions such as dcmj2k to indicate a DICOM wrapped JPEG 2000 image. While not
 * optimal, this allows the ultimate flexibility.  When new "problem" images appear, they can simply
 * be dropped into this images folder and immediately are added to the test without any configuration
 * changes.
 *
 * @author VHAISWWERFEJ
 *
 */
public class TestFileTypeIdentifierStream
extends TestCase
{
	// known file extensions and formats, to add a new format, add it here and the result
	// in the getExpectedImageFormat function
	private final static String FILE_EXTENSION_DCM = "dcm";
	private final static String FILE_EXTENSION_DCMJ2K = "dcmj2k";
	private final static String FILE_EXTENSION_DCMJPG = "dcmjpg";
	private final static String FILE_EXTENSION_DCMPDF = "dcmpdf";
	private final static String FILE_EXTENSION_J2K = "j2k";
	private final static String FILE_EXTENSION_JPEG = "jpg";
	private final static String FILE_EXTENSION_PDF = "pdf";
	private final static String FILE_EXTENSION_TGA = "tga";
	private final static String FILE_EXTENSION_TIFF = "tiff";
	private final static String FILE_EXTENSION_BMP = "bmp";
	private final static String FILE_EXTENSION_AVI = "avi";
	private final static String FILE_EXTENSION_WAV = "wav";
	private final static String FILE_EXTENSION_DOC = "doc";
	private final static String FILE_EXTENSION_HTML = "html";
	private final static String FILE_EXTENSION_RTF = "rtf";
	private final static String FILE_EXTENSION_MP3 = "mp3";
	private final static String FILE_EXTENSION_MPG = "mpg";
	private final static String FILE_EXTENSION_PNG = "png";
	private final static String FILE_EXTENSION_GIF = "gif";
	private final static String FILE_EXTENSION_XLS = "xls";
	private final static String FILE_EXTENSION_DOCX = "docx";
	private final static String FILE_EXTENSION_XML = "xml";

	public TestFileTypeIdentifierStream()
	{
		super();
	}

	private String getFilesDirectory()
	{
		URL path = getClass().getResource("images");
		File f = new File(path.getFile());
		String imageDir = f.getAbsolutePath();
		imageDir = imageDir.replaceAll("%20", " ");
		return imageDir;
	}

	public void testImageIdentification()
	{
		String imageDirectory = getFilesDirectory();
		File directory = new File(imageDirectory);
		File[] files = directory.listFiles();
		assertNotSame("Did not find any images in image directory", 0, files.length);
		for(File file : files)
		{
			try
			{
				System.out.println("Testing format for file [" + file.getAbsolutePath() + "]");
				ImageFormat expectedFormat = getExpectedImageFormat(file);
				assertNotNull("Expected format for file [" + file.getAbsolutePath() + "] is null", expectedFormat);
				FileTypeIdentifierStream inputStream =
					new FileTypeIdentifierStream(new FileInputStream(file));
				ImageFormat imageFormat = inputStream.getImageFormat();
				inputStream.close();
				assertEquals("Expected image format [" + expectedFormat + "] not equal to image format [" + imageFormat + "] for file [" + file.getAbsolutePath() + "]",
						expectedFormat, imageFormat);
			}
			catch(FileNotFoundException fnfX)
			{
				fail("FileNotFoundException: " + fnfX.getMessage());
			}
			catch(IOException ioX)
			{
				fail("IO Exception: " + ioX.getMessage());
			}
		}
	}

	/**
	 * Determines the expected image format based on the file extension.
	 * @param file
	 * @return
	 */
	private ImageFormat getExpectedImageFormat(File file)
	{
		String filename = file.getName().toLowerCase();

		if(filename.endsWith(FILE_EXTENSION_DCM))
		{
			return ImageFormat.DICOM;
		}
		else if(filename.endsWith(FILE_EXTENSION_DCMJ2K))
		{
			return ImageFormat.DICOMJPEG2000;
		}
		else if(filename.endsWith(FILE_EXTENSION_DCMJPG))
		{
			return ImageFormat.DICOMJPEG;
		}
		else if(filename.endsWith(FILE_EXTENSION_DCMPDF))
		{
			return ImageFormat.DICOMPDF;
		}
		else if(filename.endsWith(FILE_EXTENSION_J2K))
		{
			return ImageFormat.J2K;
		}
		else if(filename.endsWith(FILE_EXTENSION_PDF))
		{
			return ImageFormat.PDF;
		}
		else if(filename.endsWith(FILE_EXTENSION_TGA))
		{
			return ImageFormat.TGA;
		}
		else if(filename.endsWith(FILE_EXTENSION_TIFF))
		{
			return ImageFormat.TIFF;
		}
		else if(filename.endsWith(FILE_EXTENSION_JPEG))
		{
			return ImageFormat.JPEG;
		}
		else if(filename.endsWith(FILE_EXTENSION_BMP))
		{
			return ImageFormat.BMP;
		}
		else if(filename.endsWith(FILE_EXTENSION_AVI))
		{
			return ImageFormat.AVI;
		}
		else if(filename.endsWith(FILE_EXTENSION_WAV))
		{
			return ImageFormat.WAV;
		}
		else if(filename.endsWith(FILE_EXTENSION_DOC))
		{
			return ImageFormat.DOC;
		}
		else if(filename.endsWith(FILE_EXTENSION_MP3))
		{
			return ImageFormat.MP3;
		}
		else if(filename.endsWith(FILE_EXTENSION_HTML))
		{
			return ImageFormat.HTML;
		}
		else if(filename.endsWith(FILE_EXTENSION_RTF))
		{
			return ImageFormat.RTF;
		}
		else if(filename.endsWith(FILE_EXTENSION_MPG))
		{
			return ImageFormat.MPG;
		}
		else if(filename.endsWith(FILE_EXTENSION_PNG))
		{
			return ImageFormat.PNG;
		}
		else if(filename.endsWith(FILE_EXTENSION_GIF))
		{
			return ImageFormat.GIF;
		}
		else if(filename.endsWith(FILE_EXTENSION_XLS))
		{
			return ImageFormat.XLS;
		}
		else if(filename.endsWith(FILE_EXTENSION_DOCX))
		{
			return ImageFormat.DOCX;
		}
		else if(filename.endsWith(FILE_EXTENSION_XML))
			return ImageFormat.XML;
		return null;
	}

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _pure = require('recompose/pure');

var _pure2 = _interopRequireDefault(_pure);

var _SvgIcon = require('../../SvgIcon');

var _SvgIcon2 = _interopRequireDefault(_SvgIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var CommunicationForum = function CommunicationForum(props) {
  return _react2.default.createElement(
    _SvgIcon2.default,
    props,
    _react2.default.createElement('path', { d: 'M21 6h-2v9H6v2c0 .55.45 1 1 1h11l4 4V7c0-.55-.45-1-1-1zm-4 6V3c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v14l4-4h10c.55 0 1-.45 1-1z' })
  );
};
CommunicationForum = (0, _pure2.default)(CommunicationForum);
CommunicationForum.displayName = 'CommunicationForum';

exports.default = CommunicationForum;


text:
using System;

namespace Adaptive.Arp.Api
{
     /**
        Structure representing the data a single geolocation reading.

        @author Francisco Javier Martin Bueno
        @since v2.0
        @version 1.0
     */
     public class Geolocation : APIBean
     {

          /**
             The current device altitude (or Z coordinate). Measured in meters.
          */
          public double Altitude { get; set; }
          /**
             The Y coordinate (or latitude). Measured in degrees.
          */
          public double Latitude { get; set; }
          /**
             The X coordinate (or longitude). Measured in degrees.
          */
          public double Longitude { get; set; }
          /**
             Timestamp of the geolocation reading.
          */
          public long Timestamp { get; set; }
          /**
             Dilution of precision on the X measurement. Measured in meters.
          */
          public float XDoP { get; set; }
          /**
             Dilution of precision on the Y measurement. Measured in meters.
          */
          public float YDoP { get; set; }

          /**
             Default constructor

             @since V2.0
          */
          public Geolocation()  {
          }

          /**
             Constructor with parameters

             @param Latitude  Latitude of the measurement
             @param Longitude Longitude of the measurement
             @param Altitude  Altitude of the measurement
             @param XDoP      Dilution of precision on the X measurement
             @param YDoP      Dilution of precision on the Y measurement
             @param Timestamp Timestamp of the measurement
             @since V2.0
          */
          public Geolocation(double latitude, double longitude, double altitude, float xDoP, float yDoP, long timestamp) : base () {
               this.Latitude = Latitude;
               this.Longitude = Longitude;
               this.Altitude = Altitude;
               this.XDoP = XDoP;
               this.YDoP = YDoP;
               this.Timestamp = Timestamp;
          }

          /**
             Constructor with parameters

             @param Latitude  Latitude of the measurement
             @param Longitude Longitude of the measurement
             @param Timestamp Timestamp of the measurement
             @since V2.0
          */
          public Geolocation(double latitude, double longitude, long timestamp) : base () {
               this.Latitude = Latitude;
               this.Longitude = Longitude;
               this.Timestamp = Timestamp;
          }

          /**
             Returns altitude in meters

             @return Altitude of the measurement
             @since V2.0
          */
          public double GetAltitude() {
               return this.Altitude;
          }

          /**
             Set altitude in meters

             @param Altitude Altitude of the measurement
             @since V2.0
          */
          public void SetAltitude(double Altitude) {
               this.Altitude = Altitude;
          }

          /**
             Returns the latitude in degrees

             @return Latitude of the measurement
             @since V2.0
          */
          public double GetLatitude() {
               return this.Latitude;
          }

          /**
             Set the latitude in degrees

             @param Latitude Latitude of the measurement
             @since V2.0
          */
          public void SetLatitude(double Latitude) {
               this.Latitude = Latitude;
          }

          /**
             Returns the longitude in degrees

             @return Longitude of the measurement
             @since V2.0
          */
          public double GetLongitude() {
               return this.Longitude;
          }

          /**
             Returns the latitude in degrees

             @param Longitude Longitude of the measurement
             @since V2.0
          */
          public void SetLongitude(double Longitude) {
               this.Longitude = Longitude;
          }

          /**
             Timestamp Getter

             @return Timestamp
             @since V2.0
          */
          public long GetTimestamp() {
               return this.Timestamp;
          }

          /**
             Timestamp Setter

             @param Timestamp Timestamp
             @since V2.0
          */
          public void SetTimestamp(long Timestamp) {
               this.Timestamp = Timestamp;
          }

          /**
             Gets Dilution of precision on the X measurement. Measured in meters.

             @return xDoP Dilution of precision on the X measurement. Measured in meters.
          */
          public float GetXDoP() {
               return this.XDoP;
          }

          /**
             Sets Dilution of precision on the X measurement. Measured in meters.

             @param xDoP Dilution of precision on the X measurement. Measured in meters.
          */
          public void SetXDoP(float XDoP) {
               this.XDoP = XDoP;
          }

          /**
             Gets Dilution of precision on the Y measurement. Measured in meters.

             @return yDoP Dilution of precision on the Y measurement. Measured in meters.
          */
          public float GetYDoP() {
               return this.YDoP;
          }

          /**
             Sets Dilution of precision on the Y measurement. Measured in meters.

             @param yDoP Dilution of precision on the Y measurement. Measured in meters.
          */
          public void SetYDoP(float YDoP) {
               this.YDoP = YDoP;
          }

     }
}

/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace SeriesNamer.tvdb
{
    public class MirrorList
    {
        public MirrorList(XmlElement root)
        {
            foreach (XmlElement e in Xml.ElementsNamed(root, "Mirror"))
            {
                Mirror m = new Mirror();
                m.id = Xml.GetTextOfSubElement(e, "id");
                m.url = Xml.GetTextOfSubElement(e, "mirrorpath");
                int typemask = int.Parse(Xml.GetTextOfSubElement(e, "typemask"));
                m.xml = (typemask & 1) != 0;
                m.banner = (typemask & 2) != 0;
                m.zip = (typemask & 4) != 0;
                mirrors.Add(m);
            }
        }

        private List<Mirror> mirrors = new List<Mirror>();

        private struct Mirror
        {
            public string id;
            public string url;
            public bool xml;
            public bool banner;
            public bool zip;

            public bool match(YesNo xml, YesNo banner, YesNo zip)
            {
                return match(this.xml, xml)
                    && match(this.banner, banner)
                    && match(this.zip, zip)
                    ;
            }

            private static bool match(bool b, YesNo y)
            {
                if( b == false && y == YesNo.Yes) return false;
                if( b == true && y == YesNo.No) return false;
                return true;
            }
        }

        internal string suggest(YesNo xml, YesNo banner, YesNo zip)
        {
            List<Mirror> suitables = new List<Mirror>();
            foreach (Mirror m in mirrors)
            {
                if (m.match(xml, banner, zip))
                    suitables.Add(m);
            }

            int count = suitables.Count;
            if( count == 0 ) throw new Exception("No sutiable mirror found");

            // pick a random suitable
            Random r = new Random();
            int index = r.Next(count);
            return suitables[index].url;
        }
    }
}


text:
<?php
namespace Desmond\data_types;

class TrueType extends AbstractAtom
{
    public function __construct()
    {
        $this->setValue(true);
    }

    public function __toString()
    {
        return 'true';
    }
}


text:
class CreateQuestions < ActiveRecord::Migration[5.0]
  def change
    create_table :questions do |t|
      t.string :question_text, null: false
      t.string :answer,null: false
      t.integer :quiz_id
      t.integer :value, null: false

      t.timestamps
    end
  end
end


text:
import * as React from "react";
import { useIsomorphicLayoutEffect } from "../lib/useIsomorphicLayoutEffect";
import { canUseDOM } from "../lib/dom";
export function useTimeout(cb, duration) {
  var options = React.useRef({
    cb: cb,
    duration: duration
  });
  useIsomorphicLayoutEffect(function () {
    options.current.cb = cb;
    options.current.duration = duration;
  }, [cb, duration]);
  var timeout = React.useRef();
  var clear = React.useCallback(function () {
    if (canUseDOM && timeout !== null && timeout !== void 0 && timeout.current) {
      clearTimeout(timeout.current);
    }
  }, []);
  var set = React.useCallback(function () {
    var duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : options.current.duration;
    clear();
    if (canUseDOM) {
      timeout.current = setTimeout(function () {
        var cb = options.current.cb;
        typeof cb === "function" && cb();
      }, duration);
    }
  }, [clear]);
  useIsomorphicLayoutEffect(function () {
    return clear;
  }, []);
  return {
    set: set,
    clear: clear
  };
}
//# sourceMappingURL=useTimeout.js.map


text:
package org.uda.preciosjustos.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * clase que tiene la configuración relacionada al accesso a datos,
 * transacciones y sessión de hibernate
 * @author zeta
 *
 */
@Configuration
@EnableTransactionManagement
@Import(value = { DevelopmentDatabaseConfig.class, TestingDatabaseConfig.class, ProductionDatabaseConfig.class })
public class PersistenceConfig {

	@Autowired
	private DataSource dataSource;

	@Autowired
	private Properties hibernateProperties;

	@Bean
	public SessionFactory sessionFactory() {
		LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
		builder.scanPackages("org.uda.preciosjustos.model").addProperties(
				hibernateProperties);

		return builder.buildSessionFactory();
	}

	@Bean
	@Autowired
	public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
		HibernateTransactionManager txManager = new HibernateTransactionManager();
		txManager.setSessionFactory(sessionFactory);
		return txManager;
	}

	@Bean
	public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
		return new PersistenceExceptionTranslationPostProcessor();
	}

}


text:
'use strict';

const loadGruntTasks = require('load-grunt-tasks');
const rollupPluginIncludePaths = require('rollup-plugin-includepaths');
const rollupPluginNodeResolve = require('rollup-plugin-node-resolve');
const rollupPluginReplace = require('rollup-plugin-replace');

module.exports = function register(grunt) {
  loadGruntTasks(grunt);

  grunt.initConfig({
    eslint: {
      options: {
        cache: true,
      },
      all: ['lib', 'test'],
    },

    clean: {
      all: ['dist', 'tmp'],
    },

    rollup: {
      options: {
        plugins: [
          rollupPluginReplace({
            include: 'node_modules/unicode-8.0.0/**/*.js',
            values: {
              'module.exports=': 'export default',
            },
          }),
          rollupPluginIncludePaths({ extensions: [] }),
          rollupPluginNodeResolve({ extensions: [] }),
        ],
        format: 'cjs',
      },
      dist: {
        files: {
          'dist/index.js': 'lib/index.js',
        },
      },
      test: {
        files: {
          'tmp/lexer.js': 'lib/lexer.js',
          'tmp/parser.js': 'lib/parser/index.js',
        },
      },
    },

    mochaTest: {
      test: {
        options: {
          timeout: 500,
        },
        src: [
          'test/boot.js',
          'test/**/*.test.js',
        ],
      },
    },
  });

  grunt.registerTask('prepublish', ['eslint', 'clean', 'rollup:dist']);
  grunt.registerTask('test', ['prepublish', 'rollup:test', 'mochaTest']);

  grunt.registerTask('default', ['test']);
};


text:
<?php

namespace Magento\SampleData\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\App\State;
use Symfony\Component\Console\Input\ArrayInput;
use Magento\Framework\App\Filesystem\DirectoryList;
use Composer\Console\Application;
use Magento\Setup\Model\PackagesAuth;

/**
 * Command for deployment of Sample Data
 */
class SampleDataDeployCommand extends Command
{
    /**
     * @var \Magento\Framework\Filesystem
     */
    private $filesystem;

    /**
     * @var \Magento\SampleData\Model\Dependency
     */
    private $sampleDataDependency;

    /**
     * @var \Symfony\Component\Console\Input\ArrayInputFactory
     * @deprecated
     */
    private $arrayInputFactory;

    /**
     * @var \Composer\Console\ApplicationFactory
     */
    private $applicationFactory;

    /**
     * @param \Magento\Framework\Filesystem $filesystem
     * @param \Magento\SampleData\Model\Dependency $sampleDataDependency
     * @param \Symfony\Component\Console\Input\ArrayInputFactory $arrayInputFactory
     * @param \Composer\Console\ApplicationFactory $applicationFactory
     */
    public function __construct(
        \Magento\Framework\Filesystem $filesystem,
        \Magento\SampleData\Model\Dependency $sampleDataDependency,
        \Symfony\Component\Console\Input\ArrayInputFactory $arrayInputFactory,
        \Composer\Console\ApplicationFactory $applicationFactory
    ) {
        $this->filesystem = $filesystem;
        $this->sampleDataDependency = $sampleDataDependency;
        $this->arrayInputFactory = $arrayInputFactory;
        $this->applicationFactory = $applicationFactory;
        parent::__construct();
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName('sampledata:deploy')
            ->setDescription('Deploy sample data modules');
        parent::configure();
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->updateMemoryLimit();
        $this->createAuthFile();
        $sampleDataPackages = $this->sampleDataDependency->getSampleDataPackages();
        if (!empty($sampleDataPackages)) {
            $baseDir = $this->filesystem->getDirectoryRead(DirectoryList::ROOT)->getAbsolutePath();
            $commonArgs = ['--working-dir' => $baseDir, '--no-progress' => 1];
            $packages = [];
            foreach ($sampleDataPackages as $name => $version) {
                $packages[] = "$name:$version";
            }
            $commonArgs = array_merge(['packages' => $packages], $commonArgs);
            $arguments = array_merge(['command' => 'require'], $commonArgs);
            $commandInput = new ArrayInput($arguments);

            /** @var Application $application */
            $application = $this->applicationFactory->create();
            $application->setAutoExit(false);
            $result = $application->run($commandInput, $output);
            if ($result !== 0) {
                $output->writeln(
                    '<info>' . 'There is an error during sample data deployment. Composer file will be reverted.'
                    . '</info>'
                );
                $application->resetComposer();
            }
        } else {
            $output->writeln('<info>' . 'There is no sample data for current set of modules.' . '</info>');
        }
    }

    /**
     * Create new auth.json file if it doesn't exist.
     *
     * We create auth.json with correct permissions instead of relying on Composer.
     *
     * @return void
     * @throws \Exception
     */
    private function createAuthFile()
    {
        $directory = $this->filesystem->getDirectoryWrite(DirectoryList::COMPOSER_HOME);

        if (!$directory->isExist(PackagesAuth::PATH_TO_AUTH_FILE)) {
            try {
                $directory->writeFile(PackagesAuth::PATH_TO_AUTH_FILE, '{}');
            } catch (\Exception $e) {
                $message = 'Error in writing Auth file '
                    . $directory->getAbsolutePath(PackagesAuth::PATH_TO_AUTH_FILE)
                    . '. Please check permissions for writing.';
                throw new \Exception($message);
            }
        }
    }

    /**
     * @return void
     */
    private function updateMemoryLimit()
    {
        if (function_exists('ini_set')) {
            @ini_set('display_errors', 1);
            $memoryLimit = trim(ini_get('memory_limit'));
            if ($memoryLimit != -1 && $this->getMemoryInBytes($memoryLimit) < 768 * 1024 * 1024) {
                @ini_set('memory_limit', '768M');
            }
        }
    }

    /**
     * @param string $value
     * @return int
     */
    private function getMemoryInBytes($value)
    {
        $unit = strtolower(substr($value, -1, 1));
        $value = (int) $value;
        switch($unit) {
            case 'g':
                $value *= 1024 * 1024 * 1024;
                break;
            case 'm':
                $value *= 1024 * 1024;
                break;
            case 'k':
                $value *= 1024;
        }
        return $value;
    }
}


text:
<?xml version="1.0"?>
<!DOCTYPE myname [

<!ELEMENT myname ANY>
<!ELEMENT firstname ANY>
<!ELEMENT lastname ANY>
<!NOTATION JPEG SYSTEM "urn:foo">
<!ENTITY false SYSTEM "http://webserver/../somepic.jpg" NDATA JPEG>
]>

<myname>
<firstname>Pranav</firstname>
<lastname>Kandula</lastname>
</myname>


text:
package com.epam.ta.reportportal.core.configs;

import com.epam.ta.reportportal.ws.resolver.JacksonViewAwareModule;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Andrei Varabyeu
 */
@Configuration
public class JacksonConfiguration {

	/**
	 * @return Configured object mapper
	 */
	@Bean(name = "objectMapper")
	public ObjectMapper objectMapper() {
		ObjectMapper om = new ObjectMapper();
		om.setAnnotationIntrospector(new JacksonAnnotationIntrospector());
		om.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
		om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		om.registerModule(new JacksonViewAwareModule(om));
		om.registerModule(new JavaTimeModule());
		return om;
	}
}


text:
package org.jitsi.jigasi.sounds;

import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.media.*;
import org.gagravarr.ogg.*;
import org.gagravarr.opus.*;
import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.codec.*;
import org.jitsi.jigasi.*;
import org.jitsi.jigasi.util.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.codec.*;
import org.jitsi.utils.*;
import org.jitsi.utils.logging.Logger;
import org.jitsi.xmpp.extensions.jibri.*;
import org.jivesoftware.smack.packet.*;

import java.util.*;
import java.util.concurrent.*;

/**
 * Manages all sounds notifications that are send to a SIP session side.
 *
 * @author Damian Minkov
 */
public class SoundNotificationManager
{
    /**
     * The logger.
     */
    private final static Logger logger = Logger.getLogger(
        SoundNotificationManager.class);

    /**
     * The sound file to use when recording is ON.
     */
    private static final String REC_ON_SOUND = "sounds/RecordingOn.opus";

    /**
     * The sound file to use when recording is OFF.
     */
    private static final String REC_OFF_SOUND = "sounds/RecordingStopped.opus";

    /**
     * The sound file to use when live streaming is ON.
     */
    private static final String LIVE_STREAMING_ON_SOUND
        = "sounds/LiveStreamingOn.opus";

    /**
     * The sound file to use when live streaming is OFF.
     */
    private static final String LIVE_STREAMING_OFF_SOUND
        = "sounds/LiveStreamingOff.opus";

    /**
     * The sound file to use when the max occupants limit is reached.
     */
    private static final String MAX_OCCUPANTS_SOUND
        = "sounds/MaxOccupants.opus";

    /**
     * The sound file to use to notify sip participant that
     * nobody is in the conference.
     */
    public static final String PARTICIPANT_ALONE = "sounds/Alone.opus";

    /**
     * The sound file to use to notify sip participant that a
     * participant has left.
     */
    public static final String PARTICIPANT_LEFT = "sounds/ParticipantLeft.opus";

    /**
     * The sound file to use to notify sip partitipant that a
     * new participant has joined.
     */
    public static final String PARTICIPANT_JOINED = "sounds/ParticipantJoined.opus";

    /**
     * The sound file to use to notify the participant that access was granted to join the
     * main room.
     */
    private static final String LOBBY_ACCESS_GRANTED = "sounds/LobbyAccessGranted.opus";

    /**
     * The sound file to use to notify the participant that access was denied to join the
     * main room.
     */
    private static final String LOBBY_ACCESS_DENIED = "sounds/LobbyAccessDenied.opus";

    /**
     * The sound file to use to notify the participant that the conference has ended.
     */
    private static final String LOBBY_MEETING_END = "sounds/LobbyMeetingEnd.opus";

    /**
     * The sound file to use to notify the participant that request to join is being reviewed.
     */
    private static final String LOBBY_JOIN_REVIEW = "sounds/LobbyWait.opus";

    /**
     * Approximate duration of the file to be played, we need it as to know
     * when to hangup the call. The actual file is 10 seconds but we give a
     * little longer for the file to be played and call to be answered.
     */
    private static final int MAX_OCCUPANTS_SOUND_DURATION_SEC = 15;

    /**
     * The current Jibri status in the conference.
     */
    private JibriIq.Status currentJibriStatus = JibriIq.Status.OFF;

    /**
     * The current jibri On sound to use, recording or live streaming.
     */
    private String currentJibriOnSound = null;

    /**
     * {@link SipGatewaySession} that uses this instance.
     */
    private final SipGatewaySession gatewaySession;

    /**
     * When set will indicate that we only need to play announcement to the
     * sip side and hangup the call.
     */
    private boolean callMaxOccupantsLimitReached = false;

    /**
     * In certain scenarios (max occupants) we wait till we hangup the call.
     */
    private CountDownLatch hangupWait = null;

    /**
     * Rate limiter of participant left sound notification.
     */
    private SoundRateLimiter participantLeftRateLimiterLazy = null;

    /**
     * Rate limiter of participant joined sound notification.
     */
    private SoundRateLimiter participantJoinedRateLimiterLazy = null;

    /**
     * Rate limiter of recording on sound notification.
     */
    private SoundRateLimiter recordingOnRateLimiterLazy = null;

    /**
     * Timeout of rate limiter for participant alone notification.
     */
    private static final long PARTICIPANT_ALONE_TIMEOUT_MS = 15000;

    /**
     * Timeout of rate limiter for participant left notification.
     */
    private static final long PARTICIPANT_LEFT_RATE_TIMEOUT_MS = 30000;

    /**
     * Timeout of rate limiter for recording on.
     */
    private static final long RECORDING_ON_RATE_TIMEOUT_MS = 10000;

    /**
     * Timeout of rate limiter for participant joined notification.
     */
    private static final long PARTICIPANT_JOINED_RATE_TIMEOUT_MS = 30000;

    /**
     * Timer trigger notification when participant is the only one
     * in the conference for a certain amount of time.
     */
    private Timer participantAloneNotificationTimerLazy = null;

    /**
     * Task to trigger notification when participant is the only one
     * in the conference from a certain amount of time.
     */
    private TimerTask participantAloneNotificationTask = null;

    /**
     * To sync schedule and cancel the participant alone notification.
     */
    private final Object participantAloneNotificationSync = new Object();

    /**
     * A queue of files to be played when call is connected.
     */
    private PlaybackQueue playbackQueue = new PlaybackQueue();

    /**
     * Constructs new <tt>SoundNotificationManager</tt>.
     *
     * @param gatewaySession The sip session using this instance.
     */
    public SoundNotificationManager(SipGatewaySession gatewaySession)
    {
        this.gatewaySession = gatewaySession;
    }

    /**
     * Returns the call context for the current session.

     * @return the call context for the current session.
     */
    private CallContext getCallContext()
    {
        return this.gatewaySession.getCallContext();
    }

    /**
     * Processes a member presence change.
     * @param presence the presence to process.
     */
    public void process(Presence presence)
    {
        RecordingStatus rs = presence.getExtension(RecordingStatus.class);

        if (rs != null
            && gatewaySession.getFocusResourceAddr().equals(
                presence.getFrom().getResourceOrEmpty().toString()))
        {
            notifyRecordingStatusChanged(rs.getRecordingMode(), rs.getStatus());
        }
    }

    /**
     * Method called notify that a recording status change was detected.
     *
     * @param mode The recording mode.
     * @param status The recording status.
     */
    private void notifyRecordingStatusChanged(
        JibriIq.RecordingMode mode, JibriIq.Status status)
    {
        // not a change, ignore
        if (currentJibriStatus.equals(status))
        {
            return;
        }
        currentJibriStatus = status;

        String offSound;
        if (mode.equals(JibriIq.RecordingMode.FILE))
        {
            currentJibriOnSound = REC_ON_SOUND;
            offSound = REC_OFF_SOUND;
        }
        else if (mode.equals(JibriIq.RecordingMode.STREAM))
        {
            currentJibriOnSound = LIVE_STREAMING_ON_SOUND;
            offSound = LIVE_STREAMING_OFF_SOUND;
        }
        else
        {
            return;
        }

        try
        {
            if (JibriIq.Status.ON.equals(status) && !getRecordingOnRateLimiter().on())
            {
                playbackQueue.queueNext(gatewaySession.getSipCall(), currentJibriOnSound);
            }
            else if (JibriIq.Status.OFF.equals(status))
            {
                playbackQueue.queueNext(gatewaySession.getSipCall(), offSound);
            }
        }
        catch(InterruptedException ex)
        {
            logger.error(getCallContext() + " Error playing sound notification");
        }
    }

    /**
     * Injects sound file in a call's <tt>MediaStream</tt> using injectPacket
     * method and constructing RTP packets for it.
     * Supports opus only (when using translator mode calls from the jitsi-meet
     * side are using opus and are just translated to the sip side).
     *
     * The file will be played if possible, if there is call passed and that
     * call has call peers of type MediaAwareCallPeer with media handler that
     * has MediaStream for Audio.
     *
     * @param call the call (sip one) to inject the sound as rtp.
     * @param fileName the file name to play.
     */
    public static void injectSoundFile(Call call, String fileName)
    {
        MediaStream stream = getMediaStream(call);

        // if there is no stream or the calling account is not using translator
        // or the current call is not using opus
        if (stream == null
            || !call.getProtocolProvider().getAccountID().getAccountPropertyBoolean(
                    ProtocolProviderFactory.USE_TRANSLATOR_IN_CONFERENCE, false)
            || stream.getDynamicRTPPayloadType(Constants.OPUS) == -1
            || fileName == null)
        {
            return;
        }

        final MediaStream streamToPass = stream;

        try
        {
            injectSoundFileInStream(streamToPass, fileName);
        }
        catch (Throwable t)
        {
            logger.error(call.getData(CallContext.class) + " Error playing:" + fileName, t);
        }
    }

    /**
     * The internal implementation where we read the file and inject it in
     * the stream.
     * @param stream the stream where we inject the sound as rtp.
     * @param fileName the file name to play.
     * @throws Throwable cannot read source sound file or cannot transmit it.
     */
    static void injectSoundFileInStream(MediaStream stream, String fileName)
        throws Throwable
    {
        OpusFile of = new OpusFile(new OggPacketReader(
            Util.class.getClassLoader().getResourceAsStream(fileName)));

        OpusAudioData opusAudioData;
        // Random timestamp, ssrc and seq
        int seq = new Random().nextInt(0xFFFF);
        long ts = new Random().nextInt(0xFFFF);
        long ssrc = new Random().nextInt(0xFFFF);
        byte pt = stream.getDynamicRTPPayloadType(Constants.OPUS);
        long timeForNextPacket = System.currentTimeMillis();
        long sentDuration = 0;

        while ((opusAudioData = of.getNextAudioPacket()) != null)
        {
            // seq may rollover
            if (seq > AbstractCodec2.SEQUENCE_MAX)
            {
                seq = 0;
            }

            int nSamples = opusAudioData.getNumberOfSamples();
            ts += nSamples;
            // timestamp may rollover
            if (ts > TimestampUtils.MAX_TIMESTAMP_VALUE)
            {
                ts = ts - TimestampUtils.MAX_TIMESTAMP_VALUE;
            }

            byte[] data = opusAudioData.getData();
            RawPacket rtp = Util.makeRTP(
                ssrc, // ssrc
                pt, // payload
                seq++, /// seq
                ts, // ts
                data.length + RawPacket.FIXED_HEADER_SIZE// len
            );
            rtp.setSkipStats(true);

            System.arraycopy(
                data, 0, rtp.getBuffer(), rtp.getPayloadOffset(), data.length);
            int duration = nSamples/48;
            timeForNextPacket += duration;
            sentDuration += duration;
            if (stream instanceof MediaStreamImpl)
            {
                ((MediaStreamImpl)stream).injectPacket(rtp, true, null, true);
            }
            else
            {
                stream.injectPacket(rtp, true, null);
            }

            long sleep = timeForNextPacket - System.currentTimeMillis();
            if (sleep > 0 && sentDuration > 200) // we let the first 200ms to be sent without waiting
            {
                Thread.sleep(sleep);
            }
        }
    }

    /**
     * Process call peer state change, if we are going to play a notification
     * we want to return the time in seconds to wait before hanging up the sip
     * side, this is in order to be able to signal a message to the caller.
     *
     * @param callPeerState The call peer state to process.
     */
    public void process(CallPeerState callPeerState)
    {
        long delayedHangupSeconds = -1;

        if (CallPeerState.BUSY.equals(callPeerState))
        {
            // Hangup the call with 5 sec delay, so that we can see BUSY
            // status in jitsi-meet
            delayedHangupSeconds = 5 * 1000;
        }

        // when someone connects and recording is on, play notification
        if (CallPeerState.CONNECTED.equals(callPeerState))
        {
            try
            {
                if (currentJibriStatus.equals(JibriIq.Status.ON) && !getRecordingOnRateLimiter().on())
                {
                    playbackQueue.queueNext(gatewaySession.getSipCall(), currentJibriOnSound);
                }

                if (callMaxOccupantsLimitReached)
                {
                    playbackQueue.queueNext(gatewaySession.getSipCall(), MAX_OCCUPANTS_SOUND);

                    delayedHangupSeconds = MAX_OCCUPANTS_SOUND_DURATION_SEC * 1000;
                }
                else
                {
                    playbackQueue.start();

                    playParticipantJoinedNotification();
                }
            }
            catch(InterruptedException ex)
            {
                logger.error(getCallContext() + " Error playing sound notification");
            }
        }
        else if (CallPeerState.DISCONNECTED.equals(callPeerState))
        {
            playbackQueue.stopAtNextPlayback();
        }

        if (delayedHangupSeconds != -1)
        {
            final long mills = delayedHangupSeconds;
            new Thread(() -> {
                try
                {
                    Thread.sleep(mills);
                }
                catch(InterruptedException e)
                {
                    throw new RuntimeException(e);
                }
                CallManager.hangupCall(gatewaySession.getSipCall());

                if (hangupWait != null)
                    hangupWait.countDown();
            }).start();
        }
    }

    /**
     * Stops playback.
     */
    public void stop()
    {
        this.playbackQueue.stopAtNextPlayback();
    }

    /**
     * We need to play a sound notification that the limit is reached, so we
     * need to answer the call once connected, play the sound and then wait for
     * the hangup before returning.
     */
    public void indicateMaxOccupantsLimitReached()
    {
        callMaxOccupantsLimitReached = true;

        // will wait for answering and then the hangup before returning
        hangupWait = new CountDownLatch(1);

        // answer play and hangup
        try
        {
            CallManager.acceptCall(gatewaySession.getSipCall());
        }
        catch(OperationFailedException e)
        {
            logger.error(getCallContext() + " Cannot answer call to play max occupants sound", e);
            return;
        }

        try
        {
            hangupWait.await(
                MAX_OCCUPANTS_SOUND_DURATION_SEC, TimeUnit.SECONDS);
        }
        catch(InterruptedException e)
        {
            logger.warn(getCallContext() + " Didn't finish waiting for hangup on max occupants");
        }
    }

    /**
     * Schedules a sound notification playback to notify
     * the participant is the only one in the conference.
     */
    private void scheduleAloneNotification(long timeout)
    {
        synchronized(participantAloneNotificationSync)
        {
            this.cancelAloneNotification();

            this.participantAloneNotificationTask
                = new TimerTask()
            {
                @Override
                public void run()
                {
                    try
                    {
                        playParticipantAloneNotification();
                    }
                    catch(Exception ex)
                    {
                        logger.error(getCallContext() + ex.getMessage(), ex);
                    }
                }
            };

            getParticipantAloneNotificationTimer().schedule(this.participantAloneNotificationTask, timeout);
        }
    }

    /**
     * Cancels the participant alone notification.
     */
    private void cancelAloneNotification()
    {
        synchronized(participantAloneNotificationSync)
        {
            if (this.participantAloneNotificationTask != null)
            {
                this.participantAloneNotificationTask.cancel();
            }
        }
    }

    /**
     * Called when no other participant is left in the conference.
     */
    public void onJvbCallEnded()
    {
        scheduleAloneNotification(0);

        if (this.participantJoinedRateLimiterLazy != null)
        {
            this.participantJoinedRateLimiterLazy.reset();
        }

        if (this.participantLeftRateLimiterLazy != null)
        {
            participantLeftRateLimiterLazy.reset();
        }

        if (this.recordingOnRateLimiterLazy != null)
        {
            this.recordingOnRateLimiterLazy.reset();
        }
    }

    /**
     * Called when a new participant has joined the conference.
     *
     * @param member the member who joined the JVB conference.
     */
    public void notifyChatRoomMemberJoined(ChatRoomMember member)
    {
        boolean sendNotification = false;

        Call sipCall = gatewaySession.getSipCall();
        Call jvbCall = gatewaySession.getJvbCall();

        if (sipCall != null)
        {
            sendNotification
                = (sendNotification ||
                    sipCall.getCallState() == CallState.CALL_IN_PROGRESS);
        }

        if (jvbCall != null)
        {
            sendNotification
                = (sendNotification ||
                    jvbCall.getCallState() == CallState.CALL_IN_PROGRESS);
        }

        if (sendNotification)
        {
            playParticipantJoinedNotification();
        }

        this.cancelAloneNotification();
    }

    /**
     * Called when a new participant has left the conference.
     *
     * @param member the member who joined the JVB conference.
     */
    public void notifyChatRoomMemberLeft(ChatRoomMember member)
    {
        // if this is the sip hanging up (stopping) skip playing
        if (gatewaySession.getJvbConference().isStarted()
            && gatewaySession.getSipCall() != null)
        {
            playParticipantLeftNotification();
        }
    }

    /**
     * Called when JVB conference was joined.
     */
    public void notifyJvbRoomJoined()
    {
        int participantCount = gatewaySession.getParticipantsCount();

        if (participantCount <= 2)
        {
            scheduleAloneNotification(PARTICIPANT_ALONE_TIMEOUT_MS);
        }
    }

    /**
     * Tries to play a sound file if connected if not it will be queued.
     *
     * @param fileName The sound file to be played.
     */
    private void playSoundFileIfPossible(String fileName)
    {
        try
        {
            if (gatewaySession.getSipCall() != null)
            {
                if (gatewaySession.getSipCall().getCallState()
                        != CallState.CALL_IN_PROGRESS)
                {
                    // Queue playback of file
                    CallManager.acceptCall(gatewaySession.getSipCall());
                }

                // Hangup in these two cases
                if (fileName.equals(LOBBY_ACCESS_DENIED) || fileName.equals(LOBBY_MEETING_END))
                {
                        playbackQueue.queueNext(
                            gatewaySession.getSipCall(),
                            fileName,
                            () -> {
                                // Hangup
                                CallManager.hangupCall(gatewaySession.getSipCall());
                            });
                }
                else if (fileName.equals(LOBBY_JOIN_REVIEW))
                {
                    playbackQueue.queueNext(
                            gatewaySession.getSipCall(),
                            fileName,
                            () -> gatewaySession.notifyLobbyJoined());
                }
                else
                {
                    playbackQueue.queueNext(gatewaySession.getSipCall(), fileName);
                }
            }
        }
        catch (Exception ex)
        {
            logger.error(getCallContext() + " " + ex.toString(), ex);
        }
    }

    /**
     * Called when the user waits for approval to join.
     */
    public void notifyLobbyWaitReview()
    {
        playSoundFileIfPossible(LOBBY_JOIN_REVIEW);
    }

    /**
     * Called when the user was granted access to JVB conference.
     */
    public void notifyLobbyAccessGranted()
    {
        playSoundFileIfPossible(LOBBY_ACCESS_GRANTED);
    }

    /**
     * Called when the user was denied access to JVB conference.
     */
    public void notifyLobbyAccessDenied()
    {
        playSoundFileIfPossible(LOBBY_ACCESS_DENIED);
    }

    /**
     * Used to notify the user that the main room was destroyed - meetings has ended.
     */
    public void notifyLobbyRoomDestroyed()
    {
        playSoundFileIfPossible(LOBBY_MEETING_END);
    }

    /**
     * Sends sound notification that tells the user
     * is alone in the conference.
     */
    private void playParticipantAloneNotification()
    {
        try
        {
            Call sipCall = gatewaySession.getSipCall();

            if (sipCall != null)
            {
                playbackQueue.queueNext(sipCall, PARTICIPANT_ALONE);

                if (sipCall.getCallState() != CallState.CALL_IN_PROGRESS)
                {
                    CallManager.acceptCall(sipCall);
                }
            }
        }
        catch(Exception ex)
        {
            logger.error(getCallContext() + " " + ex.getMessage(), ex);
        }
    }

    /**
     * Sends sound notification for sip participants if
     * rate limiter allows.
     */
    private void playParticipantLeftNotification()
    {
        try
        {
            if (!getParticipantLeftRateLimiter().on())
            {
                Call sipCall = gatewaySession.getSipCall();

                if (sipCall != null)
                {
                    playbackQueue.queueNext(sipCall, PARTICIPANT_LEFT);
                }
            }
        }
        catch(Exception ex)
        {
            logger.error(getCallContext() + " " + ex.getMessage(), ex);
        }
    }

    /**
     * Sends sound notification for sip participant if
     * rate limiter allows.
     */
    private void playParticipantJoinedNotification()
    {
        try
        {
            this.cancelAloneNotification();

            if (!getParticipantJoinedRateLimiter().on())
            {
                Call sipCall = gatewaySession.getSipCall();

                if (sipCall != null)
                {
                    playbackQueue.queueNext(gatewaySession.getSipCall(), PARTICIPANT_JOINED);
                }
            }
        }
        catch(Exception ex)
        {
            logger.error(getCallContext() + " " + ex.getMessage());
        }
    }

    /**
     * Returns new Timer that will trigger playback for
     * PARTICIPANT_ALONE notification.
     *
     * @return participantAloneNotificationTimerLazy
     */
    private Timer getParticipantAloneNotificationTimer()
    {
        if (this.participantAloneNotificationTimerLazy == null)
        {
            this.participantAloneNotificationTimerLazy
                = new Timer();
        }

        return participantAloneNotificationTimerLazy;
    }

    /**
     * Returns new SoundRateLimiter to be used for participant left
     * if not created already.
     *
     * @return participantLeftRateLimiterLazy
     */
    private SoundRateLimiter getParticipantLeftRateLimiter()
    {
        if (this.participantLeftRateLimiterLazy == null)
        {
            this.participantLeftRateLimiterLazy
                = new SoundRateLimiter(PARTICIPANT_LEFT_RATE_TIMEOUT_MS);
        }

        return this.participantLeftRateLimiterLazy;
    }

    /**
     * Returns new SoundRateLimiter to be used for participant joined
     * if not created already.
     *
     * @return participantJoinedRateLimiterLazy
     */
    private SoundRateLimiter getParticipantJoinedRateLimiter()
    {
        if (this.participantJoinedRateLimiterLazy == null)
        {
            this.participantJoinedRateLimiterLazy
                = new SoundRateLimiter(PARTICIPANT_JOINED_RATE_TIMEOUT_MS);
        }

        return this.participantJoinedRateLimiterLazy;
    }

    /**
     * Returns new SoundRateLimiter to be used for recording on if not created already.
     *
     * @return recordingOnRateLimiterLazy
     */
    private SoundRateLimiter getRecordingOnRateLimiter()
    {
        if (this.recordingOnRateLimiterLazy == null)
        {
            this.recordingOnRateLimiterLazy = new SoundRateLimiter(RECORDING_ON_RATE_TIMEOUT_MS);
        }

        return this.recordingOnRateLimiterLazy;
    }

    /**
     * Extracts MediaStream from call.
     * @param call the call.
     * @return null or <tt>MediaStream</tt> if available.
     */
    static MediaStream getMediaStream(Call call)
    {
        CallPeer peer;
        if (call != null
            && call.getCallPeers() != null
            && call.getCallPeers().hasNext()
            && (peer = call.getCallPeers().next()) != null
            && peer instanceof MediaAwareCallPeer)
        {
            MediaAwareCallPeer peerMedia = (MediaAwareCallPeer) peer;

            CallPeerMediaHandler mediaHandler
                = peerMedia.getMediaHandler();
            if (mediaHandler != null)
            {
                return mediaHandler.getStream(MediaType.AUDIO);
            }
        }

        return null;
    }
}


text:
import graphene

from .....webhook.deprecated_event_types import WebhookEventType
from .....webhook.models import Webhook
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import WebhookEventTypeEnum

WEBHOOK_CREATE_BY_APP = """
    mutation webhookCreate($name: String, $target_url: String,
            $events: [WebhookEventTypeEnum!]){
      webhookCreate(input:{name: $name, targetUrl:$target_url, events:$events}){
        errors{
          field
          message
        }
        webhook{
          id
        }
      }
    }
"""

def test_webhook_create_by_app(app_api_client, permission_manage_orders):
    query = WEBHOOK_CREATE_BY_APP
    variables = {
        "name": "New integration",
        "target_url": "https://www.example.com",
        "events": [
            WebhookEventTypeEnum.ORDER_CREATED.name,
            WebhookEventTypeEnum.ORDER_CREATED.name,
        ],
    }
    response = app_api_client.post_graphql(
        query,
        variables=variables,
        permissions=[permission_manage_orders],
        check_no_permissions=False,
    )
    get_graphql_content(response)
    new_webhook = Webhook.objects.get()
    assert new_webhook.name == "New integration"
    assert new_webhook.target_url == "https://www.example.com"
    events = new_webhook.events.all()
    assert len(events) == 1
    assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.value

def test_webhook_create_inactive_app(app_api_client, app, permission_manage_orders):
    app.is_active = False
    app.save()
    query = WEBHOOK_CREATE_BY_APP
    variables = {
        "target_url": "https://www.example.com",
        "events": [WebhookEventTypeEnum.ORDER_CREATED.name],
        "name": "",
    }

    response = app_api_client.post_graphql(
        query, variables=variables, permissions=[permission_manage_orders]
    )
    assert_no_permission(response)

def test_webhook_create_without_app(app_api_client, app):
    app_api_client.app = None
    app_api_client.app_token = None
    query = WEBHOOK_CREATE_BY_APP
    variables = {
        "target_url": "https://www.example.com",
        "events": [WebhookEventTypeEnum.ORDER_CREATED.name],
        "name": "",
    }
    response = app_api_client.post_graphql(query, variables=variables)
    assert_no_permission(response)

def test_webhook_create_app_doesnt_exist(app_api_client, app):
    app.delete()

    query = WEBHOOK_CREATE_BY_APP
    variables = {
        "target_url": "https://www.example.com",
        "events": [WebhookEventTypeEnum.ORDER_CREATED.name],
        "name": "",
    }
    response = app_api_client.post_graphql(query, variables=variables)
    assert_no_permission(response)

WEBHOOK_CREATE_BY_STAFF = """
    mutation webhookCreate(
        $target_url: String, $events: [WebhookEventTypeEnum!], $app: ID){
      webhookCreate(input:{
            targetUrl:$target_url, events:$events, app: $app}){
        errors{
          field
          message
        }
        webhook{
          id
        }
      }
    }
"""

def test_webhook_create_by_staff(
    staff_api_client,
    app,
    permission_manage_apps,
    permission_manage_orders,
):
    query = WEBHOOK_CREATE_BY_STAFF
    app.permissions.add(permission_manage_orders)
    app_id = graphene.Node.to_global_id("App", app.pk)
    variables = {
        "target_url": "https://www.example.com",
        "events": [WebhookEventTypeEnum.ORDER_CREATED.name],
        "app": app_id,
    }
    staff_api_client.user.user_permissions.add(permission_manage_apps)
    response = staff_api_client.post_graphql(query, variables=variables)
    get_graphql_content(response)
    new_webhook = Webhook.objects.get()
    assert new_webhook.target_url == "https://www.example.com"
    assert new_webhook.app == app
    events = new_webhook.events.all()
    assert len(events) == 1
    assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.value

def test_webhook_create_by_staff_with_inactive_app(staff_api_client, app):
    app.is_active = False
    query = WEBHOOK_CREATE_BY_STAFF
    app_id = graphene.Node.to_global_id("App", app.pk)
    variables = {
        "target_url": "https://www.example.com",
        "events": [WebhookEventTypeEnum.ORDER_CREATED.name],
        "app": app_id,
    }
    response = staff_api_client.post_graphql(query, variables=variables)
    assert_no_permission(response)
    assert Webhook.objects.count() == 0

def test_webhook_create_by_staff_without_permission(staff_api_client, app):
    query = WEBHOOK_CREATE_BY_STAFF
    app_id = graphene.Node.to_global_id("App", app.pk)
    variables = {
        "target_url": "https://www.example.com",
        "events": [WebhookEventTypeEnum.ORDER_CREATED.name],
        "app": app_id,
    }
    response = staff_api_client.post_graphql(query, variables=variables)
    assert_no_permission(response)
    assert Webhook.objects.count() == 0

WEBHOOK_UPDATE = """
    mutation webhookUpdate(
        $id: ID!, $events: [WebhookEventTypeEnum!], $is_active: Boolean){
      webhookUpdate(id: $id, input:{events: $events, isActive: $is_active}){
        errors{
          field
          message
        }
        webhook{
          events{
            eventType
          }
          isActive
        }
      }
    }
"""

def test_webhook_update_not_allowed_by_app(app_api_client, app, webhook):
    query = WEBHOOK_UPDATE
    webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
    variables = {
        "id": webhook_id,
        "events": [WebhookEventTypeEnum.ORDER_CREATED.name],
        "is_active": False,
    }
    response = app_api_client.post_graphql(query, variables=variables)
    assert_no_permission(response)

def test_webhook_update_by_staff(
    staff_api_client, app, webhook, permission_manage_apps
):
    query = WEBHOOK_UPDATE
    webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
    variables = {
        "id": webhook_id,
        "events": [
            WebhookEventTypeEnum.CUSTOMER_CREATED.name,
            WebhookEventTypeEnum.CUSTOMER_CREATED.name,
        ],
        "is_active": False,
    }
    staff_api_client.user.user_permissions.add(permission_manage_apps)
    response = staff_api_client.post_graphql(query, variables=variables)
    get_graphql_content(response)
    webhook.refresh_from_db()
    assert webhook.is_active is False
    events = webhook.events.all()
    assert len(events) == 1
    assert events[0].event_type == WebhookEventTypeEnum.CUSTOMER_CREATED.value

def test_webhook_update_by_staff_without_permission(staff_api_client, app, webhook):
    query = WEBHOOK_UPDATE
    webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
    variables = {
        "id": webhook_id,
        "events": [
            WebhookEventTypeEnum.ORDER_CREATED.name,
            WebhookEventTypeEnum.CUSTOMER_CREATED.name,
        ],
        "is_active": False,
    }
    response = staff_api_client.post_graphql(query, variables=variables)
    assert_no_permission(response)

QUERY_WEBHOOK = """
    query webhook($id: ID!){
      webhook(id: $id){
        id
        isActive
        events{
          eventType
        }
      }
    }
"""

def test_query_webhook_by_staff(staff_api_client, webhook, permission_manage_apps):
    query = QUERY_WEBHOOK

    webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
    variables = {"id": webhook_id}
    staff_api_client.user.user_permissions.add(permission_manage_apps)
    response = staff_api_client.post_graphql(query, variables=variables)

    content = get_graphql_content(response)
    webhook_response = content["data"]["webhook"]
    assert webhook_response["id"] == webhook_id
    assert webhook_response["isActive"] == webhook.is_active
    events = webhook.events.all()
    assert len(events) == 1
    assert events[0].event_type == WebhookEventTypeEnum.ORDER_CREATED.value

WEBHOOK_EVENTS_QUERY = """
{
  webhookEvents {
    eventType
    name
  }
}
"""

def test_query_webhook_events(staff_api_client, permission_manage_apps):
    query = WEBHOOK_EVENTS_QUERY
    staff_api_client.user.user_permissions.add(permission_manage_apps)
    response = staff_api_client.post_graphql(query)
    content = get_graphql_content(response)
    webhook_events = content["data"]["webhookEvents"]
    assert len(webhook_events) == len(WebhookEventType.CHOICES)

def test_query_webhook_events_without_permissions(staff_api_client):
    query = WEBHOOK_EVENTS_QUERY
    response = staff_api_client.post_graphql(query)
    assert_no_permission(response)


text:
import React from 'react';
import { components } from 'react-select';
import Cross from '@strapi/icons/Cross';
import IconBox from './IconBox';

const ClearIndicator = props => {
  const Component = components.ClearIndicator;

  return (
    <Component {...props}>
      <IconBox as="button" type="button">
        <Cross />
      </IconBox>
    </Component>
  );
};

export default ClearIndicator;


text:
package ru.job4j.tracker;

/**
 * Created by Екатерина on 13.08.2017.
 */
public class ValidateInput {
}


text:
package org.basex.query.func.fn;

import org.basex.query.*;
import org.basex.query.iter.*;
import org.basex.query.value.item.*;
import org.basex.util.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 */
public final class FnAvg extends Aggr {
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    final Iter iter = exprs[0].atomIter(qc, ii);
    final Item it = iter.next();
    return it == null ? null : sum(iter, it, true);
  }
}


text:
<?php

if (!class_exists('Sprout_Nav')) {

	class Sprout_Nav extends Sprout_Module {

		protected function __construct() {

		}

		public function init() {

			register_nav_menus(array(
				'primary_navigation' => __('Primary Navigation', 'sprout'),
			));

			$this->register_hooks();

		}

		public function register_hooks() {

			add_filter('nav_menu_css_class', array ($this, 'nav_menu_css_class'), 10, 2);
			add_filter('nav_menu_item_id', '__return_null');
			add_filter('wp_nav_menu_args', array ($this, 'nav_menu_args'));

		}

		/**
		 * Clean menu classes
		 */
		public function nav_menu_css_class($classes, $item) {

			$slug = sanitize_title($item->title);
			$classes = preg_replace('/(current(-menu-|[-_]page[-_])(item|parent|ancestor))/', 'current', $classes);
			$classes = preg_replace('/^((menu|page)[-_\w+]+)+/', '', $classes);

			$classes[] = 'menu-' . $slug;

			$classes = array_filter(array_map('trim', array_unique($classes)));

			return $classes;

		}

		/**
		 * Clean up wp_nav_menu_args
		 *
		 * Remove the container
		 * Use Sprout_Nav_Walker by default
		 */
		public function nav_menu_args($args = '') {

			$sprout_nav_menu_args['container'] = false;

			if (!$args['items_wrap']) {
				$sprout_nav_menu_args['items_wrap'] = '
%3$s
';
			}

			if (!$args['walker']) {
				$sprout_nav_menu_args['walker'] = new Sprout_Nav_Walker();
			}

			return array_merge($args, $sprout_nav_menu_args);

		}

	}

	Sprout::add_module('Sprout_Nav', 'nav');

}

?>


text:
package gcp

import (
	"context"
	"path/filepath"
	"testing"

	"github.com/golang/glog"
	"github.com/google/hashr/common"
	"google.golang.org/api/option"
	"google.golang.org/grpc"

	"cloud.google.com/go/spanner"
	database "cloud.google.com/go/spanner/admin/database/apiv1"
	instance "cloud.google.com/go/spanner/admin/instance/apiv1"

	dbadminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1"
	instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1"
)

const (
	samplesTable = `
	CREATE TABLE samples (
		sha256 STRING(100),
		mimetype STRING(MAX),
		file_output  STRING(MAX),
		size INT64
	) PRIMARY KEY(sha256)`

	payloadsTable = `
	CREATE TABLE payloads (
		sha256 STRING(100),
		gcs_path STRING(200)
	) PRIMARY KEY(sha256)`

	sourcesTable = `
	CREATE TABLE sources (
		sha256 STRING(100),
        source_id  ARRAY<STRING(MAX)>,
        source_path STRING(MAX),
        source_description STRING(MAX),
        repo_name STRING(MAX),
        repo_path STRING(MAX),
	) PRIMARY KEY(sha256)`

	samplesSourcesTable = `CREATE TABLE samples_sources (
		sample_sha256 STRING(100),
		source_sha256 STRING(100),
		sample_paths ARRAY<STRING(MAX)>,
		CONSTRAINT FK_Sample FOREIGN KEY (sample_sha256) REFERENCES samples (sha256),
		CONSTRAINT FK_Source FOREIGN KEY (source_sha256) REFERENCES sources (sha256),
	)  PRIMARY KEY (sample_sha256, source_sha256)`
)

func TestExport(t *testing.T) {
	ctx := context.Background()

	o := []option.ClientOption{
		option.WithEndpoint("localhost:9010"),
		option.WithoutAuthentication(),
		option.WithGRPCDialOption(grpc.WithInsecure()),
	}

	instanceAdmin, err := instance.NewInstanceAdminClient(ctx, o...)
	if err != nil {
		glog.Fatalf("error dialing instance admin: %v", err)
	}
	defer instanceAdmin.Close()

	if err := instanceAdmin.DeleteInstance(ctx, &instancepb.DeleteInstanceRequest{Name: "projects/hashr/instances/hashr"}); err != nil {
		glog.Warning(err)
	}

	op, err := instanceAdmin.CreateInstance(ctx, &instancepb.CreateInstanceRequest{
		Parent:     "projects/hashr",
		InstanceId: "hashr",
		Instance: &instancepb.Instance{
			DisplayName: "hashr",
			NodeCount:   1,
		},
	})
	if err != nil {
		glog.Fatalf("error creating test spanner instance: %v", err)
	}
	if _, err := op.Wait(ctx); err != nil {
		glog.Fatalf("error creating test spanner instance: %v", err)
	}

	databaseAdmin, err := database.NewDatabaseAdminClient(ctx, o...)
	if err != nil {
		glog.Fatalf("error creating database admin client for emulator: %v", err)
	}

	dbURI := "projects/hashr/instances/hashr/databases/hashr"
	op2, err := databaseAdmin.CreateDatabase(ctx, &dbadminpb.CreateDatabaseRequest{
		Parent:          "projects/hashr/instances/hashr",
		CreateStatement: "CREATE DATABASE hashr",
		ExtraStatements: []string{samplesTable, sourcesTable, payloadsTable, samplesSourcesTable},
	})
	if err != nil {
		glog.Fatalf("error creating test DB %v: %v", dbURI, err)
	}
	if _, err = op2.Wait(ctx); err != nil {
		glog.Fatalf("error creating test DB %v: %v", dbURI, err)
	}

	spannerClient, err := spanner.NewClient(ctx, dbURI, o...)
	if err != nil {
		glog.Fatalf("error creating Spanner client %v: %v", dbURI, err)
	}

	exporter, err := NewExporter(spannerClient, nil, "gcs-bucket", false, 10)
	if err != nil {
		glog.Fatalf("error creating Cloud Spanner exporter: %v", err)
	}

	samples := []common.Sample{
		{
			Sha256: "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
			Paths:  []string{filepath.Join("testdata/extraction", "file.01")},
			Upload: true,
		},
		{
			Sha256: "5c7a0f6e38f86f4db12130e5ca9f734f4def519b9a884ee8ea9fc45f9626c6fb",
			Paths:  []string{filepath.Join("testdata/extraction", "file.02")},
			Upload: true,
		},
		{
			Sha256: "9ad2027cae0d7b0f041a6fc1e3124ad4046b2665068c44c74546ad9811e81ec7",
			Paths:  []string{filepath.Join("testdata/extraction", "file.03")},
			Upload: true,
		},
	}

	if err := exporter.Export(ctx, "GCP", "ubuntu", "ubuntu-1604-lts", "07123e1f482356c415f684407a3b8723e10b2cbbc0b8fcd6282c49d37c9c1abc", "", "Official Ubuntu GCP image.", samples); err != nil {
		t.Fatalf("unexpected error while running Export() = %v", err)
	}

}


text:
<ng-select
  [ngClass]="{'max-select-one': maxSelectedItems === 1 && ngSelectSelected.length}"
  [items]="ngSelectOptions"
  [multiple]="!single"
  [closeOnSelect]="single || closeOnSelect"
  [maxSelectedItems]="maxSelectedItems"
  [searchable]="searchable"
  [disabled]="disabled"
  [clearable]="clearable"
  bindLabel="name"
  bindValue="value"
  [placeholder]="placeholder"
  [(ngModel)]="ngSelectSelected"
  (change)="onChange()">
</ng-select>


text:
package edu.ucdenver.ccp.datasource.rdfizer.rdf.ice;

import edu.ucdenver.ccp.datasource.fileparsers.idlist.IdListFileFactory;

public class FileDataSourceParams {

	public static enum RequiresManualDownload {
		YES, NO
	}

	public static enum IsTaxonAware {
		YES,
		/**
		 * In this case, the data source can be made taxon-aware by providing
		 * mappings from identifiers (gene/protein) to taxon IDs. These mappings
		 * usually take the for of ID list files generated by
		 * {@link IdListFileFactory}
		 */
		YES_BUT_REQUIRES_EXTERNAL_ID_TO_TAXON_MAPPINGS,
		NO
	}

}