text:
package ru.org.linux.user;

import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import ru.org.linux.auth.AccessViolationException;
import ru.org.linux.util.StringUtil;

import java.sql.Timestamp;

@Controller
@RequestMapping("/reset-password")
public class ResetPasswordController {
  private static final Logger logger = LoggerFactory.getLogger(ResetPasswordController.class);

  @Autowired
  private UserDao userDao;

  @Autowired
  private UserService userService;

  @RequestMapping(method=RequestMethod.GET)
  public ModelAndView showCodeForm() {
    return new ModelAndView("reset-password-form");
  }

  @RequestMapping(method=RequestMethod.POST)
  public ModelAndView resetPassword(
    @RequestParam("nick") String nick,
    @RequestParam("code") String formCode
  ) throws Exception {
    User user = userDao.getUser(nick);

    user.checkBlocked();
    user.checkAnonymous();

    if (user.isAdministrator()) {
      throw new AccessViolationException("this feature is not for you, ask me directly");
    }

    Timestamp resetDate = userDao.getResetDate(user);

    String resetCode = userService.getResetCode(user.getNick(), user.getEmail(), resetDate);

    if (!resetCode.equals(formCode)) {
      logger.warn("Код проверки не совпадает; login={} formCode={} resetCode={}", nick, formCode, resetCode);

      throw new UserErrorException("Код не совпадает");
    }

    String password = userDao.resetPassword(user);

    return new ModelAndView(
            "action-done",
            ImmutableMap.of(
                    "message", "Установлен новый пароль",
                    "bigMessage", "Ваш новый пароль: " + StringUtil.escapeHtml(password)
            )
    );
  }

  @ExceptionHandler({UserNotFoundException.class, UserErrorException.class})
  public ModelAndView handleUserError(Exception ex) {
    return new ModelAndView("reset-password-form", "error", ex.getMessage());
  }
}


text:
package org.nephtys.keepaseat.internal.eventdata

import org.nephtys.keepaseat.filter.XSSCleaner

/**
  *
  * used in database, should be able to model every currently needed type of reservation (therefore does not have to be
  * generic yet)
  *
  * Uses japanese date system - YYYY-MM-DD---hh-mm
  *
  * Created by nephtys on 9/28/16.
  */
case class Event(
                id : Long,
                elements : Seq[EventElementBlock], //all blocks SHOULD (but are not required to) be on the same from/to
                // values
                name : String,
                email : String,
                telephone : String,
                commentary : String,
                confirmedBySupseruser : Boolean
                ) {

  assert(elements.forall(b => b.from < b.to))
  assert(elements.nonEmpty)
  assert(elements.map(_.from).distinct.size == 1)
  assert(elements.map(_.to).distinct.size == 1)

  //TODO: check these in validator before creating events
  //require(elements.nonEmpty)
  //require(elements.forall(s => s!= null && s.nonEmpty && s.toLowerCase().trim().equals(s)))

  def cleanHTML(implicit xSSCleaner: XSSCleaner) : Event = {
      Event(id, elements.map(_.cleanHTML), xSSCleaner.removeHTML(name), xSSCleaner.removeHTML(email), xSSCleaner
        .removeHTML(telephone), xSSCleaner.removeHTML(commentary), confirmedBySupseruser)
  }

  def equalExceptID(other : Event) : Boolean = this.copy(id = other.id).equals(other)
}

/**
  * this is remapped when writing to the database into a second table with a foreign key to Event
  * @param element
  * @param from
  * @param to
  */
case class EventElementBlock(
                            element : String,
                            from : Long, //inclusive
                            to : Long //exclusive
                            ) {

  def cleanHTML(implicit xSSCleaner: XSSCleaner) : EventElementBlock = {
    val d = xSSCleaner.removeHTML(element)
    EventElementBlock(d, from, to)
  }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation ZWTabBar

// 这里可以做一些初始化设置
-(instancetype)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]) {
        [self setUpInit];
    }
    return self;
}

- (void)setUpInit {
    // 设置样式, 去除tabbar上面的黑线
    self.barStyle = UIBarStyleBlack;

    // 设置tabbar 背景图片
    NSBundle *containingBundle = [NSBundle bundleForClass:[self class]];
    NSString *bundleName = [containingBundle.infoDictionary[@"CFBundleName"] stringByAppendingString:@".bundle"];
    NSString *imagePath = [NSString stringWithFormat:@"%@@%@x.png", @"tabbar_bg", @([UIScreen mainScreen].scale)];

    NSString *path = [containingBundle pathForResource:imagePath ofType:nil inDirectory:bundleName];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    self.backgroundImage  = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

}

- (void)setTabBarBackgroundImage:(UIImage *)tabBarBackgroundImage{
    _tabBarBackgroundImage = tabBarBackgroundImage;
    self.backgroundImage = tabBarBackgroundImage;
}
-(void)layoutSubviews {
    [super layoutSubviews];

    // 将中间按钮, 移动到顶部
    //    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    //    [window.rootViewController.view bringSubviewToFront:self.middleBtn];

    NSInteger count = self.items.count;

    // 1. 遍历所有的子控件
    NSArray *subViews = self.subviews;

    // 确定单个控件的大小
    CGFloat btnW = self.width / (count);
    CGFloat btnH = self.height;
    CGFloat btnY = 5;

    NSInteger index = 0;
    for (UIView *subView in subViews) {
        if ([subView isKindOfClass:NSClassFromString(@"UITabBarButton")]) {

            CGFloat btnX = index * btnW;
            subView.frame = CGRectMake(btnX, btnY, btnW, btnH);

            index ++;
        }
    }

}

@end


text:
/*
Huerate - Mobile System for Customer Feedback Collection
Master Thesis at BUT FIT (http://www.fit.vutbr.cz), 2013
Available at http://huerate.cz

Author: Bc. Jakub Kadlubiec, xkadlu00@stud.fit.vutbr.cz or jakub.kadlubiec@gmail.com
*/

using System.Collections.Generic;
using System.Globalization;
using Huerate.Domain.Entities;

namespace Huerate.Services.Settings
{
    public interface ISettingsService
    {
        bool SendEmails { get; }

        SmtpSettings SmtpSettings { get; }

        SendGridSettings SendGridSettings { get; }

        string DefaultLanguage { get; }

        IList<string> MonitoringEmailAddresses { get; }

        bool ContentFilesOnBlob { get; }

        string ContentFilesBlobUri { get; }
    }
}


text:
<?php

namespace Kash;

use Kash\Driver\DriverInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

/**
 * @since 0.1.0
 */
class CachePool implements CachePoolInterface
{
    /**
     * regex pattern used to determine if a key is valid.
     *
     * @var string
     */
    const VALID_KEY_PATTERN = '[a-zA-Z0-9_\.]';

    /**
     * @var integer
     */
    protected $defaultTtl = 120; // Seconds

    /**
     * @var DriverInterface
     */
    protected $driver;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @var array
     */
    protected $itemsToSave;

    /**
     * @since 0.1.0
     * @param DriverInterface $driver
     */
    public function __construct(DriverInterface $driver)
    {
        $this->itemsToSave = array();
        $this->driver      = $driver;
    }

    /**
     * @since 0.1.0
     */
    public function __destruct()
    {
        $this->commit();
    }

    /**
     * @since 0.1.0
     * @param string $key
     * @return CacheItemInterface
     */
    public function getItem($key)
    {
        $isInvalid = preg_replace('/'.self::VALID_KEY_PATTERN.'/', '', $key);

        if ('' !== $isInvalid) {
            $this->log(LogLevel::ALERT, '"{key}" is invalid', array('key' => $key));
            throw new InvalidArgumentException('Invalid key');
        }

        $item = $this->driver->get(new CacheItem($key));

        if (!($item instanceof \Kash\CacheItemInterface)) {
            $this->log(LogLevel::ALERT, 'The driver did not return a valid "\Kash\CacheItem". It must implement "\Kash\CacheItemInterface"');
            throw new CacheException('Driver returned invalid item');
        }

        if (null === $item->getExpiration()) {
            $this->log(LogLevel::DEBUG, 'Setting default ttl of "{ttl}" seconds', array('ttl' => $this->defaultTtl));
            $item->setExpiration($this->defaultTtl);
        }

        $item->setDriver($this->driver);

        if ($this->logger) {
            $item->setLogger($this->logger);
        }

        return $item;
    }

    /**
     * @since 0.1.0
     * @param array[string] $keys
     * @return array[CacheItemInterface]
     */
    public function getItems(array $keys = array())
    {
        if (0 === count($keys)) {
            return array();
        }

        $itemsToReturn = array();

        foreach ($keys as $key) {
            $itemsToReturn[$key] = $this->getItem($key);
        }

        return $itemsToReturn;
    }

    /**
     * @since 0.1.0
     * @return boolean
     */
    public function clear()
    {
        $this->itemsToSave = array();

        return $this->driver->clear();
    }

    /**
     * @since 0.1.0
     * @param array $keys
     * @return self
     */
    public function deleteItems(array $keys)
    {
        foreach ($keys as $key) {
            $this->driver->delete(new CacheItem($key));
        }

        return $this;
    }

    /**
     * @since 0.1.0
     * @param CacheItemInterface $item
     * @return self
     */
    public function save(CacheItemInterface $item)
    {
        $this->driver->save($item);

        return $this;
    }

    /**
     * @since 0.1.0
     * @param CacheItemInterface $item
     * @return self
     */
    public function saveDeferred(CacheItemInterface $item)
    {
        $this->itemsToSave[] = $item;

        return $this;
    }

    /**
     * @since 0.1.0
     * @return boolean
     */
    public function commit()
    {
        $success = true;

        foreach ($this->itemsToSave as $item) {
            if (!$this->driver->save($item)) {
                $success = false;
            }
        }

        return $success;
    }

    /**
     * @since 0.1.0
     * {@inheritDoc}
     */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @since 0.1.0
     * @see \Psr\Log\LoggerInterface::log
     * @param mixed $level
     * @param string $message
     * @param array $context
     * @return null
     */
    protected function log($level, $message, array $context = array())
    {
        if (null === $this->logger) {
            return;
        }

        $this->logger->log($level, $message, $context);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false">
    <file url="file://$PROJECT_DIR$/datamodel" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/javaee-client" charset="UTF-8" />
  </component>
</project>


text:
package com.samynarrainen.domain;

import com.samynarrainen.Data.Status;
import com.samynarrainen.Data.Type;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Data structure for anime entires.
 */
public class Entry {

    /**
     * The entrie's main title.
     */
    public String name = "";

    /**
     * Stored in a 0-10 rating system.
     */
    public int rating = -1;

    /**
     * The status of this anime in the list. E.g watching.
     */
    public Status status = Status.None;

    /**
     * The anime's corresponding MAL id.
     */
    public int id = -1;

    /**
     * Alternative titles of the anime.
     */
    public List<String> altTitles = new ArrayList<String>();

    /**
     * The id was found by a perfect match. Thus little chance of mismatch.
     */
    public boolean perfectMatch = false;

    /**
     * Number of episodes seen by the user.
     * Relevant if DROPPED or STALLED, WATCHED where all episodes have been seen.
     */
    public int episodes = -1;

    /**
     * The AP equivalent of id, used as a unique identifier by AP.
     */
    public String AnimePlanetURL = "";

    /**
     * The start and end date that the user watched this anime from.
     * The end date is not used if the anime has not been completely watched.
     * Purposely kept null to prevent un-assigned dates from being used.
     */
    public Date start, end;

    /**
     * The number of times the series has been watched.
     * 1 implies the show has been completed, 2 implies it has been completed and re-watched once.
     */
    public int watchCount = -1;

    /**
     * The studios that produced this show.
     */
    public List<String> studios = new ArrayList<String>();

    /**
     * The publishing year and the year publishing ended, AKA the airing of the last episode.
     */
    public int year = -1, yearEnd = -1;

    /**
     * The season this show belonged to, e.g Summer 2017.
     */
    public String season = "";

    /**
     * The number of episodes available in this show.
     * @see this.episodes
     */
    public int totalEpisodes = -1;

    /**
     * The type of show, for example TV, Movie, Web...
     */
    public Type type = Type.None;

    /**
     * Date format used by MAL.
     */
    private final SimpleDateFormat MAL_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * Normalises a 0-5 float scale rating system to 0-10 integer which is used by MAL.
     * @param rating a String representing a numerical value.
     */
    public static int convertRating(String rating) {
        //AP uses a 0-5 float rating system.
        return (int) Float.parseFloat(rating) * 2;
    }

    public String toString() {
        String to_return = "";

        to_return += "(NAME: " + name + ") ";
        if(!AnimePlanetURL.equals("")) {
            to_return += "(AP URL: http://www.anime-planet.com/anime/" +  AnimePlanetURL + ") "; //TODO need to change anime to manga if we add manga.
        }
        to_return += "(ID: " + id + ") ";
        to_return += "(STATUS: " + status.literal + ") ";
        to_return += "(RATING: " + rating + ") ";
        to_return += "(EPS: " + episodes + ") ";
        if(id != -1) {
            to_return += "(URL: " + "https://myanimelist.net/anime/" + id + "/)";
        }
        if(start != null && end != null) {
            to_return += "(START: " + start + ") ";
            to_return += "(END: " + end + ") ";
        }
        if(status.equals(Status.Watched)) {
            to_return += "(WATCH_COUNT: " + watchCount + ") ";
        }

        return to_return;
    }

    /**
     * Exports into the XML format used by MAL. Used for uploading the results to a MAL account.
     */
    public String toXML() {
        StringBuilder sb = new StringBuilder();
        sb.append("<anime>");
        sb.append("<series_animedb_id>" + id + "</series_animedb_id>");
        sb.append("<my_status>" + status.literal + "</my_status>");
        sb.append("<update_on_import>1</update_on_import>");

        if (episodes >= 0) {
            sb.append("<my_watched_episodes>" + episodes + "</my_watched_episodes>");
        }

        if (rating >= 0) {
            sb.append("<my_score>" + rating + "</my_score>");
        }

        if (start != null) {
            sb.append("<my_start_date>" + MAL_DATE_FORMAT.format(start) + "</my_start_date>");
        }

        if (status.equals(Status.Watched)) {
            //'finish date' only makes sense if the show is finished.
            if (end != null) {
                sb.append("<my_finish_date>" + MAL_DATE_FORMAT.format(end) + "</my_finish_date>");
            }

            //Accounting for number of times re-watched, so -1 for for the initial viewing.
            sb.append("<my_rewatching>" + (watchCount - 1) +"</my_rewatching>");
        }

        sb.append("</anime>");
        return sb.toString();
    }
}


text:
Projektziel
-----------

Erstellen Sie eine Pendenzenlisten Applikation mit:
- Responsive Layout
- 2-Tier Architektur
- RESTful Schnittstelle
- JSON Datenstrukturen
- Serverseitiger Persistenz

Meilensteine & Abgaben
----------------------

Um die Komplexität zu reduzieren wird die Pendenzenlisten Applikation in drei Iterationen erstellt. Diese Meilensteine werden einzeln abgegeben und bewertet:

1. Pendenzenliste als Javascript Objekte
2. Dynamische HTML Seite
3. Pendenzenliste über Web-Schnittstelle lesen und persistieren

Alle Abgaben werden nach den folgenden Kriterien bewertet:
- Validiert: Valider HTML, CSS und Javascript Code (1 Punkt)
- Deployed: Zugreifbar auf Lab-Server2 (1 Punkt)
- Getested: Code ist unter Test (1 Punkt)
- Funktional: Code erfüllt funktionale Anforderungen des jeweiligen Meilensteines (2 Punkte)


text:
import { createAsyncComponent } from 'react-async-component';

export default createAsyncComponent({
  resolve: () => System.import('./Home'),
  ssrMode: 'boundary',
  name: 'AsyncHome',
});


text:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:clickable="true"
        android:clipChildren="false"
        android:clipToPadding="false"
        android:elevation="7dp"
        card_view:cardCornerRadius="2dp"
        card_view:cardElevation="5dp"
        card_view:cardPreventCornerOverlap="true"
        card_view:cardUseCompatPadding="true">

        <RelativeLayout
            android:id="@+id/fullcard"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:background="@color/card_color"
            android:elevation="4dp">

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:clickable="true"
                android:gravity="center" />

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/thumbnail"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="16dp"
                android:gravity="center"
                android:textColor="@color/card_text_color"
                android:textSize="17sp" />

            <TextView
                android:id="@+id/pos"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <TextView
                android:id="@+id/count"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/title"
                android:layout_centerHorizontal="true"
                android:paddingBottom="@dimen/songs_count_padding_bottom"
                android:paddingLeft="@dimen/album_title_padding"
                android:paddingRight="@dimen/album_title_padding"
                android:textSize="@dimen/songs_count"
                android:visibility="gone" />

            <ImageView
                android:id="@+id/overflow"
                android:layout_width="@dimen/ic_album_overflow_width"
                android:layout_height="@dimen/ic_album_overflow_height"
                android:layout_alignParentRight="true"
                android:layout_below="@id/thumbnail"
                android:layout_marginTop="@dimen/ic_album_overflow_margin_top"
                android:scaleType="centerCrop"
                android:src="@drawable/ic_dots"
                android:visibility="gone" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</android.support.design.widget.CoordinatorLayout>


text:
<?php

class_exists('Twig_Environment');
class_exists('Twig_Node');

/**
 * Twig_NodeVisitorInterface is the interface the all node visitor classes must implement.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface Twig_NodeVisitorInterface
{
    /**
     * Called before child nodes are visited.
     *
     * @return Twig_NodeInterface The modified node
     */
    public function enterNode(Twig_NodeInterface $node, Twig_Environment $env);

    /**
     * Called after child nodes are visited.
     *
     * @return Twig_NodeInterface|false The modified node or false if the node must be removed
     */
    public function leaveNode(Twig_NodeInterface $node, Twig_Environment $env);

    /**
     * Returns the priority for this visitor.
     *
     * Priority should be between -10 and 10 (0 is the default).
     *
     * @return int The priority level
     */
    public function getPriority();
}

class_alias('Twig_NodeVisitorInterface', 'Twig\NodeVisitor\NodeVisitorInterface', false);


text:
package org.kuali.kfs.module.cg.identity;

import org.kuali.kfs.module.cg.businessobject.ResearchRiskType;
import org.kuali.kfs.sys.identity.KfsKimAttributes;

public class CgKimAttributes extends KfsKimAttributes {
    public static final String RESEARCH_RISK_TYPE_CODE = "researchRiskTypeCode";

    protected String researchRiskTypeCode;

    protected ResearchRiskType researchRiskType;

    public String getResearchRiskTypeCode() {
        return researchRiskTypeCode;
    }
    public void setResearchRiskTypeCode(String researchRiskTypeCode) {
        this.researchRiskTypeCode = researchRiskTypeCode;
    }

    public ResearchRiskType getResearchRiskType() {
        return researchRiskType;
    }
    public void setResearchRiskType(ResearchRiskType researchRiskType) {
        this.researchRiskType = researchRiskType;
    }
}


text:
namespace extensions {

namespace keys = bookmark_api_constants;
using api::bookmarks::BookmarkTreeNode;

namespace bookmark_api_helpers {

namespace {

void AddNodeHelper(const BookmarkNode* node,
                   std::vector<linked_ptr<BookmarkTreeNode> >* nodes,
                   bool recurse,
                   bool only_folders) {
  if (node->IsVisible()) {
    linked_ptr<BookmarkTreeNode> new_node(GetBookmarkTreeNode(node,
                                                              recurse,
                                                              only_folders));
    nodes->push_back(new_node);
  }
}

// TODO(mwrosen): Remove this function once chrome.bookmarkManagerPrivate is
// refactored to use the JSON schema compiler.
void AddNodeHelper(const BookmarkNode* node,
                   base::ListValue* list,
                   bool recurse,
                   bool only_folders) {
  if (node->IsVisible()) {
    base::DictionaryValue* dict =
        GetNodeDictionary(node, recurse, only_folders);
    list->Append(dict);
  }
}

}  // namespace

BookmarkTreeNode* GetBookmarkTreeNode(const BookmarkNode* node,
                                      bool recurse,
                                      bool only_folders) {
  BookmarkTreeNode* bookmark_tree_node = new BookmarkTreeNode;

  bookmark_tree_node->id = base::Int64ToString(node->id());

  const BookmarkNode* parent = node->parent();
  if (parent) {
    bookmark_tree_node->parent_id.reset(new std::string(
        base::Int64ToString(parent->id())));
    bookmark_tree_node->index.reset(new int(parent->GetIndexOf(node)));
  }

  if (!node->is_folder()) {
    bookmark_tree_node->url.reset(new std::string(node->url().spec()));
  } else {
    // Javascript Date wants milliseconds since the epoch, ToDoubleT is seconds.
    base::Time t = node->date_folder_modified();
    if (!t.is_null()) {
      bookmark_tree_node->date_group_modified.reset(
          new double(floor(t.ToDoubleT() * 1000)));
    }
  }

  bookmark_tree_node->title = UTF16ToUTF8(node->GetTitle());
  if (!node->date_added().is_null()) {
    // Javascript Date wants milliseconds since the epoch, ToDoubleT is seconds.
    bookmark_tree_node->date_added.reset(
        new double(floor(node->date_added().ToDoubleT() * 1000)));
  }

  if (recurse && node->is_folder()) {
    std::vector<linked_ptr<BookmarkTreeNode> > children;
    for (int i = 0; i < node->child_count(); ++i) {
      const BookmarkNode* child = node->GetChild(i);
      if (child->IsVisible() && (!only_folders || child->is_folder())) {
        linked_ptr<BookmarkTreeNode> child_node(
            GetBookmarkTreeNode(child, true, only_folders));
        children.push_back(child_node);
      }
    }
    bookmark_tree_node->children.reset(
        new std::vector<linked_ptr<BookmarkTreeNode> >(children));
  }
  return bookmark_tree_node;
}

base::DictionaryValue* GetNodeDictionary(const BookmarkNode* node,
                                         bool recurse,
                                         bool only_folders) {
  base::DictionaryValue* dict = new base::DictionaryValue;
  dict->SetString(keys::kIdKey, base::Int64ToString(node->id()));

  const BookmarkNode* parent = node->parent();
  if (parent) {
    dict->SetString(keys::kParentIdKey, base::Int64ToString(parent->id()));
    dict->SetInteger(keys::kIndexKey, parent->GetIndexOf(node));
  }

  if (!node->is_folder()) {
    dict->SetString(keys::kUrlKey, node->url().spec());
  } else {
    // Javascript Date wants milliseconds since the epoch, ToDoubleT is seconds.
    base::Time t = node->date_folder_modified();
    if (!t.is_null())
      dict->SetDouble(keys::kDateFolderModifiedKey,
                      floor(t.ToDoubleT() * 1000));
  }

  dict->SetString(keys::kTitleKey, node->GetTitle());
  if (!node->date_added().is_null()) {
    // Javascript Date wants milliseconds since the epoch, ToDoubleT is seconds.
    dict->SetDouble(keys::kDateAddedKey,
                    floor(node->date_added().ToDoubleT() * 1000));
  }

  if (recurse && node->is_folder()) {
    base::ListValue* children = new base::ListValue;
    for (int i = 0; i < node->child_count(); ++i) {
      const BookmarkNode* child = node->GetChild(i);
      if (child->IsVisible() && (!only_folders || child->is_folder())) {
        base::DictionaryValue* dict =
            GetNodeDictionary(child, true, only_folders);
        children->Append(dict);
      }
    }
    dict->Set(keys::kChildrenKey, children);
  }
  return dict;
}

void AddNode(const BookmarkNode* node,
             std::vector<linked_ptr<BookmarkTreeNode> >* nodes,
             bool recurse) {
  return AddNodeHelper(node, nodes, recurse, false);
}

void AddNodeFoldersOnly(const BookmarkNode* node,
                        std::vector<linked_ptr<BookmarkTreeNode> >* nodes,
                        bool recurse) {
  return AddNodeHelper(node, nodes, recurse, true);
}

void AddNode(const BookmarkNode* node, base::ListValue* list, bool recurse) {
  return AddNodeHelper(node, list, recurse, false);
}

void AddNodeFoldersOnly(const BookmarkNode* node,
                        base::ListValue* list,
                        bool recurse) {
  return AddNodeHelper(node, list, recurse, true);
}

bool RemoveNode(BookmarkModel* model,
                int64 id,
                bool recursive,
                std::string* error) {
  const BookmarkNode* node = model->GetNodeByID(id);
  if (!node) {
    *error = keys::kNoNodeError;
    return false;
  }
  if (model->is_permanent_node(node)) {
    *error = keys::kModifySpecialError;
    return false;
  }
  if (node->is_folder() && !node->empty() && !recursive) {
    *error = keys::kFolderNotEmptyError;
    return false;
  }

  const BookmarkNode* parent = node->parent();
  model->Remove(parent, parent->GetIndexOf(node));
  return true;
}

}  // namespace bookmark_api_helpers
}  // namespace extensions


text:
import datetime

from logging import getLogger

LOG = getLogger(__name__)

class RecordDetail(object):

    def __init__(self, name):
        self.name = name
        self.status = None
        self.start_time = datetime.datetime.now()
        self.stop_time = None
        self.number_of_records = None
        self.other_details = None

    def save(self,):
        # Do stuff to write to database
        LOG.info('saving %s ', self)

    def __str__(self):
        return ('name: %s start: %s stop : %s' % (self.name, self.start_time, self.stop_time))

    def stop(self, status):
        LOG.info('stopping')
        self.status = status
        self.stop_time = datetime.datetime.now()
        self.save()


text: This is foo/index.html.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using System.Diagnostics;
using CCT.NUI.Core;
using CCT.NUI.Core.OpenNI;
using CCT.NUI.Core.Video;
using CCT.NUI.Visual;
using CCT.NUI.HandTracking;
using CCT.NUI.KinectSDK;
using CCT.NUI.Core.Clustering;
using System.Windows.Media.Media3D;
using System.Threading;
using System.Windows.Threading;
using OpenNI;

namespace CCT.NUI.WPFSamples
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Microsoft.Kinect.KinectSensor sensor;

        // initialize the int
        public int resultfinger = -1; // int that cointains number of fingers
        public int palm = -1; // cointains number of palm
        public int rand = -1; // initialize the random int

        private HandInterfaceElement element = null;

        private IDataSourceFactory factory;
        private IHandDataSource handDataSource;
        private IClusterDataSource clusterDataSource;

        public MainWindow()
        {
            InitializeComponent();
            this.Start();
            this.ToggleLayers();
            txtInfo.Text = "RPS Kinect v1.0 Developed by Niccolò Fabbri   E-mail: niccolo.fabbri@stud.unifi.it   Teacher: Prof. Andrew David Bagdanov";
            textBox1.FontSize = 36;
        }

        // this method allows to choose the image

        enum GestureStatus
        {
            None = 0,
            Rock = 1,
            Paper = 2,
            Scissors = 3
        }
        GestureStatus gs = GestureStatus.None;
        private void GestureReact()
        {
            switch (gs)
            {
                case GestureStatus.None:
                    imgGesture.Source = new BitmapImage(new Uri("./Images/None.png", UriKind.Relative));
                    break;
                case GestureStatus.Rock:
                    imgGesture.Source = new BitmapImage(new Uri("./Images/SASSO.png", UriKind.Relative));
                    break;
                case GestureStatus.Paper:
                    imgGesture.Source = new BitmapImage(new Uri("./Images/CARTA.png", UriKind.Relative));
                    break;
                case GestureStatus.Scissors:
                    imgGesture.Source = new BitmapImage(new Uri("./Images/FORBICE.png", UriKind.Relative));
                    break;
            }
        }

        // this method allows to choose the image for USER Icon
        enum GestureStatus1
        {
            doubt = 0,
            smile = 1,
            nosmile = 2
        }
        GestureStatus1 gs1 = GestureStatus1.doubt;
        private void GestureReact1()
        {
            switch (gs1)
            {
                case GestureStatus1.doubt:
                    man.Source = new BitmapImage(new Uri("./Images/YELLOW.jpg", UriKind.Relative));
                    break;
                case GestureStatus1.smile:
                    man.Source = new BitmapImage(new Uri("./Images/GREEN.jpg", UriKind.Relative));
                    break;
                case GestureStatus1.nosmile:
                    man.Source = new BitmapImage(new Uri("./Images/RED.jpg", UriKind.Relative));
                    break;
            }
        }

        // this method allows to choose the image for CPU Icon
        enum GestureStatus2
        {
            doubt = 0,
            smile = 1,
            nosmile = 2
        }
        GestureStatus2 gs2 = GestureStatus2.doubt;
        private void GestureReact2()
        {
            switch (gs2)
            {
                case GestureStatus2.doubt:
                    cpu.Source = new BitmapImage(new Uri("./Images/YELLOW.jpg", UriKind.Relative));
                    break;
                case GestureStatus2.smile:
                    cpu.Source = new BitmapImage(new Uri("./Images/GREEN.jpg", UriKind.Relative));
                    break;
                case GestureStatus2.nosmile:
                    cpu.Source = new BitmapImage(new Uri("./Images/RED.jpg", UriKind.Relative));
                    break;
            }
        }

        // Little logic to RPS Game,  when no hand found, it reset the GetRandom Number
        public void RPS_Game()
        {
            if (resultfinger == 5 || resultfinger == 4)
            {
                GetWinner_Paper(rand);
            }
            if (resultfinger == 3 || resultfinger == 2)
            {
                GetWinner_Scissors(rand);
            }
            if (resultfinger == 1 || resultfinger == 0)
            {
                GetWinner_Rock(rand);
                resultfinger = -1;
            }
            else if ((palm == 1 && resultfinger == 0) || resultfinger == -1) // palm == 1 || || resultfinger == -1 || count == 0)
            {
                textBox1.Text = "No Hand Found";
                imgGesture.Source = new BitmapImage(new Uri("./Images/banhand1.png", UriKind.Relative));
                cpu.Source = new BitmapImage(new Uri("./Images/CPU.png", UriKind.Relative));
                man.Source = new BitmapImage(new Uri("./Images/MAN.png", UriKind.Relative));
                rand = GetRandomNumber(0, 3);
            }
        }

        public void HandInterfaceWindow(IHandDataSource handDataSource, IImageDataSource imageDataSource)
        {
            this.element = new HandInterfaceElement();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Start()
        {
            // initialize sensor Microsoft Kinect SDK
            sensor = Microsoft.Kinect.KinectSensor.KinectSensors.FirstOrDefault();
            sensor.Start();
            sensor.ElevationAngle = 13;

            // initialize some element

            this.Cursor = Cursors.Wait;
            this.factory = new SDKDataSourceFactory();

            this.clusterDataSource = this.factory.CreateClusterDataSource(new Core.Clustering.ClusterDataSourceSettings { MaximumDepthThreshold = 900 });
            this.handDataSource = new HandDataSource(this.factory.CreateShapeDataSource(this.clusterDataSource, new Core.Shape.ShapeDataSourceSettings()));

            var depthImageSource = this.factory.CreateDepthImageDataSource();
            depthImageSource.NewDataAvailable += new NewDataHandler<ImageSource>(MainWindow_NewDataAvailable);
            handDataSource.NewDataAvailable += new NewDataHandler<HandCollection>(handDataSource_NewDataAvailable);
            HandInterfaceWindow(this.handDataSource, depthImageSource);
            //new HandInterfaceWindow(this.handDataSource, this.rgbImageDataSource).Show();
            depthImageSource.Start();
            handDataSource.Start();
            this.Cursor = Cursors.Arrow;

        }

        void handDataSource_NewDataAvailable(HandCollection data)
        {
            // for each frame, count number of fingers (resultfinger), if no hand found is 0
            for (int index = 0; index < data.Count; index++)
            {
                var hand = data.Hands[index];
                resultfinger = hand.FingerCount;
                if (hand.HasPalmPoint == true)
                {
                    palm = 1;
                }
                else
                {
                    palm = 0;
                }
                this.element.Update(data);
            }
        }

        // random function to choose int between 0 and 2. 0 rock, 1 scissors, 2 paper
        public int GetRandomNumber(int min, int max)
        {
            Random r = new Random();
            int rInt = r.Next(min, max);
            return rInt;
        }

        //function that calculates the win of paper gesture
        public void GetWinner_Paper(int rand)
        {
            GestureReact();
            GestureReact1();
            GestureReact2();
            if (rand == 2)
            {
                gs = GestureStatus.Paper;
                textBox1.Text = "Play Again? Remove your hand!";
                gs1 = GestureStatus1.doubt;
                gs2 = GestureStatus2.doubt;
            }
            else if (rand == 0)
            {
                gs = GestureStatus.Rock;
                textBox1.Text = "Play Again? Remove your hand!";
                gs1 = GestureStatus1.smile;
                gs2 = GestureStatus2.nosmile;
            }
            else if (rand == 1)
            {
                gs = GestureStatus.Scissors;
                textBox1.Text = "Play Again? Remove your hand!";
                gs1 = GestureStatus1.nosmile;
                gs2 = GestureStatus2.smile;
            }
        }

        //function that calculates the win of scissors gesture
        public void GetWinner_Scissors(int rand)
        {
            GestureReact();
            GestureReact1();
            GestureReact2();
            if (rand == 1)
            {
                gs = GestureStatus.Scissors;
                textBox1.Text = "Play Again? Remove your hand!";
                gs1 = GestureStatus1.doubt;
                gs2 = GestureStatus2.doubt;
            }
            else if (rand == 0)
            {
                gs = GestureStatus.Rock;
                textBox1.Text = "Play Again? Remove your hand!";
                gs1 = GestureStatus1.nosmile;
                gs2 = GestureStatus2.smile;
            }
            else if (rand == 2)
            {
                gs = GestureStatus.Paper;
                textBox1.Text = "Play Again? Remove your hand!";
                gs1 = GestureStatus1.smile;
                gs2 = GestureStatus2.nosmile;
            }
        }

        //function that calculates the win of rock gesture
        public void GetWinner_Rock(int rand)
        {
            GestureReact();
            GestureReact1();
            GestureReact2();
            if (rand == 0)
            {
                gs = GestureStatus.Rock;
                textBox1.Text = "Play Again? Remove your hand!";
                gs1 = GestureStatus1.doubt;
                gs2 = GestureStatus2.doubt;
            }
            else if (rand == 1)
            {
                gs = GestureStatus.Scissors;
                textBox1.Text = "Play Again? Remove your hand!";
                gs1 = GestureStatus1.smile;
                gs2 = GestureStatus2.nosmile;
            }
            else if (rand == 2)
            {
                gs = GestureStatus.Paper;
                textBox1.Text = "Play Again? Remove your hand!";
                gs1 = GestureStatus1.nosmile;
                gs2 = GestureStatus2.smile;
            }
        }

        void MainWindow_NewDataAvailable(ImageSource data)
        {
            RPS_Game();
            this.videoControl.Dispatcher.Invoke(new Action(() =>
            {
                this.videoControl.ShowImageSource(data);
            }));
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            new Action(() =>
            {
                this.handDataSource.Stop();
                this.factory.Dispose();
            }).BeginInvoke(null, null);
        }

        // add the layers (read report) around at the hand found
        private void ToggleLayers()
        {
            var layers = new List<IWpfLayer>();
            layers.Add(new WpfHandLayer(this.handDataSource));
            this.videoControl.Layers = layers;
        }

        private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {

        }

        private void txtInfo_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {

        }

        private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)
        {

        }

        //button to show instruction
        private void btn_Click(object sender, RoutedEventArgs e)
        {
            popup.IsOpen = true;
        }

        private void focusTarger_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
    }
}


text:
import os
import subprocess

def bytesToHex(bytes):
    return ' '.join(["%02X" % ord(x) for x in bytes])

def readFile(fileName):
    with open(fileName, "r") as f:
        return f.read()

def writeFile(fileName, contents):
    with open(fileName, "w") as f:
        f.write(contents)

os.makedirs('Scratch', exist_ok=True)
os.chdir('Scratch')

contents = '''    a
\tb
 \t   c
  d
\t  e
\t@""
    @"
\t1
    2"
f'''

writeFile('test_chisel.txt', contents)
print(bytesToHex(contents))

subprocess.call(("/usr/local/bin/python3", "../../chisel.py", "test_chisel.txt", "-m", "t", "-o", "test_chisel_result.txt"))

contents = readFile('test_chisel_result.txt')
print(bytesToHex(contents))


text:
using System.Collections.Generic;
using BenchmarkDotNet.Analysers;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Validators;
using JetBrains.Annotations;

namespace BenchmarkDotNet.Diagnosers
{
    public interface IDiagnoser
    {
        IEnumerable<string> Ids { get; }

        IEnumerable<IExporter> Exporters { get; }

        IEnumerable<IAnalyser> Analysers { get; }

        RunMode GetRunMode(BenchmarkCase benchmarkCase);

        bool RequiresBlockingAcknowledgments(BenchmarkCase benchmarkCase);

        void Handle(HostSignal signal, DiagnoserActionParameters parameters);

        IEnumerable<Metric> ProcessResults(DiagnoserResults results);

        void DisplayResults(ILogger logger);

        IEnumerable<ValidationError> Validate(ValidationParameters validationParameters);
    }

    public interface IConfigurableDiagnoser<in TConfig> : IDiagnoser
    {
        [PublicAPI] IConfigurableDiagnoser<TConfig> Configure(TConfig config);
    }
}


text:
using System;

namespace ManagedLua.Environment.Types {
	/// <summary>
	/// Description of Nil.
	/// </summary>
	public class Nil {
		private Nil() {}

		public static Nil Value = new Nil();

		public override string ToString() {
			return "nil";
		}
	}
}


text:
from swift.common.utils import get_remote_client, get_logger
from swift.common.swob import Request, HTTPForbidden

class VerbAclMiddleware(object):
    """
    Middleware that manages access (permission) to the methods
    based on the IP address.
    """

    def __init__(self, app, conf):
        self.app = app
        self.logger = get_logger(conf)

        # TODO Check pipeline

        self.verb_acl = {}
        verb_acl = conf.get('verb_acl', None)
        if verb_acl is None:
            raise ValueError(
                'verb_acl: missing "verb_acl" configuration entry')
        for acl in verb_acl.split(';'):
            if not acl:
                continue
            if acl.count(':') != 1:
                raise ValueError('verb_acl: bad format: "%s"' % acl)
            methods, blocks = acl.split(':', 1)
            for method in methods.split(','):
                if not method:
                    raise ValueError(
                        'verb_acl: bad format: missing method: "%s"' % acl)
                for block in blocks.split(','):
                    if not block:
                        raise ValueError(
                            'verb_acl: bad format: empty address block: "%s"' %
                            acl)
                    self.verb_acl.setdefault(method.upper(), []).append(block)
        self.logger.debug("Verb ACL: " + str(self.verb_acl))

    def __call__(self, env, start_response):
        req = Request(env)
        if req.method in self.verb_acl:
            remote = get_remote_client(req)
            for block in self.verb_acl[req.method]:
                if remote.startswith(block):
                    break
            else:
                raise HTTPForbidden(request=req,
                                    body='Forbidden method for %s' % remote)

        return self.app(env, start_response)

def filter_factory(global_conf, **local_config):
    conf = global_conf.copy()
    conf.update(local_config)

    def factory(app):
        return VerbAclMiddleware(app, conf)
    return factory


text:
import unittest
from models import *

""" crud testing """

class TestSiteModel(unittest.TestCase):
  def setUp(self):
    site = Site()
    site.actions = ['view','add','edit','delete','comment','rate']
    site.title = "Test Website"
    site.description = "Test Website Description"
    site.keywords = ['1','2','3']
    site.tags = ['tag1','tag2','tag3','tag4','tag5','tag6']
    site.put()
  def test_tags_exist(self):
    site = Site.all().get()
    self.assertTrue(['tag1','tag2','tag3','tag4','tag5','tag6'] == site.tags)
  def test_title_works(self):
    site = Site.all().get()
    self.assertTrue('Test Website' == site.title)
class TestPageMode(unittest.TestCase):
  def setUp(self):
    page = Page()

  def test_tags_exist(self):
    page = Page.all().get()
    self.assertTrue([] == page.tags


text:
'use strict';

const execute = require('../../lib/execute');
const assert = require('assert');
const nock = require('nock');
const githubMock = require('../execute/github_mock');

describe('rule commit-user', () => {
  afterEach(() => {
    nock.cleanAll();
  });

  it('should check that commit commit author and commiter have associated GitHub user login', () => {
    githubMock.mock('/repos/MailOnline/jest-tap-reporter/commits?since=2017-04-23&per_page=30&page=1', '../fixtures/mailonline_jest-tap-reporter_commits');
    githubMock.mock('/repos/milojs/milo/commits?since=2017-04-23&per_page=30&page=1', '../fixtures/milojs_milo_commits');

    const config = {
      org: 'MailOnline',
      repositories: {
        'jest-tap-reporter': {
          rules: {
            'commit-user': 2
          }
        },
        'milojs/milo': {
          rules: {
            'commit-user': 2
          }
        }
      }
    };

    return execute.checkRules(config, {commits: {since: '2017-04-23'}})
    .then((results) => {
      assert.deepStrictEqual(results, require('../fixtures/commit-user_expected_results.json'));
      assert(nock.isDone());
    });
  });
});


text:
using System;

namespace AdaptiveConsole
{
    /// <summary>
    /// The AdaptiveConsole exception which indicates that the option is invalid.
    /// </summary>
    public class InvalidOptionException : AdaptiveConsoleException
    {
        #region Constructors
        /// <summary>
        /// Initializes the exception with the given message.
        /// </summary>
        /// <param name="message">The exception message.</param>
        public InvalidOptionException(string message) : base(message) { }
        /// <summary>
        /// Initializes the exception with the given message and its inner exception.
        /// </summary>
        /// <param name="message">The exception message.</param>
        /// <param name="innerException">The inner exception instance.</param>
        public InvalidOptionException(string message, Exception innerException) : base(message, innerException) { }
        /// <summary>
        /// Initializes the exception with the formatting string and the parameters.
        /// </summary>
        /// <param name="format">The formatting string.</param>
        /// <param name="arguments">Parameters.</param>
        public InvalidOptionException(string format, params object[] arguments) : base(format, arguments) { }
        #endregion
    }
}


text:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'
require 'spec_helper'
# require 'factory_helper'

# include all the RSpec shared examples
Dir["./spec/support/shared_examples_for_*.rb"].sort.each { |f| require f}

# Add additional requires below this line. Rails is not loaded until this point!

# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|

  # conditionally turn off mock checking for view specs
  # since we tend to mock helpers, which would throw
  # lots of errors
  config.around(:each, type: :view) do |ex|
    config.mock_with :rspec do |mocks|
      mocks.verify_partial_doubles = false
      ex.run
      mocks.verify_partial_doubles = true
    end
  end

  config.include Rails.application.routes.url_helpers, type: :controller

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # RSpec Rails can automatically mix in different behaviours to your tests
  # based on their file location, for example enabling you to call `get` and
  # `post` in specs under `spec/controllers`.
  #
  # You can disable this behaviour by removing the line below, and instead
  # explicitly tag your specs with their type, e.g.:
  #
  #     RSpec.describe UsersController, :type => :controller do
  #       # ...
  #     end
  #
  # The different available types are documented in the features, such as in
  # https://relishapp.com/rspec/rspec-rails/docs
  config.infer_spec_type_from_file_location!
end


text:
'use strict';
module.exports = {
	name: 'Midgaard',
	id: 'midgaard',
	type: ['camp'],
	levels: 'All',
	description: 'Base camp for the Southern Mine across the sea.',
	reloads: 0,
	created: '',
	saved: '',
	author: 'Rocky',
	messages: [
		{msg: 'A cold breeze blows through the camp.'},
		{msg: 'A strong southern gust tests the tents.'}
	],
	respawnOn: 8,
	persistence: false,
	rooms: [
		{
			id: '1',
			title: 'Center of the Southern Mine Encampment',
			light: true,
			area: 'midgaard',
			content: 'An open space at the intersection of rows upon rows of snow covered tents. A large fire warms the area.',
			outdoors: true,
			exits: [
				{
					cmd: 'north',
					id: '2'
				}, {
					cmd: 'east',
					id: '3'
				}, {
					cmd: 'south',
					id: '4'
				}, {
					cmd: 'west',
					id: '5'
				}, {
					cmd: 'down',
					id: '6',
					door: true,
					isOpen: false,
					locked: true,
					key: '101',
					name: 'gate',
					openMsg: 'A foul smell flows in from below.'
				}
			],
			playersInRoom: [],
			monsters: [
				{
					name: 'Expedition Leader William',
					lastName: 'Green',
					level: 15,
					short: 'Expedition Leader William Green',
					long: 'William Green the leader of the current mine expedition is here overseeing camp activities',
					description: '',
					inName: 'Expedition Leader William',
					race: 'human',
					charClass: "Fighter",
					id: 9,
					area: 'midgaard',
					weight: 245,
					baseStr: 1,
					position: 'standing',
					attackType: 'punch',
					damroll: 10,
					hitroll: 10,
					ac: 20,
					runOnAliveWhenEmpty: true,
					items: [
						{
							name: 'Leather Armor',
							short: 'a leather chestplate',
							long: 'Some leather armor was left here',
							area: 'midgaard',
							id: '111',
							level: 1,
							itemType: 'armor',
							material: 'leather',
							ac: 3,
							weight: 1,
							slot: 'body',
							equipped: false,
							value: 5
						},
						{
							name: 'Burlap sack',
							short: 'a worn, tan, burlap sack',
							long: 'A tan burlap sack with frizzed edges and various stains lies here',
							area: 'midgaard',
							id: '27',
							level: 1,
							itemType: 'container',
							weight: 1,
							items: [{
								name: 'Sewer key',
								short: 'small rusty key',
								long: 'A small rusty key made iron was left here',
								area: 'midgaard',
								id: '101',
								level: 1,
								itemType: 'key',
								material: 'iron',
								weight: 0,
								slot: '',
								value: 1,
								equipped: false,
								isKey: true
							}],
							isOpen: true,
							carryLimit: 50
						}
					],
					behaviors: [{
						module: 'expedition_leader'
					}, {
						module: 'wander',
						wanderCheck: 90,
						moveDirections: ['north', 'east', 'west', 'south']
					}]
				}
			],
			items: [
				{
					name: 'Wooden water barrel',
					short: 'a barrel of fresh water',
					long: 'A large wooden barrel filled with water',
					area: 'midgaard',
					id: '112',
					waterSource: true,
					weight: 10000,
					modifiers: {
						thirst: -1
					},
					itemType: 'ornament'
				},
				{
					name: 'Wooden Torch',
					short: 'a wooden torch',
					long: 'A wooden torch rests on the ground',
					area: 'midgaard',
					id: '104',
					level: 1,
					itemType: 'weapon',
					material: 'wood',
					weaponType: 'club',
					diceNum: 1,
					diceSides: 3,
					attackType: 'smash',
					weight: 2,
					slot: 'hands',
					equipped: false,
					light: true,
					lightDecay: 10,
					flickerMsg: '',
					extinguishMsg: '',
					behaviors: [{
						module: 'cursed_item'
					}],
					spell: {
						id: 'spark',
						display: 'Spark',
						mod: 0,
						train: 85,
						type: 'spell',
						wait: 2
					}
				}
			]
		},
		{
			id: '2',
			title: 'North of Camp Center',
			area: 'midgaard',
			content: 'A couple of large stained tents are here shuttering in the wind. Wood cutting blocks reside in front of both settlements but little else can be found.',
			outdoors: true,
			exits: [
				{
					cmd: 'south',
					id: '1'
				}, {
					cmd: 'north',
					id: '1',
					area: 'the_great_valley'
				}
			],
			playersInRoom: [],
			monsters: [],
			items: [{
				name: 'Tattered Buckler Shield',
				displayName: 'Tattered Buckler',
				short: 'a tattered buckler',
				long: 'A round buckler that looks like its seen heavy use is lying here' ,
				area: 'midgaard',
				id: '2',
				level: 1,
				itemType: 'shield',
				material: 'wood',
				ac: 2,
				weight: 6,
				slot: 'hands',
				equipped: false
			}, {
				name: 'Short Sword',
				displayName: 'Short Sword',
				short: 'a common looking short sword',
				long: 'A short sword with a hilt wrapped in leather straps was left on the ground' ,
				area: 'midgaard',
				id: '8',
				level: 1,
				itemType: 'weapon',
				weaponType: 'sword',
				material: 'iron',
				diceNum: 1,
				diceSides: 6,
				attackType: 'slash',
				attackElement: '',
				weight: 4,
				slot: 'hands',
				equipped: false,
				modifiers: {
					damroll: 1,
					hitroll: 1
				}
			}]
		},
		{
			id: '3',
			title: 'East of Camp Center',
			area: 'midgaard',
			content: 'A distance away from camp center the snow is about a foot deeper and is carved with the tracks of people traveling to and from the eastern forest.',
			terrain: ['snow', 'road'],
			moveMod: 2,
			outdoors: true,
			exits: [
				{
					cmd: 'west',
					id: '1'
				}
			],
			playersInRoom: [],
			monsters: [{
				name: 'Skipp Mastiff Dog',
				displayName: 'Skipp',
				level: 3,
				short: 'Skipp, an enormous mastiff with brown and white spots',
				long: 'Skipp, William Green\'s large spotted mastiff sniffs about the area',
				inName: 'A canine',
				race: 'animal',
				id: '6',
				area: 'midgaard',
				weight: 120,
				position: 'standing',
				attackType: 'bite',
				baseStr: 3,
				size: {value: 3, display: 'medium'},
				runOnAliveWhenEmpty: true,
				behaviors: [{
					module: 'wander',
					moveDirections: ['north', 'east', 'west', 'south']
				}]
			}],
			items: [{
				name: 'Brown waterskin',
				short: 'a light brown waterskin',
				long: 'A brown waterskin, the hide seems worn and used, was left here.' ,
				area: 'midgaard',
				id: '102',
				level: 1,
				drinks: 0,
				maxDrinks: 6,
				itemType: 'bottle',
				material: 'leather',
				weight: 0,
				value: 1,
				modifiers: {
					thirst: -1
				}
			}]
		},
		{
			id: '4',
			title: 'South of Camp Center',
			area: 'midgaard',
			content: 'The southern trail from camp is well traveled. The smithing tent is just east of here and the bustle of the mine can be seen to the south.',
			outdoors: true,
			exits: [
				{
					cmd: 'north',
					id: '1'
				},
				{
					cmd: 'south',
					id: '1',
					area: 'midgaard_academy'
				}
			],
			playersInRoom: [],
			monsters: [],
			items: [

				{
					name: 'Small Buckler',
					short: 'a small round buckler',
					long: 'A small basic looking round buckler lies here' ,
					area: 'midgaard',
					id: '103',
					level: 1,
					itemType: 'shield',
					material: 'wood',
					weight: 1,
					slot: 'hands',
					equipped: false,
					modifiers: {
						ac: 2
					},
					affects: [{
						id: 'hidden',
						affect: 'hidden',
						decay: -1
					}]
				}, {
					name: 'Loaf of Bread',
					short: 'a brown loaf of bread',
					long: 'A rather stale looking loaf of bread is lying on the ground' ,
					area: 'midgaard',
					id: '7',
					level: 1,
					itemType: 'food',
					weight: 0.5,
					modifiers: {
						hunger: -3
					},
					decay: 3
				}
			]
		},
		{
			id: '5',
			title: 'West of Camp Center',
			area: 'midgaard',
			content: 'Toward the docks.',
			exits: [
				{
					cmd: 'west',
					id: '8'
				}, {
					cmd: 'east',
					id: '1'
				}
			],
			playersInRoom: [],
			monsters: [],
			items: [{
				name: 'Leather Helmet',
				short: 'a leather helmet',
				long: 'A simple leather helmet was left here' ,
				area: 'midgaard',
				id: '3',
				level: 1,
				itemType: 'armor',
				material: 'leather',
				ac: 1,
				weight: 1,
				slot: 'head',
				equipped: false,
				modifiers: {
					ac: 1
				}
			}]
		},
		{
			id: '6',
			title: 'Beneath Town Square',
			area: 'midgaard',
			content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent congue sagittis efficitur. Vivamus dapibus sem ac mauris pharetra dapibus. Nunc id ex orci. Quisque fringilla dictum orci molestie condimentum. Duis volutpat porttitor ipsum. Sed ac aliquet leo. Nulla at facilisis orci, eu suscipit nibh. ',
			size: {value: 3, display: 'medium'},
			outdoors: false,
			exits: [
				{
					cmd: 'up',
					id: '1',
					door: true,
					name: 'gate',
					isOpen: false,
					locked: true,
					key: '101'
				}
			]
		},
		{
			id: '8',
			title: 'Tom Kerr\'s Tent',
			area: 'midgaard',
			content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent congue sagittis efficitur. Vivamus dapibus sem ac mauris pharetra dapibus. Nunc id ex orci. Quisque fringilla dictum orci molestie condimentum. Duis volutpat porttitor ipsum. Sed ac aliquet leo. Nulla at facilisis orci, eu suscipit nibh. ',
			outdoors: false,
			light: true,
			exits: [
				{
					cmd: 'east',
					id: '5'
				}
			],
			playersInRoom: [],
			monsters: [
				{
					name: 'Thomas',
					lastName: 'Kerr',
					displayName: 'Thomas Kerr',
					level: 15,
					short: 'Thomas the Storekeeper',
					long: 'Thomas Kerr the Dwarven Storekeeper is here',
					description: '',
					race: 'dwarf',
					id: '9',
					area: 'midgaard',
					weight: 200,
					baseStr: 10,
					gold: 1000,
					position: 'standing',
					attackType: 'punch',
					damroll: 10,
					hitroll: 10,
					ac: 20,
					merchant: true,
					preventItemDecay: true,
					items: [{
						name: 'Pemmican',
						short: 'a piece of Pemmican',
						long: 'A bit of Pemmican was left here' ,
						area: 'midgaard',
						id: '110',
						level: 1,
						itemType: 'food',
						material: 'flesh',
						weight: 0,
						slot: '',
						value: 10,
						equipped: false,
						spawn: 4
					}],
					behaviors: [{
						module: 'thomas_kerr',
						onVisit: function(World, behavior, merchant, roomObj, incomingRoomObj, target, command) {
							if (target.race !== 'ogre') {
								if (World.dice.roll(1, 3) == 1 || target.level === 1) {
									World.addCommand({
										cmd: 'say',
										msg: 'Welcome. Something worth trading?',
										roomObj: roomObj
									}, merchant);

									if (World.dice.roll(1, 3) === 1) {
										setTimeout(function() {
											World.addCommand({
												cmd: 'say',
												msg: 'I\'m buying up all the furs I can. I\'ll give you a good price.',
												roomObj: roomObj
											}, merchant);
										}, 2600);
									}
								}
							} else {
								World.addCommand({
									cmd: 'emote',
									msg: 'looks sternly at ' + target.displayName,
									roomObj: roomObj,
									prompt: false
								}, merchant);

								setTimeout(function() {
									World.addCommand({
										cmd: 'say',
										msg: 'You can turn around and leave. I don\'t trade with Ogres,'
											+ ' I don\t care what you think you\'ve found. Go on, get out!',
										roomObj: roomObj
									}, merchant);
								}, 280);
							}
						},
						beforeSell: function(World, behavior, merchant, roomObj, buyer) {
							if (buyer.race === 'ogre') {
								World.addCommand({
									cmd: 'say',
									msg: 'Sell to an Ogre? Are you insane?',
									roomObj: roomObj
								}, merchant);

								return false;
							} else {
								return true;
							}
						},
						beforeBuy: function(World, behavior, merchant, roomObj, buyer) {
							if (buyer.race === 'ogre') {
								World.addCommand({
									cmd: 'say',
									msg: 'I\'ll freeze before buying from an Ogre!',
									roomObj: roomObj
								}, merchant);

								return false;
							} else {
								return true;
							}
						}
					}]
				}
			],
			items: []
		}
	]
};


text:
<?php

namespace GrapheneNodeClient\Commands\Single;

use GrapheneNodeClient\Commands\CommandQueryDataInterface;
use GrapheneNodeClient\Commands\Commands;
use GrapheneNodeClient\Connectors\ConnectorInterface;

abstract class CommandAbstract
{
    /** @var string */
    protected $method = '';
    /** @var ConnectorInterface */
    protected $connector;

    public function __construct(ConnectorInterface $connector)
    {
        $this->connector = $connector;
    }

    /**
     * @param CommandQueryDataInterface $commandQueryData
     * @param string $answerFormat
     * @param string $getElementWithKey If you want to get only certain element from answer.
     *                                  Example: 'key:123:qwe' => $array['key']['123']['qwe'] or $object->key->123->qwe
     * @return array|object
     */
    public function execute(CommandQueryDataInterface $commandQueryData, $getElementWithKey = null, $answerFormat = ConnectorInterface::ANSWER_FORMAT_ARRAY)
    {
        $commands = new Commands($this->connector);
        return $commands->{$this->method}()->execute($commandQueryData, $getElementWithKey, $answerFormat);
    }
}


text:
import {Component, OnInit} from '@angular/core';
import {MatDialog, MatDialogRef} from "@angular/material/dialog";
import {ActivatedRoute, Router} from '@angular/router';
import {ApplicationService} from '../../../../../services/application.service';
import {SnackbarService} from '../../../../../services/snackbar.service';
import {FactorService} from '../../../../../services/factor.service';
import {AuthService} from '../../../../../services/auth.service';

@Component({
  selector: 'app-application-factors',
  templateUrl: './factors.component.html',
  styleUrls: ['./factors.component.scss']
})
export class ApplicationFactorsComponent implements OnInit {
  private domainId: string;

  private factorTypes: any = {
    'TOTP' : 'OTP',
    'SMS' : 'SMS',
    'EMAIL' : 'EMAIL'
  };

  private factorIcons: any = {
    'TOTP' : 'mobile_friendly',
    'SMS' : 'sms',
    'EMAIL' : 'email'
  };

  application: any;
  formChanged = false;
  factors: any[];
  editMode: boolean;
  mfaStepUpRule: string;

  constructor(private route: ActivatedRoute,
              private router: Router,
              private applicationService: ApplicationService,
              private factorService: FactorService,
              private authService: AuthService,
              private snackbarService: SnackbarService,
              public dialog: MatDialog) { }

  ngOnInit(): void {
    this.domainId = this.route.snapshot.data['domain']?.id;
    this.application = this.route.snapshot.data['application'];
    const applicationMfaSettings = this.application.settings == null ? {} : this.application.settings.mfa || {};
    this.mfaStepUpRule = applicationMfaSettings.stepUpAuthenticationRule;
    this.editMode = this.authService.hasPermissions(['application_settings_update']);
    this.factorService.findByDomain(this.domainId).subscribe(response => this.factors = [...response]);
  }

  patch(): void {
    const data: any = {};
    data.factors = this.application.factors;
    data.settings = {};
    data.settings.mfa = { 'stepUpAuthenticationRule': this.mfaStepUpRule };
    this.applicationService.patch(this.domainId, this.application.id, data).subscribe(data => {
      this.application = data;
      this.formChanged = false;
      this.snackbarService.open('Application updated');
      this.router.navigate(['.'], { relativeTo: this.route, queryParams: { 'reload': true }});
    });
  }

  selectFactor(event, factorId) {
    if (event.checked) {
      this.application.factors.push(factorId);
    } else {
      this.application.factors.splice(this.application.factors.indexOf(factorId), 1);
    }
    this.formChanged = true;
  }

  isFactorSelected(factorId) {
    return this.application.factors !== undefined && this.application.factors.includes(factorId);
  }

  hasFactors() {
    return this.factors && this.factors.length > 0;
  }

  getFactorTypeIcon(type) {
    if (this.factorIcons[type]) {
      return this.factorIcons[type];
    }
    return 'donut_large';
  }

  displayFactorType(type) {
    if (this.factorTypes[type]) {
      return this.factorTypes[type];
    }
    return 'Custom';
  }

  openDialog(event) {
    event.preventDefault();
    this.dialog.open(MfaStepUpDialog, { width : '700px' });
  }
}

@Component({
  selector: 'mfa-step-up-dialog',
  templateUrl: './dialog/mfa-step-up-info.component.html',
})
export class MfaStepUpDialog {
  constructor(public dialogRef: MatDialogRef<MfaStepUpDialog>) {}
}