text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="../../../../../src/reporter/format-xspec-report.xsl"?>
<x:report xmlns:test="http://www.jenitennison.com/xslt/unit-test"
          xmlns:xs="http://www.w3.org/2001/XMLSchema"
          xmlns:x="http://www.jenitennison.com/xslt/xspec"
          xmlns:svrl="http://purl.oclc.org/dsdl/svrl"
          stylesheet="../../schematron-01.sch-compiled.xsl"
          date="ONCE-UPON-A-TIME"
          xspec="../../schematron-01.xspec"
          schematron="../../schematron-01.sch">
   <x:scenario>
      <x:label>schematron-01</x:label>
      <x:context href="../../schematron-01.xml"/>
      <x:scenario>
         <x:label>article should have a title</x:label>
         <x:result select="/element()">
            <svrl:schematron-output xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                                    xmlns:saxon="http://saxon.sf.net/"
                                    xmlns:schold="http://www.ascc.net/xml/schematron"
                                    xmlns:iso="http://purl.oclc.org/dsdl/schematron"
                                    xmlns:xhtml="http://www.w3.org/1999/xhtml"
                                    title=""
                                    schemaVersion=""><!--

		 -->
               <svrl:active-pattern document="../../schematron-01.xml"/>
               <svrl:fired-rule context="article"/>
               <svrl:fired-rule context="section"/>
               <svrl:fired-rule context="section"/>
               <svrl:failed-assert test="title" id="a002" location="/article[1]/section[2]">
                  <svrl:text>
                section should have a title
            </svrl:text>
               </svrl:failed-assert>
               <svrl:fired-rule context="section"/>
               <svrl:failed-assert test="title" id="a002" location="/article[1]/section[3]">
                  <svrl:text>
                section should have a title
            </svrl:text>
               </svrl:failed-assert>
            </svrl:schematron-output>
         </x:result>
         <x:test successful="true">
            <x:label>not assert a001</x:label>
            <x:expect test="boolean(svrl:schematron-output[svrl:fired-rule]) and empty(svrl:schematron-output/svrl:failed-assert[(@id, preceding-sibling::svrl:fired-rule[1]/@id, preceding-sibling::svrl:active-pattern[1]/@id)[1] = 'a001'])"
                      select="()"/>
         </x:test>
      </x:scenario>
      <x:scenario>
         <x:label>section should have a title</x:label>
         <x:result select="/element()">
            <svrl:schematron-output xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                                    xmlns:saxon="http://saxon.sf.net/"
                                    xmlns:schold="http://www.ascc.net/xml/schematron"
                                    xmlns:iso="http://purl.oclc.org/dsdl/schematron"
                                    xmlns:xhtml="http://www.w3.org/1999/xhtml"
                                    title=""
                                    schemaVersion=""><!--

		 -->
               <svrl:active-pattern document="../../schematron-01.xml"/>
               <svrl:fired-rule context="article"/>
               <svrl:fired-rule context="section"/>
               <svrl:fired-rule context="section"/>
               <svrl:failed-assert test="title" id="a002" location="/article[1]/section[2]">
                  <svrl:text>
                section should have a title
            </svrl:text>
               </svrl:failed-assert>
               <svrl:fired-rule context="section"/>
               <svrl:failed-assert test="title" id="a002" location="/article[1]/section[3]">
                  <svrl:text>
                section should have a title
            </svrl:text>
               </svrl:failed-assert>
            </svrl:schematron-output>
         </x:result>
         <x:test successful="true">
            <x:label>assert a002 /article[1]/section[2]</x:label>
            <x:expect test="exists(svrl:schematron-output/svrl:failed-assert[(@id, preceding-sibling::svrl:fired-rule[1]/@id, preceding-sibling::svrl:active-pattern[1]/@id)[1] = 'a002'][x:schematron-location-compare('/article[1]/section[2]', @location, preceding-sibling::svrl:ns-prefix-in-attribute-values)])"
                      select="()"/>
         </x:test>
         <x:test successful="true">
            <x:label>assert a002 /article[1]/section[3]</x:label>
            <x:expect test="exists(svrl:schematron-output/svrl:failed-assert[(@id, preceding-sibling::svrl:fired-rule[1]/@id, preceding-sibling::svrl:active-pattern[1]/@id)[1] = 'a002'][x:schematron-location-compare('/article[1]/section[3]', @location, preceding-sibling::svrl:ns-prefix-in-attribute-values)])"
                      select="()"/>
         </x:test>
      </x:scenario>
   </x:scenario>
</x:report>


text:
using FluentValidation;

namespace SFA.DAS.ProviderApprenticeshipsService.Application.Commands.UpdateUserNotificationSettings
{
    public class UpdateUserNotificationSettingsValidator : AbstractValidator<UpdateUserNotificationSettingsCommand>
    {
        public UpdateUserNotificationSettingsValidator()
        {
            RuleFor(m => m.UserRef).NotNull().NotEmpty();
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
jupyter nbextension enable --py widgetsnbextension
jupyter notebook --ip=0.0.0.0 --allow-root


text:
<?php

namespace Symfony\Component\PropertyInfo;

/**
 * Default {@see PropertyInfoExtractorInterface} implementation.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class PropertyInfoExtractor implements PropertyInfoExtractorInterface
{
    /**
     * @var PropertyListExtractorInterface[]
     */
    private $listExtractors;

    /**
     * @var PropertyTypeExtractorInterface[]
     */
    private $typeExtractors;

    /**
     * @var PropertyDescriptionExtractorInterface[]
     */
    private $descriptionExtractors;

    /**
     * @var PropertyAccessExtractorInterface[]
     */
    private $accessExtractors;

    /**
     * @param PropertyListExtractorInterface[]        $listExtractors
     * @param PropertyTypeExtractorInterface[]        $typeExtractors
     * @param PropertyDescriptionExtractorInterface[] $descriptionExtractors
     * @param PropertyAccessExtractorInterface[]      $accessExtractors
     */
    public function __construct(array $listExtractors = array(), array $typeExtractors = array(),  array $descriptionExtractors = array(), array $accessExtractors = array())
    {
        $this->listExtractors = $listExtractors;
        $this->typeExtractors = $typeExtractors;
        $this->descriptionExtractors = $descriptionExtractors;
        $this->accessExtractors = $accessExtractors;
    }

    /**
     * {@inheritdoc}
     */
    public function getProperties($class, array $context = array())
    {
        return $this->extract($this->listExtractors, 'getProperties', array($class, $context));
    }

    /**
     * {@inheritdoc}
     */
    public function getShortDescription($class, $property, array $context = array())
    {
        return $this->extract($this->descriptionExtractors, 'getShortDescription', array($class, $property, $context));
    }

    /**
     * {@inheritdoc}
     */
    public function getLongDescription($class, $property, array $context = array())
    {
        return $this->extract($this->descriptionExtractors, 'getLongDescription', array($class, $property, $context));
    }

    /**
     * {@inheritdoc}
     */
    public function getTypes($class, $property, array $context = array())
    {
        return $this->extract($this->typeExtractors, 'getTypes', array($class, $property, $context));
    }

    /**
     * {@inheritdoc}
     */
    public function isReadable($class, $property, array $context = array())
    {
        return $this->extract($this->accessExtractors, 'isReadable', array($class, $property, $context));
    }

    /**
     * {@inheritdoc}
     */
    public function isWritable($class, $property, array $context = array())
    {
        return $this->extract($this->accessExtractors, 'isWritable', array($class, $property, $context));
    }

    /**
     * Iterates over registered extractors and return the first value found.
     *
     * @param array  $extractors
     * @param string $method
     * @param array  $arguments
     *
     * @return mixed
     */
    private function extract(array $extractors, $method, array $arguments)
    {
        foreach ($extractors as $extractor) {
            $value = call_user_func_array(array($extractor, $method), $arguments);
            if (null !== $value) {
                return $value;
            }
        }
    }
}


text:
package io.github.katrix.katlib.command

import java.util.Locale

import scala.annotation.tailrec
import scala.collection.JavaConverters._
import scala.collection.mutable

import org.spongepowered.api.command.args.{CommandContext, GenericArguments}
import org.spongepowered.api.command.spec.CommandSpec
import org.spongepowered.api.command.{CommandException, CommandResult, CommandSource}
import org.spongepowered.api.service.pagination.PaginationList
import org.spongepowered.api.text.Text
import org.spongepowered.api.text.action.TextActions
import org.spongepowered.api.text.format.TextColors._
import org.spongepowered.api.text.format.{TextColors, TextStyles}

import io.github.katrix.katlib.KatPlugin
import io.github.katrix.katlib.helper.Implicits._
import io.github.katrix.katlib.helper.LogHelper
import io.github.katrix.katlib.i18n.{KLResource, Localized}
import io.github.katrix.katlib.lib.LibCommonTCommandKey

final class CmdHelp(cmdPlugin: CmdPlugin)(implicit plugin: KatPlugin) extends LocalizedCommand(Some(cmdPlugin)) {

  private val commandParents = new mutable.HashMap[CommandBase, Seq[CommandBase]]

  lazy private val commandsAliases = commandParents.flatMap {
    case (topCmd, xs) =>
      val named = xs.map(_.aliases)

      val allAliases = named.reduce { (names, acc) =>
        for {
          cmdName <- names
          str     <- acc
        } yield s"$cmdName $str"
      }.sorted

      allAliases.map(_ -> topCmd)
  }

  def execute(src: CommandSource, args: CommandContext): CommandResult = Localized(src) { implicit locale =>
    args.one(LibCommonTCommandKey.Command) match {
      case None =>
        val pages = PaginationList.builder()
        pages.title(t"$RED${KLResource.get("cmd.help.pageTitle", "plugin" -> plugin.container.name)}")

        if(commandParents.nonEmpty) {
          val text = commandParents.keys.toSeq.flatMap(commandBase => getCommandHelp(commandBase, src)).sorted
          pages.contents(text.asJavaCollection)
        }
        else {
          pages.contents(t"${RED}No commands found")
        }

        plugin.globalVersionAdapter.sendPagination(pages, src)
        CommandResult.success()
      case Some(commandName) =>
        val data = for {
          cmd <- commandsAliases
            .get(commandName)
            .toRight(new CommandException(t"$RED${KLResource.get("cmd.help.cmdNotFound")}"))
          help <- getCommandHelp(cmd, src).toRight(
            new CommandException(t"$RED${KLResource.get("cmd.help.noHelpFound")}")
          )
        } yield help

        data match {
          case Right(help) =>
            src.sendMessage(help)
            CommandResult.success()
          case Left(e) => throw e
        }
    }
  }

  override def localizedDescription(implicit locale: Locale): Option[Text] =
    Some(KLResource.getText("cmd.help.description"))
  override def localizedExtendedDescription(implicit locale: Locale): Option[Text] =
    Some(KLResource.getText("cmd.help.extendedDescription"))

  def commandSpec: CommandSpec =
    CommandSpec.builder
      .description(this)
      .extendedDescription(this)
      .permission(s"${plugin.container.id}.help")
      .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(LibCommonTCommandKey.Command)))
      .executor(this)
      .build

  def aliases: Seq[String] = Seq("help")

  /**
		* Creates a written command that is what needs to be entered when
		* the specified command is passed in.
		*/
  private def stringCommand(command: CommandBase): Option[String] =
    commandParents.get(command).map(seq => s"/${seq.map(_.aliases.head).mkString(" ")}")

  /**
		* Creates a help [[Text]] based on the passed in command
		*/
  private def getCommandHelp(commandBase: CommandBase, src: CommandSource): Option[Text] = {
    stringCommand(commandBase).map { strCommand =>
      val commandText = Text.builder().append(Text.of(TextColors.GREEN, TextStyles.UNDERLINE, strCommand))
      commandText.onHover(TextActions.showText(commandBase.help(src)))
      commandText.onClick(TextActions.suggestCommand(strCommand))
      Text.of(commandText, " ", commandBase.description(src).getOrElse(commandBase.usage(src)))
    }
  }

  private[command] def registerCommandHelp(command: CommandBase) {

    @tailrec
    def commandParent(optParent: Option[CommandBase], acc: List[CommandBase]): List[CommandBase] = optParent match {
      case Some(cmdParent) => commandParent(cmdParent.parent, cmdParent :: acc)
      case None            => acc
    }

    val parents = commandParent(Some(command), Nil)
    LogHelper.trace(s"Registering help command: $parents")
    commandParents.put(command, parents)
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Navbar example</title>

    <link rel="stylesheet" href="../../assets/css/bootstrap.css" />

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          Toggle navigation

        </button>
        Project name

Home

About

Contact

            Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Default (current)

Static top

Fixed top

Navbar example

This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.

      View navbar docs »


text:
function [Dest, A, lams, W] = tpm(SX, K, momtype, c0)
%TPM Tensor power method for topic modeling
%
% [A, lams, W] = tpm(SX, K, momtype, c0)
%
% Input:
%   SX      : sparse M-by-N matrix of word counts X with docs in columns
%   K       : number of topics
%   momtype : either 'lda' for LDA-moments or 'dica' for DICA-cumulants
%   c0      : parameter (only for LDA-moments, i.e. momtype = 'lda')
%
% Output:
%   Dest : estimation of the topic matrix
%   A    : K-by-M diagonalizing matrix
%   lams : K-vector with robust eigenvalues
%   W    : K-by-M whitening matrix
%
% Comment 1: See "estimate_D.m" for details on estimation of D.

% Copyright 2015, Anastasia Podosinnikova

  if ~( strcmp(momtype,'lda') || strcmp(momtype,'dica') )
    error('Wrong momtype')
  end

  % whitening and precomputation
  if strcmp(momtype,'dica')
    [W, M1] = compute_S_and_W_dica(SX,K);
    precomputed = precompute_for_wtw(SX, W, momtype, M1);
  end
  if strcmp(momtype,'lda')
    [W, M1, M2] = compute_S_and_W_lda(SX,K,c0);
    precomputed = precompute_for_wtw(SX, W, momtype, M1, M2);
  end

  thetas = zeros(K,K); % robust eigenvectors
  lams   = zeros(K,1); % robust eigenvalues

  for k = 1:K
    if strcmp(momtype,'dica')
      [theta,lam] = find_eigenpair(...
                 SX, W, K, M1, thetas, lams, precomputed, momtype);
    end
    if strcmp(momtype,'lda')
      [theta,lam] = find_eigenpair(...
                 SX, W, K, M1, thetas, lams, precomputed, momtype, c0, M2);
    end
    thetas(:,k) = theta;
    lams(k) = lam;
  end
  W = full(W);
  A = thetas'*W;

  Dest = estimate_D(A);
end

function [theta, lam] = find_eigenpair(...
                  SX, W, K, M1, thetas, lams, precomputed, momtype, c0, M2)
% lam is a robust eigenvalue
% theta is the respective robust eigenvector

  % It is known (theoretical result in the tpm paper) that for some bad
  % starting points tpm's convergence can be extremely slow. However, there
  % are other good starting points which converge fast and, in practice,
  % always to a better solution. Therefore, when looking for a robust
  % eigenpair, it is better to have several restarts (nruns) but limit the
  % number of iterations in each restart to some relatively small value
  % (maxiter). We experimentally found some reasonable values for these
  % parameters. There could be other good values.
  eps = 1e-5;
  maxiter = 100; % N in the tpm paper
  nruns = 10; % L in the tpm paper

  vects = cell(nruns,1);
  vals  = zeros(nruns,1);

  i = 1;
  while 1>0
    u = rand(K,1); u = u/norm(u);
    iter = 1;
    while 1>0
      if strcmp(momtype,'dica')
        WTW = compute_wtw_single_dica(SX, W, W'*u, M1, precomputed);
      end
      if strcmp(momtype,'lda')
        WTW = compute_wtw_single_lda(SX, W, W'*u, M1, M2, c0, precomputed);
      end
      gradient = WTW*u - thetas*(lams.*(thetas'*u).^2);
      unew = gradient/norm(gradient);

      if norm(u-unew) < eps, break, end
      u = unew;
      iter = iter + 1;
      if iter > maxiter, break, end
    end

    vects{i} = u;
    vals(i) = u'*gradient;
    i = i + 1;

    if i > nruns, break, end
  end

  [~,ind] = max(vals);

  theta = vects{ind};
  lam = vals(ind);

end


text:
package saiba.bml.feedback;

import hmi.xml.XMLFormatting;
import hmi.xml.XMLTokenizer;

import java.util.HashMap;

import saiba.bml.BMLInfo;

public class BMLBlockProgressFeedback extends AbstractBMLFeedback
{
    private String bmlId;
    private String syncId;
    private double globalTime;
    private String characterId;

    public BMLBlockProgressFeedback()
    {

    }

    public BMLBlockProgressFeedback(String bmlId, String syncId, double globalTime)
    {
        this(bmlId,syncId,globalTime,null);
    }

    public BMLBlockProgressFeedback(String bmlId, String syncId, double globalTime, String characterId)
    {
        this.bmlId = bmlId;
        this.syncId = syncId;
        this.globalTime = globalTime;
        this.characterId = characterId;
    }

    public void setCharacterId(String characterId)
    {
        this.characterId = characterId;
    }

    @Override
    public void decodeAttributes(HashMap<String, String> attrMap, XMLTokenizer tokenizer)
    {
        String id = getRequiredAttribute("id", attrMap, tokenizer);
        String[] idSplit = id.split(":");
        bmlId = idSplit[0];
        syncId = idSplit[1];
        globalTime = getRequiredFloatAttribute("globalTime", attrMap, tokenizer);
        characterId = getOptionalAttribute("characterId", attrMap);
        caHandler.decodeCustomAttributes(attrMap, tokenizer, BMLInfo.getCustomFeedbackFloatAttributes(getClass()),
                BMLInfo.getCustomFeedbackStringAttributes(getClass()), this);
    }

    @Override
    public StringBuilder appendAttributeString(StringBuilder buf, XMLFormatting fmt)
    {
        if(characterId!=null)
        {
            appendAttribute(buf, "characterId", characterId);
        }
        appendAttribute(buf, "id", bmlId+":"+syncId);
        appendAttribute(buf, "globalTime", globalTime);
        caHandler.appendCustomAttributeString(buf, fmt);
        return buf;
    }

    public String getBmlId()
    {
        return bmlId;
    }

    public String getSyncId()
    {
        return syncId;
    }

    public double getGlobalTime()
    {
        return globalTime;
    }

    public String getCharacterId()
    {
        return characterId;
    }

    /**
     * The XML Stag for XML encoding
     */
    private static final String XMLTAG = "blockProgress";

    /**
     * The XML Stag for XML encoding -- use this static method when you want to
     * see if a given String equals the xml tag for this class
     */
    public static String xmlTag()
    {
        return XMLTAG;
    }

    /**
     * The XML Stag for XML encoding -- use this method to find out the run-time
     * xml tag of an object
     */
    @Override
    public String getXMLTag()
    {
        return XMLTAG;
    }
    public static final String BMLNAMESPACE = "http://www.bml-initiative.org/bml/bml-1.0";

    @Override
    public String getNamespace()
    {
        return BMLNAMESPACE;
    }
}


text:
package graphite

import (
	"fmt"
	"sort"
	"strings"

	"github.com/influxdata/telegraf"
)

type GraphiteSerializer struct {
	Prefix string
}

func (s *GraphiteSerializer) Serialize(metric telegraf.Metric) ([]string, error) {
	out := []string{}
	// Get name
	name := metric.Name()
	// Convert UnixNano to Unix timestamps
	timestamp := metric.UnixNano() / 1000000000
	tag_str := buildTags(metric)

	for field_name, value := range metric.Fields() {
		// Convert value
		value_str := fmt.Sprintf("%#v", value)
		// Write graphite metric
		var graphitePoint string
		if name == field_name {
			graphitePoint = fmt.Sprintf("%s.%s %s %d",
				tag_str,
				strings.Replace(name, ".", "_", -1),
				value_str,
				timestamp)
		} else {
			graphitePoint = fmt.Sprintf("%s.%s.%s %s %d",
				tag_str,
				strings.Replace(name, ".", "_", -1),
				strings.Replace(field_name, ".", "_", -1),
				value_str,
				timestamp)
		}
		if s.Prefix != "" {
			graphitePoint = fmt.Sprintf("%s.%s", s.Prefix, graphitePoint)
		}
		out = append(out, graphitePoint)
	}
	return out, nil
}

func buildTags(metric telegraf.Metric) string {
	var keys []string
	tags := metric.Tags()
	for k := range tags {
		if k == "host" {
			continue
		}
		keys = append(keys, k)
	}
	sort.Strings(keys)

	var tag_str string
	if host, ok := tags["host"]; ok {
		if len(keys) > 0 {
			tag_str = strings.Replace(host, ".", "_", -1) + "."
		} else {
			tag_str = strings.Replace(host, ".", "_", -1)
		}
	}

	for i, k := range keys {
		tag_value := strings.Replace(tags[k], ".", "_", -1)
		if i == 0 {
			tag_str += tag_value
		} else {
			tag_str += "." + tag_value
		}
	}
	return tag_str
}


text:
class OrangeTree
  def initialize(fruit = 50)
    @fruit = fruit
  end

  def pick!(amount = 1)
    if amount > @fruit
      nil
    else
      puts 'amount = ' + amount.to_s # this is for debugging puts
      @fruit -= amount
    end
  end

  def pick(amount = 1)
    if amount > @fruit
      nil
    else
      OrangeTree.new(@fruit - amount)
      # Otherwise, returns a new OrangeTree object with it's fruit instance
      # variable initialized to the difference between `@fruit` and `amount`.
    end
  end

  def ==(other)
    if @fruit == other.fruit
      true
    else
      false
    end
  end

  def fruit
    @fruit
  end
end

orange_tree_1 = OrangeTree.new
orange_tree_2 = orange_tree_1.pick

puts orange_tree_1.fruit
puts orange_tree_2.fruit

orange_tree = OrangeTree.new
puts orange_tree.fruit        # => 50

tree_2 = orange_tree.pick     # => OrangeTree.new(49)
puts orange_tree.fruit        # => 50
puts tree_2.fruit
puts

tree_3 = orange_tree.pick(49) # => OrangeTree.new(1)
puts orange_tree.fruit        # => 50
puts tree_3.fruit
puts

tree_4 = orange_tree.pick(50) # => OrangeTree.new(0)
puts orange_tree.fruit        # => 50
puts tree_4.fruit
puts

tree_5 = orange_tree.pick(51) # => nil
puts orange_tree.fruit        # => 50
if tree_5 != nil
  puts tree_5.fruit           # b/c tree_5 = nil ... it'll blow up
end


text:
import jsonwebtoken from 'jsonwebtoken';
import { User, Recipe, Review, Favorite } from '../models';
import Encryption from '../middleware/encryption';
import { validateUserName } from '../middleware/userValidation';
import { validateSignUp } from '../middleware/inputValidation';
import trimWhiteSpaces from '../services/trimWhiteSpaces';
import cloudinary, { uploadWithMulter } from '../services/uploadImage';

import * as Mailer from '../services/mailer';

const newEncryption = new Encryption();
const notify = new Mailer.default();

const { JWT_SECRET } = process.env;

/**
 * @description - Checks if email or username already exist in the database
 *
 * @param {string} username - Username
 *
 * @param {string} email - Email address
 *
 * @returns {Promise} promise - Asynchronous promise
 */
const verifyAuthName = (username, email) => {
  const promise = new Promise((resolve, reject) => {
    User
      .findOne({
        attributes: ['email', 'username'],
        where: {
          $or: [
            {
              username: {
                $iLike: username
              }
            }, {
              email: {
                $iLike: email
              }
            }
          ]
        }
      })
      .then((userFound) => {
        if (userFound) {
          let field;
          if (userFound.username.toUpperCase() === username.toUpperCase()) {
            field = 'Username';
          } else {
            field = 'Email';
          }

          reject(`${field} already taken!`);
        }

        resolve();
      });
  });
  return promise;
};

/**
 * @description - Class Definition for the User Object
 *
 * @export
 *
 * @class Users
 */
export default class Users {
  /**
   * @description - Sign Up user (Create new user)
   *
   * @param {object} req - HTTP Request
   *
   * @param {object} res - HTTP Response
   *
   * @return {object} this - Class instance
   *
   * @memberof Users
   */
  signUp({ body }, res) {
    const name = trimWhiteSpaces(body.name, ' ');
    const username = trimWhiteSpaces(body.username);
    const email = trimWhiteSpaces(body.email);
    const password = (body.password || '');

    const validateSignUpError =
      validateSignUp({
        name,
        username,
        email,
        password
      });

    if (validateSignUpError.length > 0) {
      return res.status(400).json({
        success: false,
        message: validateSignUpError
      });
    }

    verifyAuthName(username, email).then(() => {
      User
        .create({
          name,
          username,
          email,
          imageUrl: '',
          password: newEncryption.generateHash(password),
        })
        .then((result) => {
          const token = jsonwebtoken.sign({
            id: result.id,
            username: result.username,
            exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24)
          }, JWT_SECRET);

          notify.send({
            type: 'welcome',
            email,
            name,
            userId: result.id,
            subject: 'Welcome to more recipe'
          });

          return res.status(201).json({
            success: true,
            message: 'New user created/token generated!',
            token
          });
        })
        .catch(error => res.status(500).json({
          success: false,
          message: `Error creating user ${error.message}`
        }));
    }).catch(error =>
      res.status(409).json({
        success: false,
        message: error
      }));

    return this;
  }

  /**
   * @description - Sign In a user (Search for user)
   *
   * @param {object} req - HTTP Request
   *
   * @param {object} res - HTTP Response
   *
   * @return {object} this - Class instance
   *
   * @memberof Users
   */
  signIn(req, res) {
    const authName =
      trimWhiteSpaces(req.body.authName);

    User
      .findOne({
        attributes: ['id', 'name', 'username', 'email', 'password'],
        where: {
          $or: [
            {
              username: {
                $iLike: authName
              }
            }, {
              email: {
                $iLike: authName
              }
            }
          ]
        }
      })
      .then((userFound) => {
        if (!userFound) {
          return res.status(401).json({
            success: false,
            message: 'Invalid Login Credentials!'
          });
        }

        if (newEncryption.verifyHash(req.body.password, userFound.password)) {
          const { id, username } = userFound;
          const token = jsonwebtoken.sign({
            id,
            username,
            exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24)
          }, JWT_SECRET);

          return res.status(200).json({
            success: true,
            message: 'User Signed In/token generated!',
            token
          });
        }
        res.status(401).json({
          success: false,
          message: 'Invalid Login Credentials!'
        });
      })
      .catch((/* error */) => res.status(500).json({
        success: false,
        message: 'An error occured'
      }));

    return this;
  }

  /**
   * @description - Get the user record (e.g for profile page)
   *
   * @param {any} req - HTTP request
   *
   * @param {any} res - HTTP reponse
   *
   * @returns {void} Nothing
   *
   * @memberof Users
   */
  getUser({ params }, res) {
    const { userId } = params;
    User
      .findOne({
        attributes: ['id', 'name', 'username', 'email', 'imageUrl'],
        where: { id: userId }
      })
      .then((userFound) => {
        if (!userFound) {
          return res.status(404).json({
            success: false,
            message: 'User not found!'
          });
        }

        const {
          id, name, username, email, imageUrl
        } = userFound;

        const userInfo = {
          userId: id, name, username, email, imageUrl
        };

        Recipe.count({
          where: { userId },
        })
          .then((recipeCount) => {
            userInfo.myRecipes = recipeCount;

            Review.count({
              where: { userId },
            })
              .then((reviewCount) => {
                userInfo.myReviews = reviewCount;

                Favorite.count({
                  where: { userId },
                })
                  .then((favCount) => {
                    userInfo.myFavs = favCount;
                    return res.status(200).json({
                      success: true,
                      message: 'User found!',
                      user: userInfo
                    });
                  });
              });
          })
          .catch((/* error */) => res.status(500).json({
            success: false,
            message: 'Error fetching other details'
          }));
      })
      .catch((/* error */) => res.status(500).json({
        success: false,
        message: 'Error fetching user details'
      }));

    return this;
  }

  /**
   * @description - Change user password
   *
   * @param {any} req - HTTP request
   *
   * @param {any} res - HTTP response
   *
   * @returns {void} Nothing
   *
   * @memberof Users
   */
  changePassword({ body, user }, res) {
    const { id } = user;
    const { oldPassword } = body;
    const newPassword = (body.newPassword || '');

    if (newPassword.trim().length === 0 || newPassword.length < 6) {
      return res.status(400).json({
        success: false,
        message: 'Password must be at least 6 characters!'
      });
    }

    const password = newEncryption.generateHash(newPassword);
    User
      .findOne({
        attributes: ['id', 'password'],
        where: { id }
      })
      .then((userFound) => {
        if (!userFound) {
          return res.status(404).json({
            success: false,
            message: 'User does not exist!'
          });
        }

        if (!newEncryption.verifyHash(oldPassword, userFound.password)) {
          return res.status(401).json({
            success: false,
            message: 'Incorrect Password'
          });
        }

        userFound.updateAttributes({
          password
        }).then(() => res.status(200).json({
          success: true,
          message: 'Password Changed Successfully'
        }));
      })
      .catch((/* error */) => res.status(500).json({
        success: false,
        message: 'An error occured'
      }));

    return this;
  }

  /**
   * @description - Modify user record
   *
   * @param {object} req - HTTP Request
   *
   * @param {object} res - HTTP Response
   *
   * @return {object} this - Class instance
   *
   * @memberof Users
   */
  modifyUser(req, res) {
    /**
     * @description - Updates the user details in the database
     *
     * @param {object} userData - User details
     *
     * @returns {object} Response - HTTP Response
     */
    const updateDatabase = ({
      name, username, imageUrl, res, userId, imageId
    }) => {
      User.findOne({
        where: { id: userId },
      })
        .then((foundUser) => {
          if (!foundUser) {
            return res.status(404).json({
              success: false,
              message: 'User not found'
            });
          }

          if (imageId !== foundUser.imageId) {
            cloudinary.destroy(foundUser.imageId, () => { });
          }

          foundUser.updateAttributes({
            name,
            username,
            imageUrl: imageUrl || foundUser.imageUrl,
            imageId: imageId || foundUser.imageId
          })
            .then((user) => {
              const { id } = user;
              const token = jsonwebtoken.sign({
                id,
                username,
                exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24)
              }, JWT_SECRET);

              return res.status(200).json({
                success: true,
                message: 'User record updated',
                user: {
                  username, name, imageUrl: user.imageUrl, token
                }
              });
            });
        })
        .catch((/* error */) => res.status(500).json({
          success: false,
          message: 'An error occured'
        }));
    };

    uploadWithMulter(req, res).then(({ file, user, body }) => {
      const userId = user.id;
      const name = trimWhiteSpaces(body.name, ' ');
      const username = trimWhiteSpaces(body.username);

      if (name.length < 3 || name.length > 100) {
        return res.status(400).json({
          success: false,
          message: 'Name must be between 3 to 100 characters!'
        });
      }

      if (username.length < 3 || username.length > 50) {
        return res.status(400).json({
          success: false,
          message: 'Username must be between 3 to 50 character!'
        });
      }

      validateUserName(User, username, userId).then(() => {
        if (file) {
          cloudinary.upload_stream(({ error, secure_url, public_id }) => {
            if (!error) {
              updateDatabase({
                name,
                username,
                res,
                userId,
                imageUrl: secure_url,
                imageId: public_id
              });
            } else {
              res.status(503).json({
                success: false,
                message: 'Error uploading image, check your network connection'
              });
            }
          }).end(file.buffer);
        } else {
          updateDatabase({
            name,
            username,
            res,
            userId,
            imageUrl: '',
            imageId: ''
          });
        }
      })
        .catch(({ status, message }) => {
          res.status(status).json({
            success: false,
            message
          });
        });
    })
      .catch(({ message }) => {
        res.status(400).json({
          success: false,
          message
        });
      });
    return this;
  }
}


text:
function gcrExtEditorUpdateAnswersList(){
    list.innerHTML = "";
    for(var i = 0; i < __gcrExtAnswers.length; i++){
        var li = gcrExtEditorCreateItem(__gcrExtAnswers[i].name, __gcrExtAnswers[i].description, __quickReply[__gcrExtAnswers[i].name]);
        li.answerId = i;
        list.appendChild(li);
    }
}

function gcrExtEditorSetup(){
    list = document.getElementById("gcrExtAnswerList");

    document.querySelector("#gcr-auto-submit").checked = __submitOnClick;

    document.querySelector("#gcrExtNewButton").addEventListener("click", function(event){
        var name = document.getElementById("gcrExtNewTitle").value;
        var text = document.getElementById("gcrExtNewText").value;

        if(name.trim() === "" || text.trim() === ""){
            document.querySelector("#gcrExtNewConfirm").hidden = true;
            document.querySelector("#gcrExtNewError").hidden = false;
            return;
        }

        document.querySelector("#gcrExtNewConfirm").hidden = true;
        document.querySelector("#gcrExtNewError").hidden = true;

        var answerId = __gcrExtAnswers.length;
        __gcrExtAnswers.push({name: name, description: text});

        // Save to local storage.
        gcrExtEditorSaveAnswers();

        // Add to the UI list.
        var li = gcrExtEditorCreateItem(name, text);
        li.answerId = answerId;
        list.appendChild(li);

        document.querySelector("#gcrExtNewConfirm").hidden = false;
        document.getElementById("gcrExtNewTitle").value = "";
        document.getElementById("gcrExtNewText").value = "";

        // Clear it after a bit.
        setTimeout(function(){
            document.querySelector("#gcrExtNewConfirm").hidden = true;
        }, 2000);
    });

    document.querySelector(".gcr-ext-editor-list").addEventListener("click", function(event){
        var target = null;

        if(event.target.classList.contains("quick-reply")) {
            target = event.target.parentNode;
        }
        else if(event.target.tagName.toLowerCase() !== "button") {
            return;
        }
        else {
            target = event.target;
        }

        var item = target.parentNode;
        var title = item.querySelector(".gcr-ext-editor-answer-title");
        var text = item.querySelector(".gcr-ext-editor-answer-text");

        // This is pretty lame.
        if(target.textContent.toLowerCase() === "edit"){
            title.disabled = text.disabled = false;
            target.textContent = "Save";
            title.focus();
        }
        else if(target.textContent.toLowerCase() === "save"){
            title.disabled = text.disabled = true;
            target.textContent = "Edit";

            // Save locally.
            var answerId = item.answerId;

            if (__quickReply[__gcrExtAnswers[item.answerId].name]) {
                delete __quickReply[__gcrExtAnswers[item.answerId].name];
                __quickReply[title.value] = text.value;
            }

            __gcrExtAnswers[item.answerId].name = title.value;
            __gcrExtAnswers[item.answerId].description = text.value;

            // Save to local storage.
            gcrExtEditorSaveAnswers();
        }
        else if(target.textContent.toLowerCase() === "delete"){
            __gcrExtAnswers.splice(item.answerId, 1);
            delete __quickReply[title.value];

            // Save to local storage.
            gcrExtEditorSaveAnswers();
            gcrExtEditorUpdateAnswersList();
        }
        else if(event.target.classList.contains("quick-reply")) {
            var checkbox = event.target;

            if (event.target.type === "LABEL") {
                checkbox = event.target.previousSibling;
            }

            if (checkbox.checked) {
                __quickReply[title.value] = text.value;
            }
            else {
                delete __quickReply[title.value];
            }

            // Save to local storage.
            gcrExtEditorSaveAnswers();
            gcrExtEditorUpdateAnswersList();
        }
    });

    document.querySelector("#gcr-auto-submit").addEventListener("click", function(event){
        __submitOnClick = this.checked;
        // Save to local storage.
        gcrExtEditorSaveAnswers();
    });
}

function gcrExtEditorCreateItem(name, text, isQuickReply){
    var li = document.createElement("li");

    var title = document.createElement("input");
    title.className = "gcr-ext-editor-answer-title gcr-ext-editor-single-line";
    title.value = name;
    title.disabled = true;

    var desc = document.createElement("textarea");
    desc.className = "gcr-ext-editor-answer-text";
    desc.textContent = text;
    desc.disabled = true;

    var edit = document.createElement("button");
    edit.className = "btn btn-sm btn-primary";
    edit.textContent = "Edit";

    var del = document.createElement("button");
    del.className = "btn btn-sm";
    del.textContent = "Delete";
    del.style.marginLeft = "10px";

    var quickReply = document.createElement("div");
    quickReply.className = "btn btn-sm";
    quickReply.innerHTML =
        "<input type='checkbox' id='quick-reply-" + name + "' class='quick-reply quick-reply-check' " + (isQuickReply ? "checked" : "") + "></input>" +
        "<label class='quick-reply quick-reply-label' for='quick-reply-" + name + "'>Quick reply</label>";
    quickReply.style.marginLeft = "10px";
    quickReply.style.display = "inline-block";

    li.appendChild(title);
    li.appendChild(desc);
    li.appendChild(edit);
    li.appendChild(del);
    li.appendChild(quickReply);
    return li;
}


text:
"""Test MongoClient's mongos load balancing using a mock."""

import sys
import threading

sys.path[0:0] = [""]

from test import MockClientTest, client_context, unittest
from test.pymongo_mocks import MockClient
from test.utils import connected, wait_until

from pymongo.errors import AutoReconnect, InvalidOperation
from pymongo.server_selectors import writable_server_selector
from pymongo.topology_description import TOPOLOGY_TYPE

@client_context.require_connection
@client_context.require_no_load_balancer
def setUpModule():
    pass

class SimpleOp(threading.Thread):
    def __init__(self, client):
        super(SimpleOp, self).__init__()
        self.client = client
        self.passed = False

    def run(self):
        self.client.db.command("ping")
        self.passed = True  # No exception raised.

def do_simple_op(client, nthreads):
    threads = [SimpleOp(client) for _ in range(nthreads)]
    for t in threads:
        t.start()

    for t in threads:
        t.join()

    for t in threads:
        assert t.passed

def writable_addresses(topology):
    return set(
        server.description.address for server in topology.select_servers(writable_server_selector)
    )

class TestMongosLoadBalancing(MockClientTest):
    def mock_client(self, **kwargs):
        mock_client = MockClient(
            standalones=[],
            members=[],
            mongoses=["a:1", "b:2", "c:3"],
            host="a:1,b:2,c:3",
            connect=False,
            **kwargs
        )
        self.addCleanup(mock_client.close)

        # Latencies in seconds.
        mock_client.mock_rtts["a:1"] = 0.020
        mock_client.mock_rtts["b:2"] = 0.025
        mock_client.mock_rtts["c:3"] = 0.045
        return mock_client

    def test_lazy_connect(self):
        # While connected() ensures we can trigger connection from the main
        # thread and wait for the monitors, this test triggers connection from
        # several threads at once to check for data races.
        nthreads = 10
        client = self.mock_client()
        self.assertEqual(0, len(client.nodes))

        # Trigger initial connection.
        do_simple_op(client, nthreads)
        wait_until(lambda: len(client.nodes) == 3, "connect to all mongoses")

    def test_failover(self):
        nthreads = 10
        client = connected(self.mock_client(localThresholdMS=0.001))
        wait_until(lambda: len(client.nodes) == 3, "connect to all mongoses")

        # Our chosen mongos goes down.
        client.kill_host("a:1")

        # Trigger failover to higher-latency nodes. AutoReconnect should be
        # raised at most once in each thread.
        passed = []

        def f():
            try:
                client.db.command("ping")
            except AutoReconnect:
                # Second attempt succeeds.
                client.db.command("ping")

            passed.append(True)

        threads = [threading.Thread(target=f) for _ in range(nthreads)]
        for t in threads:
            t.start()

        for t in threads:
            t.join()

        self.assertEqual(nthreads, len(passed))

        # Down host removed from list.
        self.assertEqual(2, len(client.nodes))

    def test_local_threshold(self):
        client = connected(self.mock_client(localThresholdMS=30))
        self.assertEqual(30, client.options.local_threshold_ms)
        wait_until(lambda: len(client.nodes) == 3, "connect to all mongoses")
        topology = client._topology

        # All are within a 30-ms latency window, see self.mock_client().
        self.assertEqual(set([("a", 1), ("b", 2), ("c", 3)]), writable_addresses(topology))

        # No error
        client.admin.command("ping")

        client = connected(self.mock_client(localThresholdMS=0))
        self.assertEqual(0, client.options.local_threshold_ms)
        # No error
        client.db.command("ping")
        # Our chosen mongos goes down.
        client.kill_host("%s:%s" % next(iter(client.nodes)))
        try:
            client.db.command("ping")
        except:
            pass

        # We eventually connect to a new mongos.
        def connect_to_new_mongos():
            try:
                return client.db.command("ping")
            except AutoReconnect:
                pass

        wait_until(connect_to_new_mongos, "connect to a new mongos")

    def test_load_balancing(self):
        # Although the server selection JSON tests already prove that
        # select_servers works for sharded topologies, here we do an end-to-end
        # test of discovering servers' round trip times and configuring
        # localThresholdMS.
        client = connected(self.mock_client())
        wait_until(lambda: len(client.nodes) == 3, "connect to all mongoses")

        # Prohibited for topology type Sharded.
        with self.assertRaises(InvalidOperation):
            client.address

        topology = client._topology
        self.assertEqual(TOPOLOGY_TYPE.Sharded, topology.description.topology_type)

        # a and b are within the 15-ms latency window, see self.mock_client().
        self.assertEqual(set([("a", 1), ("b", 2)]), writable_addresses(topology))

        client.mock_rtts["a:1"] = 0.045

        # Discover only b is within latency window.
        wait_until(
            lambda: set([("b", 2)]) == writable_addresses(topology),
            'discover server "a" is too far',
        )

if __name__ == "__main__":
    unittest.main()


text:
package org.springframework.cloud.stream.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.beans.factory.annotation.Qualifier;

/**
 * Indicates an instance of an interface containing methods returning bound
 * inputs and outputs.
 *
 * @author Dave Syer
 * @author Marius Bogoevici
 * @deprecated As of 1.1 for being redundant (beans qualified by it are already
 *             uniquely identified by their type)
 */

@Qualifier
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Deprecated
public @interface Bindings {

	Class<?> value();

}


text:
namespace captive_portal {

void CaptivePortalMetrics::LogCaptivePortalBlockingPageEvent(
    CaptivePortalBlockingPageEvent event) {
  UMA_HISTOGRAM_ENUMERATION("interstitial.captive_portal", event,
                            CAPTIVE_PORTAL_BLOCKING_PAGE_EVENT_COUNT);
}

}  // namespace captive_portal


text:
package org.apache.skywalking.library.elasticsearch.requests.factory.v7.codec;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.io.SerializedString;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Strings;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.library.elasticsearch.response.IndexTemplate;
import org.apache.skywalking.library.elasticsearch.response.IndexTemplates;

import static java.util.stream.Collectors.toMap;

@Slf4j
final class V78IndexTemplatesDeserializer extends JsonDeserializer<IndexTemplates> {
    private static final TypeReference<List<IndexTemplateWrapper>> TYPE_REFERENCE =
        new TypeReference<List<IndexTemplateWrapper>>() {
        };

    @Override
    public IndexTemplates deserialize(final JsonParser p,
                                      final DeserializationContext ctxt)
        throws IOException {
        while (!p.nextFieldName(new SerializedString("index_templates"))) {
            if (p.currentName() == null) {
                return new IndexTemplates(Collections.emptyMap());
            }
            p.skipChildren();
        }
        if (p.nextToken() != JsonToken.START_ARRAY) {
            throw new UnsupportedOperationException(
                "this might be a new ElasticSearch version and we don't support yet");
        }

        final JsonNode array = p.getCodec().readTree(p);
        final List<IndexTemplate> templates = new ArrayList<>(array.size());
        for (final JsonNode node : array) {
            final String name = node.get("name").asText();
            if (Strings.isNullOrEmpty(name)) {
                log.error("index template without a name: {}", node);
                continue;
            }

            final JsonNode indexTemplateNode = node.get("index_template");
            if (indexTemplateNode == null) {
                log.error("index template without index_template: {}", node);
                continue;
            }
            final IndexTemplateWrapper wrapper =
                p.getCodec().treeToValue(indexTemplateNode, IndexTemplateWrapper.class);
            wrapper.getTemplate().setName(name);
            wrapper.getTemplate().setIndexPatterns(wrapper.getIndexPatterns());
            templates.add(wrapper.getTemplate());
        }

        final Map<String, IndexTemplate> templateMap =
            templates.stream()
                     .collect(toMap(IndexTemplate::getName, Function.identity()));
        return new IndexTemplates(templateMap);
    }

    @Data
    static final class IndexTemplateWrapper {
        @JsonProperty("index_patterns")
        private List<String> indexPatterns;
        private IndexTemplate template;
    }
}


text:
bool CanAddURLToHistory(const GURL& url) {
  if (!url.is_valid())
    return false;

  // TODO: We should allow kChromeUIScheme URLs if they have been explicitly
  // typed.  Right now, however, these are marked as typed even when triggered
  // by a shortcut or menu action.
  // Right now, URLs like about:version are not registered in the history.
  if (url.SchemeIs(url::kJavaScriptScheme) || url.SchemeIs(url::kAboutScheme) ||
      url.SchemeIs(url::kContentScheme) ||
      url.SchemeIs(content::kChromeDevToolsScheme) ||
      url.SchemeIs(content::kChromeUIScheme) ||
      url.SchemeIs(content::kChromeUIUntrustedScheme) ||
      url.SchemeIs(content::kViewSourceScheme) ||
      url.SchemeIs(chrome::kChromeNativeScheme) ||
      url.SchemeIs(chrome::kChromeSearchScheme) ||
      url.SchemeIs(dom_distiller::kDomDistillerScheme))
    return false;

  return true;
}


text: Program that contains a method that accepts n and returns the nth number in the Fibonacci sequence.


text:
MS in Computer Science and Engineering Courses assignments and exams. The Code comments and project report will be explanatory. If in case you have a doubt or you find a mistake please let me know.

Project 1: Probability Distributions and Bayesian Networks
           The aim of the project is to construct a Bayesian network which results in a higher loglikelihood using the correlation between variables.

Project 2: Learning to Rank using Linear Regression
           The goal of this project is to use machine learning to solve a problem that arises in Information Retrieval,
one known as the Learning to Rank (LeToR) problem.

Project 3: Classification

Project 4: Introduction to Deep Learning
In the previous assignment we learnt how to implement a Convolutional Neural Network on MNIST images. In this project we extend our understanding of CNN and implement a model for classifying CelebA data set to determine whether the person in a portrait image is wearing eyeglasses or not. The task here is to tune hyperparameters and apply regularization to improve performance.


text:
<?php

declare(strict_types=1);

namespace LizardsAndPumpkins\Util\Storage;

interface Clearable
{
    /**
     * @return void
     */
    public function clear();
}


text:
import os

try:
    import urlparse
except ImportError:
    from urllib import parse as urlparse

def construct_url(url, href):
    u = urlparse.urlsplit(url)
    base_url = u.scheme + "://" + u.netloc
    relative_path = urlparse.urljoin(base_url, os.path.split(u.path)[0])

    if not href:
        return url

    if href[0] == "/":
        # Absolute paths
        cat = urlparse.urljoin(base_url, href)
    elif href[0:4] == "http":
        # Full HTTP links
        cat = href
    else:
        # Relative paths.
        cat = relative_path + "/" + href

    return cat


text:
Flux = require('./../flux');
var Constants = require('./constants');

module.exports = Flux.createActions({
    receiveMatchId: function(id) {
        return {
            actionType: Constants.RECEIVE_MATCH_ID,
            id: id
        }
    },
    receiveMoves: function() {
        return {
            actionType: Constants.RECEIVE_MOVES
        }
    },
    receiveStadiums: function() {
        return {
            actionType: Constants.RECEIVE_STADIUMS
        }
    },
    receiveChants: function() {
        return {
            actionType: Constants.RECEIVE_CHANTS
        }
    },
    receivePokerPlayers: function() {
        return {
            actionType: Constants.RECEIVE_POKER_PLAYERS
        }
    }
});


text:
export async function getServerSideProps() {
  // We will use this route to simulate a route change errors
  throw new Error('KABOOM!')
}

export default function Page() {
  return null
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<scriptmodule xmlns="http://xlt.xceptance.com/xlt-script/2" version="6">
  <description>Validate shipping address.</description>
  <parameter name="firstname" desc="firstname"/>
  <parameter name="lastname" desc="lastname"/>
  <parameter name="address1" desc="address1"/>
  <parameter name="address2" desc="address2"/>
  <parameter name="city" desc="city"/>
  <parameter name="statesStateShort" desc="states state short"/>
  <parameter name="postalCode" desc="postal code"/>
  <parameter name="country" desc="country"/>
  <parameter name="phone" desc="phone"/>
  <parameter name="shippingMethod_name" desc="shipping method name"/>
  <parameter name="shippingStatus" desc="shipping status"/>
  <codecomment>Validate column shipping</codecomment>
  <command name="store" target="css=#main #primary .order-shipment-table .order-shipment-details" value="css_column_shipping"/>
  <codecomment>Validate shipping address</codecomment>
  <command name="waitForText" target="${css_column_shipping} .order-shipment-address .firstname" value="@{firstname}"/>
  <command name="assertText" target="${css_column_shipping} .order-shipment-address .lastname" value="@{lastname}"/>
  <command name="assertText" target="${css_column_shipping} .order-shipment-address .street" value="*@{address1}*@{address2}*"/>
  <command name="assertText" target="${css_column_shipping} .order-shipment-address .location" value="*@{city}*@{statesStateShort}*@{postalCode}*"/>
  <command name="assertText" target="${css_column_shipping} .order-shipment-address .country" value="@{country}"/>
  <command name="assertText" target="${css_column_shipping} .order-shipment-address .phone" value="*@{phone}*"/>
  <codecomment>Validate shipping method</codecomment>
  <command name="assertText" target="${css_column_shipping} .shipping-method span:nth-of-type(2)" value="@{shippingMethod_name}"/>
  <codecomment>Validate shipping status</codecomment>
  <command name="assertText" target="${css_column_shipping} .shipping-status" value="*@{shippingStatus}*"/>
</scriptmodule>


text:
package com.dtolabs.rundeck.server.plugins.services;

import com.dtolabs.rundeck.core.execution.service.ProviderCreationException;
import com.dtolabs.rundeck.core.plugins.*;
import com.dtolabs.rundeck.core.plugins.configuration.DescribableServiceUtil;
import com.dtolabs.rundeck.core.plugins.configuration.Description;

import java.util.List;

/**
 * Created by greg on 9/9/15.
 */
public class BasePluginProviderService<T> extends BasePluggableProviderService<T> {
    private ServiceProviderLoader rundeckServerServiceProviderLoader;

    public BasePluginProviderService(
            final String name,
            final Class<? extends T> implementationClass
    )
    {
        super(name, implementationClass);
    }

    @Override
    public ServiceProviderLoader getPluginManager() {
        return getRundeckServerServiceProviderLoader();
    }

    public ServiceProviderLoader getRundeckServerServiceProviderLoader() {
        return rundeckServerServiceProviderLoader;
    }

    public void setRundeckServerServiceProviderLoader(ServiceProviderLoader rundeckServerServiceProviderLoader) {
        this.rundeckServerServiceProviderLoader = rundeckServerServiceProviderLoader;
    }

    @Override
    public <X extends T> T
    createProviderInstance(Class<X> clazz, String name) throws PluginException, ProviderCreationException
    {
        return createProviderInstanceFromType(clazz, name);
    }

    public boolean isScriptPluggable() {
        return false;
    }

    @Override
    public T createScriptProviderInstance(final ScriptPluginProvider provider)
            throws PluginException
    {
        return null;
    }

    public List<Description> listDescriptions() {
        //TODO: enable field annotations for properties, update plugin Interface and deprecate use of Factory
        return DescribableServiceUtil.listDescriptions(this, false);
    }

    public List<ProviderIdent> listDescribableProviders() {
        return DescribableServiceUtil.listDescribableProviders(this);
    }

}


text:
import sbt._

package object sbtrelease {
  type Versions = (String, String)

  @deprecated("Use ReleaseStep", since = "0.5")
  type ReleasePart = ReleaseStep

  def releaseTask[T](key: TaskKey[T]) = { st: State =>
    Project.extract(st).runAggregated(key, st)
  }

  def versionFormatError = sys.error("Version format is not compatible with " + Version.VersionR.pattern.toString)
}


text:
package com.netflix.spinnaker.halyard.cli.command.v1.config.metricStores.prometheus;

import com.beust.jcommander.Parameters;
import com.netflix.spinnaker.halyard.cli.command.v1.config.metricStores.MetricStoreCommand;
import com.netflix.spinnaker.halyard.config.model.v1.node.MetricStores;

@Parameters(separators = "=")
public class PrometheusCommand extends MetricStoreCommand {
  public MetricStores.MetricStoreType getMetricStoreType() {
    return MetricStores.MetricStoreType.PROMETHEUS;
  }

  public PrometheusCommand() {
    super();
    registerSubcommand(new EditPrometheusCommand());
  }
}


text:
namespace GafferImageTest
{

void testOIIOJpgRead();
void testOIIOExrRead();

} // namespace GafferImageTest

#endif // GAFFERIMAGETEST_IMAGEREADER_H


text:
apiGeoSearch
============

NodeJS with API Google Maps Integration example


text:
require 'spec_helper'

describe Ubiregi::Connect do

  # after do
  #   Ubiregi::Connect.reset!
  # end

  # describe '.client' do
  #   it 'returns an instance of Ubiregi::Connect::Client' do
  #     Ubiregi::Connect.client.must_be_instance_of Ubiregi::Connect::Client
  #   end
  # end

  # describe '.respond_to?' do
  #   it 'delegates to Ubiregi::Connect::Client' do
  #     Ubiregi::Connect.respond_to?(:merchant).must_equal true
  #   end
  # end

  # describe '.method_missing' do
  #   it 'delegates to Ubiregi::Connect::Client' do
  #     Ubiregi::Connect.access_token.must_be_nil
  #   end

  #   it 'raises NoMethodError when undefined method is called' do
  #     -> { Ubiregi::Connect.undefined }.must_raise NoMethodError
  #   end
  # end

end


text:
QuickSpecBegin(SDLOnAppServiceDataSpec)

describe(@"Getter/Setter Tests", ^{
    __block SDLAppServiceData *testAppServiceData = nil;

    beforeEach(^{
        testAppServiceData = [[SDLAppServiceData alloc] init];
        testAppServiceData.serviceId = @"testServiceId";
    });

    it(@"Should set and get correctly", ^{
        SDLOnAppServiceData *testNotification = [[SDLOnAppServiceData alloc] init];
        testNotification.serviceData = testAppServiceData;

        expect(testNotification.serviceData).to(equal(testAppServiceData));
    });

    it(@"Should get correctly when initialized with a dictionary", ^{
        NSDictionary *dict = @{SDLRPCParameterNameNotification:@{
                                       SDLRPCParameterNameParameters:@{
                                               SDLRPCParameterNameServiceData:testAppServiceData
                                               },
                                       SDLRPCParameterNameOperationName:SDLRPCFunctionNameOnAppServiceData}};
        SDLOnAppServiceData *testNotification = [[SDLOnAppServiceData alloc] initWithDictionary:dict];

        expect(testNotification.serviceData).to(equal(testAppServiceData));
    });

    it(@"Should get correctly when initialized with initWithServiceData:", ^{
        SDLOnAppServiceData *testNotification = [[SDLOnAppServiceData alloc] initWithServiceData:testAppServiceData];

        expect(testNotification.serviceData).to(equal(testAppServiceData));
    });

    it(@"Should return nil if not set", ^{
        SDLOnAppServiceData *testNotification = [[SDLOnAppServiceData alloc] init];

        expect(testNotification.serviceData).to(beNil());
    });
});

QuickSpecEnd


text:
package aima.gui.fx.applications.search.games;

import aima.core.agent.Action;
import aima.core.environment.eightpuzzle.BidirectionalEightPuzzleProblem;
import aima.core.environment.eightpuzzle.EightPuzzleBoard;
import aima.core.environment.eightpuzzle.EightPuzzleFunctions;
import aima.core.search.framework.Metrics;
import aima.core.search.framework.Node;
import aima.core.search.framework.SearchForActions;
import aima.core.search.framework.problem.Problem;
import aima.core.search.framework.qsearch.BidirectionalSearch;
import aima.core.search.framework.qsearch.GraphSearch;
import aima.core.search.informed.AStarSearch;
import aima.core.search.informed.GreedyBestFirstSearch;
import aima.core.search.local.Scheduler;
import aima.core.search.local.SimulatedAnnealingSearch;
import aima.core.search.uninformed.BreadthFirstSearch;
import aima.core.search.uninformed.DepthLimitedSearch;
import aima.core.search.uninformed.IterativeDeepeningSearch;
import aima.core.util.Tasks;
import aima.gui.fx.framework.IntegrableApplication;
import aima.gui.fx.framework.Parameter;
import aima.gui.fx.framework.TaskExecutionPaneBuilder;
import aima.gui.fx.framework.TaskExecutionPaneCtrl;
import aima.gui.fx.views.EightPuzzleViewCtrl;
import javafx.application.Platform;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;

import java.util.*;

/**
 * Integrable application which demonstrates how different search strategies
 * solve the Eight Puzzle problem.
 *
 * @author Ruediger Lunde
 *
 */
public class EightPuzzleApp extends IntegrableApplication {

	public static void main(String[] args) {
		launch(args);
	}

	/** List of supported search algorithm names. */
	protected static List<String> SEARCH_NAMES = new ArrayList<>();
	/** List of supported search algorithms. */
	protected static List<SearchForActions<EightPuzzleBoard, Action>> SEARCH_ALGOS = new ArrayList<>();

	private EightPuzzleBoard board;

	/** Adds a new item to the list of supported search algorithms. */
	public static void addSearchAlgorithm(String name, SearchForActions<EightPuzzleBoard, Action> algo) {
		SEARCH_NAMES.add(name);
		SEARCH_ALGOS.add(algo);
	}

	static {
		addSearchAlgorithm("Breadth First Search (Graph Search)", new BreadthFirstSearch<>(new GraphSearch<>()));
		addSearchAlgorithm("Breadth First Search (Bidirectional Search)",
				new BreadthFirstSearch<>(new BidirectionalSearch<>()));
		addSearchAlgorithm("Depth Limited Search (9)", new DepthLimitedSearch<>(9));
		addSearchAlgorithm("Iterative Deepening Search", new IterativeDeepeningSearch<>());
		addSearchAlgorithm("Greedy Best First Search (MisplacedTileHeuristic)",
				new GreedyBestFirstSearch<>(new GraphSearch<>(), EightPuzzleFunctions::getNumberOfMisplacedTiles));
		addSearchAlgorithm("Greedy Best First Search (ManhattanHeuristic)",
				new GreedyBestFirstSearch<>(new GraphSearch<>(),
						EightPuzzleFunctions::getManhattanDistance));
		addSearchAlgorithm("AStar Search (MisplacedTileHeuristic)",
				new AStarSearch<>(new GraphSearch<>(), EightPuzzleFunctions::getNumberOfMisplacedTiles));
		addSearchAlgorithm("AStar Search (ManhattanHeuristic)",
				new AStarSearch<>(new GraphSearch<>(), EightPuzzleFunctions::getManhattanDistance));
		addSearchAlgorithm("Simulated Annealing Search (ManhattanHeuristic)",
				new SimulatedAnnealingSearch<>(EightPuzzleFunctions::getManhattanDistance,
						new Scheduler(20, 0.05, 200)));
	}

	public final static String PARAM_INIT_CONF = "initConf";
	public final static String PARAM_STRATEGY = "strategy";

	private EightPuzzleViewCtrl stateViewCtrl;
	private TaskExecutionPaneCtrl simPaneCtrl;

	public EightPuzzleApp() {
	}

	@Override
	public String getTitle() {
		return "Eight Puzzle App";
	}

	/**
	 * Defines state view, parameters, and call-back functions and calls the
	 * simulation pane builder to create layout and controller objects.
	 */
	@Override
	public Pane createRootPane() {
		BorderPane root = new BorderPane();

		StackPane stateView = new StackPane();
		stateViewCtrl = new EightPuzzleViewCtrl(stateView);

		List<Parameter> params = createParameters();

		TaskExecutionPaneBuilder builder = new TaskExecutionPaneBuilder();
		builder.defineParameters(params);
		builder.defineStateView(stateView);
		builder.defineInitMethod(this::initialize);
		builder.defineTaskMethod(this::startExperiment);
		simPaneCtrl = builder.getResultFor(root);

		return root;
	}

	protected List<Parameter> createParameters() {
		Parameter p1 = new Parameter(PARAM_INIT_CONF, "Three Moves", "Medium", "Extreme", "Random");
		Parameter p2 = new Parameter(PARAM_STRATEGY, (Object[]) SEARCH_NAMES.toArray());
		return Arrays.asList(p1, p2);
	}

	/** Displays the initialized board on the state view. */
	@Override
	public void initialize() {
		board = null;
		switch (simPaneCtrl.getParamValueIndex(PARAM_INIT_CONF)) {
			case 0: // three moves
				board = new EightPuzzleBoard(new int[] { 1, 2, 5, 3, 4, 0, 6, 7, 8 });
				break;
			case 1: // medium
				board = new EightPuzzleBoard(new int[] { 1, 4, 2, 7, 5, 8, 3, 0, 6 });
				break;
			case 2: // extreme
				board = new EightPuzzleBoard(new int[] { 0, 8, 7, 6, 5, 4, 3, 2, 1 });
				break;
			case 3: // random
				board = new EightPuzzleBoard(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });
				Random r = new Random(System.currentTimeMillis());
				for (int i = 0; i < 200; i++) {
					switch (r.nextInt(4)) {
						case 0:
							board.moveGapUp();
							break;
						case 1:
							board.moveGapDown();
							break;
						case 2:
							board.moveGapLeft();
							break;
						case 3:
							board.moveGapRight();
							break;
					}
				}
		}
		stateViewCtrl.initialize(board);
	}

	@Override
	public void cleanup() {
		simPaneCtrl.cancelExecution();
	}

	/** Starts the experiment. */
	public void startExperiment() {
		int strategyIdx = simPaneCtrl.getParamValueIndex(PARAM_STRATEGY);

		Problem<EightPuzzleBoard, Action> problem = new BidirectionalEightPuzzleProblem(board);
		SearchForActions<EightPuzzleBoard, Action> search = SEARCH_ALGOS.get(strategyIdx);
		Optional<List<Action>> actions = search.findActions(problem);
		if (actions.isPresent()) {
			for (Action action : actions.get()) {
				if (action == EightPuzzleBoard.UP)
					board.moveGapUp();
				else if (action == EightPuzzleBoard.DOWN)
					board.moveGapDown();
				else if (action == EightPuzzleBoard.LEFT)
					board.moveGapLeft();
				else if (action == EightPuzzleBoard.RIGHT)
					board.moveGapRight();
				Metrics m = new Metrics();
				m.set("misplacedTileHeuristic", EightPuzzleFunctions.getNumberOfMisplacedTiles(new Node<>(board)));
				m.set("manhattanHeuristic", EightPuzzleFunctions.getManhattanDistance(new Node<>(board)));
				updateStateView(m);
				if (Tasks.currIsCancelled())
					break;
				simPaneCtrl.waitAfterStep();
			}
		}
		updateStateView(search.getMetrics());
	}

	/**
	 * Caution: While the background thread should be slowed down, updates of
	 * the GUI have to be done in the GUI thread!
	 */
	private void updateStateView(Metrics metrics) {
		Platform.runLater(() -> updateStateViewLater(metrics));
		simPaneCtrl.waitAfterStep();
	}

	/**
	 * Must be called by the GUI thread!
	 */
	private void updateStateViewLater(Metrics metrics) {
		stateViewCtrl.update();
		if (metrics != null)
			simPaneCtrl.setStatus(metrics.toString());
	}
}


text:
require 'spec_helper'
require Rails.root.join('db', 'post_migrate', '20200130145430_reschedule_migrate_issue_trackers_data.rb')

RSpec.describe RescheduleMigrateIssueTrackersData do
  let(:services) { table(:services) }
  let(:migration_class) { Gitlab::BackgroundMigration::MigrateIssueTrackersSensitiveData }
  let(:migration_name)  { migration_class.to_s.demodulize }

  let(:properties) do
    {
      'url' => 'http://example.com'
    }
  end

  let!(:jira_service) do
    services.create(id: 10, type: 'JiraService', properties: properties, category: 'issue_tracker')
  end

  let!(:jira_service_nil) do
    services.create(id: 11, type: 'JiraService', properties: nil, category: 'issue_tracker')
  end

  let!(:bugzilla_service) do
    services.create(id: 12, type: 'BugzillaService', properties: properties, category: 'issue_tracker')
  end

  let!(:youtrack_service) do
    services.create(id: 13, type: 'YoutrackService', properties: properties, category: 'issue_tracker')
  end

  let!(:youtrack_service_empty) do
    services.create(id: 14, type: 'YoutrackService', properties: '', category: 'issue_tracker')
  end

  let!(:gitlab_service) do
    services.create(id: 15, type: 'GitlabIssueTrackerService', properties: properties, category: 'issue_tracker')
  end

  let!(:gitlab_service_empty) do
    services.create(id: 16, type: 'GitlabIssueTrackerService', properties: {}, category: 'issue_tracker')
  end

  let!(:other_service) do
    services.create(id: 17, type: 'OtherService', properties: properties, category: 'other_category')
  end

  before do
    stub_const("#{described_class}::BATCH_SIZE", 2)
  end

  describe "#up" do
    it 'schedules background migrations at correct time' do
      Sidekiq::Testing.fake! do
        Timecop.freeze do
          migrate!

          expect(migration_name).to be_scheduled_delayed_migration(3.minutes, jira_service.id, bugzilla_service.id)
          expect(migration_name).to be_scheduled_delayed_migration(6.minutes, youtrack_service.id, gitlab_service.id)
          expect(BackgroundMigrationWorker.jobs.size).to eq(2)
        end
      end
    end
  end

  describe "#down" do
    let(:issue_tracker_data) { table(:issue_tracker_data) }
    let(:jira_tracker_data) { table(:jira_tracker_data) }

    let!(:valid_issue_tracker_data) do
      issue_tracker_data.create(
        service_id: bugzilla_service.id,
        encrypted_issues_url: 'http://url.com',
        encrypted_issues_url_iv: 'somevalue'
      )
    end

    let!(:invalid_issue_tracker_data) do
      issue_tracker_data.create(
        service_id: bugzilla_service.id,
        encrypted_issues_url: 'http:url.com',
        encrypted_issues_url_iv: nil
      )
    end

    let!(:valid_jira_tracker_data) do
      jira_tracker_data.create(
        service_id: bugzilla_service.id,
        encrypted_url: 'http://url.com',
        encrypted_url_iv: 'somevalue'
      )
    end

    let!(:invalid_jira_tracker_data) do
      jira_tracker_data.create(
        service_id: bugzilla_service.id,
        encrypted_url: 'http://url.com',
        encrypted_url_iv: nil
      )
    end

    it 'removes the invalid jira tracker data' do
      expect { described_class.new.down }.to change { jira_tracker_data.count }.from(2).to(1)

      expect(jira_tracker_data.all).to eq([valid_jira_tracker_data])
    end

    it 'removes the invalid issue tracker data' do
      expect { described_class.new.down }.to change { issue_tracker_data.count }.from(2).to(1)

      expect(issue_tracker_data.all).to eq([valid_issue_tracker_data])
    end
  end
end


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxCreditsAlertsResponse extends BxBaseModGeneralAlertsResponse
{
    public function __construct()
    {
        $this->MODULE = 'bx_credits';

        parent::__construct();
    }

    public function response($oAlert)
    {
        parent::response($oAlert);

        $sMethod = '_process' . bx_gen_method_name($oAlert->sUnit . '_' . $oAlert->sAction);
        if(!method_exists($this, $sMethod))
            return;

        return $this->$sMethod($oAlert);
    }

    protected function _processProfileAdd($oAlert)
    {
        $CNF = &$this->_oModule->_oConfig->CNF;

        $iProfile = (int)$oAlert->iObject;
        $oProfile = BxDolProfile::getInstance($iProfile);
        if(!$oProfile)
            return;

        if(getParam($CNF['PARAM_PROVIDER_ENABLE']) == 'on') {
            $oProvider = BxDolPayments::getInstance()->getProvider($CNF['PARAM_PROVIDER_NAME'], $iProfile);
            if($oProvider)
                $oProvider->setOption('active', 'on', true);
        }
    }

    protected function _processProfileDelete($oAlert)
    {
        if(empty($oAlert->aExtras['delete_with_content']))
            return;

        return BxDolService::call($this->MODULE, 'delete_entities_by_author', array($oAlert->iObject));
    }
}

/** @} */


text:
package org.bkpathak.ds.graph;

import java.util.*;

/**
 * Created by bijay on 2/7/16.
 * Prim's MST implementation using Priority Queue
 * O(n) : O(E log v)
 */
public class PrimMST {
    boolean[] visited;
    int vertex; // number of vertex in graph
    PriorityQueue<WeightedGraph.Node> queue;
    int[] parent; // To store the MST

    PrimMST(int v) {
        vertex = v;
        visited = new boolean[v];
        // Implements anonymous Comparator class
        queue = new PriorityQueue<WeightedGraph.Node>(v, new Comparator<WeightedGraph.Node>() {
            public int compare(WeightedGraph.Node o1, WeightedGraph.Node o2) {
                if (o1.weight == o2.weight) {
                    return 0;
                } else if (o1.weight < o2.weight) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });

        parent = new int[v];
        Arrays.fill(parent, -1);
    }

    /**
     * Algorithm
     * 1. while count < vertices
     * if current node not visited
     * mark it visited
     * push all its edges to the PriorityQueue if not visited
     * extract the minimum edge from PriorityQueue
     * if the minimum edge leads to an unvisited vertex
     * add it to MST
     * current = newVertex
     * ++count
     * else
     * extract the minimum edge from PriorityQueue again
     * if the minimum edge leads to an unvisited vertex
     * add it to MST
     * current = newVertex
     */

    public void primMST(WeightedGraph graph, int startV) {
        int i = 0;
        int current = startV;
        WeightedGraph.Node tempNode, minNode;
        int src, dst;

        while (i < vertex) {
            if (!visited[current]) {
                visited[current] = true;
                // Traverse all the adjacent nodes of the current Nodes
                Iterator<WeightedGraph.Node> itr = graph.getIterator(current);

                while (itr.hasNext()) {
                    tempNode = itr.next();

                    if (!visited[tempNode.dest]) {
                        // Add it to queue
                        queue.add(tempNode);
                    }
                }
                // Get the minimum edge from the queue
                minNode = queue.poll();
                src = minNode.src;
                dst = minNode.dest;
                if (!visited[dst]) {
                    parent[dst] = src;
                }
                current = dst;
                i++;
            } else {
                minNode = queue.poll();
                src = minNode.src;
                dst = minNode.dest;
                if (!visited[dst]) {
                    parent[dst] = src;
                }
                current = dst;
            }
        }

    }

    /**
     * Print the MST
     */
    public void displayMST() {
        System.out.println("Prim's MST:");
        for (int i = 0; i < vertex; i++) {
            System.out.println(parent[i] + " -> " + i);
        }
    }

    public static void main(String[] args) {
        WeightedGraph graph = new WeightedGraph(9);
        graph.addEdge(0, 1, 4);
        graph.addEdge(0, 7, 8);
        graph.addEdge(1, 2, 8);
        graph.addEdge(1, 7, 11);
        graph.addEdge(2, 3, 7);
        graph.addEdge(2, 8, 2);
        graph.addEdge(2, 5, 4);
        graph.addEdge(3, 4, 9);
        graph.addEdge(3, 5, 14);
        graph.addEdge(4, 5, 10);
        graph.addEdge(5, 6, 2);
        graph.addEdge(6, 7, 1);
        graph.addEdge(6, 8, 6);
        graph.addEdge(7, 8, 7);

        PrimMST mst = new PrimMST(9);
        mst.primMST(graph,0);
        mst.displayMST();
    }

}


text:
#include "tensorflow/core/platform/s3/s3_file_system.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/s3/s3_crypto.h"

#include <aws/core/Aws.h>
#include <aws/core/utils/FileSystemUtils.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/S3Errors.h>
#include <aws/s3/model/CopyObjectRequest.h>
#include <aws/s3/model/DeleteObjectRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/HeadBucketRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/s3/model/ListObjectsRequest.h>
#include <aws/s3/model/PutObjectRequest.h>

#include <cstdlib>

namespace tensorflow {

static const char* kS3FileSystemAllocationTag = "S3FileSystemAllocation";
static const size_t kS3ReadAppendableFileBufferSize = 1024 * 1024;
static const int kS3GetChildrenMaxKeys = 100;

Aws::Client::ClientConfiguration& GetDefaultClientConfig() {
  static mutex cfg_lock(LINKER_INITIALIZED);
  static bool init(false);
  static Aws::Client::ClientConfiguration cfg;

  std::lock_guard<mutex> lock(cfg_lock);

  if (!init) {
    const char* endpoint = getenv("S3_ENDPOINT");
    if (endpoint) {
      cfg.endpointOverride = Aws::String(endpoint);
    }
    const char* region = getenv("AWS_REGION");
    if (region) {
      cfg.region = Aws::String(region);
    } else {
      // TODO (yongtang): `S3_REGION` should be deprecated after 2.0.
      const char* region = getenv("S3_REGION");
      if (region) {
        cfg.region = Aws::String(region);
      }
    }
    const char* use_https = getenv("S3_USE_HTTPS");
    if (use_https) {
      if (use_https[0] == '0') {
        cfg.scheme = Aws::Http::Scheme::HTTP;
      } else {
        cfg.scheme = Aws::Http::Scheme::HTTPS;
      }
    }
    const char* verify_ssl = getenv("S3_VERIFY_SSL");
    if (verify_ssl) {
      if (verify_ssl[0] == '0') {
        cfg.verifySSL = false;
      } else {
        cfg.verifySSL = true;
      }
    }

    init = true;
  }

  return cfg;
};

Status ParseS3Path(const string& fname, bool empty_object_ok, string* bucket,
                   string* object) {
  if (!bucket || !object) {
    return errors::Internal("bucket and object cannot be null.");
  }
  StringPiece scheme, bucketp, objectp;
  io::ParseURI(fname, &scheme, &bucketp, &objectp);
  if (scheme != "s3") {
    return errors::InvalidArgument("S3 path doesn't start with 's3://': ",
                                   fname);
  }
  *bucket = bucketp.ToString();
  if (bucket->empty() || *bucket == ".") {
    return errors::InvalidArgument("S3 path doesn't contain a bucket name: ",
                                   fname);
  }
  objectp.Consume("/");
  *object = objectp.ToString();
  if (!empty_object_ok && object->empty()) {
    return errors::InvalidArgument("S3 path doesn't contain an object name: ",
                                   fname);
  }
  return Status::OK();
}

class S3RandomAccessFile : public RandomAccessFile {
 public:
  S3RandomAccessFile(const string& bucket, const string& object)
      : bucket_(bucket), object_(object) {}

  Status Read(uint64 offset, size_t n, StringPiece* result,
              char* scratch) const override {
    Aws::S3::S3Client s3Client(GetDefaultClientConfig());
    Aws::S3::Model::GetObjectRequest getObjectRequest;
    getObjectRequest.WithBucket(bucket_.c_str()).WithKey(object_.c_str());
    string bytes = strings::StrCat("bytes=", offset, "-", offset + n - 1);
    getObjectRequest.SetRange(bytes.c_str());
    getObjectRequest.SetResponseStreamFactory([]() {
      return Aws::New<Aws::StringStream>(kS3FileSystemAllocationTag);
    });
    auto getObjectOutcome = s3Client.GetObject(getObjectRequest);
    if (!getObjectOutcome.IsSuccess()) {
      n = 0;
      *result = StringPiece(scratch, n);
      return Status(error::OUT_OF_RANGE, "Read less bytes than requested");
    }
    n = getObjectOutcome.GetResult().GetContentLength();
    std::stringstream ss;
    ss << getObjectOutcome.GetResult().GetBody().rdbuf();
    ss.read(scratch, n);

    *result = StringPiece(scratch, n);
    return Status::OK();
  }

 private:
  string bucket_;
  string object_;
};

class S3WritableFile : public WritableFile {
 public:
  S3WritableFile(const string& bucket, const string& object)
      : bucket_(bucket),
        object_(object),
        sync_needed_(true),
        outfile_(Aws::MakeShared<Aws::Utils::TempFile>(
            kS3FileSystemAllocationTag, "/tmp/s3_filesystem_XXXXXX",
            std::ios_base::binary | std::ios_base::trunc | std::ios_base::in |
                std::ios_base::out)) {}

  Status Append(const StringPiece& data) override {
    if (!outfile_) {
      return errors::FailedPrecondition(
          "The internal temporary file is not writable.");
    }
    sync_needed_ = true;
    outfile_->write(data.data(), data.size());
    if (!outfile_->good()) {
      return errors::Internal(
          "Could not append to the internal temporary file.");
    }
    return Status::OK();
  }

  Status Close() override {
    if (outfile_) {
      TF_RETURN_IF_ERROR(Sync());
      outfile_.reset();
    }
    return Status::OK();
  }

  Status Flush() override { return Sync(); }

  Status Sync() override {
    if (!outfile_) {
      return errors::FailedPrecondition(
          "The internal temporary file is not writable.");
    }
    if (!sync_needed_) {
      return Status::OK();
    }
    Aws::Client::ClientConfiguration clientConfig = GetDefaultClientConfig();
    clientConfig.connectTimeoutMs = 300000;
    clientConfig.requestTimeoutMs = 600000;
    Aws::S3::S3Client s3Client(clientConfig);
    Aws::S3::Model::PutObjectRequest putObjectRequest;
    putObjectRequest.WithBucket(bucket_.c_str()).WithKey(object_.c_str());
    long offset = outfile_->tellp();
    outfile_->seekg(0);
    putObjectRequest.SetBody(outfile_);
    putObjectRequest.SetContentLength(offset);
    auto putObjectOutcome = s3Client.PutObject(putObjectRequest);
    outfile_->clear();
    outfile_->seekp(offset);
    if (!putObjectOutcome.IsSuccess()) {
      string error = strings::StrCat(
          putObjectOutcome.GetError().GetExceptionName().c_str(), ": ",
          putObjectOutcome.GetError().GetMessage().c_str());
      return errors::Internal(error);
    }
    return Status::OK();
  }

 private:
  string bucket_;
  string object_;
  bool sync_needed_;
  std::shared_ptr<Aws::Utils::TempFile> outfile_;
};

class S3ReadOnlyMemoryRegion : public ReadOnlyMemoryRegion {
 public:
  S3ReadOnlyMemoryRegion(std::unique_ptr<char[]> data, uint64 length)
      : data_(std::move(data)), length_(length) {}
  const void* data() override { return reinterpret_cast<void*>(data_.get()); }
  uint64 length() override { return length_; }

 private:
  std::unique_ptr<char[]> data_;
  uint64 length_;
};

S3FileSystem::S3FileSystem() {
  Aws::SDKOptions options;
  options.cryptoOptions.sha256Factory_create_fn = []() {
    return Aws::MakeShared<S3SHA256Factory>(S3CryptoAllocationTag);
  };
  options.cryptoOptions.sha256HMACFactory_create_fn = []() {
    return Aws::MakeShared<S3SHA256HmacFactory>(S3CryptoAllocationTag);
  };
  Aws::InitAPI(options);
}

S3FileSystem::~S3FileSystem() {
  Aws::SDKOptions options;
  Aws::ShutdownAPI(options);
}

Status S3FileSystem::NewRandomAccessFile(
    const string& fname, std::unique_ptr<RandomAccessFile>* result) {
  string bucket, object;
  TF_RETURN_IF_ERROR(ParseS3Path(fname, false, &bucket, &object));
  result->reset(new S3RandomAccessFile(bucket, object));
  return Status::OK();
}

Status S3FileSystem::NewWritableFile(const string& fname,
                                     std::unique_ptr<WritableFile>* result) {
  string bucket, object;
  TF_RETURN_IF_ERROR(ParseS3Path(fname, false, &bucket, &object));
  result->reset(new S3WritableFile(bucket, object));
  return Status::OK();
}

Status S3FileSystem::NewAppendableFile(const string& fname,
                                       std::unique_ptr<WritableFile>* result) {
  std::unique_ptr<RandomAccessFile> reader;
  TF_RETURN_IF_ERROR(NewRandomAccessFile(fname, &reader));
  std::unique_ptr<char[]> buffer(new char[kS3ReadAppendableFileBufferSize]);
  Status status;
  uint64 offset = 0;
  StringPiece read_chunk;

  string bucket, object;
  TF_RETURN_IF_ERROR(ParseS3Path(fname, false, &bucket, &object));
  result->reset(new S3WritableFile(bucket, object));

  while (true) {
    status = reader->Read(offset, kS3ReadAppendableFileBufferSize, &read_chunk,
                          buffer.get());
    if (status.ok()) {
      (*result)->Append(read_chunk);
      offset += kS3ReadAppendableFileBufferSize;
    } else if (status.code() == error::OUT_OF_RANGE) {
      (*result)->Append(read_chunk);
      break;
    } else {
      (*result).reset();
      return status;
    }
  }

  return Status::OK();
}

Status S3FileSystem::NewReadOnlyMemoryRegionFromFile(
    const string& fname, std::unique_ptr<ReadOnlyMemoryRegion>* result) {
  uint64 size;
  TF_RETURN_IF_ERROR(GetFileSize(fname, &size));
  std::unique_ptr<char[]> data(new char[size]);

  std::unique_ptr<RandomAccessFile> file;
  TF_RETURN_IF_ERROR(NewRandomAccessFile(fname, &file));

  StringPiece piece;
  TF_RETURN_IF_ERROR(file->Read(0, size, &piece, data.get()));

  result->reset(new S3ReadOnlyMemoryRegion(std::move(data), size));
  return Status::OK();
}

Status S3FileSystem::FileExists(const string& fname) {
  FileStatistics stats;
  TF_RETURN_IF_ERROR(this->Stat(fname, &stats));
  return Status::OK();
}

Status S3FileSystem::GetChildren(const string& dir,
                                 std::vector<string>* result) {
  string bucket, prefix;
  TF_RETURN_IF_ERROR(ParseS3Path(dir, false, &bucket, &prefix));

  if (prefix.back() != '/') {
    prefix.push_back('/');
  }

  Aws::S3::S3Client s3Client(GetDefaultClientConfig());
  Aws::S3::Model::ListObjectsRequest listObjectsRequest;
  listObjectsRequest.WithBucket(bucket.c_str())
      .WithPrefix(prefix.c_str())
      .WithMaxKeys(kS3GetChildrenMaxKeys)
      .WithDelimiter("/");
  listObjectsRequest.SetResponseStreamFactory(
      []() { return Aws::New<Aws::StringStream>(kS3FileSystemAllocationTag); });

  Aws::S3::Model::ListObjectsResult listObjectsResult;
  do {
    auto listObjectsOutcome = s3Client.ListObjects(listObjectsRequest);
    if (!listObjectsOutcome.IsSuccess()) {
      string error = strings::StrCat(
          listObjectsOutcome.GetError().GetExceptionName().c_str(), ": ",
          listObjectsOutcome.GetError().GetMessage().c_str());
      return errors::Internal(error);
    }

    listObjectsResult = listObjectsOutcome.GetResult();
    for (const auto& object : listObjectsResult.GetCommonPrefixes()) {
      Aws::String s = object.GetPrefix();
      s.erase(s.length() - 1);
      Aws::String entry = s.substr(strlen(prefix.c_str()));
      if (entry.length() > 0) {
        result->push_back(entry.c_str());
      }
    }
    for (const auto& object : listObjectsResult.GetContents()) {
      Aws::String s = object.GetKey();
      Aws::String entry = s.substr(strlen(prefix.c_str()));
      if (entry.length() > 0) {
        result->push_back(entry.c_str());
      }
    }
    listObjectsRequest.SetMarker(listObjectsResult.GetNextMarker());
  } while (listObjectsResult.GetIsTruncated());

  return Status::OK();
}

Status S3FileSystem::Stat(const string& fname, FileStatistics* stats) {
  string bucket, object;
  TF_RETURN_IF_ERROR(ParseS3Path(fname, true, &bucket, &object));

  Aws::S3::S3Client s3Client(GetDefaultClientConfig());
  if (object.empty()) {
    Aws::S3::Model::HeadBucketRequest headBucketRequest;
    headBucketRequest.WithBucket(bucket.c_str());
    auto headBucketOutcome = s3Client.HeadBucket(headBucketRequest);
    if (!headBucketOutcome.IsSuccess()) {
      string error = strings::StrCat(
          headBucketOutcome.GetError().GetExceptionName().c_str(), ": ",
          headBucketOutcome.GetError().GetMessage().c_str());
      return errors::Internal(error);
    }
    stats->length = 0;
    stats->is_directory = 1;
    return Status::OK();
  }

  bool found = false;

  Aws::S3::Model::HeadObjectRequest headObjectRequest;
  headObjectRequest.WithBucket(bucket.c_str()).WithKey(object.c_str());
  headObjectRequest.SetResponseStreamFactory(
      []() { return Aws::New<Aws::StringStream>(kS3FileSystemAllocationTag); });
  auto headObjectOutcome = s3Client.HeadObject(headObjectRequest);
  if (headObjectOutcome.IsSuccess()) {
    stats->length = headObjectOutcome.GetResult().GetContentLength();
    stats->is_directory = 0;
    stats->mtime_nsec =
        headObjectOutcome.GetResult().GetLastModified().Millis() * 1e6;
    found = true;
  }
  string prefix = object;
  if (prefix.back() != '/') {
    prefix.push_back('/');
  }
  Aws::S3::Model::ListObjectsRequest listObjectsRequest;
  listObjectsRequest.WithBucket(bucket.c_str())
      .WithPrefix(prefix.c_str())
      .WithMaxKeys(1);
  listObjectsRequest.SetResponseStreamFactory(
      []() { return Aws::New<Aws::StringStream>(kS3FileSystemAllocationTag); });
  auto listObjectsOutcome = s3Client.ListObjects(listObjectsRequest);
  if (listObjectsOutcome.IsSuccess()) {
    if (listObjectsOutcome.GetResult().GetContents().size() > 0) {
      stats->length = 0;
      stats->is_directory = 1;
      found = true;
    }
  }
  if (!found) {
    return errors::NotFound("Object ", fname, " does not exist");
  }
  return Status::OK();
}

Status S3FileSystem::DeleteFile(const string& fname) {
  string bucket, object;
  TF_RETURN_IF_ERROR(ParseS3Path(fname, false, &bucket, &object));

  Aws::S3::S3Client s3Client(GetDefaultClientConfig());
  Aws::S3::Model::DeleteObjectRequest deleteObjectRequest;
  deleteObjectRequest.WithBucket(bucket.c_str()).WithKey(object.c_str());

  auto deleteObjectOutcome = s3Client.DeleteObject(deleteObjectRequest);
  if (!deleteObjectOutcome.IsSuccess()) {
    string error = strings::StrCat(
        deleteObjectOutcome.GetError().GetExceptionName().c_str(), ": ",
        deleteObjectOutcome.GetError().GetMessage().c_str());
    return errors::Internal(error);
  }
  return Status::OK();
}

Status S3FileSystem::CreateDir(const string& dirname) {
  string bucket, object;
  TF_RETURN_IF_ERROR(ParseS3Path(dirname, true, &bucket, &object));

  if (object.empty()) {
    Aws::S3::S3Client s3Client(GetDefaultClientConfig());
    Aws::S3::Model::HeadBucketRequest headBucketRequest;
    headBucketRequest.WithBucket(bucket.c_str());
    auto headBucketOutcome = s3Client.HeadBucket(headBucketRequest);
    if (!headBucketOutcome.IsSuccess()) {
      return errors::NotFound("The bucket ", bucket, " was not found.");
    }
    return Status::OK();
  }
  string filename = dirname;
  if (filename.back() != '/') {
    filename.push_back('/');
  }
  std::unique_ptr<WritableFile> file;
  TF_RETURN_IF_ERROR(NewWritableFile(filename, &file));
  TF_RETURN_IF_ERROR(file->Close());
  return Status::OK();
}

Status S3FileSystem::DeleteDir(const string& dirname) {
  string bucket, object;
  TF_RETURN_IF_ERROR(ParseS3Path(dirname, false, &bucket, &object));

  Aws::S3::S3Client s3Client(GetDefaultClientConfig());
  string prefix = object;
  if (prefix.back() != '/') {
    prefix.push_back('/');
  }
  Aws::S3::Model::ListObjectsRequest listObjectsRequest;
  listObjectsRequest.WithBucket(bucket.c_str())
      .WithPrefix(prefix.c_str())
      .WithMaxKeys(2);
  listObjectsRequest.SetResponseStreamFactory(
      []() { return Aws::New<Aws::StringStream>(kS3FileSystemAllocationTag); });
  auto listObjectsOutcome = s3Client.ListObjects(listObjectsRequest);
  if (listObjectsOutcome.IsSuccess()) {
    auto contents = listObjectsOutcome.GetResult().GetContents();
    if (contents.size() > 1 ||
        (contents.size() == 1 && contents[0].GetKey() != prefix.c_str())) {
      return errors::FailedPrecondition("Cannot delete a non-empty directory.");
    }
    if (contents.size() == 1 && contents[0].GetKey() == prefix.c_str()) {
      string filename = dirname;
      if (filename.back() != '/') {
        filename.push_back('/');
      }
      return DeleteFile(filename);
    }
  }
  return Status::OK();
}

Status S3FileSystem::GetFileSize(const string& fname, uint64* file_size) {
  FileStatistics stats;
  TF_RETURN_IF_ERROR(this->Stat(fname, &stats));
  *file_size = stats.length;
  return Status::OK();
}

Status S3FileSystem::RenameFile(const string& src, const string& target) {
  string src_bucket, src_object, target_bucket, target_object;
  TF_RETURN_IF_ERROR(ParseS3Path(src, false, &src_bucket, &src_object));
  TF_RETURN_IF_ERROR(
      ParseS3Path(target, false, &target_bucket, &target_object));
  if (src_object.back() == '/') {
    if (target_object.back() != '/') {
      target_object.push_back('/');
    }
  } else {
    if (target_object.back() == '/') {
      target_object.pop_back();
    }
  }

  Aws::S3::S3Client s3Client(GetDefaultClientConfig());

  Aws::S3::Model::CopyObjectRequest copyObjectRequest;
  Aws::S3::Model::DeleteObjectRequest deleteObjectRequest;

  Aws::S3::Model::ListObjectsRequest listObjectsRequest;
  listObjectsRequest.WithBucket(src_bucket.c_str())
      .WithPrefix(src_object.c_str())
      .WithMaxKeys(kS3GetChildrenMaxKeys);
  listObjectsRequest.SetResponseStreamFactory(
      []() { return Aws::New<Aws::StringStream>(kS3FileSystemAllocationTag); });

  Aws::S3::Model::ListObjectsResult listObjectsResult;
  do {
    auto listObjectsOutcome = s3Client.ListObjects(listObjectsRequest);
    if (!listObjectsOutcome.IsSuccess()) {
      string error = strings::StrCat(
          listObjectsOutcome.GetError().GetExceptionName().c_str(), ": ",
          listObjectsOutcome.GetError().GetMessage().c_str());
      return errors::Internal(error);
    }

    listObjectsResult = listObjectsOutcome.GetResult();
    for (const auto& object : listObjectsResult.GetContents()) {
      Aws::String src_key = object.GetKey();
      Aws::String target_key = src_key;
      target_key.replace(0, src_object.length(), target_object.c_str());
      Aws::String source = Aws::String(src_bucket.c_str()) + "/" + src_key;

      copyObjectRequest.SetBucket(target_bucket.c_str());
      copyObjectRequest.SetKey(target_key);
      copyObjectRequest.SetCopySource(source);

      auto copyObjectOutcome = s3Client.CopyObject(copyObjectRequest);
      if (!copyObjectOutcome.IsSuccess()) {
        string error = strings::StrCat(
            copyObjectOutcome.GetError().GetExceptionName().c_str(), ": ",
            copyObjectOutcome.GetError().GetMessage().c_str());
        return errors::Internal(error);
      }

      deleteObjectRequest.SetBucket(src_bucket.c_str());
      deleteObjectRequest.SetKey(src_key.c_str());

      auto deleteObjectOutcome = s3Client.DeleteObject(deleteObjectRequest);
      if (!deleteObjectOutcome.IsSuccess()) {
        string error = strings::StrCat(
            deleteObjectOutcome.GetError().GetExceptionName().c_str(), ": ",
            deleteObjectOutcome.GetError().GetMessage().c_str());
        return errors::Internal(error);
      }
    }
    listObjectsRequest.SetMarker(listObjectsResult.GetNextMarker());
  } while (listObjectsResult.GetIsTruncated());

  return Status::OK();
}

REGISTER_FILE_SYSTEM("s3", S3FileSystem);

}  // namespace tensorflow