text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :invitable, :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable
end

redpajama_set_name: RedPajamaGithub


text:
package org.voovan.docker.message.swarm;

import org.voovan.docker.message.swarm.atom.SwarmSpec;
import org.voovan.tools.json.JSON;
import org.voovan.tools.log.Logger;

/**
 *
 * @author helyho
 * <p>
 * DockerFly Framework.
 * WebSite: https://git.oschina.net/helyho/JDocker
 * Licence: Apache v2 License
 */
public class SwarmInit {
    private String listenAddr;
    private String advertiseAddr;
    private Boolean forceNewCluster;
    private SwarmSpec spec;

    public SwarmInit() {
        listenAddr = "0.0.0.0:2737";
        forceNewCluster = false;
        spec = new SwarmSpec();
    }

    public String getListenAddr() {
        return listenAddr;
    }

    public void setListenAddr(String listenAddr) {
        this.listenAddr = listenAddr;
    }

    public String getAdvertiseAddr() {
        return advertiseAddr;
    }

    public void setAdvertiseAddr(String advertiseAddr) {
        this.advertiseAddr = advertiseAddr;
    }

    public Boolean isForceNewCluster() {
        return forceNewCluster;
    }

    public void setForceNewCluster(Boolean forceNewCluster) {
        this.forceNewCluster = forceNewCluster;
    }

    public SwarmSpec getSpec() {
        return spec;
    }

    public void setSpec(SwarmSpec spec) {
        this.spec = spec;
    }

    public static void main(String[] args) {
        SwarmInit swarmInit = new SwarmInit();
        swarmInit.setAdvertiseAddr("192.168.65.2:2377");
        Logger.simple(JSON.formatJson(JSON.toJSON(swarmInit)));
    }
}


text:
<?php

class SystemUsersTable extends Object
{
	private $user_id;
	public $group_id;
	public $username;
	public $password;
	public $email;
	public $firstname;
	public $middlename;
	public $lastname;
	public $lang_id;
	public $date_create;
	public $date_edit;
	public $create_by;
	public $modified_by;

	public function __construct() {

	}

	public function SetId($id) {
		$this->user_id = $id;
	}

	public function GetId() {
		return $this->user_id;
	}

}


text:
<?xml version="1.0"?>
<!-- Dicta build script -->

<project name="geocentral.net.dicta" default="all">

  <property name="app.name" value="Dicta"/>
  <property name="app.version" value="1.0"/>
  <property name="build.dir" value="build"/>
  <property name="test.dir" value="test"/>
  <property name="package.dir" value="package"/>

  <target name="clean">
    <delete dir="${build.dir}"/>
    <delete dir="${test.dir}"/>
    <delete dir="${package.dir}"/>
  </target>

  <target name="test" depends="testbrowser,testjava,testdotnet"/>

  <target name="testbrowser">
    <copy todir="${test.dir}/browser">
      <fileset dir="lib/mongoose" includes="Startup.exe"/>
      <fileset dir="${basedir}" includes="html/**"/>
      <fileset dir="${basedir}" includes="dicta/**"/>
      <fileset dir="${basedir}" includes="images/*.ico"/>
    </copy>
    <copy todir="${test.dir}/browser/js">
      <fileset dir="js" includes="*.js lib/** test/core/** test/sundry/**"/>
      <fileset dir="js/browser" includes="DictaBrowser.js"/>
    </copy>
  </target>

  <target name="testjava" depends="preparepackage">
    <copy todir="${test.dir}">
      <fileset dir="${basedir}" includes="java/**"/>
    </copy>
    <copy todir="${test.dir}/java/DictaTest/js">
      <fileset dir="${build.dir}/browser/release/package" includes="Dicta.min.js"/>
      <fileset dir="js" includes="test/core/** test/java/** test/sundry/**"/>
      <fileset dir="js/java" includes="**"/>
      <fileset dir="js/lib" includes="r.js"/>
    </copy>
    <copy todir="${test.dir}/java">
      <fileset dir="${basedir}" includes="dicta/**"/>
    </copy>
    <copy todir="${test.dir}/java/DictaSamples/AllCaps/js">
      <fileset dir="${build.dir}/browser/release/package" includes="Dicta.min.js"/>
      <fileset dir="js/java" includes="**"/>
      <fileset dir="js/lib" includes="r.js"/>
    </copy>
    <copy todir="${test.dir}/java/DictaSamples/AllCaps">
      <fileset dir="${basedir}" includes="dicta/samples/**"/>
    </copy>
    <copy todir="${test.dir}/java/DictaSamples/AutoIncrement/js">
      <fileset dir="${build.dir}/browser/release/package" includes="Dicta.min.js"/>
      <fileset dir="js/java" includes="**"/>
      <fileset dir="js/lib" includes="r.js"/>
    </copy>
    <copy todir="${test.dir}/java/DictaSamples/AutoIncrement">
      <fileset dir="${basedir}" includes="dicta/samples/**"/>
    </copy>
  </target>

  <target name="testdotnet" depends="preparepackage">
    <copy todir="${test.dir}">
      <fileset dir="${basedir}" includes="dotnet/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaDotNet">
      <fileset dir="lib" includes="edge/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaTest">
      <fileset dir="lib" includes="edge/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaTest/edge/js">
      <fileset dir="${build.dir}/browser/release/package" includes="Dicta.min.js"/>
      <fileset dir="js" includes="test/core/** test/dotnet/** test/sundry/**"/>
      <fileset dir="js/dotnet" includes="**"/>
      <fileset dir="js/lib" includes="r.js"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaTest">
      <fileset dir="${basedir}" includes="dicta/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaWPF">
      <fileset dir="lib" includes="edge/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Http">
      <fileset dir="lib" includes="edge/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Http/edge/js">
      <fileset dir="${build.dir}/browser/release/package" includes="Dicta.min.js"/>
      <fileset dir="js/dotnet" includes="**"/>
      <fileset dir="js/lib" includes="r.js"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Http">
      <fileset dir="${basedir}" includes="dicta/samples/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Interest">
      <fileset dir="lib" includes="edge/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Interest/edge/js">
      <fileset dir="${build.dir}/browser/release/package" includes="Dicta.min.js"/>
      <fileset dir="js/dotnet" includes="**"/>
      <fileset dir="js/lib" includes="r.js"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Interest">
      <fileset dir="${basedir}" includes="dicta/samples/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/UpperCase">
      <fileset dir="lib" includes="edge/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/UpperCase/edge/js">
      <fileset dir="${build.dir}/browser/release/package" includes="Dicta.min.js"/>
      <fileset dir="js/dotnet" includes="**"/>
      <fileset dir="js/lib" includes="r.js"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/UpperCase">
      <fileset dir="${basedir}" includes="dicta/samples/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Splice">
      <fileset dir="lib" includes="edge/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Splice/edge/js">
      <fileset dir="${build.dir}/browser/release/package" includes="Dicta.min.js"/>
      <fileset dir="js/dotnet" includes="**"/>
      <fileset dir="js/lib" includes="r.js"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Splice">
      <fileset dir="${basedir}" includes="dicta/samples/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Table">
      <fileset dir="lib" includes="edge/**"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Table/edge/js">
      <fileset dir="${build.dir}/browser/release/package" includes="Dicta.min.js"/>
      <fileset dir="js/dotnet" includes="**"/>
      <fileset dir="js/lib" includes="r.js"/>
    </copy>
    <copy todir="${test.dir}/dotnet/DictaSamples/Table">
      <fileset dir="${basedir}" includes="dicta/samples/**"/>
    </copy>
  </target>

  <target name="package" depends="packagebrowser,packagejava,packagedotnet"/>

  <target name="preparepackage">
  <copy todir="${build.dir}/browser" file="js/lib/r.js"/>
    <copy todir="${build.dir}/browser/package">
      <fileset dir="js" includes="*.js lib/**"/>
      <fileset dir="js/browser" includes="**"/>
    </copy>
    <copy todir="${build.dir}/browser/package">
      <fileset dir="js/lib" includes="require*.js"/>
      <globmapper from="require*.js" to="require.js"/>
    </copy>
    <exec executable="cmd" dir="${build.dir}/browser/package">
      <arg value="/c"/>
      <arg value="node"/>
      <arg value="-o"/>
      <arg value="optimizeBrowser.js"/>
    </exec>
  </target>

  <target name="packagebrowser" depends="preparepackage">
    <mkdir dir="${package.dir}"/>
    <copy todir="${package.dir}/browser/js">
      <fileset dir="${build.dir}/browser/release/package" includes="DictaBrowser.min.js"/>
    </copy>
    <copy todir="${test.dir}/browser/js">
      <fileset dir="${build.dir}/browser/release/package" includes="DictaBrowser.min.js"/>
    </copy>
  </target>

  <target name="packagejava"/>

  <target name="packagedotnet"/>

  <target name="all" depends="clean,package,test"/>

</project>


text:
using My.AspNetCore.WebForms;

namespace WebFormsWebsite
{
    public class Index : Page
    {
    }
}


text:
export interface IJsonable {
  toJson(): object;
}

export interface IJsonConvertible {
  fromJson(json: object): void;
}

export interface IStringable {
  toString(): string;
}

export interface IDisposable<T = void> {
  dispose(): T;
}


text:
<?php

class Trendmarke_Ajaxsession_ValueController extends Mage_Core_Controller_Front_Action
{

    public function unsetAction()
    {
        $_params = $this->getRequest()->getParams();
        $response = true;
        try {
            if (isset($_params['key']) && $_params['key'] != null) {
                Mage::getSingleton('core/session')->unsetData('ajaxsession_'.$_params['key']);
            }
        } catch (Exception $e) {
            $response = true;
        }
        $this->getResponse()->clearHeaders()->setHeader('Content-type','application/json',true);
        $this->getResponse()->setBody(json_encode(array('response' => $response)));
	}

	public function setAction()
    {
        $_params = $this->getRequest()->getParams();
        $response = false;
        if (isset($_params['key']) && $_params['key'] != null && isset($_params['value']) && $_params['value'] != null) {
            Mage::getModel('core/session')->setData('ajaxsession_'.$_params['key'],$_params['value']);
            $response = true;
        }
        $this->getResponse()->clearHeaders()->setHeader('Content-type','application/json',true);
        $this->getResponse()->setBody(json_encode(array('response' => $response)));
	}
}


text:
package demo.components.semanticui

import chandu0101.macros.tojs.GhPagesMacros
import chandu0101.scalajs.react.components.semanticui._
import demo.components.CodeExample
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.html_<^._

object SuiGridDemo {

  val code = GhPagesMacros.exampleSource

  // EXAMPLE:START

  case class Backend($ : BackendScope[Unit, Unit]) {

    val columns = (1 to 16).map(
      i =>
        (SuiGridColumn(key = i.toString)(
          SuiImage(src = "http://semantic-ui.com/images/wireframe/image.png")()).vdomElement))
    def render() =
      <.div(CodeExample(code, "SuiGrid")(SuiGrid()(columns: _*)))
  }

  val component = ScalaComponent
    .builder[Unit]("SuiGridDemo")
    .renderBackend[Backend]
    .build

  // EXAMPLE:END

  def apply() = component()
}


text:
package com.rs.game.npc.godwars.armadyl;

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

import com.rs.game.Entity;
import com.rs.game.World;
import com.rs.game.WorldTile;
import com.rs.game.item.Item;
import com.rs.game.npc.NPC;
import com.rs.game.npc.combat.NPCCombatDefinitions;
import com.rs.game.npc.godwars.zammorak.GodwarsZammorakFaction;
import com.rs.game.player.Player;
import com.rs.utils.Utils;

@SuppressWarnings("serial")
public class GodwarsArmadylFaction extends NPC {

	public GodwarsArmadylFaction(int id, WorldTile tile, int mapAreaNameHash,
			boolean canBeAttackFromOutOfArea, boolean spawned) {
		super(id, tile, mapAreaNameHash, canBeAttackFromOutOfArea, spawned);
	}

	@Override
	public boolean checkAgressivity() {
		NPCCombatDefinitions defs = getCombatDefinitions();
		if (defs.getAgressivenessType() == NPCCombatDefinitions.PASSIVE)
			return false;
		ArrayList<Entity> possibleTarget = new ArrayList<Entity>();
		for (int regionId : getMapRegionsIds()) {
			List<Integer> playerIndexes = World.getRegion(regionId)
					.getPlayerIndexes();
			if (playerIndexes != null) {
				for (int npcIndex : playerIndexes) {
					Player player = World.getPlayers().get(npcIndex);
					if (player == null
							|| player.isDead()
							|| !player.isRunning()
							|| !player
							.withinDistance(
									this,
									getCombatDefinitions()
									.getAttackStyle() == NPCCombatDefinitions.MELEE ? 4
											: getCombatDefinitions()
											.getAttackStyle() == NPCCombatDefinitions.SPECIAL ? 16
													: 8)
													|| ((!isAtMultiArea() || !player.isAtMultiArea())
															&& player.getAttackedBy() != this && player
															.getAttackedByDelay() > Utils
															.currentTimeMillis())
															|| !clipedProjectile(player, false) || !hasGodItem(player))
						continue;
					possibleTarget.add(player);
				}
			}
			List<Integer> npcsIndexes = World.getRegion(regionId)
					.getNPCsIndexes();
			if (npcsIndexes != null) {
				for (int npcIndex : npcsIndexes) {
					NPC npc = World.getNPCs().get(npcIndex);
					if (npc == null
							|| npc == this
							|| npc instanceof GodwarsZammorakFaction
							|| npc.isDead()
							|| npc.hasFinished()
							|| !npc.withinDistance(
									this,
									getCombatDefinitions().getAttackStyle() == NPCCombatDefinitions.MELEE ? 4
											: getCombatDefinitions()
											.getAttackStyle() == NPCCombatDefinitions.SPECIAL ? 16
													: 8)
													|| !npc.getDefinitions().hasAttackOption()
													|| ((!isAtMultiArea() || !npc.isAtMultiArea())
															&& npc.getAttackedBy() != this && npc
															.getAttackedByDelay() > Utils
															.currentTimeMillis())
															|| !clipedProjectile(npc, false))
						continue;
					possibleTarget.add(npc);
				}
			}
		}
		if (!possibleTarget.isEmpty()) {
			setTarget(possibleTarget
					.get(Utils.getRandom(possibleTarget.size() - 1)));
			return true;
		}
		return false;
	}

	private boolean hasGodItem(Player player) {
		for (Item item : player.getEquipment().getItems().getItems()) {
			if (item == null) continue; // shouldn't happen
			String name = item.getDefinitions().getName();
			// using else as only one item should count
			if(name.contains("Armadyl Helmet") || name.contains("Armadyl mitre") || name.contains("Armadyl full helm") || name.contains("Armadyl coif") || name.contains("Torva full helm") || name.contains("Pernix cowl") || name.contains("Virtus mask"))
				return true;
			else if (name.contains("Armadyl cloak"))
				return true;
			else if (name.contains("Armadyl pendant") || name.contains("Armadyl stole"))
				return true;
			else if (name.contains("Armadyl godsword") ||  name.contains("Armadyl crozier") || name.contains("Zaryte Bow"))
				return true;
			else if (name.contains("Armadyl body") ||  name.contains("Armadyl robe top") || name.contains("Armadyl chestplate") || name.contains("Armadyl platebody") || name.contains("Torva platebody") || name.contains("Pernix body") || name.contains("Virtus robe top"))
				return true;
			else if (name.contains("Illuminated book of law") ||  name.contains("Book of law") || name.contains("Armadyl kiteshield"))
				return true;
			else if (name.contains("Armadyl robe legs") || name.contains("Armadyl plateskirt") || name.contains("Armadyl chaps") || name.contains("Armadyl platelegs") || name.contains("Armadyl Chainskirt") || name.contains("Torva platelegs") || name.contains("Pernix chaps") || name.contains("Virtus robe legs"))
				return true;
			else if (name.contains("Armadyl vambraces"))
				return true;
		}
		return false;
	}
}


text:
var should = require('should');
var util = require('util');
var testUtils = require('../util/util');
var CLITest = require('../framework/cli-test');

var suite;
var vmPrefix = 'cliNegtestvm';
var testPrefix = 'cli.vm.negative-tests';

var requiredEnvironment = [{
  name: 'AZURE_VM_TEST_LOCATION',
  defaultValue: 'West US'
}];

describe('cli', function() {
  describe('vm', function() {
    var location, username = 'azureuser',
      password = 'Pa$$word@123',
      vmNegName, retry = 5;

    before(function(done) {
      suite = new CLITest(testPrefix, requiredEnvironment);
      suite.setupSuite(done);
    });

    beforeEach(function(done) {
      suite.setupTest(function() {
        location = process.env.AZURE_VM_TEST_LOCATION;
        vmNegName = suite.isMocked ? vmPrefix : suite.generateId(vmPrefix, null);
        done();
      });
    });

    afterEach(function(done) {
      suite.teardownTest(done);
    });

    after(function(done) {
      suite.teardownSuite(done);
    });

    // Negative Test Case by specifying invalid Password
    it('Negative test case for password', function(done) {
      getImageName('Linux', function(ImageName) {
        suite.execute('vm create %s %s %s "Coll" --json --location %s',
          vmNegName, ImageName, username, location, function(result) {
            result.exitStatus.should.equal(1);
            result.errorText.should.include('password must be at least 8 character in length, it must contain a lower case, an upper case, a number and a special character such as !@#$%^&+=');
            done();
          });
      });
    });

    // Negative Test Case for Vm Create with Invalid Name
    it('Negative Test Case for Vm Create with Invalid name', function(done) {
      vmNegName = 'test1@1';
      getImageName('Linux', function(ImageName) {
        suite.execute('vm create %s %s %s %s --json --location %s',
          vmNegName, ImageName, username, password, location, function(result) {
            // check the error code for error
            result.exitStatus.should.equal(1);
            result.errorText.should.include('The hosted service name is invalid.');
            done();
          });
      });
    });

    // Negative Test Case by specifying invalid Location
    it('Negative Test Case for Vm create Location', function(done) {
      getImageName('Linux', function(ImageName) {
        suite.execute('vm create %s %s %s %s --json --location %s',
          vmNegName, ImageName, username, password, 'SomeLoc', function(result) {
            result.exitStatus.should.equal(1);
            result.errorText.should.include(' No location found which has DisplayName or Name same as value of --location');
            done();
          });
      });
    });

    // Get name of an image of the given category
    function getImageName(category, callBack) {
      if (process.env.VM_LINUX_IMAGE) {
        callBack(process.env.VM_LINUX_IMAGE);
      } else {
        var cmd = util.format('vm image list --json').split(' ');
        testUtils.executeCommand(suite, retry, cmd, function(result) {
          result.exitStatus.should.equal(0);
          var imageList = JSON.parse(result.text);
          imageList.some(function(image) {
            if ((image.operatingSystemType || image.oSDiskConfiguration.operatingSystem).toLowerCase() === category.toLowerCase() && image.category.toLowerCase() === 'public') {
              process.env.VM_LINUX_IMAGE = image.name;
              return true;
            }
          });
          callBack(process.env.VM_LINUX_IMAGE);
        });
      }
    }
  });
});


text:
/* global window */
'use strict';
const ApiActions = require('../../actions/api');
const Constants = require('./constants');
const ReturnUrlActions = require('../../actions/return-url');
const ForgotStore = require('./forgot/store');
const LoginStore = require('./home/store');
const LogoutStore = require('./logout/store');
const ResetStore = require('./reset/store');

class Actions {
  static forgot(data) {

    ApiActions.post(
      '/api/login/forgot',
      data,
      ForgotStore,
      Constants.FORGOT,
      Constants.FORGOT_RESPONSE
    );
  }

  static login(data) {

    ApiActions.post(
      '/api/login',
      data,
      LoginStore,
      Constants.LOGIN,
      Constants.LOGIN_RESPONSE,
      (err, response) => {

        if (!err) {
          const returnUrl = window.localStorage.getItem('returnUrl');

          if (returnUrl) {
            ReturnUrlActions.clearReturnUrl();
            window.location.href = returnUrl;
          }
          else if (response.user.roles.admin) {
            window.location.href = '/admin';
          }
          else {
            window.location.href = '/account';
          }
        }
      }
    );
  }

  static logout() {

    ApiActions.delete(
      '/api/logout',
      undefined,
      LogoutStore,
      Constants.LOGOUT,
      Constants.LOGOUT_RESPONSE
    );
  }

  static reset(data) {

    ApiActions.post(
      '/api/login/reset',
      data,
      ResetStore,
      Constants.RESET,
      Constants.RESET_RESPONSE
    );
  }
}

module.exports = Actions;


text:
package com.google.teampot.api;

import com.google.teampot.Constants;
import com.google.teampot.util.AppHelper;

public class API {

	private API() {

	}

	public static String getBaseUrl() {
		return "https://"+API.getBaseUrlWithoutSchema();
	}

	public static String getBaseUrlWithoutSchema() {
		return AppHelper.getBaseUrlWithoutSchema()+API.getBaseUrlWithoutHostAndSchema();
	}

	public static String getBaseUrlWithoutHostAndSchema() {
		return "/_ah/api/teampot/"+Constants.CURRENT_API_VERSION;
	}

}


text:
package routing

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"

	"github.com/matrix-org/dendrite/clientapi/auth/storage/accounts"
	"github.com/matrix-org/dendrite/clientapi/httputil"
	"github.com/matrix-org/dendrite/clientapi/jsonerror"
	"github.com/matrix-org/dendrite/clientapi/producers"
	"github.com/matrix-org/dendrite/common"
	"github.com/matrix-org/dendrite/common/config"
	"github.com/matrix-org/dendrite/roomserver/api"

	"github.com/matrix-org/gomatrixserverlib"
	"github.com/matrix-org/util"

	"github.com/sirupsen/logrus"
)

type invite struct {
	MXID   string                `json:"mxid"`
	RoomID string                `json:"room_id"`
	Sender string                `json:"sender"`
	Token  string                `json:"token"`
	Signed common.TPInviteSigned `json:"signed"`
}

type invites struct {
	Medium  string   `json:"medium"`
	Address string   `json:"address"`
	MXID    string   `json:"mxid"`
	Invites []invite `json:"invites"`
}

var (
	errNotLocalUser = errors.New("the user is not from this server")
	errNotInRoom    = errors.New("the server isn't currently in the room")
)

// CreateInvitesFrom3PIDInvites implements POST /_matrix/federation/v1/3pid/onbind
func CreateInvitesFrom3PIDInvites(
	req *http.Request, queryAPI api.RoomserverQueryAPI, cfg config.Dendrite,
	producer *producers.RoomserverProducer, federation *gomatrixserverlib.FederationClient,
	accountDB *accounts.Database,
) util.JSONResponse {
	var body invites
	if reqErr := httputil.UnmarshalJSONRequest(req, &body); reqErr != nil {
		return *reqErr
	}

	evs := []gomatrixserverlib.Event{}
	for _, inv := range body.Invites {
		event, err := createInviteFrom3PIDInvite(
			req, queryAPI, cfg, inv, federation, accountDB,
		)
		if err != nil {
			return httputil.LogThenError(req, err)
		}
		if event != nil {
			evs = append(evs, *event)
		}
	}

	// Send all the events
	if _, err := producer.SendEvents(req.Context(), evs, cfg.Matrix.ServerName, nil); err != nil {
		return httputil.LogThenError(req, err)
	}

	return util.JSONResponse{
		Code: http.StatusOK,
		JSON: struct{}{},
	}
}

// ExchangeThirdPartyInvite implements PUT /_matrix/federation/v1/exchange_third_party_invite/{roomID}
func ExchangeThirdPartyInvite(
	httpReq *http.Request,
	request *gomatrixserverlib.FederationRequest,
	roomID string,
	queryAPI api.RoomserverQueryAPI,
	cfg config.Dendrite,
	federation *gomatrixserverlib.FederationClient,
	producer *producers.RoomserverProducer,
) util.JSONResponse {
	var builder gomatrixserverlib.EventBuilder
	if err := json.Unmarshal(request.Content(), &builder); err != nil {
		return util.JSONResponse{
			Code: http.StatusBadRequest,
			JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()),
		}
	}

	// Check that the room ID is correct.
	if builder.RoomID != roomID {
		return util.JSONResponse{
			Code: http.StatusBadRequest,
			JSON: jsonerror.BadJSON("The room ID in the request path must match the room ID in the invite event JSON"),
		}
	}

	// Check that the state key is correct.
	_, targetDomain, err := gomatrixserverlib.SplitID('@', *builder.StateKey)
	if err != nil {
		return util.JSONResponse{
			Code: http.StatusBadRequest,
			JSON: jsonerror.BadJSON("The event's state key isn't a Matrix user ID"),
		}
	}

	// Check that the target user is from the requesting homeserver.
	if targetDomain != request.Origin() {
		return util.JSONResponse{
			Code: http.StatusBadRequest,
			JSON: jsonerror.BadJSON("The event's state key doesn't have the same domain as the request's origin"),
		}
	}

	// Auth and build the event from what the remote server sent us
	event, err := buildMembershipEvent(httpReq, &builder, queryAPI, cfg)
	if err == errNotInRoom {
		return util.JSONResponse{
			Code: http.StatusNotFound,
			JSON: jsonerror.NotFound("Unknown room " + roomID),
		}
	} else if err != nil {
		return httputil.LogThenError(httpReq, err)
	}

	// Ask the requesting server to sign the newly created event so we know it
	// acknowledged it
	signedEvent, err := federation.SendInvite(httpReq.Context(), request.Origin(), *event)
	if err != nil {
		return httputil.LogThenError(httpReq, err)
	}

	// Send the event to the roomserver
	if _, err = producer.SendEvents(
		httpReq.Context(), []gomatrixserverlib.Event{signedEvent.Event}, cfg.Matrix.ServerName, nil,
	); err != nil {
		return httputil.LogThenError(httpReq, err)
	}

	return util.JSONResponse{
		Code: http.StatusOK,
		JSON: struct{}{},
	}
}

// createInviteFrom3PIDInvite processes an invite provided by the identity server
// and creates a m.room.member event (with "invite" membership) from it.
// Returns an error if there was a problem building the event or fetching the
// necessary data to do so.
func createInviteFrom3PIDInvite(
	req *http.Request, queryAPI api.RoomserverQueryAPI, cfg config.Dendrite,
	inv invite, federation *gomatrixserverlib.FederationClient,
	accountDB *accounts.Database,
) (*gomatrixserverlib.Event, error) {
	localpart, server, err := gomatrixserverlib.SplitID('@', inv.MXID)
	if err != nil {
		return nil, err
	}

	if server != cfg.Matrix.ServerName {
		return nil, errNotLocalUser
	}

	// Build the event
	builder := &gomatrixserverlib.EventBuilder{
		Type:     "m.room.member",
		Sender:   inv.Sender,
		RoomID:   inv.RoomID,
		StateKey: &inv.MXID,
	}

	profile, err := accountDB.GetProfileByLocalpart(req.Context(), localpart)
	if err != nil {
		return nil, err
	}

	content := common.MemberContent{
		AvatarURL:   profile.AvatarURL,
		DisplayName: profile.DisplayName,
		Membership:  "invite",
		ThirdPartyInvite: &common.TPInvite{
			Signed: inv.Signed,
		},
	}

	if err = builder.SetContent(content); err != nil {
		return nil, err
	}

	event, err := buildMembershipEvent(req, builder, queryAPI, cfg)
	if err == errNotInRoom {
		return nil, sendToRemoteServer(req.Context(), inv, federation, cfg, *builder)
	}
	if err != nil {
		return nil, err
	}

	return event, nil
}

// buildMembershipEvent uses a builder for a m.room.member invite event derived
// from a third-party invite to auth and build the said event. Returns the said
// event.
// Returns errNotInRoom if the server is not in the room the invite is for.
// Returns an error if something failed during the process.
func buildMembershipEvent(
	req *http.Request,
	builder *gomatrixserverlib.EventBuilder, queryAPI api.RoomserverQueryAPI,
	cfg config.Dendrite,
) (*gomatrixserverlib.Event, error) {
	eventsNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(builder)
	if err != nil {
		return nil, err
	}

	// Ask the roomserver for information about this room
	queryReq := api.QueryLatestEventsAndStateRequest{
		RoomID:       builder.RoomID,
		StateToFetch: eventsNeeded.Tuples(),
	}
	var queryRes api.QueryLatestEventsAndStateResponse
	if err = queryAPI.QueryLatestEventsAndState(req.Context(), &queryReq, &queryRes); err != nil {
		return nil, err
	}

	if !queryRes.RoomExists {
		// Use federation to auth the event
		return nil, errNotInRoom
	}

	// Auth the event locally
	builder.Depth = queryRes.Depth
	builder.PrevEvents = queryRes.LatestEvents

	authEvents := gomatrixserverlib.NewAuthEvents(nil)

	for i := range queryRes.StateEvents {
		err = authEvents.AddEvent(&queryRes.StateEvents[i])
		if err != nil {
			return nil, err
		}
	}

	if err = fillDisplayName(builder, authEvents); err != nil {
		return nil, err
	}

	refs, err := eventsNeeded.AuthEventReferences(&authEvents)
	if err != nil {
		return nil, err
	}
	builder.AuthEvents = refs

	eventID := fmt.Sprintf("$%s:%s", util.RandomString(16), cfg.Matrix.ServerName)
	eventTime := common.ParseTSParam(req)
	event, err := builder.Build(eventID, eventTime, cfg.Matrix.ServerName, cfg.Matrix.KeyID, cfg.Matrix.PrivateKey)

	return &event, err
}

// sendToRemoteServer uses federation to send an invite provided by an identity
// server to a remote server in case the current server isn't in the room the
// invite is for.
// Returns an error if it couldn't get the server names to reach or if all of
// them responded with an error.
func sendToRemoteServer(
	ctx context.Context, inv invite,
	federation *gomatrixserverlib.FederationClient, _ config.Dendrite,
	builder gomatrixserverlib.EventBuilder,
) (err error) {
	remoteServers := make([]gomatrixserverlib.ServerName, 2)
	_, remoteServers[0], err = gomatrixserverlib.SplitID('@', inv.Sender)
	if err != nil {
		return
	}
	// Fallback to the room's server if the sender's domain is the same as
	// the current server's
	_, remoteServers[1], err = gomatrixserverlib.SplitID('!', inv.RoomID)
	if err != nil {
		return
	}

	for _, server := range remoteServers {
		err = federation.ExchangeThirdPartyInvite(ctx, server, builder)
		if err == nil {
			return
		}
		logrus.WithError(err).Warn("failed to send 3PID invite via %s", server)
	}

	return errors.New("failed to send 3PID invite via any server")
}

// fillDisplayName looks in a list of auth events for a m.room.third_party_invite
// event with the state key matching a given m.room.member event's content's token.
// If such an event is found, fills the "display_name" attribute of the
// "third_party_invite" structure in the m.room.member event with the display_name
// from the m.room.third_party_invite event.
// Returns an error if there was a problem parsing the m.room.third_party_invite
// event's content or updating the m.room.member event's content.
// Returns nil if no m.room.third_party_invite with a matching token could be
// found. Returning an error isn't necessary in this case as the event will be
// rejected by gomatrixserverlib.
func fillDisplayName(
	builder *gomatrixserverlib.EventBuilder, authEvents gomatrixserverlib.AuthEvents,
) error {
	var content common.MemberContent
	if err := json.Unmarshal(builder.Content, &content); err != nil {
		return err
	}

	// Look for the m.room.third_party_invite event
	thirdPartyInviteEvent, _ := authEvents.ThirdPartyInvite(content.ThirdPartyInvite.Signed.Token)

	if thirdPartyInviteEvent == nil {
		// If the third party invite event doesn't exist then we can't use it to set the display name.
		return nil
	}

	var thirdPartyInviteContent common.ThirdPartyInviteContent
	if err := json.Unmarshal(thirdPartyInviteEvent.Content(), &thirdPartyInviteContent); err != nil {
		return err
	}

	// Use the m.room.third_party_invite event to fill the "displayname" and
	// update the m.room.member event's content with it
	content.ThirdPartyInvite.DisplayName = thirdPartyInviteContent.DisplayName
	return builder.SetContent(content)
}


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

using NUnit.Framework;

namespace PopX
{
	public class Json_UnitTest
	{
		[System.Serializable]
		public class StructHello
		{
			public string	Hello;

			public StructHello(string _HelloValue)
			{
				Hello = _HelloValue;
			}
		};

		[System.Serializable]
		public class StructHelloCat : StructHello
		{
			public string	Cat;

			public StructHelloCat(string _HelloValue,string _CatValue) : base(_HelloValue)
			{
				Cat = _CatValue;
			}
		};

		[Test]
		public void Replace_Test()
		{
			//	use a struct to avoid whitespace hassle. We just need to know if it de/serialises
			var Struct = new StructHello ("World");
			var NewValue = "Universe";
			var Json = JsonUtility.ToJson (Struct);
			PopX.Json.Replace (ref Json, "Hello", NewValue);
			JsonUtility.FromJsonOverwrite (Json, Struct);

			Assert.AreEqual ( NewValue,Struct.Hello);
		}

		[Test]
		public void Append_ToEmptyJson()
		{
			var Json = "{}";
			var Value = "World";
			PopX.Json.Append (ref Json, "Hello",Value);

			//	read new json (will throw json syntax errors for us)
			var Struct = JsonUtility.FromJson<StructHello>(Json);

			Assert.AreEqual (Value,Struct.Hello);
		}

		[Test]
		public void Append_ToShallowJson()
		{
			var Json = JsonUtility.ToJson (new StructHello ("World"));
			var CatValue = "Dog";
			PopX.Json.Append (ref Json, "Cat", CatValue );

			//	read new json (will throw json syntax errors for us)
			var Struct = JsonUtility.FromJson<StructHelloCat>(Json);

			Assert.AreEqual (CatValue,Struct.Cat);
		}
	}
}


text:
module Seek
  module Roles
    module AdminDefinedRoles
      extend ActiveSupport::Concern

      included do
        fail 'Only People can have roles' unless self == Person
        requires_can_manage :roles_mask

        include StandAloneRoles::PersonInstanceMethods
        extend StandAloneRoles::PersonClassMethods

        include ProjectRelatedRoles::PersonInstanceMethods
        extend ProjectRelatedRoles::PersonClassMethods

        include ProgrammeRelatedRoles::PersonInstanceMethods
        extend ProgrammeRelatedRoles::PersonClassMethods
      end

      def roles
        Seek::Roles::Roles.instance.role_names_for_mask(roles_mask)
      end

      def assign_or_remove_roles(rolename, flag_and_items)
        flag_and_items = Array(flag_and_items)
        flag = flag_and_items[0]
        items = flag_and_items[1]
        if flag
          add_roles(Seek::Roles::RoleInfo.new(role_name: rolename, items: items))
        else
          remove_roles(Seek::Roles::RoleInfo.new(role_name: rolename, items: items))
        end
      end

      def add_roles(role_infos)
        self.roles_mask ||= 0
        Array(role_infos).each do |role_info|
          select_handler(role_info.role_name).instance.add_roles(self, role_info)
        end
      end

      def remove_roles(role_infos)
        Array(role_infos).each do |role_info|
          select_handler(role_info.role_name).instance.remove_roles(self, role_info)
        end
      end

      def select_handler(role_name)
        handler = role_handlers.detect do |subclass|
          subclass.role_names.include?(role_name)
        end
        fail Seek::Roles::UnknownRoleException.new("Unknown role '#{role_name.inspect}'") if handler.nil?
        handler
      end

      def role_handlers
        [Seek::Roles::StandAloneRoles, Seek::Roles::ProjectRelatedRoles, ::Seek::Roles::ProgrammeRelatedRoles]
      end

      def is_admin_or_project_administrator?
        is_admin? || is_project_administrator_of_any_project?
      end

      def has_role?(role_name)
        (roles_mask && roles_mask != 0) && (roles_mask & Seek::Roles::Roles.instance.mask_for_role(role_name) != 0)
      end

      def check_for_role(rolename, item)
        has_role?(rolename) && check_role_for_item(rolename, item)
      end

      def check_role_for_item(role_name, item)
        select_handler(role_name).instance.check_role_for_item(self, role_name, item)
      end

      include Seek::ProjectHierarchies::AdminDefinedRolesExtension if Seek::Config.project_hierarchy_enabled
    end
  end
end


text:
"""
@file    HybridVAControl.py
@author  Craig Rafter
@date    19/08/2016

class for fixed time signal control

"""
import signalControl, readJunctionData, traci
from math import atan2, degrees
import numpy as np
from collections import defaultdict

class HybridVAControl(signalControl.signalControl):
    def __init__(self, junctionData, minGreenTime=10, maxGreenTime=60, scanRange=250, packetRate=0.2):
        super(HybridVAControl, self).__init__()
        self.junctionData = junctionData
        self.firstCalled = self.getCurrentSUMOtime()
        self.lastCalled = self.getCurrentSUMOtime()
        self.lastStageIndex = 0
        traci.trafficlights.setRedYellowGreenState(self.junctionData.id,
            self.junctionData.stages[self.lastStageIndex].controlString)

        self.packetRate = int(1000*packetRate)
        self.transition = False
        self.CAMactive = False
        # dict[vehID] = [position, heading, velocity, Tdetect]
        self.newVehicleInfo = {}
        self.oldVehicleInfo = {}
        self.scanRange = scanRange
        self.jcnCtrlRegion = self._getJncCtrlRegion()
        # print(self.junctionData.id)
        # print(self.jcnCtrlRegion)
        self.controlledLanes = traci.trafficlights.getControlledLanes(self.junctionData.id)
        # dict[laneID] = [heading, shape]
        self.laneDetectionInfo = self._getIncomingLaneInfo()
        self.stageTime = 0.0
        self.minGreenTime = minGreenTime
        self.maxGreenTime = maxGreenTime
        self.secondsPerMeterTraffic = 0.45
        self.nearVehicleCatchDistance = 25
        self.extendTime = 1.0 # 5 m in 10 m/s (acceptable journey 1.333)
        self.laneInductors = self._getLaneInductors()

    def process(self):
        # Packets sent on this step
        # packet delay + only get packets towards the end of the second
        if (not self.getCurrentSUMOtime() % self.packetRate) and (self.getCurrentSUMOtime() % 1000 > 500):
            self.CAMactive = True
            self._getCAMinfo()
        else:
            self.CAMactive = False

        # Update stage decisions
        # If there's no ITS enabled vehicles present use VA ctrl
        if len(self.oldVehicleInfo) < 1 and not self.getCurrentSUMOtime() % 1000:
            detectTimePerLane = self._getLaneDetectTime()
            #print(detectTimePerLane)
            # Set adaptive time limit
            #print(detectTimePerLane < 3)
            if np.any(detectTimePerLane < 2):
                extend = self.extendTime
            else:
                extend = 0.0

            self.stageTime = max(self.stageTime + extend, self.minGreenTime)
            self.stageTime = min(self.stageTime, self.maxGreenTime)
        # If active and on the second, or transition then make stage descision
        elif (self.CAMactive and not self.getCurrentSUMOtime() % 1000) or self.transition:
            oncomingVeh = self._getOncomingVehicles()
            # If new stage get furthest from stop line whose velocity < 5% speed
            # limit and determine queue length
            if self.transition:
                furthestVeh = self._getFurthestStationaryVehicle(oncomingVeh)
                if furthestVeh[0] != '':
                    meteredTime = self.secondsPerMeterTraffic*furthestVeh[1]
                    self.stageTime = max(self.minGreenTime, meteredTime)
                    self.stageTime = min(self.stageTime, self.maxGreenTime)
                # If we're in this state this should never happen but just in case
                else:
                    self.stageTime = self.minGreenTime
            # If currently staging then extend time if there are vehicles close
            # to the stop line
            else:
                nearestVeh = self._getNearestVehicle(oncomingVeh)
                # If a vehicle detected
                if nearestVeh != '' and nearestVeh[1] <= self.nearVehicleCatchDistance:
                    if (self.oldVehicleInfo[nearestVeh[0]][2] != 1e6
                        and self.oldVehicleInfo[nearestVeh[0]][2] > 1.0/self.secondsPerMeterTraffic):
                        meteredTime = nearestVeh[1]/self.oldVehicleInfo[nearestVeh[0]][2]
                    else:
                        meteredTime = self.secondsPerMeterTraffic*nearestVeh[1]
                    elapsedTime = 0.001*(self.getCurrentSUMOtime() - self.lastCalled)
                    Tremaining = self.stageTime - elapsedTime
                    self.stageTime = elapsedTime + max(meteredTime, Tremaining)
                    self.stageTime = min(self.stageTime, self.maxGreenTime)
                # no detectable near vehicle try inductive loop info
                elif nearestVeh == '' or nearestVeh[1] <= self.nearVehicleCatchDistance:
                    detectTimePerLane = self._getLaneDetectTime()
                    print('Loops2')
                    # Set adaptive time limit
                    if np.any(detectTimePerLane < 2):
                        extend = self.extendTime
                    else:
                        extend = 0.0

                    self.stageTime = max(self.stageTime + extend, self.minGreenTime)
                    self.stageTime = min(self.stageTime, self.maxGreenTime)
                else:
                    pass
        # process stage as normal
        else:
            pass

        # print(self.stageTime)
        self.transition = False
        if self.transitionObject.active:
            # If the transition object is active i.e. processing a transition
            pass
        elif (self.getCurrentSUMOtime() - self.firstCalled) < (self.junctionData.offset*1000):
            # Process offset first
            pass
        elif (self.getCurrentSUMOtime() - self.lastCalled) < self.stageTime*1000:
            # Before the period of the next stage
            pass
        else:
            # Not active, not in offset, stage not finished
            if len(self.junctionData.stages) != (self.lastStageIndex)+1:
                # Loop from final stage to first stage
                self.transitionObject.newTransition(
                    self.junctionData.id,
                    self.junctionData.stages[self.lastStageIndex].controlString,
                    self.junctionData.stages[self.lastStageIndex+1].controlString)
                self.lastStageIndex += 1
            else:
                # Proceed to next stage
                #print(0.001*(self.getCurrentSUMOtime() - self.lastCalled))
                self.transitionObject.newTransition(
                    self.junctionData.id,
                    self.junctionData.stages[self.lastStageIndex].controlString,
                    self.junctionData.stages[0].controlString)
                self.lastStageIndex = 0

            #print(0.001*(self.getCurrentSUMOtime() - self.lastCalled))
            self.lastCalled = self.getCurrentSUMOtime()
            self.transition = True
            self.stageTime = 0.0

        super(HybridVAControl, self).process()

    def _getHeading(self, currentLoc, prevLoc):
        dy = currentLoc[1] - prevLoc[1]
        dx = currentLoc[0] - prevLoc[0]
        if currentLoc[1] == prevLoc[1] and currentLoc[0] == prevLoc[0]:
            heading = -1
        else:
            if dy >= 0:
                heading = degrees(atan2(dy, dx))
            else:
                heading = 360 + degrees(atan2(dy, dx))

        # Map angle to make compatible with SUMO heading
        if 0 <= heading <= 90:
            heading = 90 - heading
        elif 90 < heading < 360:
            heading = 450 - heading

        return heading

    def _getJncCtrlRegion(self):
        jncPosition = traci.junction.getPosition(self.junctionData.id)
        otherJuncPos = [traci.junction.getPosition(x) for x in traci.trafficlights.getIDList() if x != self.junctionData.id]
        ctrlRegion = {'N':jncPosition[1]+self.scanRange, 'S':jncPosition[1]-self.scanRange,
            'E':jncPosition[0]+self.scanRange, 'W':jncPosition[0]-self.scanRange}

        TOL = 10 # Exclusion region around junction boundary
        if otherJuncPos != []:
            for pos in otherJuncPos:
                dx = jncPosition[0] - pos[0]
                dy = jncPosition[1] - pos[1]
                # North/South Boundary
                if abs(dy) < self.scanRange:
                    if dy < -TOL:
                        ctrlRegion['N'] = min(pos[1] - TOL, ctrlRegion['N'])
                    elif dy > TOL:
                        ctrlRegion['S'] = max(pos[1] + TOL, ctrlRegion['S'])
                    else:
                        pass
                else:
                    pass

                # East/West Boundary
                if abs(dx) < self.scanRange:
                    if dx < -TOL:
                        ctrlRegion['E'] = min(pos[0] - TOL, ctrlRegion['E'])
                    elif dx > TOL:
                        ctrlRegion['W'] = max(pos[0] + TOL, ctrlRegion['W'])
                    else:
                        pass
                else:
                    pass

        return ctrlRegion

    def _isInRange(self, vehID):
        vehPosition = np.array(traci.vehicle.getPosition(vehID))
        jcnPosition = np.array(traci.junction.getPosition(self.junctionData.id))
        distance = np.linalg.norm(vehPosition - jcnPosition)
        if (distance < self.scanRange
            and self.jcnCtrlRegion['W'] <= vehPosition[0] <= self.jcnCtrlRegion['E']
            and self.jcnCtrlRegion['S'] <= vehPosition[1] <= self.jcnCtrlRegion['N']):
            return True
        else:
            return False

    def _getVelocity(self, vehID, vehPosition, Tdetect):
        if vehID in self.oldVehicleInfo.keys():
            oldX = np.array(self.oldVehicleInfo[vehID][0])
            newX = np.array(vehPosition)

            dx = np.linalg.norm(newX - oldX)
            dt = Tdetect - self.oldVehicleInfo[vehID][3]
            velocity = dx/dt

            return velocity
        else:
            return 1e6

    def _getCAMinfo(self):
        self.oldVehicleInfo = self.newVehicleInfo.copy()
        self.newVehicleInfo = {}
        Tdetect = 0.001*self.getCurrentSUMOtime()
        for vehID in traci.vehicle.getIDList():
            if traci.vehicle.getTypeID(vehID) == 'typeITSCV' and self._isInRange(vehID):
                vehPosition = traci.vehicle.getPosition(vehID)
                vehHeading = traci.vehicle.getAngle(vehID)
                vehVelocity = self._getVelocity(vehID, vehPosition, Tdetect)
                self.newVehicleInfo[vehID] = [vehPosition, vehHeading, vehVelocity, Tdetect]

    def _getIncomingLaneInfo(self):
        laneInfo = defaultdict(list)
        for lane in list(np.unique(np.array(self.controlledLanes))):
            shape = traci.lane.getShape(lane)
            width = traci.lane.getWidth(lane)
            heading = self._getHeading(shape[1], shape[0])

            dx = shape[0][0] - shape[1][0]
            dy = shape[0][1] - shape[1][1]
            if abs(dx) > abs(dy):
                roadBounds = ((shape[0][0], shape[0][1] + width), (shape[1][0], shape[1][1] - width))
            else:
                roadBounds = ((shape[0][0] + width, shape[0][1]), (shape[1][0] - width, shape[1][1]))
            laneInfo[lane] = [heading, roadBounds]

        return laneInfo

    def _getOncomingVehicles(self):
        # Oncoming if (in active lane & heading matches oncoming heading &
        # is in lane bounds)
        activeLanes = self._getActiveLanes()
        vehicles = []
        for lane in activeLanes:
            for vehID in self.oldVehicleInfo.keys():
                # If on correct heading pm 10deg
                if (np.isclose(self.oldVehicleInfo[vehID][1], self.laneDetectionInfo[lane][0], atol=10)
                    # If in lane x bounds
                    and min(self.laneDetectionInfo[lane][1][0][0], self.laneDetectionInfo[lane][1][1][0]) <
                    self.oldVehicleInfo[vehID][0][0] <
                    max(self.laneDetectionInfo[lane][1][0][0], self.laneDetectionInfo[lane][1][1][0])
                    # If in lane y bounds
                    and min(self.laneDetectionInfo[lane][1][0][1], self.laneDetectionInfo[lane][1][1][1]) <
                    self.oldVehicleInfo[vehID][0][1] <
                    max(self.laneDetectionInfo[lane][1][0][1], self.laneDetectionInfo[lane][1][1][1])):
                    # Then append vehicle
                    vehicles.append(vehID)

        vehicles = list(np.unique(np.array(vehicles)))
        return vehicles

    def _getActiveLanes(self):
        # Get the current control string to find the green lights
        stageCtrlString = self.junctionData.stages[self.lastStageIndex].controlString
        activeLanes = []
        for i, letter in enumerate(stageCtrlString):
            if letter == 'G':
                activeLanes.append(self.controlledLanes[i])
        # Get a list of the unique active lanes
        activeLanes = list(np.unique(np.array(activeLanes)))
        return activeLanes

    def _getLaneInductors(self):
        laneInductors = defaultdict(list)

        for loop in traci.inductionloop.getIDList():
            loopLane = traci.inductionloop.getLaneID(loop)
            if loopLane in self.controlledLanes and 'upstream' not in loop:
                laneInductors[loopLane].append(loop)

        return laneInductors

    def _getFurthestStationaryVehicle(self, vehIDs):
        furthestID = ''
        maxDistance = -1
        jcnPosition = np.array(traci.junction.getPosition(self.junctionData.id))
        speedLimit = traci.lane.getMaxSpeed(self._getActiveLanes()[0])
        for ID in vehIDs:
            vehPosition = np.array(self.oldVehicleInfo[ID][0])
            distance = np.linalg.norm(vehPosition - jcnPosition)
            if distance > maxDistance and self.oldVehicleInfo[ID][2] < 0.05*speedLimit:
                furthestID = ID
                maxDistance = distance

        return [furthestID, maxDistance]

    def _getNearestVehicle(self, vehIDs):
        nearestID = ''
        minDistance = self.nearVehicleCatchDistance + 1
        jcnPosition = np.array(traci.junction.getPosition(self.junctionData.id))

        for ID in vehIDs:
            vehPosition = np.array(self.oldVehicleInfo[ID][0])
            distance = np.linalg.norm(vehPosition - jcnPosition)
            if distance < minDistance:
                nearestID = ID
                minDistance = distance

        return [nearestID, minDistance]

    def _getLaneDetectTime(self):
        activeLanes = self._getActiveLanes()
        meanDetectTimePerLane = np.zeros(len(activeLanes))
        for i, lane in enumerate(activeLanes):
            detectTimes = []
            for loop in self.laneInductors[lane]:
                detectTimes.append(traci.inductionloop.getTimeSinceDetection(loop))
            meanDetectTimePerLane[i] = np.mean(detectTimes)

        return meanDetectTimePerLane


text:
import React from 'react';
import { useOption, useUiTranslator } from '../../core/components/hooks';
import ToggleEdit from './ToggleEdit/index';
import ToggleInsert from './ToggleInsert/index';
import ToggleLayout from './ToggleLayout/index';
import TogglePreview from './TogglePreview/index';
import ToggleResize from './ToggleResize/index';
import UndoRedo from './UndoRedo';
import Zoom from './Zoom';

const getStickyNessstyle = (stickyness?: StickyNess): React.CSSProperties => {
  if (
    !stickyness ||
    (!stickyness.shouldStickToBottom && !stickyness.shouldStickToTop)
  ) {
    return {
      position: 'fixed',
    };
  }

  return {
    position: 'absolute',
    bottom: stickyness.shouldStickToBottom ? 0 : 'auto',
    top: stickyness.shouldStickToTop ? 0 : 'auto',
    right: -stickyness.rightOffset || 0,
  };
};

export type StickyNess = {
  shouldStickToTop: boolean;
  shouldStickToBottom: boolean;
  rightOffset: number;
  stickyElRef?: React.Ref<HTMLDivElement>;
};
export const Sidebar: React.SFC<{
  stickyNess?: StickyNess;
}> = ({ stickyNess }) => {
  const { t } = useUiTranslator();
  const zoomEnabled = useOption('zoomEnabled');
  const defaultLabels = {
    edit: 'Edit blocks',
    insert: 'Add blocks',
    layout: 'Move blocks',
    resize: 'Resize blocks',
    preview: 'Preview page',
  };
  const actions = [
    // eslint-disable-next-line react/jsx-key
    { action: <UndoRedo labelRedo="redo" labelUndo="undo" /> },
    zoomEnabled
      ? { action: <Zoom labelZoomIn="zoom in" labelZoomOut="zoom out" /> }
      : null,
    { action: <ToggleEdit label={t(defaultLabels.edit)} /> },
    { action: <ToggleInsert label={t(defaultLabels.insert)} /> },
    { action: <ToggleLayout label={t(defaultLabels.layout)} /> },
    { action: <ToggleResize label={t(defaultLabels.resize)} /> },
    { action: <TogglePreview label={t(defaultLabels.preview)} /> },
  ].filter(Boolean);
  return (
    <div
      className="react-page-controls-mode-toggle-control-group"
      style={{
        position: 'fixed',
        zIndex: 10001,
        bottom: 0,
        right: 0,
        display: 'flex',
        maxHeight: '100%',
        ...getStickyNessstyle(stickyNess),
      }}
    >
      <div
        ref={stickyNess.stickyElRef}
        style={{
          padding: 16,
          position: 'relative',

          flexFlow: 'column wrap',
          direction: 'rtl',

          display: 'flex',
        }}
      >
        {actions.map(({ action }, index) => (
          <div
            key={index}
            className="react-page-controls-mode-toggle-control"
            style={{
              animationDelay: (actions.length - index) * 150 + 'ms',
            }}
          >
            {action}
            <div className="react-page-controls-mode-toggle-clearfix" />
          </div>
        ))}
      </div>
    </div>
  );
};


text:
import { ShippingService } from "../shipping/shipping-service";
import { Bill } from "./bill";
import { Order } from "../sales/order";
export class BillingService {
    constructor() {
        this.shippingService = new ShippingService();
    }
    processPaymentFor(order) {
        console.log(order.customer.fullname);
        this.shippingService.arrangeShippingFor(order);
        return new Bill(order);
    }
}


text:
namespace Microsoft.Azure.Management.StreamAnalytics.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.StreamAnalytics;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Describes a Service Bus Queue data source.
    /// </summary>
    [Newtonsoft.Json.JsonObject("Microsoft.ServiceBus/Queue")]
    [Rest.Serialization.JsonTransformation]
    public partial class ServiceBusQueueOutputDataSource : OutputDataSource
    {
        /// <summary>
        /// Initializes a new instance of the ServiceBusQueueOutputDataSource
        /// class.
        /// </summary>
        public ServiceBusQueueOutputDataSource()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ServiceBusQueueOutputDataSource
        /// class.
        /// </summary>
        /// <param name="serviceBusNamespace">The namespace that is associated
        /// with the desired Event Hub, Service Bus Queue, Service Bus Topic,
        /// etc. Required on PUT (CreateOrReplace) requests.</param>
        /// <param name="sharedAccessPolicyName">The shared access policy name
        /// for the Event Hub, Service Bus Queue, Service Bus Topic, etc.
        /// Required on PUT (CreateOrReplace) requests.</param>
        /// <param name="sharedAccessPolicyKey">The shared access policy key
        /// for the specified shared access policy. Required on PUT
        /// (CreateOrReplace) requests.</param>
        /// <param name="queueName">The name of the Service Bus Queue. Required
        /// on PUT (CreateOrReplace) requests.</param>
        /// <param name="propertyColumns">A string array of the names of output
        /// columns to be attached to Service Bus messages as custom
        /// properties.</param>
        public ServiceBusQueueOutputDataSource(string serviceBusNamespace = default(string), string sharedAccessPolicyName = default(string), string sharedAccessPolicyKey = default(string), string queueName = default(string), IList<string> propertyColumns = default(IList<string>))
        {
            ServiceBusNamespace = serviceBusNamespace;
            SharedAccessPolicyName = sharedAccessPolicyName;
            SharedAccessPolicyKey = sharedAccessPolicyKey;
            QueueName = queueName;
            PropertyColumns = propertyColumns;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the namespace that is associated with the desired
        /// Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on
        /// PUT (CreateOrReplace) requests.
        /// </summary>
        [JsonProperty(PropertyName = "properties.serviceBusNamespace")]
        public string ServiceBusNamespace { get; set; }

        /// <summary>
        /// Gets or sets the shared access policy name for the Event Hub,
        /// Service Bus Queue, Service Bus Topic, etc. Required on PUT
        /// (CreateOrReplace) requests.
        /// </summary>
        [JsonProperty(PropertyName = "properties.sharedAccessPolicyName")]
        public string SharedAccessPolicyName { get; set; }

        /// <summary>
        /// Gets or sets the shared access policy key for the specified shared
        /// access policy. Required on PUT (CreateOrReplace) requests.
        /// </summary>
        [JsonProperty(PropertyName = "properties.sharedAccessPolicyKey")]
        public string SharedAccessPolicyKey { get; set; }

        /// <summary>
        /// Gets or sets the name of the Service Bus Queue. Required on PUT
        /// (CreateOrReplace) requests.
        /// </summary>
        [JsonProperty(PropertyName = "properties.queueName")]
        public string QueueName { get; set; }

        /// <summary>
        /// Gets or sets a string array of the names of output columns to be
        /// attached to Service Bus messages as custom properties.
        /// </summary>
        [JsonProperty(PropertyName = "properties.propertyColumns")]
        public IList<string> PropertyColumns { get; set; }

    }
}


text:
<!doctype html>

    <meta charset="utf-8">

<title>Posts by Category · soar's blog (mirror)</title>
<meta name="description" content="GitHub Pages powered mirror for the blog https://soar.name">

  <meta name="author" content="Aleksey @soar Smyrnov">

<meta property="og:type" content="website">
<meta property="og:locale" content="en">
<meta property="og:site_name" content="soar's blog (mirror)">
<meta property="og:title" content="Posts by Category">
<meta property="og:url" content="/categories/">

  <meta property="og:description" content="GitHub Pages powered mirror for the blog https://soar.name">

<link rel="canonical" href="/categories/">

<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="soar's blog (mirror) Feed">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="/assets/css/main.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5/css/all.min.css">

Skip links

Skip to primary navigation

Skip to content

Skip to footer

          soar's blog (mirror)
          Mirror for soar.name

        <button class="search__toggle" type="button">
          Toggle search
          <svg class="icon" width="16" height="16" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15.99 16">
            <path d="M15.5,13.12L13.19,10.8a1.69,1.69,0,0,0-1.28-.55l-0.06-.06A6.5,6.5,0,0,0,5.77,0,6.5,6.5,0,0,0,2.46,11.59a6.47,6.47,0,0,0,7.74.26l0.05,0.05a1.65,1.65,0,0,0,.5,1.24l2.38,2.38A1.68,1.68,0,0,0,15.5,13.12ZM6.4,2A4.41,4.41,0,1,1,2,6.4,4.43,4.43,0,0,1,6.4,2Z" transform="translate(-.01)"></path>
          </svg>
        </button>

        <button class="greedy-nav__toggle hidden" type="button">
          Toggle menu

        </button>

Aleksey @soar Smyrnov

My awesome biography constrained to a sentence or two goes here.

    <button class="btn btn--inverse">Follow</button>

My Blog

GitHub

Posts by Category

            jekyll 2

            update 2

jekyll

        Welcome to Jekyll!

        <time datetime="2021-02-02T08:09:38+00:00">February 2, 2021</time>

          less than 1 minute read

You'll find this post in your _posts directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different wa...

        Test2!

        <time datetime="2021-02-02T08:09:38+00:00">February 2, 2021</time>

          less than 1 minute read

This is test2 post

        Back to Top ↑

update

        Welcome to Jekyll!

        <time datetime="2021-02-02T08:09:38+00:00">February 2, 2021</time>

          less than 1 minute read

You'll find this post in your _posts directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different wa...

        Test2!

        <time datetime="2021-02-02T08:09:38+00:00">February 2, 2021</time>

          less than 1 minute read

This is test2 post

        Back to Top ↑

<form class="search-content__form" onkeydown="return event.key != 'Enter';">

      Enter your search term...

    <input type="search" id="search" class="search-input" tabindex="-1" placeholder="Enter your search term..." />
  </form>

 GitHub

 Feed

© 2021 soar. Powered by Jekyll & Minimal Mistakes.


text:
package com.google.cloud.dialogflow.v2.samples;

// [START dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_Sessionentitytype_sync]
import com.google.cloud.dialogflow.v2.SessionEntityType;
import com.google.cloud.dialogflow.v2.SessionEntityTypesClient;

public class SyncUpdateSessionEntityTypeSessionentitytype {

  public static void main(String[] args) throws Exception {
    syncUpdateSessionEntityTypeSessionentitytype();
  }

  public static void syncUpdateSessionEntityTypeSessionentitytype() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.create()) {
      SessionEntityType sessionEntityType = SessionEntityType.newBuilder().build();
      SessionEntityType response =
          sessionEntityTypesClient.updateSessionEntityType(sessionEntityType);
    }
  }
}
// [END dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_Sessionentitytype_sync]


text:
def split_edge(edge_type_mat):
    """
    Add two nodes for each nontree edge to implement scaffold crossovers.
    Added nodes (pseudo-vertices) have a reference vertex (one of the V real
    vertices) to maintain relative spatial coordinates among all
    vertices.

    Parameters
    ----------
    edge_type_mat : networkx.classes.digraph.DiGraph
        sparse matrix where
            1 is non-spanning tree edge: DX edge with 1 scaffold crossover
            2 is spanning tree edge: DX edge with 0 scaffold crossovers
    Returns
    -------
    edge_type_mat_wHalfs
        VxV sparse matrix where
            -1 is half of a non-spanning tree edge (one side of scaffold
            crossover)
            2 is spanning tree edge: DX edge with 0 scaffold crossovers
    pseudo_vert
        row vector where value j at index i indicate that vertex i corresponds
        to vertex j, one of the V real vertices
    """
    # # Initialize output variables. These will be augmented from input vars
    edge_type_mat_wHalfs = edge_type_mat.copy()

    # Start with known nodes.  Pseudo nodes added to graph as needed.
    pseudo_vert = edge_type_mat_wHalfs.nodes()

    non_tree_edges = [edge for edge in edge_type_mat.edges(data=True)
                      if edge[2]['type'] == 1]

    # # ID non-tree edges (value 1), replace with 2 half-edges (value = -1)
    # edges = edge_type_mat.edges()
    # for i in range(num_vert):
    #     for j in range(num_vert):
    #         if (i, j) in edges:
    #             properties = edge_type_mat[i][j]
    #             if properties['type'] == 1:
    # !! replace the next two lines with the above 6 if you want an exact
    # match with the matlab code.  (else, order of pseudonodes not assured)
    for edge in non_tree_edges:
        i, j, properties = edge
        # `i` is the node that stays. `j` is cut off and replaced by pseudo
        # vert.  Since this digraph was built from a graph, a link from 2, 3
        # will also have a link from 3, 2.  Meaning in the 2, 3 case, you'll
        # keep 2 and replace 3.  And in teh 3, 2 case, you'll keep 3 and
        # replace 2.

        index_of_new_vert = len(pseudo_vert)
        properties['type'] = -1

        pseudo_vert.append(j)  # vert_list[new_node_id] = original_node_id
        edge_type_mat_wHalfs.remove_edge(i, j)

        edge_type_mat_wHalfs.add_node(index_of_new_vert)
        edge_type_mat_wHalfs.add_edge(i, index_of_new_vert,
                                      attr_dict=properties)
        edge_type_mat_wHalfs.add_edge(index_of_new_vert, i,
                                      attr_dict=properties)

    return edge_type_mat_wHalfs, pseudo_vert


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <integer name="progress_max">1000</integer>

</resources>


text:
require "spec_helper"

describe Logidze::Model, :db do
  let(:user) do
    User.create!(
      name: "test",
      age: 10,
      active: false,
      log_data: {
        "v" => 5,
        "h" =>
          [
            {"v" => 1, "ts" => time(100), "c" => {"name" => nil, "age" => nil, "active" => nil, "log_data" => nil}},
            {"v" => 2, "ts" => time(200), "c" => {"active" => true}},
            {"v" => 3, "ts" => time(200), "r" => 1, "c" => {"name" => "test"}, "m" => {"some_key" => "old_val"}},
            {"v" => 4, "ts" => time(300), "c" => {"age" => 0}},
            {"v" => 5, "ts" => time(400), "c" => {"age" => 10, "active" => false}, "m" => {"_r" => 2, "some_key" => "current_val"}}
          ]
      }
    )
  end

  describe "#at(time)" do
    it "returns version at specified time", :aggregate_failures do
      user_old = user.at(time: time(350))
      expect(user_old.name).to eq "test"
      expect(user_old.age).to eq 0
      expect(user_old.active).to eq true
    end

    it "returns nil if time is invalid (too early)" do
      expect(user.at(time: time(99))).to be_nil
    end

    it "returns self if actual version" do
      expect(user.at(time: time(401))).to be_equal(user)
    end

    it "returns self if log_data is nil" do
      user.log_data = nil
      expect(user.at(time: time(100))).to be_equal(user)
    end

    it "returns dup", :aggregate_failures do
      user_old = user.at(time: time(100))
      expect(user_old).not_to be_equal(user)

      user_old.age = 100
      expect(user.age).to eq 10
    end

    it "retains original object's id" do
      user_old = user.at(time: time(100))
      expect(user_old.id).to be_equal(user.id)
    end

    it "handles time as string", :aggregate_failures do
      user_old = user.at(time: "2016-04-12 12:05:50")
      expect(user_old.name).to eq "test"
      expect(user_old.age).to eq 0
      expect(user_old.active).to eq true
    end

    it "handles time as Time", :aggregate_failures do
      user_old = user.at(time: Time.new(2016, 0o4, 12, 12, 0o5, 50))
      expect(user_old.name).to eq "test"
      expect(user_old.age).to eq 0
      expect(user_old.active).to eq true
    end

    it "handles time as Date", :aggregate_failures do
      user_old = user.at(time: Date.new(2016, 0o4, 13))
      expect(user_old).to be_equal user
    end

    context "when Logidze.return_self_if_log_data_is_empty = false" do
      around do |ex|
        Logidze.return_self_if_log_data_is_empty = false
        ex.run
        Logidze.return_self_if_log_data_is_empty = true
      end

      it "returns nil if log_data is nil" do
        user.log_data = nil
        expect(user.at(time: time(100))).to be_nil
      end
    end
  end

  describe "#at(version)" do
    it "returns specified version", :aggregate_failures do
      user_old = user.at(version: 4)
      expect(user_old.name).to eq "test"
      expect(user_old.age).to eq 0
      expect(user_old.active).to eq true
    end
  end

  describe "#at!" do
    it "update object in-place", :aggregate_failures do
      user.at!(time: time(350))

      expect(user.name).to eq "test"
      expect(user.age).to eq 0
      expect(user.active).to eq true

      expect(user.changes).to include("age" => [10, 0], "active" => [false, true])
    end

    it "raises ArgumentError if log_data is nil" do
      user.log_data = nil
      expect { user.at!(time: time(100)) }.to raise_error(ArgumentError)
    end
  end

  describe "#diff_from" do
    it "returns diff from specified time" do
      expect(user.diff_from(time: time(350)))
        .to eq(
          "id" => user.id,
          "changes" =>
            {
              "age" => {"old" => 0, "new" => 10},
              "active" => {"old" => true, "new" => false}
            }
        )
    end

    it "returns empty hash if log_data is nil" do
      user.log_data = nil
      expect(user.diff_from(time: time(350))).to eq({"id" => user.id, "changes" => {}})
    end
  end

  describe "undo!" do
    it "revert record to previous state", :aggregate_failures do
      expect(user.undo!).to eq true
      user.reload
      expect(user.name).to eq "test"
      expect(user.age).to eq 0
      expect(user.active).to eq true
    end

    it "revert record several times", :aggregate_failures do
      user.undo!
      expect(user.reload.age).to eq 0

      user.undo!
      expect(user.age).to be_nil

      user.undo!
      expect(user.name).to be_nil

      user.undo!
      user.reload

      expect(user.name).to be_nil
      expect(user.age).to be_nil
      expect(user.active).to be_nil
    end

    it "return false no possible undo" do
      u = User.create!(
        log_data: {
          "v" => 1,
          "h" =>
          [
            {"v" => 1, "ts" => time(100), "c" => {"name" => nil, "age" => nil, "active" => nil}}
          ]
        }
      )

      expect(u.undo!).to eq false
    end
  end

  describe "redo!" do
    before do
      user.undo!
      user.reload
    end

    it "revert record to future state", :aggregate_failures do
      expect(user.redo!).to eq true
      user.reload
      expect(user.name).to eq "test"
      expect(user.age).to eq 10
      expect(user.active).to eq false
    end

    it "revert record several times", :aggregate_failures do
      user.undo!
      user.reload

      expect(user.name).to eq "test"
      expect(user.age).to be_nil
      expect(user.active).to eq true

      user.redo!
      user.redo!
      user.reload

      expect(user.name).to eq "test"
      expect(user.age).to eq 10
      expect(user.active).to eq false
    end

    it "return false no possible redo" do
      u = User.create!(
        log_data: {
          "v" => 1,
          "h" =>
          [
            {"v" => 1, "ts" => time(100), "c" => {"name" => nil, "age" => nil, "active" => nil}}
          ]
        }
      )

      expect(u.redo!).to eq false
    end
  end

  describe "#switch_to!" do
    it "revert record to the specified version", :aggregate_failures do
      expect(user.switch_to!(3)).to eq true
      user.reload
      expect(user.log_version).to eq 3
      expect(user.name).to eq "test"
      expect(user.age).to be_nil
      expect(user.active).to eq true
    end

    it "return false if version is unknown" do
      expect(user.switch_to!(10)).to eq false
    end
  end

  describe ".at" do
    before { user }

    it "returns reverted records", :aggregate_failures do
      u = User.at(time: time(350)).first

      expect(u.name).to eq "test"
      expect(u.age).to eq 0
      expect(u.active).to eq true
    end

    it "returns reverted records when called on relation", :aggregate_failures do
      u = User.where(active: false).order(age: :desc).at(time: time(350)).first

      expect(u.name).to eq "test"
      expect(u.age).to eq 0
      expect(u.active).to eq true
    end

    it "skips nil records" do
      User.create!(
        log_data: {
          "v" => 1,
          "h" =>
            [
              {"v" => 1, "ts" => time(400), "c" => {"name" => nil, "age" => nil, "active" => nil}}
            ]
        }
      )

      expect(User.at(time: time(350)).size).to eq 1
    end
  end

  describe ".diff_from" do
    before { user }

    it "returns diffs for records", :aggregate_failures do
      expect(
        User.diff_from(time: time(350)).first
      ).to eq(
        "id" => user.id,
        "changes" =>
          {
            "age" => {"old" => 0, "new" => 10},
            "active" => {"old" => true, "new" => false}
          }
      )
    end

    it "returns diffs for records when called on relation", :aggregate_failures do
      expect(
        User.where(active: false).order(age: :desc).diff_from(time: time(350)).first
      ).to eq(
        "id" => user.id,
        "changes" =>
          {
            "age" => {"old" => 0, "new" => 10},
            "active" => {"old" => true, "new" => false}
          }
      )
    end
  end

  describe "#responsible_id" do
    it "returns id for current version" do
      expect(user.log_data.responsible_id).to eq 2
    end

    it "returns nil if no information" do
      expect(user.at(time: time(350)).log_data.responsible_id).to be_nil
    end

    it "returns id for previous version" do
      expect(user.at(time: time(250)).log_data.responsible_id).to eq 1
    end
  end

  describe "#meta" do
    it "returns meta for current version" do
      expect(user.log_data.meta).to eq("_r" => 2, "some_key" => "current_val")
    end

    it "returns nil if no information" do
      expect(user.at(time: time(350)).log_data.meta).to be_nil
    end

    it "returns meta for previous version" do
      expect(user.at(time: time(250)).log_data.meta).to eq("some_key" => "old_val")
    end
  end

  describe ".reload_log_data" do
    it "returns log_data" do
      expect(User).to receive(:where).and_call_original
      expect(user.reload_log_data).to eq(user.log_data)
    end
  end

  describe "#log_size" do
    subject { user.log_size }

    it { is_expected.to eq(user.log_data.size) }

    context "when model created within a without_logging block" do
      let(:user) { User.create!(name: "test") }

      before { Logidze.without_logging { user } }

      it { is_expected.to be_zero }
    end
  end

  describe ".reset_log_data" do
    let!(:user2) { user.dup.tap(&:save!) }
    let!(:user3) { user.dup.tap(&:save!) }

    before { User.limit(2).reset_log_data }

    it "nullify log_data column for a association" do
      expect(user.reload.log_size).to be_zero
      expect(user2.reload.log_size).to be_zero
    end

    it "not affect other model records" do
      expect(user3.reload.log_size).to eq 5
    end
  end

  describe "#reset_log_data" do
    subject { user.log_size }

    before { user.reset_log_data }

    it "nullify log_data column for a single record" do
      is_expected.to be_zero
    end
  end

  context "with ignore_log_data: true" do
    describe ".with_log_data" do
      it "generates the same query as model with ignore_log_data: false" do
        expect(NotLoggedPost.with_log_data.to_sql).to eq(
          Post.all.to_sql
        )
      end
    end
  end

  context "when logs contain outdated schema" do
    let(:user) do
      User.create!(
        name: "test",
        log_data: {
          "v" => 3,
          "h" =>
            [
              {"v" => 1, "ts" => time(100), "c" => {"age" => nil}},
              {"v" => 2, "ts" => time(120), "c" => {"age" => 1, "last_name" => "Harry"}},
              {"v" => 3, "ts" => time(200), "c" => {"name" => "Harry", "age" => 10}}
            ]
        }
      )
    end

    describe "#at" do
      it "returns version at specified time", :aggregate_failures do
        user_old = user.at(time: time(150))
        expect(user_old.name).to eq "test"
        expect(user_old.age).to eq 1
      end
    end

    describe "#diff_from" do
      it "returns diff from specified time" do
        expect(user.diff_from(version: 1))
          .to eq(
            "id" => user.id,
            "changes" =>
              {
                "age" => {"old" => nil, "new" => 10},
                "name" => {"old" => nil, "new" => "Harry"}
              }
          )
      end
    end
  end
end


text:
require 'oscillo/enumerable'

module Oscillo
  # A signal that changes over time. This change can either be explicit through
  # the use of {#change} or {#<<}, or it can be implicit when any of the signals
  # that this signal follows changes.
  #
  # @author Evan Tatarka <evan@tatarka.me>
  class Signal
    include Enumerable

    # Creates a new Signal with an optional initial value, signals to follow,
    # and block. The block converts the values from any signals that this one
    # follows to the value of this signal. If no block is given, the value will
    # be an array of all the values of the signals that it follows (or if it is
    # just following one signal, the value of that signal).
    #
    # @overload initialize(*signals)
    #   Follows some number of other signals, changing when they change.
    #   @param signals [Signal] the signals to follow
    #   @yield [*signals, self] gives the new values of the signals to the block
    #
    # @overload initialize(start_value, *signals)
    #   Starts with an initial value and follows other signals when they change.
    #   @param start_value the initial value of this signal
    #   @param signals [Signal] the signals to follow
    #   @yield [*signals, self] gives the new values of the signals to the block
    def initialize(*values, &block)
      @on_change = []
      @follows = []
      @followed_by = []

      @block = block || ->(*x, s) { x.size <= 1 ? x.first : x }

      return if values.empty?

      # first may be initial value instead of signal
      first, *rest = *values
      if first.is_a?(self.class)
        follow(*values)
      else
        @value = first
        follow(*rest)
      end
    end

    # Follows additional signals, changing when those signals change. This is
    # necessary to define mutually recursive signals.
    # @note Immediately updates value.
    #
    # @param signals [Signal] the signals to follow
    # @return [self]
    def follow(*signals)
      @follows += signals.each { |signal| signal.followed_by(self) }
      update(self)

      self
    end

    # Stops following the given signals.
    # @note Immediately updates value.
    #
    # @param signals [Signal] the signals to stop following
    # @return [self]
    def dont_follow(*signals)
      @follows -= signals.each { |signal| signal.not_followed_by(self) }
      update(self)

      self
    end

    # Updates the value if this signal to represent the values of the signals
    # that it follows. This is called automatically when dependent signals
    # change so you don't need to call this manually in most cases.
    #
    # @param source [Signal] The signal that initialized the update. If not
    #   passed, then this signal will be the source of the update.
    def update(source=nil)
      return if @follows.empty? # nothing to update

      @source = source
      @aborted = false
      new_value = @block.(*@follows.map(&:value), self)
      self.change(new_value) unless @aborted
    end

    # Returns the current value of the signal
    #
    # @return the current value
    def value
      @value
    end
    alias_method :val, :value

    # Change the current value of the signal. This will update all signals that
    # follow this on as well as call all {#on_change} callbacks registered.
    #
    # @param new_value the new value of the signal
    # @return [self]
    def change(new_value)
      @value = new_value
      @on_change.each { |c| c.(new_value) }

      unless self === source
        @followed_by.each { |f| f.update(source || self) }
      end
      @source = nil

      self
    end
    alias_method :<<, :change

    # Register a callback that will be called any time the signal value is
    # changed.
    #
    # @yield [value] gives the new value to the block
    # @return [self]
    def on_change(&block)
      @on_change << block

      self
    end

    # Aborts the change so that the value stays the same, no callbacks
    # registered by {#on_change} are called, and no dependent signals are
    # changed.
    # @note This should only be called in the block passed to {#initialize}.
    def abort
      @aborted = true
    end

    # The original source of the current run of signal changes. This can be
    # useful to know which signal caused the change if you are following
    # multiple signals.
    # @note This is only defined within the block passed to {#initialize}.
    #
    # @return [Signal] the signal that caused the change
    def source
      @source
    end

    # The value of the signal as a string, for convenience.
    #
    # @return [String] the signal value
    def to_s
      value.to_s
    end

    # The value of the signal as an integer, for convenience.
    #
    # @return [Fixnum] the signal value
    def to_i
      value.to_i
    end

    # The new signal ignores change events when the new value is the same as the
    # old value.
    #
    # @return [Signal]
    def drop_repeats
      self.class.new(self) do |v, s|
        s.abort if s.val == v; v
      end
    end

    # Updates the new signal to the value of this signal any time the value of
    # sample changes.
    #
    # @param sample [Signal] the signal to update on
    # @return [Signal]
    def sample_on(sample)
      Signal.new(self.val, sample) do |v, s|
        self.val
      end
    end

    protected

    def followed_by(follower)
      @followed_by << follower
    end

    def not_followed_by(follower)
      @followed_by.delete(follower)
    end
  end
end


text:
<?php

namespace Majora\Framework\Form\Extension\Json\Tests;

use Majora\Framework\Form\Extension\Json\JsonRequestHandler;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Exception\UnexpectedTypeException;

class JsonRequestHandlerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var JsonRequestHandler
     */
    private $jsonRequestHandler;

    /**
     * @var HttpFoundationRequestHandler
     */
    private $httpFoundationRequestHandler;

    /**
     * @var FormInterface
     */
    private $form;

    /**
     * @var Request
     */
    private $request;

    public function setUp()
    {
        $this->httpFoundationRequestHandler = \Phake::mock(HttpFoundationRequestHandler::class);
        $this->jsonRequestHandler = new JsonRequestHandler($this->httpFoundationRequestHandler);
        $this->form = \Phake::mock(FormInterface::class);
        $this->request = \Phake::mock(Request::class);
    }

    public function testRequestWithJsonContentShouldSubmitJson()
    {
        \Phake::when($this->request)
            ->getContentType()
            ->thenReturn('json');
        \Phake::when($this->request)
            ->getContent()
            ->thenReturn('{ "json": "test" }');

        $this->jsonRequestHandler->handleRequest($this->form, $this->request);

        \Phake::verify($this->form, \Phake::times(1))->submit('{ "json": "test" }');
    }

    public function testRequestWithoutJsonContentShouldSubmitProxy()
    {
        \Phake::when($this->request)
            ->getContentType()
            ->thenReturn('txt');

        $this->jsonRequestHandler->handleRequest($this->form, $this->request);

        \Phake::verify($this->httpFoundationRequestHandler, \Phake::times(1))->handleRequest($this->form, $this->request);
    }

    public function testInvalidRequestTypeShouldThrowException()
    {
        $this->setExpectedException(UnexpectedTypeException::class);

        $this->jsonRequestHandler->handleRequest($this->form, ['request']);
    }
}