text:
package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ExecutionType;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.security.ContainerTokenIdentifier;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;

import java.util.List;

import static org.mockito.Mockito.*;

/**
 * Unit test for CGroupsMemoryResourceHandlerImpl.
 */
public class TestCGroupsMemoryResourceHandlerImpl {

  private CGroupsHandler mockCGroupsHandler;
  private CGroupsMemoryResourceHandlerImpl cGroupsMemoryResourceHandler;

  @Before
  public void setup() {
    mockCGroupsHandler = mock(CGroupsHandler.class);
    cGroupsMemoryResourceHandler =
        new CGroupsMemoryResourceHandlerImpl(mockCGroupsHandler);
  }

  @Test
  public void testBootstrap() throws Exception {
    Configuration conf = new YarnConfiguration();
    conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
    conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);
    List<PrivilegedOperation> ret =
        cGroupsMemoryResourceHandler.bootstrap(conf);
    verify(mockCGroupsHandler, times(1))
        .initializeCGroupController(CGroupsHandler.CGroupController.MEMORY);
    Assert.assertNull(ret);
    Assert.assertEquals("Default swappiness value incorrect", 0,
        cGroupsMemoryResourceHandler.getSwappiness());
    conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, true);
    try {
      cGroupsMemoryResourceHandler.bootstrap(conf);
      Assert.fail("Pmem check should not be allowed to run with cgroups");
    } catch(ResourceHandlerException re) {
      // do nothing
    }
    conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
    conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, true);
    try {
      cGroupsMemoryResourceHandler.bootstrap(conf);
      Assert.fail("Vmem check should not be allowed to run with cgroups");
    } catch(ResourceHandlerException re) {
      // do nothing
    }
  }

  @Test
  public void testSwappinessValues() throws Exception {
    Configuration conf = new YarnConfiguration();
    conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
    conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);
    conf.setInt(YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS, -1);
    try {
      cGroupsMemoryResourceHandler.bootstrap(conf);
      Assert.fail("Negative values for swappiness should not be allowed.");
    } catch (ResourceHandlerException re) {
      // do nothing
    }
    try {
      conf.setInt(YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS, 101);
      cGroupsMemoryResourceHandler.bootstrap(conf);
      Assert.fail("Values greater than 100 for swappiness"
          + " should not be allowed.");
    } catch (ResourceHandlerException re) {
      // do nothing
    }
    conf.setInt(YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS, 60);
    cGroupsMemoryResourceHandler.bootstrap(conf);
    Assert.assertEquals("Swappiness value incorrect", 60,
        cGroupsMemoryResourceHandler.getSwappiness());
  }

  @Test
  public void testPreStart() throws Exception {
    Configuration conf = new Configuration();
    conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
    conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);
    cGroupsMemoryResourceHandler.bootstrap(conf);
    String id = "container_01_01";
    String path = "test-path/" + id;
    ContainerId mockContainerId = mock(ContainerId.class);
    when(mockContainerId.toString()).thenReturn(id);
    Container mockContainer = mock(Container.class);
    when(mockContainer.getContainerId()).thenReturn(mockContainerId);
    when(mockCGroupsHandler
        .getPathForCGroupTasks(CGroupsHandler.CGroupController.MEMORY, id))
        .thenReturn(path);
    int memory = 1024;
    when(mockContainer.getResource())
        .thenReturn(Resource.newInstance(memory, 1));
    List<PrivilegedOperation> ret =
        cGroupsMemoryResourceHandler.preStart(mockContainer);
    verify(mockCGroupsHandler, times(1))
        .createCGroup(CGroupsHandler.CGroupController.MEMORY, id);
    verify(mockCGroupsHandler, times(1))
        .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
            CGroupsHandler.CGROUP_PARAM_MEMORY_HARD_LIMIT_BYTES,
            String.valueOf(memory) + "M");
    verify(mockCGroupsHandler, times(1))
        .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
            CGroupsHandler.CGROUP_PARAM_MEMORY_SOFT_LIMIT_BYTES,
            String.valueOf((int) (memory * 0.9)) + "M");
    verify(mockCGroupsHandler, times(1))
        .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
            CGroupsHandler.CGROUP_PARAM_MEMORY_SWAPPINESS, String.valueOf(0));
    Assert.assertNotNull(ret);
    Assert.assertEquals(1, ret.size());
    PrivilegedOperation op = ret.get(0);
    Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
        op.getOperationType());
    List<String> args = op.getArguments();
    Assert.assertEquals(1, args.size());
    Assert.assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
        args.get(0));
  }

  @Test
  public void testReacquireContainer() throws Exception {
    ContainerId containerIdMock = mock(ContainerId.class);
    Assert.assertNull(
        cGroupsMemoryResourceHandler.reacquireContainer(containerIdMock));
  }

  @Test
  public void testPostComplete() throws Exception {
    String id = "container_01_01";
    ContainerId mockContainerId = mock(ContainerId.class);
    when(mockContainerId.toString()).thenReturn(id);
    Assert
        .assertNull(cGroupsMemoryResourceHandler.postComplete(mockContainerId));
    verify(mockCGroupsHandler, times(1))
        .deleteCGroup(CGroupsHandler.CGroupController.MEMORY, id);
  }

  @Test
  public void testTeardown() throws Exception {
    Assert.assertNull(cGroupsMemoryResourceHandler.teardown());
  }

  @Test
  public void testOpportunistic() throws Exception {
    Configuration conf = new YarnConfiguration();
    conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
    conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);

    cGroupsMemoryResourceHandler.bootstrap(conf);
    ContainerTokenIdentifier tokenId = mock(ContainerTokenIdentifier.class);
    when(tokenId.getExecutionType()).thenReturn(ExecutionType.OPPORTUNISTIC);
    Container container = mock(Container.class);
    String id = "container_01_01";
    ContainerId mockContainerId = mock(ContainerId.class);
    when(mockContainerId.toString()).thenReturn(id);
    when(container.getContainerId()).thenReturn(mockContainerId);
    when(container.getContainerTokenIdentifier()).thenReturn(tokenId);
    when(container.getResource()).thenReturn(Resource.newInstance(1024, 2));
    cGroupsMemoryResourceHandler.preStart(container);
    verify(mockCGroupsHandler, times(1))
        .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
            CGroupsHandler.CGROUP_PARAM_MEMORY_SOFT_LIMIT_BYTES, "0M");
    verify(mockCGroupsHandler, times(1))
        .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
            CGroupsHandler.CGROUP_PARAM_MEMORY_SWAPPINESS, "100");
    verify(mockCGroupsHandler, times(1))
        .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
            CGroupsHandler.CGROUP_PARAM_MEMORY_HARD_LIMIT_BYTES, "1024M");
  }
}


text:
<?php

namespace Symplify\EasyCodingStandard\Tests\Skipper\Only\Source;

abstract class SomeFileToOnlyInclude
{
}

redpajama_set_name: RedPajamaGithub


text:
from setuptools import setup

VERSION = '0.1'

setup(name='cgi_wsgi',
      version=VERSION,
      description='A CGI-like http interface for WSGI (for educational purposes only)',
      url='http://github.com/red56/cgi_wsgi',
      download_url="https://github.com/red56/cgi_wsgi/tarball/v%s" % VERSION,
      author='Tim Diggins',
      author_email='tim@red56.co.uk',
      license='MIT',
      packages=['cgi_wsgi'],
      zip_safe=False,
      test_suite='nose.collector',
      tests_require=['nose', 'WebTest'],
)


text:
bestcmsever
===========

The best CMS ever!


text:
using Autofac;
using VMLab.Graph;
using Action = VMLab.Graph.Action;

namespace VMLab.IOC
{
    public class GraphModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<GraphManager>().AsImplementedInterfaces().SingleInstance();
            builder.RegisterType<GraphValidator>().AsImplementedInterfaces();

            builder.RegisterType<Action>().AsSelf();
            builder.RegisterType<Credential>().AsSelf();
            builder.RegisterType<CredentialSet>().AsSelf();
            builder.RegisterType<Network>().AsSelf();
            builder.RegisterType<SharedFolder>().AsSelf();
            builder.RegisterType<Template>().AsSelf();
            builder.RegisterType<VM>().AsSelf();
        }
    }
}


text:
package pixlepix.auracascade.block;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import pixlepix.auracascade.AuraCascade;
import pixlepix.auracascade.data.recipe.ProcessorRecipe;
import pixlepix.auracascade.lexicon.page.PageCraftingRecipe;
import pixlepix.auracascade.registry.BlockRegistry;
import pixlepix.auracascade.registry.ITTinkererBlock;
import pixlepix.auracascade.registry.ThaumicTinkererRecipe;
import pixlepix.auracascade.registry.ThaumicTinkererRecipeMulti;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by localmacaccount on 6/5/15.
 */
public class BlockExplosionContainer extends Block implements ITTinkererBlock {

    public String type;

    public BlockExplosionContainer() {
        super(Material.rock);
        //Same as obby
        setResistance(2000F);
        type = "Dirt";
        setTickRandomly(true);
        setHardness(2F);
    }

    public BlockExplosionContainer(String s) {
        this();
        type = s;
        if (type.equals("Glass")) {
            //setLightLevel(15);
            setLightOpacity(1);
        }
    }

    public static BlockExplosionContainer getBlockFromName(String name) {
        List<Block> blockList = BlockRegistry.getBlockFromClass(BlockExplosionContainer.class);
        for (Block b : blockList) {
            if (((BlockExplosionContainer) b).type != null && ((BlockExplosionContainer) b).type.equals(name)) {
                return (BlockExplosionContainer) b;
            }
        }
        return null;
    }

    public static PageCraftingRecipe getRecipe(String unloc, String name) {
        return new PageCraftingRecipe(unloc, BlockRegistry.getRecipe(getBlockFromName(name)));
    }

    @Override
    public int onBlockPlaced(World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int meta) {
        super.onBlockPlaced(world, x, y, z, side, hitX, hitY, hitZ, meta);
        world.scheduleBlockUpdate(x, y, z, this, tickRate(world));
        return meta;
    }

    @Override
    public int tickRate(World world) {
        return 100;
    }

    @Override
    public void updateTick(World world, int x, int y, int z, Random rand) {
        super.updateTick(world, x, y, z, rand);
        if (rand.nextDouble() < getChanceToRepair()) {
            int meta = world.getBlockMetadata(x, y, z);
            if (meta > 0) {
                world.setBlockMetadataWithNotify(x, y, z, meta - 1, 3);

            }
        }
        world.scheduleBlockUpdate(x, y, z, this, tickRate(world) + rand.nextInt(5));
    }

    /**
     * Determines if this block should render in this pass.
     *
     * @param pass The pass in question
     * @return True to render
     */
    @Override
    public boolean canRenderInPass(int pass) {
        AuraCascade.proxy.renderPass = pass;
        return true;
    }

    /**
     * If this block doesn't render as an ordinary block it will return False (examples: signs, buttons, stairs, etc)
     */
    @Override
    public boolean renderAsNormalBlock() {
        return isOpaqueCube();
    }

    public double getChanceToResist() {
        return 1 - (1 / (getVirtualHealth() / 16D));
    }

    public double getChanceToRepair() {
        return 1 / (getRepairSeconds() / 5D);
    }

    public int getRepairSeconds() {
        if (type.equals("Dirt")) {
            return 120;
        }
        if (type.equals("Wood")) {
            return 5;
        }
        if (type.equals("Glass")) {
            return 120;
        }
        if (type.equals("Cobblestone")) {
            return 30;
        }
        if (type.equals("Stone")) {
            return 60;
        }
        //10m
        if (type.equals("Obsidian")) {
            return 6000;
        }
        return 0;
    }

    public int getVirtualHealth() {
        if (type.equals("Dirt")) {
            return 50;
        }
        if (type.equals("Wood")) {
            return 30;
        }
        if (type.equals("Glass")) {
            return 16;
        }
        if (type.equals("Cobblestone")) {
            return 75;
        }
        if (type.equals("Stone")) {
            return 100;
        }
        if (type.equals("Obsidian")) {
            return 1600;
        }
        return 0;

    }

    @Override
    public void registerBlockIcons(IIconRegister register) {
        blockIcon = register.registerIcon("aura:fortified" + type);
    }

    @Override
    public ArrayList<Object> getSpecialParameters() {
        // TODO Auto-generated method stub
        ArrayList result = new ArrayList<Object>();
        result.add("Wood");
        result.add("Glass");
        result.add("Cobblestone");
        result.add("Stone");
        result.add("Obsidian");
        return result;
    }

    @SideOnly(Side.CLIENT)
    public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) {
        if (!type.equals("Glass")) {
            return true;
        }
        Block block = world.getBlock(x, y, z);
        return block != this;
    }

    /**
     * Returns which pass should this block be rendered on. 0 for solids and 1 for alpha
     */
    @Override
    public int getRenderBlockPass() {
        return 1;
    }

    @Override
    public String getBlockName() {
        return "fortified" + type;
    }

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

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

    /**
     * Gets the block's texture. Args: side, meta
     *
     * @param side
     * @param meta
     */
    @Override
    public IIcon getIcon(int side, int meta) {

        return blockIcon;
    }

    @Override
    public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) {
        int meta = world.getBlockMetadata(x, y, z);
        if (AuraCascade.proxy.renderPass == 1) {
            if (meta != 0) {
                return AuraCascade.proxy.breakingIcons[getCrackedStage(meta)];
            } else {
                return AuraCascade.proxy.blankIcon;
            }
        }
        return blockIcon;
    }

    public int getCrackedStage(int meta) {
        if (meta <= 5) {
            return meta - 1;
        } else {
            return (int) (4 + Math.ceil((meta - 5) / 2));
        }

    }

    @Override
    public Class<? extends ItemBlock> getItemBlock() {
        return null;
    }

    @Override
    public Class<? extends TileEntity> getTileEntity() {
        return null;
    }

    /**
     * Is this block (a) opaque and (b) a full 1m cube?  This determines whether or not to render the shared face of two
     * adjacent blocks and also whether the player can attach torches, redstone wire, etc to this block.
     */
    @Override
    public boolean isOpaqueCube() {
        return type == null || !type.equals("Glass");
    }

    @Override
    public ThaumicTinkererRecipe getRecipeItem() {
        if (type.equals("Dirt")) {
            return new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.dirt));
        }
        if (type.equals("Wood")) {
            return new ThaumicTinkererRecipeMulti(new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.planks)),
                    new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.planks, 1, 1)),
                    new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.planks, 1, 2)),
                    new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.planks, 1, 3)),
                    new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.planks, 1, 4)),
                    new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.planks, 1, 5)));
        }
        if (type.equals("Glass")) {
            return new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.glass));
        }
        if (type.equals("Cobblestone")) {
            return new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.cobblestone));
        }
        if (type.equals("Stone")) {
            return new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.stone));
        }
        if (type.equals("Obsidian")) {
            return new ProcessorRecipe(new ItemStack(this), false, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.obsidian));
        }
        return null;
    }

    @Override
    public int getCreativeTabPriority() {
        return 23;
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using System.Reflection;
using Microsoft.Build.Shared.FileSystem;

#nullable disable

namespace Microsoft.Build.Tasks
{
    /// <summary>
    /// Take suggested redirects (from the ResolveAssemblyReference and GenerateOutOfBandAssemblyTables tasks)
    /// and add them to an intermediate copy of the App.config file.
    /// </summary>
    public class GenerateBindingRedirects : TaskExtension
    {
        // <param name="SuggestedRedirects">RAR suggested binding redirects.</param>
        // <param name="AppConfigFile">The source App.Config file.</param>
        // <param name="TargetName">The name of the target app config file: XXX.exe.config.</param>
        // <param name="OutputAppConfigFile">The output App.Config file.</param>
        // <returns>True if there was success.</returns>

        /// <summary>
        /// Sugested redirects as output from the ResolveAssemblyReference task.
        /// </summary>
        public ITaskItem[] SuggestedRedirects { get; set; }

        /// <summary>
        /// Path to the app.config source file.
        /// </summary>
        public ITaskItem AppConfigFile { get; set; }

        /// <summary>
        /// Name of the output application config file: $(TargetFileName).config
        /// </summary>
        public string TargetName { get; set; }

        /// <summary>
        /// Path to an intermediate file where we can write the input app.config plus the generated binding redirects.
        /// </summary>
        [Output]
        public ITaskItem OutputAppConfigFile { get; set; }

        /// <summary>
        /// Execute the task.
        /// </summary>
        public override bool Execute()
        {
            if (SuggestedRedirects == null || SuggestedRedirects.Length == 0)
            {
                Log.LogMessageFromResources("GenerateBindingRedirects.NoSuggestedRedirects");
                OutputAppConfigFile = null;
                return true;
            }

            var redirects = ParseSuggestedRedirects();

            var doc = LoadAppConfig(AppConfigFile);

            if (doc == null)
            {
                return false;
            }

            XElement runtimeNode = doc.Root
                                      .Nodes()
                                      .OfType<XElement>()
                                      .FirstOrDefault(e => e.Name.LocalName == "runtime");

            if (runtimeNode == null)
            {
                runtimeNode = new XElement("runtime");
                doc.Root.Add(runtimeNode);
            }
            else
            {
                UpdateExistingBindingRedirects(runtimeNode, redirects);
            }

            var ns = XNamespace.Get("urn:schemas-microsoft-com:asm.v1");

            var redirectNodes = from redirect in redirects
                                select new XElement(
                                    ns + "assemblyBinding",
                                    new XElement(
                                        ns + "dependentAssembly",
                                        new XElement(
                                            ns + "assemblyIdentity",
                                            new XAttribute("name", redirect.Key.Name),
                                            new XAttribute("publicKeyToken", ResolveAssemblyReference.ByteArrayToString(redirect.Key.GetPublicKeyToken())),
                                            new XAttribute("culture", String.IsNullOrEmpty(redirect.Key.CultureName) ? "neutral" : redirect.Key.CultureName)),
                                        new XElement(
                                            ns + "bindingRedirect",
                                            new XAttribute("oldVersion", "0.0.0.0-" + redirect.Value),
                                            new XAttribute("newVersion", redirect.Value))));

            runtimeNode.Add(redirectNodes);

            var writeOutput = true;

            if (FileSystems.Default.FileExists(OutputAppConfigFile.ItemSpec))
            {
                try
                {
                    var outputDoc = LoadAppConfig(OutputAppConfigFile);
                    if (outputDoc.ToString() == doc.ToString())
                    {
                        writeOutput = false;
                    }
                }
                catch(System.Xml.XmlException)
                {
                    writeOutput = true;
                }
            }

            if (AppConfigFile != null)
            {
                AppConfigFile.CopyMetadataTo(OutputAppConfigFile);
            }
            else
            {
                OutputAppConfigFile.SetMetadata(ItemMetadataNames.targetPath, TargetName);
            }

            if (writeOutput)
            {
                using (var stream = FileUtilities.OpenWrite(OutputAppConfigFile.ItemSpec, false))
                {
                    doc.Save(stream);
                }
            }

            return !Log.HasLoggedErrors;
        }

        /// <summary>
        /// Determins whether the name, culture, and public key token of the given assembly name "suggestedRedirect"
        /// matches the name, culture, and publicKeyToken strings.
        /// </summary>
        private static bool IsMatch(AssemblyName suggestedRedirect, string name, string culture, string publicKeyToken)
        {
            if (!String.Equals(suggestedRedirect.Name, name, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            if (ByteArrayMatchesString(suggestedRedirect.GetPublicKeyToken(), publicKeyToken))
            {
                return false;
            }

            // The binding redirect will be applied if the culture is missing from the "assemblyIdentity" node.
            // So we consider it a match if the existing binding redirect doesn't have culture specified.
            var cultureString = suggestedRedirect.CultureName;
            if (String.IsNullOrEmpty(cultureString))
            {
                // We use "neutral" for "Invariant Language (Invariant Country)" in assembly names.
                cultureString = "neutral";
            }

            if (!String.IsNullOrEmpty(culture) &&
                !String.Equals(cultureString, culture, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Determines whether string "s" is the hexdecimal representation of the byte array "a".
        /// </summary>
        private static bool ByteArrayMatchesString(Byte[] a, string s)
        {
            return !String.Equals(ResolveAssemblyReference.ByteArrayToString(a), s, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// Going through all the binding redirects in the runtime node, if anyone overlaps with a RAR suggested redirect,
        /// we update the existing redirect and output warning.
        /// </summary>
        private void UpdateExistingBindingRedirects(XElement runtimeNode, IDictionary<AssemblyName, string> redirects)
        {
            ErrorUtilities.VerifyThrow(runtimeNode != null, "This should not be called if the \"runtime\" node is missing.");

            var assemblyBindingNodes = runtimeNode.Nodes()
                .OfType<XElement>()
                .Where(e => e.Name.LocalName == "assemblyBinding");

            foreach (var assemblyBinding in assemblyBindingNodes)
            {
                // Each assemblyBinding section could have more than one dependentAssembly elements
                var dependentAssemblies = assemblyBinding.Nodes()
                    .OfType<XElement>()
                    .Where(e => e.Name.LocalName == "dependentAssembly");

                foreach (var dependentAssembly in dependentAssemblies)
                {
                    var assemblyIdentity = dependentAssembly
                        .Nodes()
                        .OfType<XElement>()
                        .FirstOrDefault(e => e.Name.LocalName == "assemblyIdentity");

                    if (assemblyIdentity == null)
                    {
                        // Due to MSDN documentation (https://msdn.microsoft.com/en-us/library/0ash1ksb(v=vs.110).aspx)
                        // assemblyIdentity is required subelement. Emitting a warning if it's not there.
                        Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MissingNode", "dependentAssembly", "assemblyBinding");
                        continue;
                    }

                    var bindingRedirect = dependentAssembly
                        .Nodes()
                        .OfType<XElement>()
                        .FirstOrDefault(e => e.Name.LocalName == "bindingRedirect");

                    if (bindingRedirect == null)
                    {
                        // Due to xsd schema and MSDN documentation bindingRedirect is not required subelement.
                        // Just skipping it without a warning.
                        continue;
                    }

                    var name = assemblyIdentity.Attribute("name");
                    var publicKeyToken = assemblyIdentity.Attribute("publicKeyToken");

                    if (name == null || publicKeyToken == null)
                    {
                        continue;
                    }

                    var nameValue = name.Value;
                    var publicKeyTokenValue = publicKeyToken.Value;
                    var culture = assemblyIdentity.Attribute("culture");
                    var cultureValue = culture?.Value ?? String.Empty;

                    var oldVersionAttribute = bindingRedirect.Attribute("oldVersion");
                    var newVersionAttribute = bindingRedirect.Attribute("newVersion");

                    if (oldVersionAttribute == null || newVersionAttribute == null)
                    {
                        continue;
                    }

                    var oldVersionRange = oldVersionAttribute.Value.Split(MSBuildConstants.HyphenChar);
                    if (oldVersionRange.Length == 0 || oldVersionRange.Length > 2)
                    {
                        continue;
                    }

                    var oldVerStrLow = oldVersionRange[0];
                    var oldVerStrHigh = oldVersionRange[oldVersionRange.Length == 1 ? 0 : 1];

                    if (!Version.TryParse(oldVerStrLow, out Version oldVersionLow))
                    {
                        Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MalformedVersionNumber", oldVerStrLow);
                        continue;
                    }

                    if (!Version.TryParse(oldVerStrHigh, out Version oldVersionHigh))
                    {
                        Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MalformedVersionNumber", oldVerStrHigh);
                        continue;
                    }

                    // We cannot do a simply dictionary lookup here because we want to allow relaxed "culture" matching:
                    // we consider it a match if the existing binding redirect doesn't specify culture in the assembly identity.
                    foreach (var entry in redirects)
                    {
                        if (IsMatch(entry.Key, nameValue, cultureValue, publicKeyTokenValue))
                        {
                            string maxVerStr = entry.Value;
                            var maxVersion = new Version(maxVerStr);

                            if (maxVersion >= oldVersionLow)
                            {
                                // Update the existing binding redirect to the RAR suggested one.
                                var newName = entry.Key.Name;
                                var newCulture = entry.Key.CultureName;
                                var newPublicKeyToken = entry.Key.GetPublicKeyToken();
                                var newProcessorArchitecture = entry.Key.ProcessorArchitecture;

                                var attributes = new List<XAttribute>(4)
                                {
                                    new XAttribute("name", newName),
                                    new XAttribute(
                                        "culture",
                                        String.IsNullOrEmpty(newCulture) ? "neutral" : newCulture),
                                    new XAttribute(
                                        "publicKeyToken",
                                        ResolveAssemblyReference.ByteArrayToString(newPublicKeyToken))
                                };
                                if (newProcessorArchitecture != 0)
                                {
                                    attributes.Add(new XAttribute("processorArchitecture", newProcessorArchitecture.ToString()));
                                }

                                assemblyIdentity.ReplaceAttributes(attributes);

                                oldVersionAttribute.Value = "0.0.0.0-" + (maxVersion >= oldVersionHigh ? maxVerStr : oldVerStrHigh);
                                newVersionAttribute.Value = maxVerStr;
                                redirects.Remove(entry.Key);

                                Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.OverlappingBindingRedirect", entry.Key.ToString(), bindingRedirect.ToString());
                            }

                            break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Load or create App.Config
        /// </summary>
        private XDocument LoadAppConfig(ITaskItem appConfigItem)
        {
            XDocument document;
            if (appConfigItem == null)
            {
                document = new XDocument(
                    new XDeclaration("1.0", "utf-8", "true"),
                    new XElement("configuration"));
            }
            else
            {
                document = XDocument.Load(appConfigItem.ItemSpec);
                if (document.Root == null || document.Root.Name != "configuration")
                {
                    Log.LogErrorWithCodeFromResources("GenerateBindingRedirects.MissingConfigurationNode");
                    return null;
                }
            }

            return document;
        }

        /// <summary>
        /// Parse the suggested redirects from RAR and return a dictionary containing all those suggested redirects
        /// in the form of AssemblyName-MaxVersion pairs.
        /// </summary>
        private IDictionary<AssemblyName, string> ParseSuggestedRedirects()
        {
            ErrorUtilities.VerifyThrow(SuggestedRedirects?.Length > 0, "This should not be called if there is no suggested redirect.");

            var map = new Dictionary<AssemblyName, string>();
            foreach (var redirect in SuggestedRedirects)
            {
                var redirectStr = redirect.ItemSpec;

                try
                {
                    var maxVerStr = redirect.GetMetadata("MaxVersion");
                    Log.LogMessageFromResources(MessageImportance.Low, "GenerateBindingRedirects.ProcessingSuggestedRedirect", redirectStr, maxVerStr);

                    var assemblyIdentity = new AssemblyName(redirectStr);

                    map.Add(assemblyIdentity, maxVerStr);
                }
                catch (Exception)
                {
                    Log.LogWarningWithCodeFromResources("GenerateBindingRedirects.MalformedAssemblyName", redirectStr);
                    continue;
                }
            }

            return map;
        }
    }
}


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

require APPPATH . '/modules/getme/libraries/Getme.php';

class Systems extends Getme
{

	function __construct() {
		parent::__construct();

		$this->load->model('systems/system_model');
	}

	function _remap($method, $params = array())
	{
		if (! method_exists($this, $method))
			show_404();

		if (! in_array($method, ['authentication', 'login', 'logout']))
		{
			if (! (bool)$this->session->userdata('user_id'))
				redirect('login');
		}

		return call_user_func_array(array($this, $method), $params);
	}

	function index()
	{
		redirect('dashboard');
	}

	function authentication()
	{
		$this->load->library('z_auth/auth');

		$remember 	= $this->input->server('HTTP_REMEMBER');
		$http_auth 	= $this->input->server('HTTP_X_AUTH');
		$username 	= $this->input->server('PHP_AUTH_USER');

		$password = NULL;
		if ($username !== NULL)
		{
				$password = $this->input->server('PHP_AUTH_PW');
		}
		elseif ($http_auth !== NULL)
		{
				if (strpos(strtolower($http_auth), 'basic') === 0)
				{
						list($username, $password) = explode(':', base64_decode(substr($http_auth, 6)));
				}
		}
		if (! $id = $this->auth->login($username, $password))
		{
			$this->xresponse(FALSE, ['message' => $this->auth->errors()], 401);
		}

		// User Data
		// $user = $this->db->get_where('a_user', ['id'=>$id])->row();
		$params['select'] = 'au.id, au.client_id, au.org_id, au.role_id, au.name, au.description, au.email,
			au.photo_url, ac.name as client_name, ao.name as org_name, ar.name as role_name';
		$params['where']['au.id'] = $id;
		$user = (object) $this->system_model->getUserAuthentication($params)[0];
		$dataUser = [
			'user_id' 	=> $id,
			'client_id'	=> $user->client_id,
			'org_id'	=> $user->org_id,
			'role_id'	=> $user->role_id,
			'name'			=> $user->name,
			'description'	=> $user->description,
			'email'			=> $user->email,
			'client_name'	=> $user->client_name,
			'org_name'		=> $user->org_name,
			'role_name'		=> $user->role_name,
			// 'photo_url' 	=> empty($user->photo_url) ? urlencode('http://lorempixel.com/160/160/people/') : urlencode($user->photo_url),
			'photo_url' 	=> urlencode($user->photo_url),
		];

		$userConfig = (object) $this->system_model->getUserConfig([
			'select' => 'attribute, value',
			'where' => ['user_id' => $id]
		]);
		$dataConfig = [];
		foreach($userConfig as $k => $v)
			$dataConfig[$v->attribute] = $v->value;

		$data = array_merge($dataUser, $dataConfig);
		$this->session->set_userdata($data);

		/* if ($remember)
		{
			$expire = (60*60*24*365*2);
			$salt = salt();
			set_cookie([
				'name'   => 'remember_user',
				'value'  => $data['user_id'],
				'expire' => $expire
			]);
			set_cookie([
				'name'   => 'remember_token',
				'value'  => $salt,
				'expire' => $expire
			]);
		} */

		$this->xresponse(TRUE);
	}

	function unlockscreen()
	{
		$this->load->library('z_auth/auth');

		$http_auth 	= $this->input->server('HTTP_X_AUTH');
		$username 	= $this->input->server('PHP_AUTH_USER');

		$password = NULL;
		if ($username !== NULL)
		{
				$password = $this->input->server('PHP_AUTH_PW');
		}
		elseif ($http_auth !== NULL)
		{
				if (strpos(strtolower($http_auth), 'basic') === 0)
				{
						list($username, $password) = explode(':', base64_decode(substr($http_auth, 6)));
				}
		}
		if (! $id = $this->auth->login($username, $password))
		{
			$this->xresponse(FALSE, ['message' => $this->auth->errors()], 401);
		}

		$this->xresponse(TRUE);

		/* $auth 	  = $this->input->server('HTTP_X_AUTH');
		$headers = [
			'TOKEN'	 	=> $this->session->userdata('token'),
			'X-AUTH' 	=> $auth,
		];
		$request = Requests::get(API_URL.'system/unlockscreen', $headers);
		$result = json_decode($request->body);

		if (! $result->status)
			$this->xresponse(FALSE, ['message' => $result->message], $request->status_code);

		// UPDATE TOKEN
		if (! empty($result->token))
			$this->session->set_userdata('token', $result->token);

		$this->xresponse(TRUE); */
	}

	function change_passwd()
	{
		$this->load->library('z_auth/auth');

		$http_auth 	= $this->input->server('HTTP_X_AUTH');
		$username 	= $this->input->server('PHP_AUTH_USER');

		$password = NULL;
		if ($username !== NULL)
		{
				$password = $this->input->server('PHP_AUTH_PW');
		}
		elseif ($http_auth !== NULL)
		{
				if (strpos(strtolower($http_auth), 'basic') === 0)
				{
						list($username, $password) = explode(':', base64_decode(substr($http_auth, 6)));
				}
		}
		if (! $this->auth->change_password($username, $password, $data->password_new))
		{
			$this->xresponse(FALSE, ['message' => $this->auth->errors()], 401);
		}

		$this->xresponse(TRUE, ['message' => $this->auth->messages()]);
		/* $auth	= $this->input->server('HTTP_X_AUTH');
		$data 	= json_decode($this->input->raw_input_stream);

		$headers = [
			'TOKEN'	 	=> $this->session->userdata('token'),
			'X-AUTH' 	=> $auth,
		];
		$request = Requests::post(API_URL.'system/change_passwd', $headers, $data);
		$result = json_decode($request->body);

		if (! $result->status)
			$this->xresponse(FALSE, ['message' => $result->message], $request->status_code);

		// UPDATE TOKEN
		if (! empty($result->token))
			$this->session->set_userdata('token', $result->token);

		$this->xresponse(TRUE, ['message' => $result->message], $request->status_code); */
	}

	function login()
	{
		$data['validate_link'] = site_url('systems/authentication');
		$this->backend_view('login', 'pages/systems/auth/login', $data);
	}

	function logout()
	{
		$this->session->unset_userdata( array('user_id') );

		// delete the remember me cookies if they exist
		if (get_cookie($this->config->item('sess_cookie_name')))
		{
			delete_cookie($this->config->item('sess_cookie_name'));
		}
		if (get_cookie('remember_user'))
		{
			delete_cookie('remember_user');
		}
		if (get_cookie('remember_token'))
		{
			delete_cookie('remember_token');
		}

		// Destroy the session
		$this->session->sess_destroy();

		//Recreate the session
		/* if (substr(CI_VERSION, 0, 1) == '2')
		{
			$this->session->sess_create();
		}
		else
		{
			$this->session->sess_regenerate(TRUE);
		} */

		// redirect('login');
		redirect('frontend');
	}

	// REQUIRED LOGIN
	function menulist()
	{
		$params = $this->input->get();
		// $this->getAPI('system', 'menulist', $params, FALSE);
		$result['data'] = [];
		$params['select'] = "am.name, am.url, am.icon";
		// if (key_exists('q', $params))
		if (! empty($params['q']))
		{
			$params['like'] = empty($params['sf'])
				? DBX::like_or('am.name', $params['q'])
				: DBX::like_or($params['sf'], $params['q']);

		}
		$result['data'] = $this->system_model->getMenu($params);
		$this->xresponse(true, $result);
	}

	function dashboard()
	{
		$this->backend_view('dashboard', 1);
	}

	function setUserRecent()
	{
		$sess 	= $this->_check_session();
		$params = (count($params = $this->input->get()) < 1) ? '' : '?'.http_build_query($params);

		$data = [
			'user_id'	=> $sess->user_id,
			'value'		=> current_url().$params
		];
		// log_message('error', $data['value']);
		$this->system_model->createUserRecent($data);

		/* $params = (count($params = $this->input->get()) < 1) ? '' : '?'.http_build_query($params);
		$data = ['value' => current_url().$params];
		// $data = ['value' => $this->uri->uri_string().$params];
		// log_message('error', $data['value']);
		$this->postAPI('system', 'userRecent', $data, TRUE); */
	}

	function setUserConfig()
	{
		$sess 	= $this->_check_session();

		$data = json_decode($this->input->raw_input_stream);
		$this->session->set_userdata((array)$data);

		$return = 0;
		$result['data'] = [];
		foreach($data as $key => $value)
		{
			$cond = ['user_id' => $sess->user_id, 'attribute' => $key];
			$qry = $this->db->get_where('a_user_config', $cond, 1);
			if ($qry->num_rows() < 1)
			{
				$data = array_merge($cond, ['value' => $value]);
				$this->system_model->createUserConfig($data);
				$return++;
			}
			else
			{
				if ($arow = $this->system_model->updateUserConfig(['value' => $value], $cond))
				{
					$return += $arow;
				}
			}
		}
		$this->xresponse(TRUE, $result);
		/* $data = json_decode($this->input->raw_input_stream);
		$this->session->set_userdata((array)$data);
		$this->postAPI('system', 'userConfig', $data, FALSE); */
	}

	function profile($mode=NULL)
	{
		$this->setUserRecent();
		if ($mode='r') {

		}
		if ($mode='c') {

		}
		if ($mode='u') {

		}
		if ($mode='d') {

		}

		$this->backend_view('crud', 'pages/systems/profile');
	}

	function user($mode=NULL)
	{
		$sess 	= $this->_check_session();
		$method = $_SERVER['REQUEST_METHOD'];
		if ($method == 'GET') {
			if ($mode=='data'){
				$params = $this->input->get();
				if (key_exists('id', $params))
				{
					$params['where']['au.id'] = $params['id'];
				}
				if (key_exists('q', $params) && !empty($params['q']))
				{
					$params['like'] = empty($params['sf'])
						? DBX::like_or('au.name, au.description', $params['q'])
						: DBX::like_or($params['sf'], $params['q']);
				}
				$result['data'] = $this->system_model->getUser($params);
				$this->xresponse(TRUE, $result);
				/* $arg = (object) $this->input->get();
				$this->getAPI('system', 'user', $arg, FALSE); */
			}

			$this->backend_view('crud', 'pages/systems/user');
		}

		if ($method == 'POST') {
			$data 	= (object) $this->post();

			$additional_data = [
				'client_id'		=> $sess->client_id,
				'created_by'	=> $sess->user_id,
				'created_at'	=> date('Y-m-d H:i:s')
			];

			$this->load->library('z_auth/auth');
			if (! $id = $this->auth->register($data->username, $data->password, $data->email, $additional_data))
				$this->xresponse(FALSE, ['message' => $this->auth->errors()], 401);

			// $this->setUserRecent();
			$this->xresponse(TRUE, ['message' => $this->lang->line('success_saving')]);
			/* $data = json_decode($this->input->raw_input_stream);
			$this->postAPI('system', 'user', $data, FALSE); */
		}

		if ($method == 'PUT') {
			$params = $this->input->get();
			$data = json_decode($this->input->raw_input_stream);
			// log_message('error', $data);
			// return out($fields);
			// return;
			$fields = [
				'is_active', 'is_deleted', 'name', 'description', 'email', 'api_token', 'remember_token',
				'is_online', 'supervisor_id', 'bpartner_id', 'is_fullbpaccess', 'is_expired', 'security_question',
				'security_answer', 'ip_address', 'photo_url'
			];
			$boolfields = ['is_active', 'is_fullbpaccess'];
			$nullfields = ['supervisor_id'];
			foreach($fields as $f){
				if (key_exists($f, $data)){
					if (in_array($f, $boolfields)){
						$datas[$f] = empty($data->{$f}) ? 0 : 1;
					}
					elseif (in_array($f, $nullfields)){
						$datas[$f] = ($data->{$f}=='') ? NULL : $data->{$f};
					}
					else {
						$datas[$f] = $data->{$f};
					}
				}
			}

			if (key_exists('id', $params) && !empty($params['id'])) {
				if (! $this->system_model->updateUser($datas, [ 'id'=>(int)$params['id']]))
					$this->xresponse(FALSE, ['message' => $this->db->error()->message], 401);

				$this->setUserRecent();
				$this->xresponse(TRUE, ['message' => $this->lang->line('success_update')]);
			}

			$this->xresponse(FALSE, ['message' => $this->lang->line('error_update')], 400);
			// $this->putAPI('system', 'user', $params, $datas, FALSE);
		}

		if ($method == 'DELETE') {
			$params = $this->input->get();

			if (key_exists('id', $params) && !empty($params['id'])) {
				if (! $this->system_model->deleteUser($params['id'], $sess->user_id))
					$this->xresponse(FALSE, ['message' => $this->system_model->errors()], 401);

				$this->xresponse(TRUE, ['message' => $this->lang->line('success_delete')]);
			}

			$this->xresponse(FALSE, ['message' => $this->lang->line('error_delete')], 400);
		}

		/* switch($_SERVER['REQUEST_METHOD']){
		case 'GET':
			break;
		case 'POST':
			break;
		case 'PUT':
			break;
		case 'DELETE':
			break;
		} */
	}

	function userlist()
	{
		$sess 	= $this->_check_session();
		$params = $this->input->get();

		$result['data'] = [];
		$params['where']['au.client_id'] = $sess->client_id;
		$params['where']['au.org_id'] 	 = $sess->org_id;
		if (key_exists('id', $params))
		{
			$params['where']['au.id'] 	 = $params['id'];
		}
		$result['data'] = $this->system_model->getUser($params);
		$this->xresponse(TRUE, $result);
		/* $params = $this->input->get();
		$this->getAPI('system', 'userlist', $params, FALSE); */
	}

	function supervisorlist()
	{
		$sess 	= $this->_check_session();
		$params = $this->input->get();

		$result['data'] = [];
		$params['where']['au.client_id'] = $sess->client_id;
		$params['where']['au.org_id'] 	 = $sess->org_id;
		if (key_exists('id', $params))
		{
			$params['where']['au.id'] 	 = $params['id'];
		}
		$result['data'] = $this->system_model->getUser($params);
		$this->xresponse(TRUE, $result);
		/* $params = $this->input->get();
		$this->getAPI('system', 'userlist', $params, FALSE); */
	}

	function info($mode=NULL)
	{
		switch($_SERVER['REQUEST_METHOD']){
		case 'GET':
			if ($mode=='data'){
				$params = $this->input->get();

				if (key_exists('id', $params))
				{
					$params['where']['ai.id'] = $params['id'];
				}
				if (key_exists('q', $params))
				{
					$params['like'] = empty($params['sf'])
						? DBX::like_or('ai.description', $params['q'])
						: DBX::like_or($params['sf'], $params['q']);
				}
				if (key_exists('validf', $params))
				{
					$params['where']['ai.valid_from <='] = $params['validf'];
				}
				$result['data'] = $this->system_model->getInfo($params);
				$this->xresponse(TRUE, $result);
				/* $arg = (object) $this->input->get();
				$this->getAPI('system', 'info', $arg, FALSE); */
			}

			$this->backend_view('crud', 'systems/info');
			break;
		case 'POST':
			$data = json_decode($this->input->raw_input_stream);
			$this->postAPI('system', 'info', $data, FALSE);
			$this->setUserRecent();

			// echo "post";
			break;
		case 'PUT':
			$this->setUserRecent();
			echo "put";
			break;
		case 'DELETE':
			echo "del";
			break;
		}
	}

	function infolist()
	{
		$sess 	= $this->_check_session();
		$params = $this->input->get();
		// $this->getAPI('system', 'infolist', $params, FALSE);
		$params['where']['ai.client_id'] = $sess->client_id;
		$params['where']['ai.org_id'] 	 = $sess->org_id;
		$params['where']['ai.valid_from <='] = datetime_db_format();
		$result['data'] = $this->system_model->getInfo($params);
		$this->xresponse(TRUE, $result);
	}

	function countrylist()
	{
		$params = $this->input->get();
		// $this->getAPI('system', 'countrylist', $params, FALSE);
		if (key_exists('q', $params))
			$params['like'] = empty($params['sf'])
				? DBX::like_or('name', $params['q'])
				: DBX::like_or($params['sf'], $params['q']);
		if (key_exists('id', $params))
			$params['where']['id'] = $params['id'];

		$result['data'] = $this->system_model->getCountry($params);
		$this->xresponse(TRUE, $result);
	}

	function provincelist()
	{
		$sess 	= $this->_check_session();
		$params = $this->input->get();
		// $this->getAPI('system', 'provincelist', $params, FALSE);
		if (key_exists('q', $params))
			$params['like'] = empty($params['sf'])
				? DBX::like_or('name', $params['q'])
				: DBX::like_or($params['sf'], $params['q']);
		if (key_exists('id', $params))
			$params['where']['id'] = $params['id'];
		if (key_exists('country_id', $params))
			$params['where']['country_id'] = $params['country_id'];

		$result['data'] = $this->system_model->getProvince($params);
		$this->xresponse(TRUE, $result);
	}

	function citylist()
	{
		$params = $this->input->get();
		// $this->getAPI('system', 'citylist', $params, FALSE);
		if (key_exists('q', $params))
			$params['like'] = empty($params['sf'])
				? DBX::like_or('name', $params['q'])
				: DBX::like_or($params['sf'], $params['q']);
		if (key_exists('id', $params))
			$params['where']['id'] = $params['id'];
		if (key_exists('province_id', $params))
			$params['where']['province_id'] = $params['province_id'];

		$result['data'] = $this->system_model->getCity($params);
		$this->xresponse(TRUE, $result);
	}

	function districtlist()
	{
		$params = $this->input->get();
		// $this->getAPI('system', 'districtlist', $params, FALSE);
		if (key_exists('q', $params))
			$params['like'] = empty($params['sf'])
				? DBX::like_or('name', $params['q'])
				: DBX::like_or($params['sf'], $params['q']);
		if (key_exists('id', $params))
			$params['where']['id'] = $params['id'];
		if (key_exists('city_id', $params))
			$params['where']['city_id'] = $params['city_id'];

		$result['data'] = $this->system_model->getDistrict($params);
		$this->xresponse(TRUE, $result);
	}

	function villagelist()
	{
		$params = $this->input->get();
		// $this->getAPI('system', 'villagelist', $params, FALSE);
		if (key_exists('q', $params))
			$params['like'] = empty($params['sf'])
				? DBX::like_or('name', $params['q'])
				: DBX::like_or($params['sf'], $params['q']);
		if (key_exists('id', $params))
			$params['where']['id'] = $params['id'];
		if (key_exists('district_id', $params))
			$params['where']['district_id'] = $params['district_id'];

		$result['data'] = $this->system_model->getVillage($params);
		$this->xresponse(TRUE, $result);
	}

	function smarty()
	{
		$elapsed = $this->benchmark->elapsed_time('total_execution_time_start', 'total_execution_time_end');
		$data['template'] = 'SMARTY !';
		$data['elapsed_time'] = $elapsed;
		$this->smarty->view('welcome_message', $data);
	}

	function fenom()
	{
		$GLOBALS['identifier'] = ['user_id' => 1234567];
		$elapsed = $this->benchmark->elapsed_time('total_execution_time_start', 'total_execution_time_end');
		$data['template'] = 'FENOM !';
		$data['elapsed_time'] = $elapsed;
		// $this->fenom->view("welcome_message", $data);
		$this->fenom->view("index", $data);
	}

	function smarty_test()
	{
		$this->smarty->testInstall();
	}

	function test()
	{
		return out($this->getFrontendMenu(11));

		// $arr = ['assets/plugins/raphael/raphael-min.js'];
		// $arr_s = serialize($arr);
		// $arr_u = unserialize($arr_s);
		// echo $arr_s."\n";
		// return out($arr_u);
	}

}


text:
require 'Selcom'

describe Selcom::SendMoney do
  subject {
    Selcom::SendMoney.new({
      mobile_number: '+255701234567',
      amount: '543',
      telco_id: 'abc'
    })
  }

  it { expect(subject.telco_id).to        eql('abc') }
  it { expect(subject.mobile_number).to   eql('+255701234567') }
  it { expect(subject.amount).to          eql('543') }

  it { should respond_to(:telco_id) }
  it { should respond_to(:mobile_number) }
  it { should respond_to(:amount) }
  it { should respond_to(:response) }
  it { should respond_to(:reference) }
  it { should respond_to(:success) }
  it { should respond_to(:customer_name) }
  it { should respond_to(:status) }
  it { should respond_to(:status_description) }
  it { should respond_to(:status_code) }

  describe 'request params' do
    before do
      Selcom.configure do |c|
        c.vendor_id = 'def'
        c.vendor_pin = '789'
      end
    end

    subject do
      Selcom::SendMoney.new({
      amount: '543',
      mobile_number: '+255701234567',
      telco_id: 'abc'
      })
    end

    it do
      expect(subject.to_params).to eql(
        HashWithIndifferentAccess.new(
          "amount" => '543',
          "mobile_number" => '+255701234567',
          "telco_id"   => 'abc',
          "vendor_id" => 'def',
          "vendor_pin" => '789'
        )
      )
    end

  end

  describe 'sending money' do

    describe "invalid request" do
      let(:response) do
        double(
          HashWithIndifferentAccess.new(
            :body => {
              "transid" => "mwliid12345",
               "reference" => "4655259721",
                "message" => "Airtel Money Cash-in",
                 "resultcode" => "000",
                 "result" => "FAIL"
               }
             )
            )
      end

      subject { Selcom::SendMoney.new(:amount => 543, :mobile_number => '', :telco_id =>'') }
      #before{ expect(subject).to receive(:connection).with(subject.to_params).and_return(response) }
      before { subject.should_receive(:connection).with(subject.to_params).and_return(response) }
      it 'parses the response and sets accessors' do
        subject.send!
        expect(subject.status).to             eql("FAIL")
        expect(subject.status_code).to        eql("000")
        expect(subject.status_description).to eql('Airtel Money Cash-in')
        expect(subject.success).to            eql(false)
      end
    end

    describe "success" do
      let(:response) do
        double(
          HashWithIndifferentAccess.new(
            :body =>
              {"transid"=>"mwliid12345",
                 "reference"=>"4655259721",
                  "message"=>"Airtel Money Cash-in",
                   "resultcode"=>"000",
                  "result"=>"SUCCESS"
                }
              )
            )
      end

      subject { Selcom::SendMoney.new(:amount => 1234, :mobile_number => '+255701234567', :telco_id => 'qwert') }
      #before{ expect(subject).to receive(:connection).with(subject.to_params).and_return(response) }
      before { subject.should_receive(:connection).with(subject.to_params).and_return(response) }

      it 'parses the response and sets accessors' do
        subject.send!
        expect(subject.reference).to            eql('4655259721')
        expect(subject.status).to               eql("SUCCESS")
        expect(subject.status_code).to          eql('000')
        expect(subject.status_description).to   eql("Airtel Money Cash-in")
        expect(subject.success).to              eql(true)
      end
    end
  end
end


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

<title>FigurineToken (Luchess 1.0.0 API)</title>
<meta name="date" content="2014-05-17">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

io.elegie.luchess.pgn.impl.tokens

Class FigurineToken

java.lang.Object

io.elegie.luchess.pgn.impl.tokens.AbstractToken

io.elegie.luchess.pgn.impl.tokens.MultiCharToken

io.elegie.luchess.pgn.impl.tokens.FigurineToken

All Implemented Interfaces:

Token

public class FigurineToken
extends MultiCharToken

This token matches a chess figurine, such as King, Queen, Bishop, Knight and
 Rook. Note that pawns are not recognized as figurines.

 Re1, Nf3+, Bxf7, Qe4#, Kg1, e8=Q

Constructor Summary

Constructors

Constructor and Description

FigurineToken()

Method Summary

Methods

Modifier and Type
Method and Description

int
interpret(int data,
         java.io.Reader reader,
         ParserVisitor visitor)

This is the method in charge of consuming the text stream provided by the
 token.

Methods inherited from class io.elegie.luchess.pgn.impl.tokens.MultiCharToken

accepts

Methods inherited from class io.elegie.luchess.pgn.impl.tokens.AbstractToken

addSuccessor, getSuccessors, intToString, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

FigurineToken

public FigurineToken()

Method Detail

interpret

public int interpret(int data,
            java.io.Reader reader,
            ParserVisitor visitor)
              throws java.io.IOException,
                     ParseException

Description copied from interface: Token

This is the method in charge of consuming the text stream provided by the
 token. The Parser always calls the 'accepts' method prior to this one.

Specified by:

interpret in interface Token

Overrides:

interpret in class MultiCharToken

Parameters:

data - The current character in the stream.

reader - A reader to the stream.

visitor - The visitor to notify when the token has consumed all the
            necessary chars.

Returns:

The character the stream ends on, once the token has consumed all
         relevant chars.

Throws:

java.io.IOException - When the reader cannot be accessed.

ParseException - When the initial char has been accepted, but that the next
             incoming chars are not expected.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
actions :set
default_action :set

attribute :key,   kind_of: String, name_attribute: true
attribute :value, kind_of: String, required: true
attribute :scope, equal_to: %w(local global system), default: 'global'
attribute :path,  kind_of: String
attribute :user,  kind_of: String
attribute :group, kind_of: String
attribute :options, kind_of: String

attr_accessor :exists


text:
package com.asciibunny.chat.client.commands.client;

import java.util.List;

import com.asciibunny.chat.client.commands.Command;
import com.asciibunny.chat.client.gui.ChatTab;

public class PM extends Command {

	private static final String COMMAND = "pm";

	public PM() {
		super(COMMAND);
	}

	@Override
	public void command(List<String> arguments, ChatTab tab) {
		String name = arguments.get(0);
		String message = "";

		for (String argument : arguments) {
			if (!argument.equals(name)) {
				if (!message.equals("")) message += " ";
				message += argument;
			}
		}

		tab.send("/pm");
		tab.send(name);
		tab.send(message);
		tab.send("/end");
	}

}


text:
require 'spec_helper'

require 'realm/domain'
require 'realm/spec/matchers'

describe "expect(aggregate_root).to have_uncommitted_events(...)" do
  let(:event_factory) { Realm::Messaging::MessageFactory.new }

  subject(:aggregate_root) {
    double(
      Realm::Domain::AggregateRoot,
      uuid: :aggregate_uuid, uncommitted_events: uncommitted_events
    )
  }

  let(:matcher) { have_no_uncommitted_events }

  before(:each) do
    event_factory.define(:this_happened,
      properties: {
        uuid:       UUIDTools::UUID,
        property_1: String,
        property_2: String
      }
    )
    event_factory.define(:that_happened,
      properties: {
        uuid:       UUIDTools::UUID,
        property_a: String,
        property_b: String
      }
    )
  end

  context "no events" do
    let(:uncommitted_events) { [ ] }

    specify {
      expect(
        have_no_uncommitted_events.matches?(aggregate_root)
      ).to be true
    }
  end

  context "events" do
    let(:uncommitted_events) {
      [
        event_factory.build(:this_happened, uuid: :aggregate_uuid, property_1: "one", property_2: "two"),
        event_factory.build(:this_happened, uuid: :aggregate_uuid, property_1: "ein", property_2: "zwei"),
        event_factory.build(:that_happened, uuid: :aggregate_uuid, property_a: "x", property_b: "y")
      ]
    }

    context "expecting no events" do
      it "does not match" do
        expect(
          matcher.matches?(aggregate_root)
        ).to be false
      end

      specify "error message mentions all uncommitted events" do
        matcher.matches?(aggregate_root)
        expect(
          matcher.failure_message
        ).to include("this_happened", "that_happened", "one", "ein", "x")
      end
    end

    context "expecting events" do
      context "events not in the uncommitted list" do
        it "does not match" do
          expect(
            matcher.matches?(aggregate_root)
          ).to be false
        end

        specify "error message mentions all uncommitted events" do
          matcher.matches?(aggregate_root)
          expect(
            matcher.failure_message
          ).to include("this_happened", "that_happened", "one", "ein", "x")
        end
      end

      context "specified uncommitted events that does not match" do
        let(:matcher) {
          have_uncommitted_events(
            { message_type_name: :this_happened, uuid: :aggregate_uuid, property_1: "wrong value", property_2: "two"   }
          )
        }

        it "does not match" do
          expect(
            matcher.matches?(aggregate_root)
          ).to be false
        end

        specify "error message" do
          matcher.matches?(aggregate_root)
          expect(
            matcher.failure_message
          ).to include("this_happened", "property_1", "wrong value")
        end
      end

      context "specified uncommitted event that does match" do
        let(:matcher) {
          have_uncommitted_events(
            { message_type_name: :this_happened, uuid: :aggregate_uuid, property_1: "ein", property_2: "zwei"  }
          )
        }

        it "matches" do
          expect(
            matcher.matches?(aggregate_root)
          ).to be true
        end
      end

      context "multiple events" do
        context "that match" do
          let(:matcher) {
            have_uncommitted_events(
              { message_type_name: :this_happened, uuid: :aggregate_uuid, property_1: "one", property_2: "two"   },
              { message_type_name: :this_happened, uuid: :aggregate_uuid, property_1: "ein", property_2: "zwei"  },
              { message_type_name: :that_happened, uuid: :aggregate_uuid, property_a: "x",   property_b: "y"     }
            )
          }

          it "matches" do
            expect(
              matcher.matches?(aggregate_root)
            ).to be true
          end
        end

        context "that don't match" do
          let(:matcher) {
            have_uncommitted_events(
              { message_type_name: :this_happened, uuid: :aggregate_uuid, property_1: "one", property_2: "two"   },
              { message_type_name: :this_happened, uuid: :aggregate_uuid, property_1: "ein", property_2: "zwei"  },
              { message_type_name: :that_happened, uuid: :aggregate_uuid, property_a: "x",   property_b: "z"     }
            )
          }

          it "does not match" do
            expect(
              matcher.matches?(aggregate_root)
            ).to be false
          end

          specify "error message includes non-matching events" do
            matcher.matches?(aggregate_root)
            expect(
              matcher.failure_message
            ).to include("that_happened", "property_b", "z")
          end
        end
      end
    end
  end
end


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

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_switches.h"
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/ash/login/lock/screen_locker_tester.h"
#include "chrome/browser/ash/login/saml/fake_saml_idp_mixin.h"
#include "chrome/browser/ash/login/saml/lockscreen_reauth_dialog_test_helper.h"
#include "chrome/browser/ash/login/session/user_session_manager_test_api.h"
#include "chrome/browser/ash/login/test/js_checker.h"
#include "chrome/browser/ash/login/test/logged_in_user_mixin.h"
#include "chrome/browser/ash/login/test/test_condition_waiter.h"
#include "chrome/browser/ash/login/users/test_users.h"
#include "chrome/test/base/mixin_based_in_process_browser_test.h"
#include "chromeos/dbus/shill/fake_shill_manager_client.h"
#include "chromeos/network/network_connection_handler.h"
#include "chromeos/network/network_handler.h"
#include "chromeos/network/network_handler_callbacks.h"
#include "chromeos/network/network_handler_test_helper.h"
#include "chromeos/network/network_state_test_helper.h"
#include "components/account_id/account_id.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace ash {
namespace {

constexpr char kTestAuthSIDCookie1[] = "fake-auth-SID-cookie-1";
constexpr char kTestAuthLSIDCookie1[] = "fake-auth-LSID-cookie-1";
constexpr char kTestRefreshToken[] = "fake-refresh-token";
constexpr char kWifiServicePath[] = "/service/wifi1";

void ErrorCallbackFunction(base::OnceClosure run_loop_quit_closure,
                           const std::string& error_name,
                           const std::string& error_message) {
  std::move(run_loop_quit_closure).Run();
  FAIL() << "Shill Error: " << error_name << " : " << error_message;
}

void SetConnected(const std::string& service_path) {
  base::RunLoop run_loop;
  ShillServiceClient::Get()->Connect(
      dbus::ObjectPath(service_path), run_loop.QuitWhenIdleClosure(),
      base::BindOnce(&ErrorCallbackFunction, run_loop.QuitClosure()));
  run_loop.Run();
}

}  // namespace

class LockscreenWebUiTest : public MixinBasedInProcessBrowserTest {
 public:
  LockscreenWebUiTest() {
    feature_list_.InitAndEnableFeature(
        features::kEnableSamlReauthenticationOnLockscreen);
  }

  LockscreenWebUiTest(const LockscreenWebUiTest&) = delete;
  LockscreenWebUiTest& operator=(const LockscreenWebUiTest&) = delete;

  ~LockscreenWebUiTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(switches::kAllowFailedPolicyFetchForTest);
    // TODO(crbug.com/1177416) - Fix this with a proper SSL solution.
    command_line->AppendSwitch(::switches::kIgnoreCertificateErrors);

    MixinBasedInProcessBrowserTest::SetUpCommandLine(command_line);
  }

  void SetUpOnMainThread() override {
    ShillManagerClient::Get()->GetTestInterface()->SetupDefaultEnvironment();

    host_resolver()->AddRule("*", "127.0.0.1");

    test::UserSessionManagerTestApi session_manager_test_api(
        UserSessionManager::GetInstance());
    session_manager_test_api.SetShouldObtainTokenHandleInTests(false);

    fake_gaia_mixin()->fake_gaia()->RegisterSamlUser(
        FakeGaiaMixin::kEnterpriseUser1, fake_saml_idp_.GetSamlPageUrl());

    fake_gaia_mixin()->set_initialize_fake_merge_session(false);
    fake_gaia_mixin()->fake_gaia()->SetFakeMergeSessionParams(
        FakeGaiaMixin::kEnterpriseUser1, kTestAuthSIDCookie1,
        kTestAuthLSIDCookie1);
    fake_gaia_mixin()->SetupFakeGaiaForLogin(FakeGaiaMixin::kEnterpriseUser1,
                                             "", kTestRefreshToken);

    // Set up fake networks.
    network_state_test_helper_ =
        std::make_unique<chromeos::NetworkStateTestHelper>(
            true /*use_default_devices_and_services*/);
    network_state_test_helper_->manager_test()->SetupDefaultEnvironment();
    // Fake networks have been set up. Connect to WiFi network.
    SetConnected(kWifiServicePath);

    MixinBasedInProcessBrowserTest::SetUpOnMainThread();
  }

  void TearDownOnMainThread() override { network_state_test_helper_.reset(); }

  void Login() { logged_in_user_mixin_.LogInUser(); }

  FakeSamlIdpMixin* fake_saml_idp() { return &fake_saml_idp_; }

  FakeGaiaMixin* fake_gaia_mixin() {
    return logged_in_user_mixin_.GetFakeGaiaMixin();
  }

 protected:
  base::test::ScopedFeatureList feature_list_;
  std::unique_ptr<NetworkStateTestHelper> network_state_test_helper_;

 private:
  LoggedInUserMixin logged_in_user_mixin_{
      &mixin_host_,
      LoggedInUserMixin::LogInType::kRegular,
      embedded_test_server(),
      /*test_base=*/this,
      true /*should_launch_browser*/,
      AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kEnterpriseUser1,
                                     FakeGaiaMixin::kEnterpriseUser1GaiaId),
      true /*include_initial_user*/};

  FakeSamlIdpMixin fake_saml_idp_{&mixin_host_, fake_gaia_mixin()};
};

IN_PROC_BROWSER_TEST_F(LockscreenWebUiTest, Login) {
  fake_saml_idp()->SetLoginHTMLTemplate("saml_login.html");

  Login();

  // Lock the screen and trigger the lock screen SAML reauth dialog.
  ScreenLockerTester().Lock();

  absl::optional<LockScreenReauthDialogTestHelper> reauth_dialog_helper =
      LockScreenReauthDialogTestHelper::ShowDialogAndWait();
  ASSERT_TRUE(reauth_dialog_helper);
  reauth_dialog_helper->ForceSamlRedirect();

  // Expect the 'Verify Account' screen (the first screen the dialog shows) to
  // be visible and proceed to the SAML page.
  reauth_dialog_helper->WaitForVerifyAccountScreen();
  reauth_dialog_helper->ClickVerifyButton();

  reauth_dialog_helper->WaitForSamlScreen();
  reauth_dialog_helper->ExpectVerifyAccountScreenHidden();

  reauth_dialog_helper->WaitForIdpPageLoad();

  // Fill-in the SAML IdP form and submit.
  test::JSChecker signin_frame_js = reauth_dialog_helper->SigninFrameJS();
  signin_frame_js.CreateVisibilityWaiter(true, {"Email"})->Wait();
  signin_frame_js.TypeIntoPath(FakeGaiaMixin::kEnterpriseUser1, {"Email"});
  signin_frame_js.TypeIntoPath("actual_password", {"Password"});
  signin_frame_js.TapOn("Submit");

  ScreenLockerTester().WaitForUnlock();
}

IN_PROC_BROWSER_TEST_F(LockscreenWebUiTest, ShowNetworkDialog) {
  Login();

  // Lock the screen and trigger the lock screen SAML reauth dialog.
  ScreenLockerTester().Lock();

  absl::optional<LockScreenReauthDialogTestHelper> reauth_dialog_helper =
      LockScreenReauthDialogTestHelper::ShowDialogAndWait();
  ASSERT_TRUE(reauth_dialog_helper);

  reauth_dialog_helper->ShowNetworkScreenAndWait();

  // Ensures that the web element 'cr-dialog' is really visible.
  reauth_dialog_helper->ExpectNetworkDialogVisible();

  // Click on the actual button to close the dialog.
  reauth_dialog_helper->ClickCloseNetworkButton();
  // Ensures that the re-auth dialog is closed.
  reauth_dialog_helper->ExpectVerifyAccountScreenHidden();
}

IN_PROC_BROWSER_TEST_F(LockscreenWebUiTest, TriggerDialogOnNetworkOff) {
  Login();

  // Lock the screen and trigger the lock screen SAML reauth dialog.
  ScreenLockerTester().Lock();

  absl::optional<LockScreenReauthDialogTestHelper> reauth_dialog_helper =
      LockScreenReauthDialogTestHelper::ShowDialogAndWait();
  ASSERT_TRUE(reauth_dialog_helper);

  // Disconnect from all networks in order to trigger the network screen.
  network_state_test_helper_->service_test()->ClearServices();
  // TODO(crbug.com/1289309): make it clear what we are waiting for
  base::RunLoop().RunUntilIdle();
  network_state_test_helper_->service_test()->AddService(
      /*service_path=*/kWifiServicePath, /*guid=*/kWifiServicePath,
      /*name=*/kWifiServicePath, /*type=*/shill::kTypeWifi,
      /*state=*/shill::kStateOffline, /*visible=*/true);

  reauth_dialog_helper->WaitForNetworkDialogAndSetHandlers();

  reauth_dialog_helper->ExpectNetworkDialogVisible();

  // Click on the actual button to close the dialog.
  reauth_dialog_helper->ClickCloseNetworkButton();
  // Ensures that both dialogs are closed.
  reauth_dialog_helper->ExpectVerifyAccountScreenHidden();
}

IN_PROC_BROWSER_TEST_F(LockscreenWebUiTest, TriggerAndHideNetworkDialog) {
  Login();

  // Lock the screen and trigger the lock screen SAML reauth dialog.
  ScreenLockerTester().Lock();

  absl::optional<LockScreenReauthDialogTestHelper> reauth_dialog_helper =
      LockScreenReauthDialogTestHelper::ShowDialogAndWait();
  ASSERT_TRUE(reauth_dialog_helper);

  // Disconnect from all networks in order to trigger the network screen.
  network_state_test_helper_->service_test()->ClearServices();
  // TODO(crbug.com/1289309): make it clear what we are waiting for
  base::RunLoop().RunUntilIdle();
  network_state_test_helper_->service_test()->AddService(
      /*service_path=*/kWifiServicePath, /*guid=*/kWifiServicePath,
      /*name=*/kWifiServicePath, /*type=*/shill::kTypeWifi,
      /*state=*/shill::kStateOffline, /*visible=*/true);

  reauth_dialog_helper->WaitForNetworkDialogAndSetHandlers();

  reauth_dialog_helper->ExpectNetworkDialogVisible();

  // Reconnect network.
  network_state_test_helper_->service_test()->AddService(
      /*service_path=*/kWifiServicePath, /*guid=*/kWifiServicePath,
      /*name=*/kWifiServicePath, /*type=*/shill::kTypeWifi,
      /*state=*/shill::kStateOnline, /*visible=*/true);

  // TODO(crbug.com/1289309): make it clear what we are waiting for
  base::RunLoop().RunUntilIdle();

  // Ensures that the network dialog is closed.
  reauth_dialog_helper->ExpectNetworkDialogHidden();
}

IN_PROC_BROWSER_TEST_F(LockscreenWebUiTest, CaptivePortal) {
  Login();

  // Lock the screen and trigger the lock screen SAML reauth dialog.
  ScreenLockerTester().Lock();

  absl::optional<LockScreenReauthDialogTestHelper> reauth_dialog_helper =
      LockScreenReauthDialogTestHelper::ShowDialogAndWait();
  ASSERT_TRUE(reauth_dialog_helper);

  // Disconnect from all networks in order to trigger the network screen.
  network_state_test_helper_->service_test()->ClearServices();
  // TODO(crbug.com/1289309): make it clear what we are waiting for
  base::RunLoop().RunUntilIdle();
  network_state_test_helper_->service_test()->AddService(
      /*service_path=*/kWifiServicePath, /*guid=*/kWifiServicePath,
      /*name=*/kWifiServicePath, /*type=*/shill::kTypeWifi,
      /*state=*/shill::kStateOffline, /*visible=*/true);

  reauth_dialog_helper->WaitForNetworkDialogAndSetHandlers();

  reauth_dialog_helper->ExpectNetworkDialogVisible();

  // Change network to be behind a captive portal.
  network_state_test_helper_->service_test()->SetServiceProperty(
      kWifiServicePath, shill::kStateProperty,
      base::Value(shill::kStatePortal));

  reauth_dialog_helper->WaitForCaptivePortalDialogToLoad();
  reauth_dialog_helper->WaitForCaptivePortalDialogToShow();
  reauth_dialog_helper->ExpectCaptivePortalDialogVisible();

  // User actions on captive portal page should lead to network becoming online,
  // so instead of mocking a portal page we simply switch the network state.
  network_state_test_helper_->service_test()->SetServiceProperty(
      kWifiServicePath, shill::kStateProperty,
      base::Value(shill::kStateOnline));

  reauth_dialog_helper->WaitForCaptivePortalDialogToClose();

  // Ensures that captive portal and network dialogs are closed.
  reauth_dialog_helper->ExpectCaptivePortalDialogHidden();
  reauth_dialog_helper->ExpectNetworkDialogHidden();
}

IN_PROC_BROWSER_TEST_F(LockscreenWebUiTest, TriggerAndHideCaptivePortalDialog) {
  Login();

  // Lock the screen and trigger the lock screen SAML reauth dialog.
  ScreenLockerTester().Lock();

  absl::optional<LockScreenReauthDialogTestHelper> reauth_dialog_helper =
      LockScreenReauthDialogTestHelper::ShowDialogAndWait();
  ASSERT_TRUE(reauth_dialog_helper);

  // This test uses NetworkHandlerTestHelper instead of NetworkStateTestHelper
  // because closing captive portal dialog involves a call to
  // NetworkHandler::Get()
  NetworkHandlerTestHelper network_test_helper;
  network_test_helper.manager_test()->SetupDefaultEnvironment();

  // Disconnect from all networks in order to trigger the network screen.
  network_test_helper.service_test()->ClearServices();
  // TODO(crbug.com/1289309): make it clear what we are waiting for
  base::RunLoop().RunUntilIdle();
  network_test_helper.service_test()->AddService(
      /*service_path=*/kWifiServicePath, /*guid=*/kWifiServicePath,
      /*name=*/kWifiServicePath, /*type=*/shill::kTypeWifi,
      /*state=*/shill::kStateOffline, /*visible=*/true);

  reauth_dialog_helper->WaitForNetworkDialogAndSetHandlers();

  reauth_dialog_helper->ExpectNetworkDialogVisible();

  auto TriggerAndCloseCaptivePortal = [&network_test_helper,
                                       &reauth_dialog_helper] {
    // Change network to be behind a captive portal.
    network_test_helper.service_test()->SetServiceProperty(
        kWifiServicePath, shill::kStateProperty,
        base::Value(shill::kStatePortal));

    reauth_dialog_helper->WaitForCaptivePortalDialogToLoad();
    reauth_dialog_helper->WaitForCaptivePortalDialogToShow();
    reauth_dialog_helper->ExpectCaptivePortalDialogVisible();

    // Close captive portal dialog and check that we are back to network dialog
    reauth_dialog_helper->CloseCaptivePortalDialogAndWait();
    reauth_dialog_helper->ExpectCaptivePortalDialogHidden();
    reauth_dialog_helper->ExpectNetworkDialogVisible();
  };
  // Check that captive portal dialog can be opened and closed multiple times
  TriggerAndCloseCaptivePortal();
  TriggerAndCloseCaptivePortal();

  // Close all dialogs at the end of the test - otherwise these tests crash
  reauth_dialog_helper->ClickCloseNetworkButton();
  reauth_dialog_helper->ExpectVerifyAccountScreenHidden();
}

}  // namespace ash


text:
package au.edu.uts.eng.remotelabs.schedserver.session.pojo.impl;

import java.util.Date;

import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Session;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.listener.SessionEventListener.SessionEvent;
import au.edu.uts.eng.remotelabs.schedserver.logger.Logger;
import au.edu.uts.eng.remotelabs.schedserver.logger.LoggerActivator;
import au.edu.uts.eng.remotelabs.schedserver.session.SessionActivator;
import au.edu.uts.eng.remotelabs.schedserver.session.pojo.SessionService;

/**
 * Implementation of the Session POJO service.
 */
public class SessionServiceImpl implements SessionService
{
    /** Logger. */
    private Logger logger;

    public SessionServiceImpl()
    {
        this.logger = LoggerActivator.getLogger();
    }

    @Override
    public boolean finishSession(Session ses, String reason, org.hibernate.Session db)
    {
        /* Only sessions that are active and in session will be finished. */
        if (!ses.isActive() || ses.getAssignmentTime() == null)
        {
            this.logger.warn("Session '" + ses.getId() + "' not assigned to rig so will not be finished.");
            return false;
        }

        /* Finish session. */
        this.logger.debug("Finishing session '" + ses.getId() + "' with reason: " + reason);
        db.beginTransaction();
        ses.setActive(false);
        ses.setRemovalReason(reason);
        ses.setRemovalTime(new Date());
        db.flush();
        db.getTransaction().commit();

        /* Fire session finished event. */
        SessionActivator.notifySessionEvent(SessionEvent.FINISHED, ses, db);

        /* Local session, release the rig. */
        SessionActivator.release(ses, db);
        return true;
    }

}


text: default_app_config = 'fst_web.fs_doc.apps.FstConfig'


text:
function allvideonames=Scanallnames(iids)

allvideonames=cell(0);
for i = 1:numel(iids)

    [thepath, thename, theext] = fileparts(iids(i).name); if (~isempty(thepath)), fprintf('This dir name %s should be empty\n', thepath); end %#ok<NASGU>

%     inFile= fullfile(theDir, iids(i).name); %[thename, theext]

    [thevideoname]=Findthecaseandaffinity(thename); %,theaffinity

    [allvideonames]=Addfindname(allvideonames,thevideoname); %,thevpos

end


text:
@protocol EM_ChatMessageManagerDelegate;

@interface EM_ChatMessageManager : NSObject

@property (nonatomic,assign,readonly) BOOL isPlaying;
@property (nonatomic,weak) id<EM_ChatMessageManagerDelegate> delegate;

+ (instancetype)defaultManager;
- (void)showBrowserWithImagesMessage:(NSArray *)imageMessageArray index:(NSInteger)index;
- (void)showBrowserWithVideoMessage:(id)videoMessage;

- (void)playVoice:(NSArray *)voiceMessageArray index:(NSInteger)index;
- (void)stopVoice;

@end

@protocol EM_ChatMessageManagerDelegate <NSObject>

- (void)playStartWithMessage:(id)startMessage;
- (void)playCompletionWithMessage:(id)completionMessage nextMessage:(id)nextMessage;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_margin="@dimen/view_common_margin"
    android:paddingTop="@dimen/view_common_padding"
    android:background="@drawable/share_background"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_margin="@dimen/view_larget_margin"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_weight="1"
            android:layout_marginRight="@dimen/view_larget_margin"
            android:src="@drawable/list_divider_no_width"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:text="@string/share_app_to_friend"
            android:textColor="@color/colorSecondTextColor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <ImageView
            android:layout_weight="1"
            android:src="@drawable/list_divider_no_width"
            android:layout_marginLeft="@dimen/view_larget_margin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <GridView
        android:id="@+id/gv_share_list"
        android:numColumns="3"
        android:layout_marginBottom="@dimen/view_larget_margin"
        android:layout_marginRight="@dimen/view_larget_margin"
        android:layout_marginLeft="@dimen/view_larget_margin"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </GridView>
</LinearLayout>


text:
					<title>[SiPedang] Forget Password</title>

Kami turut bersimpati atas kehilangan password Anda.

Tetapi jangan khawatir! Anda dapat menggunakan link berikut untuk mereset password anda:

http://localhost/sipedang/index.php/ControlAutentikasi/do_reset_password/52a28ba8

Jika anda tidak menggunakan link ini dalam waktu 1 jam, maka link akan dinonaktifkan.

Thanks
SiPedang


text:
<?xml version="1.0" encoding="UTF-8" ?>
<enumerations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="enumerations.xsd">
    <enumerationWithAttributes id="ea">A</enumerationWithAttributes>
    <enumerationWithAttributes id="ea1"><error descr="Wrong tag value">unknown</error></enumerationWithAttributes>
</enumerations>


text:
package com.tle.common.activecache.settings;

import com.dytech.devlib.PropBagEx;
import com.tle.common.settings.ConfigurationProperties;
import com.tle.common.settings.annotation.Property;
import com.tle.common.settings.annotation.PropertyBag;
import com.tle.core.xstream.TLEXStream;
import com.tle.core.xstream.XMLData;
import com.tle.core.xstream.XMLDataMappings;
import com.tle.core.xstream.mapping.ListMapping;
import com.tle.core.xstream.mapping.NodeMapping;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/** @author Nicholas Read */
public class CacheSettings implements ConfigurationProperties {
  private static final long serialVersionUID = 1;
  private static TLEXStream xstream = TLEXStream.instance();

  @Property(key = "cache.enabled")
  private boolean enabled;

  @PropertyBag(key = "cache.groups")
  private PropBagEx groups;

  public boolean isEnabled() {
    return enabled;
  }

  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
  }

  public Node getGroups() {
    if (groups == null) {
      return null;
    }
    return (Node) xstream.fromXML(groups, Node.class);
  }

  public void setGroups(Node groups) {
    this.groups = xstream.toPropBag(groups, "groups"); // $NON-NLS-1$
  }

  public static class Node implements XMLData {
    private static final long serialVersionUID = 1L;

    private static final XMLDataMappings smappings;

    static {
      smappings = new XMLDataMappings();
      smappings.addNodeMapping(new NodeMapping("name", "@name"));
      smappings.addNodeMapping(new NodeMapping("id", "@id"));
      smappings.addNodeMapping(new NodeMapping("uuid", "@uuid"));
      smappings.addNodeMapping(
          new ListMapping("includes", "include", ArrayList.class, Query.class));
      smappings.addNodeMapping(
          new ListMapping("excludes", "exclude", ArrayList.class, Query.class));
      smappings.addNodeMapping(
          new ListMapping("nodes", "user", ArrayList.class, Node.class) {
            @Override
            public boolean hasValue(Object object) {
              return false;
            }
          });
      smappings.addNodeMapping(new ListMapping("nodes", "group", ArrayList.class, Node.class));
    }

    private List<Query> includes;
    private List<Query> excludes;
    private List<Node> nodes;

    private String id;
    private String name;
    private String uuid;

    /** For serialisation only! */
    public Node() {
      //
    }

    public Node(String string, boolean group) {
      if (group) {
        name = string;
      } else {
        id = string;
      }
      setUuid(UUID.randomUUID().toString());
    }

    @Override
    public XMLDataMappings getMappings() {
      return smappings;
    }

    public boolean isGroup() {
      return name != null;
    }

    public boolean isUser() {
      return id != null;
    }

    public List<Query> getExcludes() {
      if (excludes == null) {
        excludes = new ArrayList<Query>();
      }
      return excludes;
    }

    public void setExcludes(List<Query> excludes) {
      this.excludes = excludes;
    }

    public List<Query> getIncludes() {
      if (includes == null) {
        includes = new ArrayList<Query>();
      }
      return includes;
    }

    public void setIncludes(List<Query> includes) {
      this.includes = includes;
    }

    public List<Node> getNodes() {
      if (nodes == null) {
        nodes = new ArrayList<Node>();
      }
      return nodes;
    }

    public void setNodes(List<Node> nodes) {
      this.nodes = nodes;
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public String getId() {
      return id;
    }

    public void setId(String id) {
      this.id = id;
    }

    public String getUuid() {
      return uuid;
    }

    public void setUuid(String uuid) {
      this.uuid = uuid;
    }
  }

  public static class Query implements Serializable {
    private static final long serialVersionUID = 1L;

    private long itemdef;
    private String uuid;
    private String script;

    public Query() {
      script = "";
    }

    public Query(long id, String script) {
      itemdef = id;
      this.script = script;
    }

    public long getItemdef() {
      return itemdef;
    }

    public void setItemdef(long itemdef) {
      this.itemdef = itemdef;
    }

    public String getScript() {
      return script;
    }

    public void setScript(String script) {
      this.script = script;
    }

    public void setUuid(String uuid) {
      this.uuid = uuid;
    }

    public String getUuid() {
      return uuid;
    }
  }
}


text:
define(function(require) {
  'use strict';

  var React = require('react');
  var L10nSpan = require('components/shared/l10n-span');
  var NewsTag = require('components/news/news-tag');
  var NewsFetcher = require('backend/modules/NewsFetcher');

  var NewsContainer = React.createClass({
    getInitialState: function() {
      return {
        news: []
      };
    },

    componentDidMount: function() {
      NewsFetcher.get().then((news) => {
        this.setState({
          news: news
        });
      });
    },

    render: function() {
      var news = this.state.news;

      /* jshint ignore:start */
      return (

              <L10nSpan l10nId="news_header"/>

            {news.map(function(eachNews) {
              return <NewsTag data={eachNews}/>
            })}

      );
      /* jshint ignore:end */
    }
  });

  return NewsContainer;
});


text:
while true; do
    xdotool mousemove_relative 1 1
    sleep 20m
done


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta name="viewport" content="width=device-width,target-densitydpi=device-dpi,user-scalable=no,initial-scale=1.0">
	<link href="../../css/styles.css" rel="stylesheet" type="text/css">

	<title> HTML5 Offline detection </title>

HTML5 Offline

Demo

			This page uses the Offline feature of HTML5 to detect whether the browser has connectivity.

			This user agent is currently Unknown.

			Last checked .


text:
import mock
import testtools

from sahara.plugins.vanilla.v2_6_0 import versionhandler

CONFIGURATION_SCHEMA = {
    'cluster_configs': {
        'dfs.replication': ('HDFS', 'dfs.replication')
    },
    'node_configs': {
        'yarn.app.mapreduce.am.command-opts': (
            'MapReduce', 'yarn.app.mapreduce.am.command-opts'),
        'yarn.scheduler.maximum-allocation-mb': (
            'YARN', 'yarn.scheduler.maximum-allocation-mb'),
        'yarn.app.mapreduce.am.resource.mb': (
            'MapReduce', 'yarn.app.mapreduce.am.resource.mb'),
        'yarn.scheduler.minimum-allocation-mb': (
            'YARN', 'yarn.scheduler.minimum-allocation-mb'),
        'yarn.nodemanager.vmem-check-enabled': (
            'YARN', 'yarn.nodemanager.vmem-check-enabled'),
        'mapreduce.map.java.opts': (
            'MapReduce', 'mapreduce.map.java.opts'),
        'mapreduce.reduce.memory.mb': (
            'MapReduce', 'mapreduce.reduce.memory.mb'),
        'yarn.nodemanager.resource.memory-mb': (
            'YARN', 'yarn.nodemanager.resource.memory-mb'),
        'mapreduce.reduce.java.opts': (
            'MapReduce', 'mapreduce.reduce.java.opts'),
        'mapreduce.map.memory.mb': (
            'MapReduce', 'mapreduce.map.memory.mb'),
        'mapreduce.task.io.sort.mb': (
            'MapReduce', 'mapreduce.task.io.sort.mb')
    }
}

class TestVersionHandler(testtools.TestCase):
    @mock.patch('sahara.plugins.recommendations_utils.'
                'HadoopAutoConfigsProvider')
    @mock.patch('sahara.plugins.vanilla.v2_6_0.versionhandler.VersionHandler.'
                'get_plugin_configs')
    def test_recommend_configs(self, fake_plugin_configs, provider):
        f_cluster, f_configs = mock.Mock(), mock.Mock()
        fake_plugin_configs.return_value = f_configs
        versionhandler.VersionHandler().recommend_configs(f_cluster)
        self.assertEqual([
            mock.call(CONFIGURATION_SCHEMA, f_configs, f_cluster)
        ], provider.call_args_list)


text:
package com.example

import akka.actor._
import concurrent.Future
import scala.concurrent.duration._
import akka.util.Timeout

class PingPong extends Actor with ActorLogging {
  import PingPongProtocol._
  import context._
  implicit val timeout = Timeout(5.seconds)

    def receive = {
      case PongRequest =>
        sender ! PongResponse("pong")
      case PongFutureRequest =>
        val capturedSender = sender
        Future {
          capturedSender ! PongResponse("future pong")
        }
      case _ =>
        log.error("received unknown message")
    }
}

object PingPongProtocol {
  import spray.json._
  import DefaultJsonProtocol._

  case object PongRequest
  case object PongFutureRequest
  case class PongResponse(message:String)

  //----------------------------------------------
  // JSON
  //----------------------------------------------
  object PongResponse extends DefaultJsonProtocol {
     implicit val format = jsonFormat1(PongResponse.apply)
   }

}


text:
@interface PurchaseTableViewCell : UITableViewCell {
  UIButton * exchangeButton_;
}

@property (nonatomic, retain) UIButton * exchangeButton;

- (void)configureCellWithTitle:(NSString *)title
                         price:(NSString *)price
                          icon:(UIImage *)icon
                           odd:(BOOL)odd;

@end


text:
package com.datastax.oss.driver.api.core.cql;

import com.datastax.oss.driver.api.core.session.Session;
import com.datastax.oss.driver.internal.core.cql.DefaultPagingState;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import java.nio.ByteBuffer;

/**
 * A safe wrapper around the paging state of a query.
 *
 *
This class performs additional checks to fail fast if the paging state is not reused on the
 * same query, and it provides utility methods for conversion to/from strings and byte arrays.
 *
 *
The serialized form returned by {@link #toBytes()} and {@link Object#toString()} is an opaque
 * sequence of bytes. Note however that it is not cryptographically secure: the contents are
 * not encrypted and the checks are performed with a simple MD5 checksum. If you need stronger
 * guarantees, you should build your own wrapper around {@link ExecutionInfo#getPagingState()}.
 */
public interface PagingState {

  /** Parses an instance from a string previously generated with {@code toString()}. */
  @NonNull
  static PagingState fromString(@NonNull String string) {
    return DefaultPagingState.fromString(string);
  }

  /** Parses an instance from a byte array previously generated with {@link #toBytes()}. */
  @NonNull
  static PagingState fromBytes(byte[] bytes) {
    return DefaultPagingState.fromBytes(bytes);
  }

  /** Returns a representation of this object as a byte array. */
  byte[] toBytes();

  /**
   * Checks if this paging state can be safely reused for the given statement. Specifically, the
   * query string and any bound values must match.
   *
   *
Note that, if {@code statement} is a {@link SimpleStatement} with bound values, those values
   * must be encoded in order to perform the check. This method uses the default codec registry and
   * default protocol version. This might fail if you use custom codecs; in that case, use {@link
   * #matches(Statement, Session)} instead.
   *
   *
If {@code statement} is a {@link BoundStatement}, it is always safe to call this method.
   */
  default boolean matches(@NonNull Statement<?> statement) {
    return matches(statement, null);
  }

  /**
   * Alternative to {@link #matches(Statement)} that specifies the session the statement will be
   * executed with. You only need this for simple statements, and if you use custom codecs.
   * Bound statements already know which session they are attached to.
   */
  boolean matches(@NonNull Statement<?> statement, @Nullable Session session);

  /**
   * Returns the underlying "unsafe" paging state (the equivalent of {@link
   * ExecutionInfo#getPagingState()}).
   */
  @NonNull
  ByteBuffer getRawPagingState();
}


text:
require File.join(File.dirname(__FILE__), 'bitty', 'bit_proxy')

module Bitty
  module ActiveRecordExtensions
    def bitty(field, *args)
      field = field.to_sym

      opts = args.extract_options!

      proxy = Class.new(Bitty::BitProxy)
      proxy.bit_names = args
      proxy.column = opts[:column] || field

      # TODO: opts[:default]
      # TODO: opts[:named_scope]
      # TODO: check if field has already been defined in superclass
      write_inheritable_hash(:_bitty_fields, { field => proxy } )

      class_eval <<-RUBY
        def #{field}
          @_bitty_#{field} ||=
            self.class.read_inheritable_attribute(:_bitty_fields)[:#{field}].new(self)
        end

        def #{field}=(value)
          #{field}.set!(value)
        end
      RUBY
    end

    def bitty_named_scope(name, bitty_field, *args)
      proxy_class = read_inheritable_attribute(:_bitty_fields)[bitty_field]

      if proxy_class
        named_scope name, proxy_class.named_scope(*args)
      else
        raise ArgumentError, "There's no bitfield '#{bitty_field}' defined!"
      end
    end
  end
end

if defined? ActiveRecord::Base
  ActiveRecord::Base.send(:extend, Bitty::ActiveRecordExtensions)
end