text:
package com.suscipio_solutions.consecro_mud.Abilities.Spells;
import java.util.List;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Commands.interfaces.Command;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.Clan;
import com.suscipio_solutions.consecro_mud.Common.interfaces.Clan.MemberRecord;
import com.suscipio_solutions.consecro_mud.Common.interfaces.Session;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMSecurity;
import com.suscipio_solutions.consecro_mud.core.collections.Pair;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;

@SuppressWarnings("rawtypes")
public class Spell_Torture extends Spell
{
	@Override public String ID() { return "Spell_Torture"; }
	private final static String localizedName = CMLib.lang().L("Torture");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang().L("(being tortured)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override public int maxRange(){return adjustedMaxInvokerRange(1);}
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	@Override protected int canAffectCode(){return CAN_MOBS;}
	@Override public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_ILLUSION;}

	@Override
	public void unInvoke()
	{
		// undo the affects of this spell
		if(!(affected instanceof MOB))
			return;
		final MOB mob=(MOB)affected;

		super.unInvoke();
		if(canBeUninvoked())
		if((!mob.amDead())&&(mob.location()!=null))
			mob.location().show(mob,null,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> manage(s) to survive the torture."));
	}

	public void cryOut(MOB mob)
	{
		if((text().length()>0)&&(!text().equalsIgnoreCase("HITONLY")))
		{
			for(final Session S : CMLib.sessions().localOnlineIterable())
				if(S.mob()!=null)
					S.println(mob,null,null,text());
			setMiscText("");
			return;
		}
		int roll=CMLib.dice().roll(1,16,0);
		boolean someoneelse=false;
		for(int i=0;i<mob.location().numInhabitants();i++)
		{
			final MOB M=mob.location().fetchInhabitant(i);
			if((M!=null)&&(!M.isMonster())&&(M!=mob))
				someoneelse=true;
		}
		if(!someoneelse)
			roll=CMLib.dice().roll(1,10,0);
		else
		switch(roll)
		{
		case 11:
			if(mob.getLiegeID().length()>0)
				mob.location().show(mob,null,CMMsg.MSG_SPEAK,
				L("<S-NAME> admits that @x1 is <S-HIS-HER> liege.",mob.getLiegeID()));
			else
				roll=CMLib.dice().roll(1,10,0);
			break;
		case 12:
		{
			if(!mob.clans().iterator().hasNext())
				roll=CMLib.dice().roll(1,10,0);
			else
			{
				int numClans=0;
				for(@SuppressWarnings("unused") final Pair<Clan,Integer> p : mob.clans())
					numClans++;
				int clanNum=CMLib.dice().roll(1,numClans,-1);
				Clan C=null;
				for(final Pair<Clan,Integer> p : mob.clans())
				{
					if(clanNum==0)
					{
						C=p.first;
						break;
					}
					else
						clanNum--;
				}
				if(C==null)
					roll=CMLib.dice().roll(1,10,0);
				else
				{
					final List<MemberRecord> V=C.getMemberList();
					if(V.size()>0)
					{
						final String name=V.get(CMLib.dice().roll(1,V.size(),-1)).name;
						if(name.equals(mob.Name()))
							roll=CMLib.dice().roll(1,10,0);
						else
							mob.location().show(mob,null,CMMsg.MSG_SPEAK,
							L("<S-NAME> mutters that @x1 is a part of his clan, called @x2.",name,C.getName()));
					}
				}
			}
			break;
		}
		case 13:
			if(!mob.clans().iterator().hasNext())
				roll=CMLib.dice().roll(1,10,0);
			else
			{
				int numClans=0;
				for(@SuppressWarnings("unused") final Pair<Clan,Integer> p : mob.clans())
					numClans++;
				int clanNum=CMLib.dice().roll(1,numClans,-1);
				Clan C=null;
				for(final Pair<Clan,Integer> p : mob.clans())
				{
					if(clanNum==0)
					{
						C=p.first;
						break;
					}
					else
						clanNum--;
				}
				if(C==null)
					roll=CMLib.dice().roll(1,10,0);
				else
					mob.location().show(mob,null,CMMsg.MSG_SPEAK,
					L("<S-NAME> mutters that @x1 has @x2 experience points.",C.getName(),""+C.getExp()));
			}
			break;
		case 14:
			if(!CMSecurity.isDisabled(CMSecurity.DisFlag.EXPERIENCE)
			&&!mob.charStats().getCurrentClass().expless()
			&&!mob.charStats().getMyRace().expless())
				mob.location().show(mob,null,CMMsg.MSG_SPEAK,
				L("<S-NAME> mutters that <S-HE-SHE> scored @x1 experience points.",""+mob.getExperience()));
			break;
		case 15:
		{
			final StringBuffer str=new StringBuffer("");
			final Command C=CMClass.getCommand("Affect");
			try{str.append(C.executeInternal(mob,0,mob).toString());}catch(final Exception e){}
			mob.location().show(mob,null,CMMsg.MSG_SPEAK,
			L("<S-NAME> says OK! I am affected by:\n\r@x1",str.toString()));
			break;
		}
		case 16:
			if(mob.numAllAbilities()<1)
				roll=CMLib.dice().roll(1,10,0);
			else
			{
			   final Ability A=mob.fetchRandomAbility();
				mob.location().show(mob,null,CMMsg.MSG_SPEAK,
				L("<S-NAME> admit(s) that <S-HE-SHE> knows @x1 at @x2%.",A.name(),""+A.proficiency()));
			}
			break;
		}

		switch(roll)
		{
		case 1:    mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> struggle(s) against the pain.")); break;
		case 2:    mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> scream(s) in horror!")); break;
		case 3:    mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> beg(s) for mercy.")); break;
		case 4:    mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> grab(s) <S-HIS-HER> head and cr(ys).")); break;
		case 5:    mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> whimper(s).")); break;
		case 6:    mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> look(s) terrified!")); break;
		case 7:    mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> shake(s) in pain from <S-HIS-HER> head to <S-HIS-HER> feet.")); break;
		case 8:    mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> gasp(s) for air.")); break;
		case 9:    mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> shiver(s) in pain.")); break;
		case 10:mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,
			L("<S-NAME> cr(ys) in anticipation of pain!")); break;
		}
	}

	@Override
	public void executeMsg(Environmental host, CMMsg msg)
	{
		if((msg.amITarget(affected))
		&&(text().equalsIgnoreCase("HITONLY"))
		&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
		&&(msg.value()>0))
			cryOut((MOB)affected);
		super.executeMsg(host,msg);
	}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if((!text().equalsIgnoreCase("HITONLY"))
		&&(affected instanceof MOB))
			cryOut((MOB)affected);
		return super.tick(ticking,tickID);
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final MOB target=this.getTarget(mob,commands,givenTarget);
		if(target==null) return false;

		// the invoke method for spells receives as
		// parameters the invoker, and the REMAINING
		// command line parameters, divided into words,
		// and added as String objects to a vector.
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			// it worked, so build a copy of this ability,
			// and add it to the affects list of the
			// affected MOB.  Then tell everyone else
			// what happened.
			invoker=mob;
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> whisper(s) a torturous spell to <T-NAMESELF>.^?"));
			final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.MSK_CAST_MALICIOUS_VERBAL|CMMsg.TYP_MIND|(auto?CMMsg.MASK_ALWAYS:0),null);
			if((mob.location().okMessage(mob,msg))||(mob.location().okMessage(mob,msg2)))
			{
				mob.location().send(mob,msg);
				mob.location().send(mob,msg2);
				if((msg.value()<=0)&&(msg2.value()<=0))
					maliciousAffect(mob,target,asLevel,0,-1);
			}
		}
		else
			return maliciousFizzle(mob,target,L("<S-NAME> whisper(s) a torturous spell to <T-NAMESELF>, but the spell fades."));

		// return whether it worked
		return success;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>org.wso2.carbon.dashboards.siddhi.apps.api</artifactId>
    <version>4.1.26-SNAPSHOT</version>
    <packaging>bundle</packaging>

    <name>WSO2 Carbon Dashboards - Siddhi Apps REST API</name>

    <parent>
        <groupId>org.wso2.carbon.dashboards</groupId>
        <artifactId>carbon-dashboards</artifactId>
        <version>4.1.26-SNAPSHOT</version>
        <relativePath>../../../pom.xml</relativePath>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon.analytics</groupId>
            <artifactId>org.wso2.carbon.analytics.msf4j.interceptor.common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.analytics-common</groupId>
            <artifactId>org.wso2.carbon.analytics.permissions</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.uiserver</groupId>
            <artifactId>org.wso2.carbon.uiserver</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>${build.helper.maven.plugin.version}</version>
                <executions>
                    <execution>
                        <id>add-source</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>add-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>src/gen/java</source>
                            </sources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <properties>
        <export.package>
            !org.wso2.carbon.siddhi.apps.api.rest.internal,
            org.wso2.carbon.siddhi.apps.api.rest*;
        </export.package>
        <import.package>
            org.osgi.framework.*;version="${org.osgi.framework.version.range}",
            org.wso2.carbon.analytics.permissions.*; version="${carbon.analytics-common.version.range}",
            org.wso2.msf4j.*;version="${msf4j-core.version.range}",
            org.wso2.carbon.uiserver.api.*; version="${carbon.uiserver.version.range}",
            org.wso2.carbon.uiserver.spi.*; version="${carbon.uiserver.version.range}",
            org.wso2.carbon.analytics.permissions.*; version="${carbon.analytics-common.version.range}",
            org.wso2.carbon.analytics.idp.client.*; version="${carbon.analytics-common.version.range}",
            org.wso2.carbon.analytics.msf4j.interceptor.common.*; version="${carbon.analytics.version.range}",
            org.wso2.carbon.config.*; version="${carbon.config.version.range}",
            org.osgi.service.component.annotations.*; version="${org.osgi.service.component.annotations.version.range}",
            org.slf4j.*; version="${slf4j.version.range}",
            io.siddhi.*; version="${siddhi.version.range}",
            feign.*; version="${openfeign.version}",
            javax.ws.rs.*; version="${javax.ws.rs.version.range}",
            com.google.gson.*; version="${gson.version.range}",
        </import.package>
        <private.package>
            org.wso2.carbon.siddhi.apps.api.rest.internal.*
        </private.package>
        <carbon.component>
            osgi.service; objectClass="org.wso2.carbon.uiserver.spi.RestApiProvider"
        </carbon.component>
    </properties>
</project>

redpajama_set_name: RedPajamaGithub


text:
function TabGroup(navGroup, osname){
	var MapsWindow = require('ui/common/maps/campusMap/MapsWindow'),
		FloorPlansWindow = require('ui/common/maps/floorPlans/FloorPlansWindow'),
		SearchWindow = require('ui/common/maps/search/SearchWindow');

	var mapsWindow = new MapsWindow(navGroup, osname),
	    floorPlansWindow = new FloorPlansWindow(navGroup, osname),
		searchWindow = new SearchWindow(navGroup, osname);

	var self = Ti.UI.createTabGroup();

	var mapsTab = Ti.UI.createTab({
		title: 'Campus Map',
		icon: '/icons/tabs/pin.png',
		window: mapsWindow
	});
	mapsWindow.parentTab = mapsTab;

	var floorPlansTab = Ti.UI.createTab({
		title: 'Floor Plans',
		icon: '/icons/tabs/building.png',
		window: floorPlansWindow
	});
	floorPlansWindow.parentTab = floorPlansTab;

	var searchTab = Ti.UI.createTab({
		title: 'Search',
		icon: (Ti.Platform.osname === 'android') ? 'icons/tabs/search.png' : Ti.UI.iPhone.SystemIcon.SEARCH,
		window: searchWindow
	});
	searchWindow.parentTab = searchTab;

	self.addTab(mapsTab);
	self.addTab(floorPlansTab);
	self.addTab(searchTab);

	Ti.App.addEventListener('annotationSelected', function(e){
		self.setActiveTab(mapsTab);
	});

	self.addEventListener('close', function(){
		self.removeTab(mapsTab);
		self.removeTab(floorPlansTab);
		self.removeTab(searchTab);

		self.activeTab = null;
		mapsTab.window = null;
		floorPlansTab.window = null;
		searchTab.window = null;
		searchTab.icon = null;

		Ti.App.removeEventListener('annotationSelected', function(e){
			self.setActiveTab(mapsTab);
		});
	});

	return self;
};
module.exports = TabGroup;


text:
#ifndef TRACKING_H
#define TRACKING_H

#include<opencv2/core/core.hpp>
#include<opencv2/features2d/features2d.hpp>
#include<sensor_msgs/Image.h>
#include<sensor_msgs/image_encodings.h>

#include"FramePublisher.h"
#include"Map.h"
#include"LocalMapping.h"
#include"LoopClosing.h"
#include"Frame.h"
#include "ORBVocabulary.h"
#include"KeyFrameDatabase.h"
#include"ORBextractor.h"
#include "Initializer.h"
#include "MapPublisher.h"

#include<tf/transform_broadcaster.h>

namespace ORB_SLAM
{

class FramePublisher;
class Map;
class LocalMapping;
class LoopClosing;

class Tracking
{

public:
    Tracking(ORBVocabulary* pVoc, FramePublisher* pFramePublisher, MapPublisher* pMapPublisher, Map* pMap, string strSettingPath);

    enum eTrackingState{
        SYSTEM_NOT_READY=-1,
        NO_IMAGES_YET=0,
        NOT_INITIALIZED=1,
        INITIALIZING=2,
        WORKING=3,
        LOST=4
    };

    void SetLocalMapper(LocalMapping* pLocalMapper);
    void SetLoopClosing(LoopClosing* pLoopClosing);
    void SetKeyFrameDatabase(KeyFrameDatabase* pKFDB);

    // This is the main function of the Tracking Thread
    void Run();

    void ForceRelocalisation();

    eTrackingState mState;
    eTrackingState mLastProcessedState;

    // Current Frame
    Frame mCurrentFrame;

    // Initialization Variables
    std::vector<int> mvIniLastMatches;
    std::vector<int> mvIniMatches;
    std::vector<cv::Point2f> mvbPrevMatched;
    std::vector<cv::Point3f> mvIniP3D;
    Frame mInitialFrame;

    void CheckResetByPublishers();

protected:
    void GrabImage(const sensor_msgs::ImageConstPtr& msg);

    void FirstInitialization();
    void Initialize();
    void CreateInitialMap(cv::Mat &Rcw, cv::Mat &tcw);

    void Reset();

    bool TrackPreviousFrame();
    bool TrackWithMotionModel();

    bool RelocalisationRequested();
    bool Relocalisation();

    void UpdateReference();
    void UpdateReferencePoints();
    void UpdateReferenceKeyFrames();

    bool TrackLocalMap();
    void SearchReferencePointsInFrustum();

    bool NeedNewKeyFrame();
    void CreateNewKeyFrame();

    //Other Thread Pointers
    LocalMapping* mpLocalMapper;
    LoopClosing* mpLoopClosing;

    //ORB
    ORBextractor* mpORBextractor;
    ORBextractor* mpIniORBextractor;

    //BoW
    ORBVocabulary* mpORBVocabulary;
    KeyFrameDatabase* mpKeyFrameDB;

    // Initalization
    Initializer* mpInitializer;

    //Local Map
    KeyFrame* mpReferenceKF;
    std::vector<KeyFrame*> mvpLocalKeyFrames;
    std::vector<MapPoint*> mvpLocalMapPoints;

    //Publishers
    FramePublisher* mpFramePublisher;
    MapPublisher* mpMapPublisher;

    //Map
    Map* mpMap;

    //Calibration matrix
    cv::Mat mK;
    cv::Mat mDistCoef;

    //New KeyFrame rules (according to fps)
    int mMinFrames;
    int mMaxFrames;

    //Current matches in frame
    int mnMatchesInliers;

    //Last Frame, KeyFrame and Relocalisation Info
    KeyFrame* mpLastKeyFrame;
    Frame mLastFrame;
    unsigned int mnLastKeyFrameId;
    unsigned int mnLastRelocFrameId;

    //Mutex
    boost::mutex mMutexTrack;
    boost::mutex mMutexForceRelocalisation;

    //Reset
    bool mbPublisherStopped;
    bool mbReseting;
    boost::mutex mMutexReset;

    //Is relocalisation requested by an external thread? (loop closing)
    bool mbForceRelocalisation;

    //Motion Model
    bool mbMotionModel;
    cv::Mat mVelocity;

    //Color order (true RGB, false BGR, ignored if grayscale)
    bool mbRGB;

    // Transfor broadcaster (for visualization in rviz)
    tf::TransformBroadcaster mTfBr;
};

} //namespace ORB_SLAM

#endif // TRACKING_H


text:
package action_potential

import (
	"testing"
	"time"
)

func average(ds []time.Duration) time.Duration {
	total := time.Duration(0)
	for _, d := range ds {
		total += d
	}
	return total / time.Duration(len(ds))
}

func TestAccuracyAggretator(t *testing.T) {
	interval := 100 * time.Millisecond
	delays := []time.Duration{
		1 * interval,
		2 * interval,
		3 * interval,
	}
	accum := NewAccuracyAccumulator(new(Simple))

	for _, delay := range delays {
		accum.AddPotentialAt(5, time.Now().Add(-delay))
	}

	if accum.Count != int64(len(delays)) {
		t.Errorf("Expected Count=%d but was %d.", len(delays), accum.Count)
	}
	expected_average := average(delays)
	slop := 10 * time.Microsecond
	if accum.AverageDelta < expected_average-slop ||
		accum.AverageDelta > expected_average+slop {
		t.Errorf("Average delta was %s, expected [%s,%s]",
			accum.AverageDelta, expected_average-slop, expected_average+slop)
	}
}


text:
<?php

namespace vakata\mail;

interface MailInterface
{
    public function getTo($mailOnly = false);
    public function setTo($mail);
    public function getCc($mailOnly = false);
    public function setCc($mail);
    public function getBcc($mailOnly = false);
    public function setBcc($mail);
    public function getFrom();
    public function setFrom($mail);
    public function getSubject();
    public function setSubject($subject);
    public function getMessage();
    public function setMessage($message, $isHTML = true);
    public function isHTML();

    public function getHeaders();
    public function setHeader($header, $value);
    public function hasHeader($header);
    public function getHeader($header);
    public function removeHeader($header);
    public function removeHeaders();

    public function hasAttachments();
    public function addAttachment($content, $name);
    public function getAttachments();
    public function removeAttachments();

    public function sign($crt, $key, $pass = null, $ca = null);

    public function __toString();
}


text:
/*
 * Problem 10. N Factorial
 * Write a program to calculate n! for each n in the range [1..100].
*/
using System;
using System.Numerics;
class NFactorial
{
    static BigInteger FactorialN (int factorial)
    {
        // The bottom of the recursion
        if (factorial == 0)
        {
            return 1;
        }
        // Recursive call: the method calls itself
        else
        {
            return factorial * FactorialN(factorial - 1);
        }
    }
    static void Main()
    {
        Console.Write("Please enter n! in the rage [1..100] = ");
        int factorial = int.Parse(Console.ReadLine());

        Console.Write("{0}! = ", factorial);
        Console.WriteLine(FactorialN(factorial));
    }
}


text:
package consumer

import (
	"github.com/moonwalker/margaret/broker"
)

type Consumer interface {
	broker.Opener
	broker.Closer
	broker.Consumer
}

type consumer struct {
	broker broker.Broker
}

func (c *consumer) Connect() error {
	return c.broker.Connect()
}

func (c *consumer) Close() {
	c.broker.Close()
}

func (c *consumer) Consume(queue broker.Queue, messages chan broker.Message) (broker.Subscription, error) {
	return c.broker.Consume(queue, messages)
}

func NewConsumer(broker broker.Broker) Consumer {
	return &consumer{broker}
}


text:
using namespace std;

namespace Doremi
{
    namespace Core
    {
        MainMenuHandler::MainMenuHandler(const DoremiEngine::Core::SharedContext& p_sharedContext, DirectX::XMFLOAT2 p_resolution)
            : m_sharedContext(p_sharedContext), m_resolution(p_resolution), m_isFullscreen(false), m_currentButton(-1)
        {
        }

        MainMenuHandler::~MainMenuHandler() {}
        MainMenuHandler* MainMenuHandler::m_singleton = nullptr;

        void MainMenuHandler::StartMainMenuHandler(const DoremiEngine::Core::SharedContext& p_sharedContext, DirectX::XMFLOAT2 p_resolution)
        {
            if(m_singleton != nullptr)
            {
                std::runtime_error("MainMenuHandler StartMainMenuHandler called multiple times.");
            }
            m_singleton = new MainMenuHandler(p_sharedContext, p_resolution);
        }

        MainMenuHandler* MainMenuHandler::GetInstance()
        {
            if(m_singleton == nullptr)
            {
                std::runtime_error("MainMenuHandler not initialized, GetInstance called.");
            }

            return m_singleton;
        }

        struct TextureBoundly
        {
            TextureBoundly(const std::string& p_normal, const std::string& p_highlight, const std::string& p_pressed)
                : Normal(p_normal), Highlighted(p_highlight), Pressed(p_pressed)
            {
            }
            std::string Normal;
            std::string Highlighted;
            std::string Pressed;
        };

        void MainMenuHandler::Initialize()
        {
            using namespace DirectX;
            DoremiEngine::Graphic::MeshManager& t_meshManager = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetMeshManager();

            // initialize currentbutton
            m_currentButton = -1;

            // Create background
            DoremiEngine::Graphic::SpriteData t_data;

            t_data.halfsize = XMFLOAT2(0.5f, 0.5f);
            t_data.origo = XMFLOAT2(0.0f, 0.0f);
            t_data.position = XMFLOAT2(0.5f, 0.5f);
            t_data.txtPos = XMFLOAT2(0.0f, 0.0f);
            t_data.txtSize = XMFLOAT2(1.0f, 1.0f);

            DoremiEngine::Graphic::SpriteInfo* t_spriteInfo = t_meshManager.BuildSpriteInfo(t_data);
            DoremiEngine::Graphic::MaterialInfo* t_matInfo = t_meshManager.BuildMaterialInfo("ANB_Menu_Background.dds");

            m_background = ScreenObject(t_matInfo, t_spriteInfo);
            m_screenObjects.push_back(&m_background);

            // Create menu box
            t_data.halfsize = XMFLOAT2(0.15f, 0.4f);
            t_data.position = XMFLOAT2(0.70f, 0.5f);
            t_spriteInfo = t_meshManager.BuildSpriteInfo(t_data);
            t_matInfo = t_meshManager.BuildMaterialInfo("ANB_Menu_MenubarBackground.dds");

            m_menuBar = ScreenObject(t_matInfo, t_spriteInfo);
            m_screenObjects.push_back(&m_menuBar);

            // Initialize menu
            std::vector<TextureBoundly> p_buttonTextureNames;

            // textures under in the same way
            p_buttonTextureNames.push_back(TextureBoundly("ANB_Menu_BTN_PLAY.dds", "ANB_Menu_BTN_PLAY_Highlight.dds", "ANB_Menu_BTN_PLAY_Clicked"));
            p_buttonTextureNames.push_back(
                TextureBoundly("ANB_Menu_BTN_OPTIONS.dds", "ANB_Menu_BTN_OPTIONS_Highlight.dds", "ANB_Menu_BTN_OPTIONS_Clicked"));
            p_buttonTextureNames.push_back(TextureBoundly("ANB_Menu_BTN_EXIT.dds", "ANB_Menu_BTN_EXIT_Highlight.dds", "ANB_Menu_BTN_EXIT_Clicked"));
            // p_buttonTextureNames.push_back(TextureBoundly("Fullscreen.dds", "FullscreenHighlighted.dds", ""));

            DoremiButtonActions statesForButtons[3];
            statesForButtons[0] = DoremiButtonActions::GO_TO_SERVER_BROWSER;
            statesForButtons[1] = DoremiButtonActions::GO_TO_OPTIONS;
            statesForButtons[2] = DoremiButtonActions::EXIT;
            // statesForButtons[3] = DoremiButtonActions::SET_FULLSCREEN;

            size_t length = p_buttonTextureNames.size();

            // Basic position
            t_data.halfsize = XMFLOAT2(0.12f, 0.08f);
            t_data.origo = XMFLOAT2(0.0f, 0.0f);
            t_data.position = XMFLOAT2(0.7f, 0.0f);
            t_data.txtPos = XMFLOAT2(0.0f, 0.0f);
            t_data.txtSize = XMFLOAT2(1.0f, 1.0f);

            for(size_t i = 0; i < length; i++)
            {
                // Skapa en buttonmaterial struct. Denna håller 2 buildmaterialinfos för att göra kortare parameterlistor
                Doremi::Core::ButtonMaterials t_buttonMaterials;

                // Load materials
                t_buttonMaterials.m_vanillaMaterial = t_meshManager.BuildMaterialInfo(p_buttonTextureNames[i].Normal);
                t_buttonMaterials.m_highLightedMaterial = t_meshManager.BuildMaterialInfo(p_buttonTextureNames[i].Highlighted);
                t_buttonMaterials.m_selectedLightedMaterial = nullptr;
                ;

                t_data.position.y = 1.0f / (float)(length + 1) + i / (float)(length + 1);

                DoremiEngine::Graphic::SpriteInfo* t_spriteInfo = t_meshManager.BuildSpriteInfo(t_data);

                m_buttonList.push_back(Button(t_buttonMaterials, t_spriteInfo, statesForButtons[i]));
            }
        }

        int MainMenuHandler::GetCurrentButton() { return m_currentButton; }

        int MainMenuHandler::Update(double p_dt) // TODOKO Dont need to return int anymore
        {
            uint32_t t_mousePosX;
            uint32_t t_mousePosY;

            // Get mouse cursor position
            InputHandlerClient* t_inputHandler = static_cast<PlayerHandlerClient*>(PlayerHandler::GetInstance())->GetInputHandler();
            t_inputHandler->GetMousePos(t_mousePosX, t_mousePosY);

            // Get screen resolution
            XMFLOAT2 t_screenResolution = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetDirectXManager().GetScreenResolution();

            // Make position to screen cordinates
            float t_mouseScreenPosX = static_cast<float>(t_mousePosX) / t_screenResolution.x;
            float t_mouseScreenPosY = static_cast<float>(t_mousePosY) / t_screenResolution.y;

            // Set standard not to be selected
            m_currentButton = -1;

            // Check if cursor is inside one of the buttons if it is then save that buttons index
            size_t length = m_buttonList.size();
            for(size_t i = 0; i < length; i++)
            {
                if(m_buttonList[i].CheckIfInside(t_mouseScreenPosX, t_mouseScreenPosY))
                {
                    m_currentButton = i;
                }
                else
                {
                    // do nothing
                }
            }

            // check if player has clicked the mouse and is hovering over a button
            if(t_inputHandler->CheckForOnePress((int)UserCommandPlaying::LeftClick) && m_currentButton != -1)
            {
                switch(m_buttonList[m_currentButton].m_buttonAction)
                {
                    case Core::DoremiButtonActions::GO_TO_MAINMENU:
                    {
                        // passing state change event
                        Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
                        menuEvent->state = DoremiGameStates::MAINMENU;
                        Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);

                        break;
                    }
                    case Core::DoremiButtonActions::GO_TO_SERVER_BROWSER:
                    {
                        // passing state change event
                        Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
                        menuEvent->state = DoremiGameStates::SERVER_BROWSER;
                        Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);

                        break;
                    }
                    case Core::DoremiButtonActions::GO_TO_OPTIONS:
                    {
                        // passing state change event
                        Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
                        menuEvent->state = DoremiGameStates::OPTIONS;
                        Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);

                        break;
                    }
                    case Core::DoremiButtonActions::EXIT:
                    {
                        // passing state change event
                        Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
                        menuEvent->state = DoremiGameStates::EXIT;
                        Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);

                        break;
                    }
                    case Core::DoremiButtonActions::SET_FULLSCREEN:
                    {
                        m_sharedContext.GetGraphicModule().GetSubModuleManager().GetDirectXManager().SetFullscreen(m_isFullscreen);
                        m_isFullscreen = !m_isFullscreen;
                        break;
                    }
                    default:
                    {
                        break;
                    }
                }
            }
            else
            {
                // Nothing
            }
            return 0;
        }
    }
}


text:
package com.hisun.loganalysis.spark.kafka.processor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.spark.api.java.JavaFutureAction;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;
import org.json.JSONArray;
import org.slf4j.LoggerFactory;

import com.hisun.TxnplteConstants;
import com.hisun.loganalysis.spark.kafka.AbstractProcessor;
import com.hisun.loganalysis.spark.kafka.bean.TxnPlteData;
import com.hisun.loganalysis.spark.kafka.sql.SqlMethodInvokerDef;
import com.hisun.loganalysis.spark.kafka.sql.SqlMethodInvokerManager;
import com.hisun.util.DateKeyTool;
import com.hisun.util.DynamicNamedSqlParser;
import com.hisun.util.StringUtil;
import com.hisunpay.redis.RedisConnector;
import com.hisunpay.redis.RedisServerType;
import com.hisunpay.redis.RedisUtil;

import scala.Tuple2;

public class TxnPlteDataProcessor extends AbstractProcessor {

	private static final long serialVersionUID = 1L;
	private static final String KEYWORD_SPLIT_REGEXP = "\\s*;\\s*";
	private transient org.slf4j.Logger logger = LoggerFactory.getLogger(TxnPlteDataProcessor.class);

	private String[] resultInvokerMethodIds;
	private String topics = "default-topic";
	private String zkQuorum;
	private String group;
	private int numStreams = 3;
	private int numThreads;
	private int batch = 10;

	private RedisServerType redisType = RedisServerType.SINGEL;
	private Map<String, Object> redisParams = new HashMap<>();

	public TxnPlteDataProcessor() { }

	@Override
	public void before(JavaSparkContext context) {

		logger.info("before invoker start...");

		Arrays.asList(context.getConf().getAll()).forEach(tuple -> {
			logger.info(tuple._1 + ":" + tuple._2);
		});

		zkQuorum = context.getConf().get("kafka.zkQuorum", "127.0.0.1:2181");
		topics = context.getConf().get("kafka.topics", "default-topic");
		group = context.getConf().get("kafka.group", "default-group");
		numThreads = Integer.parseInt(context.getConf().get("kafka.numThreads", "1"));
		numStreams = Integer.parseInt(context.getConf().get("kafka.numStreams", "2"));

		batch = Integer.parseInt(context.getConf().get("batch", "10"));

		redisType = RedisServerType.parse(context.getConf().getInt("redis.serverType", 1));
		if(redisType == RedisServerType.SENTINAL_CLUSTER) {
			redisParams.put("masterName", context.getConf().get("redis.masterName", "redis-master"));
		}
		redisParams.put("servers", context.getConf().get("redis.servers", "127.0.0.1:6379"));
		redisParams.put("password", context.getConf().get("redis.password", null));

		HashSet<String> cleanKeys = new HashSet<>();
		String redisCleanExpiredZsetDataKeys = context.getConf().get("redis.zset.expiredDataClean.keys", "");
		Arrays.asList(redisCleanExpiredZsetDataKeys.split(",")).forEach(key -> cleanKeys.add(key));

		String[] sqlInvokerClassPackages = context.getConf().get("sql.invoker.packages", "").split(",");

		SqlMethodInvokerManager.register(sqlInvokerClassPackages);

		resultInvokerMethodIds = context.getConf().get("sql.invoker.method.ids", "").split(",");
		logger.info("before invoker end...");
	}

	@Override
	public void after(JavaSparkContext context) {
		logger.info("do clean opt...");
		context.stop();
		context.close();
		logger.info("clean opt finished...");
	}

	@Deprecated
	@Override
	public Object process(JavaSparkContext context) throws Exception {
		return null;
	}

	@Override
	public Object processAsAsync(JavaSparkContext context) throws Exception {

		JavaStreamingContext ssc = new JavaStreamingContext(context, Durations.seconds(batch));

		Map<String, Integer> topicMap = new HashMap<>();
		Arrays.stream(topics.split(",")).forEach(topic -> topicMap.put(topic, numThreads));
		List<JavaPairDStream<String, String>> unifiedStream = new ArrayList<>(numStreams);
		JavaPairDStream<String, String> kafkaStream;

		if(numStreams > 1) {
			for (int i = 0; i < numStreams; i++) {
				unifiedStream.add(KafkaUtils.createStream(ssc, zkQuorum, group, topicMap));
			}
			kafkaStream = ssc.union(unifiedStream.get(0),unifiedStream.subList(1, unifiedStream.size()));
		}else {
			kafkaStream = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap);
		}

		JavaDStream<String> jds1 = kafkaStream.map(tuple2 -> tuple2._2);
		jds1.foreachRDD((rdd, time) -> {
			// 统计接入总量
			long cnt = rdd.count();
			RedisConnector jedis = RedisUtil.getConnector(redisType, redisParams);
			jedis.incrBy(TxnplteConstants.TXNPLTE_REQ_TOTAL_CNT, cnt);
			jedis.hincrBy(TxnplteConstants.TXNPLTE_REQ_CNT_DAY, DateKeyTool.getDateKey(), cnt);

			String keywords = jedis.hget(TxnplteConstants.ALARM_CFG, TxnplteConstants.TXNPLTE_KEYWORDS_ALARM);
			logger.debug("关键词内容:" + keywords);

			// 监控关键字
			if(cnt > 0 && !StringUtil.isEmpty(keywords) && (keywords.split(KEYWORD_SPLIT_REGEXP).length > 0)) {
				List<Map<String, Object>> matchedData = rdd.map(s -> {
					Map<String, Object> map = new HashMap<>();
					StringBuffer matchedWords = new StringBuffer();
					for(String keyword : keywords.split(KEYWORD_SPLIT_REGEXP)) {
						if(s.contains(keyword)) matchedWords.append(keyword + ",");
					}

					if(matchedWords.length() > 0) {
						map.put("log_type", 1);
						map.put("state", 0);
						map.put("handle_time", -1);
						map.put("region_id", "");
						map.put("node_id", "");
						map.put("content", s);
						map.put("alarm_type", 4);
						map.put("content", "关键词:" + matchedWords.deleteCharAt(matchedWords.length() - 1) + ",原始数据:" + s);
						map.put("alarm_time", time.milliseconds());
					}
					return map;
				}).filter(map -> ! map.isEmpty()).collect();

				if(! matchedData.isEmpty()) {
					logger.info("匹配到关键词,时间:" + time+ ",内容:" + matchedData);
					jedis.zadd(TxnplteConstants.TXNPLTE_SYS_ALARM_KEYWORDS, time.milliseconds(), new JSONArray(matchedData).toString());
				}
			}

			logger.debug("开始统计...统计时间:" + time + ", RDD大小:" + cnt + ", partition num:" + rdd.getNumPartitions());

			SparkSession sparkSession = SparkSession.builder().config(rdd.context().conf()).getOrCreate();
			// 判断交易是否成功
			sparkSession.udf().register("isSuccess", (s -> ((String) s).endsWith("00000") ? 1 : 0),
					DataTypes.IntegerType);
			// 判断是否死SCM类型交易
			sparkSession.udf().register("isScmTran", (s -> ((String) s).startsWith("SCM") ? 1 : 0),
					DataTypes.IntegerType);

			JavaRDD<TxnPlteData> srdd = rdd.map(s -> new TxnPlteData(s, time.milliseconds()))
					.filter(data -> data != null && data.getReqId() != null && !"".equals(data.getReqId()));
			sparkSession.createDataFrame(srdd, TxnPlteData.class).createOrReplaceTempView("txnplte");

			List<Tuple2<SqlMethodInvokerDef, JavaFutureAction<List<Row>>>> methodInvokers = new ArrayList<>();

			Map<String, Object> sqlParams = new HashMap<>();
			for(Entry<String, String> entry : jedis.hgetAll(TxnplteConstants.ALARM_CFG).entrySet()) {
				if(StringUtil.isInteger(entry.getValue())) {
					sqlParams.put(entry.getKey(), Integer.parseInt(entry.getValue()));
				}else if(StringUtil.isDouble(entry.getValue())) {
					sqlParams.put(entry.getKey(), Double.parseDouble(entry.getValue()));
				}else {
					sqlParams.put(entry.getKey(), entry.getValue());
				}
			}

			// sql语句统计
			Arrays.asList(resultInvokerMethodIds)
//			.parallelStream() // 单机测试性能并没有上升,反而下降了
			.forEach(methodId -> {
				long start;
				try {
					SqlMethodInvokerDef methodDef = SqlMethodInvokerManager.getMethodInvokerDef(methodId);
					if (methodDef == null || methodDef.getSql() == null || "".equals(methodDef.getSql().trim())) {
						logger.error(methodDef + " not register or methodDef`s sql is null or empty!");
						return;
					}

					String sql =  DynamicNamedSqlParser.parseDirect(methodDef.getSql(), sqlParams);
					start = System.currentTimeMillis();
					JavaFutureAction<List<Row>> futureActions = sparkSession.sql(sql).javaRDD().collectAsync();
					logger.info(methodId + ", sql:" + sql + ",执行耗时:" + (System.currentTimeMillis() - start) + "ms.");

					methodInvokers.add(new Tuple2<SqlMethodInvokerDef, JavaFutureAction<List<Row>>>(methodDef, futureActions));
				} catch (Exception e) {
					logger.error("exec sql error. methodid -> " + methodId, e);
				} finally {
				}
			});

			// 开始回调结果
			methodInvokers.forEach(t -> {
				try {
					Method method = t._1().getComponentRef().getMethod(t._1().getMethod(), t._1().getParams());
					method.invoke(t._1().getComponentRef().newInstance(), time.milliseconds(), t._2(), redisType, redisParams);
				} catch (Exception e) {
					logger.error("invoker method sql result error. methodid -> " + t._1().getMethodId(), e);
				}
			});

			logger.info("batch exec finished, timePoint:" + time.milliseconds());
		});

		ssc.start();
		ssc.awaitTermination();

		// 注册系统停止钩子,系统终止能够优雅的停止任务
		Runtime.getRuntime().addShutdownHook(new Thread(() -> {
			ssc.stop(true, true);
			ssc.close();
		}));

		ssc.stop(true, true);
		ssc.close();

		return null;
	}

}


text:
<?php

namespace Pimcore\Model\Document\Page;

use Pimcore\Model;
use Pimcore\Tool\Serialize;

class Resource extends Model\Document\PageSnippet\Resource {

    /**
     * Get the data for the object by the given id, or by the id which is set in the object
     *
     * @param integer $id
     * @throws \Exception
     */
    public function getById($id = null) {
        try {
            if ($id != null) {
                $this->model->setId($id);
            }

            $data = $this->db->fetchRow("SELECT documents.*, documents_page.*, tree_locks.locked FROM documents
                LEFT JOIN documents_page ON documents.id = documents_page.id
                LEFT JOIN tree_locks ON documents.id = tree_locks.id AND tree_locks.type = 'document'
                    WHERE documents.id = ?", $this->model->getId());

            if ($data["id"] > 0) {
                $data["metaData"] = Serialize::unserialize($data["metaData"]);
                $this->assignVariablesToModel($data);
            }
            else {
                throw new \Exception("Page with the ID " . $this->model->getId() . " doesn't exists");
            }
        }
        catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * Create a new record for the object in the database
     *
     * @throws \Exception
     */
    public function create() {
        try {
            parent::create();

            $this->db->insert("documents_page", array(
                "id" => $this->model->getId()
            ));
        }
        catch (\Exception $e) {
            throw $e;
        }

    }

    /**
     * Deletes the object (and data) from database
     *
     * @throws \Exception
     */
    public function delete() {
        try {
            $this->deleteAllProperties();

            $this->db->delete("documents_page", $this->db->quoteInto("id = ?", $this->model->getId()));
            parent::delete();
        }
        catch (\Exception $e) {
            throw $e;
        }
    }

}


text:
import { sha1, sha256, sha384, sha512 } from 'crypto-hash';

// $ExpectType Promise<string>
sha1('🦄');
// $ExpectType Promise<ArrayBuffer>
sha1('🦄', { outputFormat: 'buffer' });
// $ExpectType Promise<string>
sha1('🦄', { outputFormat: 'hex' });

// $ExpectType Promise<string>
sha256('🦄');
// $ExpectType Promise<ArrayBuffer>
sha256('🦄', { outputFormat: 'buffer' });
// $ExpectType Promise<string>
sha256('🦄', { outputFormat: 'hex' });

// $ExpectType Promise<string>
sha384('🦄');
// $ExpectType Promise<ArrayBuffer>
sha384('🦄', { outputFormat: 'buffer' });
// $ExpectType Promise<string>
sha384('🦄', { outputFormat: 'hex' });

// $ExpectType Promise<string>
sha512('🦄');
// $ExpectType Promise<ArrayBuffer>
sha512('🦄', { outputFormat: 'buffer' });
// $ExpectType Promise<string>
sha512('🦄', { outputFormat: 'hex' });


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bragantia 5(4): 242 (1945)

#### Original name
Heterochaetella chorisae Viégas

### Remarks
null


text:
package io.buoyant.telemetry.statsd

import com.timgroup.statsd.{NoOpStatsDClient, StatsDClient}
import com.twitter.conversions.DurationOps._
import com.twitter.util.{Time, MockTimer}
import org.scalatest._

class StatsDTelemeterTest extends FunSuite {

  class MockStatsDStatsReceiver(statsDClient: StatsDClient, sampleRate: Double)
    extends StatsDStatsReceiver(statsDClient: StatsDClient, sampleRate: Double) {

    var flushes = 0
    var closed = false

    override private[statsd] def flush(): Unit = { flushes += 1 }
    override private[statsd] def close(): Unit = { closed = true }
  }

  test("creates a telemeter") {
    val stats = new MockStatsDStatsReceiver(new NoOpStatsDClient, 1.0d)

    val telemeter = new StatsDTelemeter(
      stats,
      10000,
      new MockTimer
    )

    assert(stats.flushes == 0)
    assert(!stats.closed)
  }

  test("stops on close") {
    val stats = new MockStatsDStatsReceiver(new NoOpStatsDClient, 1.0d)

    val telemeter = new StatsDTelemeter(
      stats,
      10000,
      new MockTimer
    )

    val closable = telemeter.run()

    assert(!stats.closed)
    val _ = closable.close(0.millis)
    assert(stats.closed)
  }

  test("flushes gauges every period until close") {
    val gaugeIntervalMs = 10000
    val stats = new MockStatsDStatsReceiver(new NoOpStatsDClient, 1.0d)
    val timer = new MockTimer

    val telemeter = new StatsDTelemeter(
      stats,
      gaugeIntervalMs,
      timer
    )

    Time.withCurrentTimeFrozen { time =>
      val closable = telemeter.run()

      assert(stats.flushes == 0)

      time.advance(gaugeIntervalMs.millis)
      timer.tick()
      assert(stats.flushes == 1)

      time.advance(gaugeIntervalMs.millis)
      timer.tick()
      assert(stats.flushes == 2)

      val _ = closable.close(0.millis)

      time.advance(gaugeIntervalMs.millis)
      timer.tick()
      assert(stats.flushes == 2)
    }
  }
}


text:
function configure(module) {
  "use strict";
  module.description = 'This module defines standard managers in a theater.';
  module.requires = {
    director: 'Std.Theater.Director'
  };
  module.provides = {
    'Std.Management.Loose': (Provider, required) => Provider.spawn(required.director),
    'Std.Management.Strict': (Provider, required) => Provider.spawn(required.director)
  };
}


text:
package orwell.proxy.robot;

import lejos.mf.common.UnitMessage;
import lejos.mf.common.UnitMessageType;
import orwell.messages.Controller;

/**
 * Created by Michaël Ludmann on 5/18/15.
 */
public class InputFire implements IRobotInput {

    private final static String FIRE_PAYLOAD_HEADER = "fire ";
    private Controller.Input.Fire fire;
    private boolean hasFire = false;

    public void setFire(final Controller.Input.Fire fire) {
        this.fire = fire;
        this.hasFire = true;
    }

    public boolean hasFire() {
        return hasFire;
    }

    @Override
    public void accept(final IRobotInputVisitor visitor) {
        visitor.visit(this);
    }

    public void sendUnitMessageTo(final IRobot robot) {
        // "input fire fireWeapon1 fireWeapon2"
        if (fire.getWeapon1() || fire.getWeapon2()) // We avoid flooding the robot if there is no fire
            robot.sendUnitMessage(
                    new UnitMessage(
                            UnitMessageType.Command, FIRE_PAYLOAD_HEADER +
                            fire.getWeapon1() + " " + fire.getWeapon2())
            );
    }
}


text:
function r = ConstPressureReactor(contents)
% CONSTPRESSUREREACTOR  Create a constant pressure reactor object.
% r = ConstPressureReactor(contents)
% A :mat:func:`ConstPressureReactor` is an instance of class
% :mat:func:`Reactor` where the pressure is held constant. The volume
% is not a state variable, but instead takes on whatever value is
% consistent with holding the pressure constant. Examples:
%
% .. code-block:: matlab
%
%     r1 = ConstPressureReactor         % an empty reactor
%     r2 = ConstPressureReactor(contents)    % a reactor containing contents
%
% See also: :mat:func:`Reactor`
%
% :param contents:
%     Cantera :mat:func:`Solution` to be set as the contents of the
%     reactor
% :return:
%     Instance of class :mat:func:`Reactor`
%

if nargin == 0
    contents = 0;
end
r = Reactor(contents, 4);


text:
package org.gwtnode.examples.httpserver;

import org.gwtnode.core.JsonStringObjectMap;
import org.gwtnode.core.node.Global;
import org.gwtnode.core.node.NodeJsError;
import org.gwtnode.core.node.buffer.Buffer;
import org.gwtnode.core.node.event.BooleanEventHandler;
import org.gwtnode.core.node.fs.BufferEventHandler;
import org.gwtnode.core.node.fs.Fs;
import org.gwtnode.core.node.http.ServerRequest;
import org.gwtnode.core.node.http.ServerResponse;
import org.gwtnode.core.node.path.Path;
import org.gwtnode.core.node.url.Url;
import org.gwtnode.core.node.util.Util;

/**
 * Handler for an individual request
 *
 * @author Chad Retz
 */
class HttpRequestHandler {

    /**
     * Get the mime type of the given extension (w/ '.' prepended)
     *
     * @param ext
     * @return
     */
    private static String getMimeType(String ext) {
        if (".html".equalsIgnoreCase(ext)) {
            return "text/html";
        } else if (".png".equalsIgnoreCase(ext)) {
            return "image/png";
        } else {
            return "application/octet-stream";
        }
    }

    private final ServerRequest request;
    private final ServerResponse response;
    private String path;
    private String ext;

    /**
     * Instantiate this handler
     *
     * @param request
     * @param response
     */
    public HttpRequestHandler(ServerRequest request, ServerResponse response) {
        this.request = request;
        this.response = response;
    }

    /**
     * Call the handler
     */
    public void call() {
        try {
            path = resolveProperPath();
            //if there isn't an extension, add index.html
            ext = Path.get().extname(path);
            if (ext == null || ext.isEmpty()) {
                ext = ".html";
                path = Path.get().join(path, "index.html");
            }
            //if it exists, we can add it
            Path.get().exists(path, new BooleanEventHandler() {
                @Override
                protected void onEvent(boolean value) {
                    if (!value) {
                        Util.get().log("Can't find path: " + path);
                        handleException(new HttpServerException(404, "Not found"));
                    } else {
                        //oh it does exist? word...
                        sendFile();
                    }
                }
            });
        } catch (Exception e) {
            handleException(e);
        }
    }

    private void sendFile() {
        //let's start the writing
        Util.get().log("Writing file: " + path);
        Fs.get().readFile(path, new BufferEventHandler() {
            @Override
            public void onEvent(NodeJsError error, Buffer buffer) {
                if (error != null) {
                    //uh oh
                    handleException(new HttpServerException(500, "Failure during read"));
                } else {
                    JsonStringObjectMap<String> responseHeaders = new JsonStringObjectMap<String>();
                    responseHeaders.put("Content-Type", getMimeType(ext));
                    response.writeHead(200, responseHeaders);
                    response.end(buffer);
                }
            }
        });
    }

    /**
     * Get the proper path from the requested path
     *
     * @return
     * @throws HttpServerException
     */
    private String resolveProperPath() throws HttpServerException {
        //find the resource
        String properPath = Path.get().normalize(Url.get().parse(request.url()).pathname());
        //better not have a dot at the beginning
        if (properPath.startsWith(".")) {
            throw new HttpServerException(403,
                    "User tried to go to another directory or access hidden file");
        } else if (properPath.endsWith(".js")) {
            throw new HttpServerException(403, "User tried trying to access server side code");
        }
        //join it w/ my current directory
        return Path.get().join(Global.get().dirname(), properPath);
    }

    private void handleException(Exception e) {
        Util.get().log("Error: " + e);
        int code;
        String message;
        if (e instanceof HttpServerException) {
            code = ((HttpServerException) e).getCode();
            message = e.getMessage();
        } else {
            code = 500;
            message = "Internal Server Error";
        }
        response.writeHead(code, message);
        response.end();
    }
}


text:
use gio::prelude::*;

use gst::glib;
use gst::prelude::*;

use gtk::prelude::*;

use std::cell::RefCell;

const MAIN_PIPELINE: &str = "videotestsrc is-live=true pattern=ball";
const FALLBACK_PIPELINE: &str = "videotestsrc is-live=true pattern=snow";

//const MAIN_PIPELINE: &str = "videotestsrc is-live=true pattern=ball ! x264enc tune=zerolatency";
//const FALLBACK_PIPELINE: &str = "videotestsrc is-live=true pattern=snow ! x264enc tune=zerolatency";

fn create_pipeline() -> (gst::Pipeline, gst::Pad, gst::Element, gtk::Widget) {
    let pipeline = gst::Pipeline::new(None);

    let video_src = gst::parse_bin_from_description(MAIN_PIPELINE, true)
        .unwrap()
        .upcast();
    let fallback_video_src = gst::parse_bin_from_description(FALLBACK_PIPELINE, true)
        .unwrap()
        .upcast();

    let fallbackswitch = gst::ElementFactory::make("fallbackswitch", None).unwrap();
    fallbackswitch.set_property("timeout", gst::ClockTime::SECOND);

    let decodebin = gst::ElementFactory::make("decodebin", None).unwrap();
    let videoconvert = gst::ElementFactory::make("videoconvert", None).unwrap();

    let videoconvert_clone = videoconvert.clone();
    decodebin.connect_pad_added(move |_, pad| {
        let caps = pad.current_caps().unwrap();
        let s = caps.structure(0).unwrap();

        let sinkpad = videoconvert_clone.static_pad("sink").unwrap();

        if s.name() == "video/x-raw" && !sinkpad.is_linked() {
            pad.link(&sinkpad).unwrap();
        }
    });

    let (video_sink, video_widget) =
        //if let Some(gtkglsink) = gst::ElementFactory::make("gtkglsink", None) {
        //    let glsinkbin = gst::ElementFactory::make("glsinkbin", None).unwrap();
        //    glsinkbin.set_property("sink", &gtkglsink);

        //    let widget = gtkglsink.property::<gtk::Widget>("widget");
        //    (glsinkbin, widget)
        //} else
        {
            let sink = gst::ElementFactory::make("gtksink", None).unwrap();
            let widget = sink.property::<gtk::Widget>("widget");
            (sink, widget)
        };

    pipeline
        .add_many(&[
            &video_src,
            &fallback_video_src,
            &fallbackswitch,
            &decodebin,
            &videoconvert,
            &video_sink,
        ])
        .unwrap();

    video_src
        .link_pads(Some("src"), &fallbackswitch, Some("sink"))
        .unwrap();
    fallback_video_src
        .link_pads(Some("src"), &fallbackswitch, Some("fallback_sink"))
        .unwrap();
    fallbackswitch
        .link_pads(Some("src"), &decodebin, Some("sink"))
        .unwrap();
    videoconvert
        .link_pads(Some("src"), &video_sink, Some("sink"))
        .unwrap();

    (
        pipeline,
        video_src.static_pad("src").unwrap(),
        video_sink,
        video_widget,
    )
}

fn create_ui(app: &gtk::Application) {
    let (pipeline, video_src_pad, video_sink, video_widget) = create_pipeline();

    let window = gtk::Window::new(gtk::WindowType::Toplevel);
    window.set_default_size(320, 240);
    let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0);
    vbox.pack_start(&video_widget, true, true, 0);

    let position_label = gtk::Label::new(Some("Position: 00:00:00"));
    vbox.pack_start(&position_label, true, true, 5);

    let drop_button = gtk::ToggleButton::with_label("Drop Signal");
    vbox.pack_start(&drop_button, true, true, 5);

    window.add(&vbox);
    window.show_all();

    app.add_window(&window);

    let video_sink_weak = video_sink.downgrade();
    let timeout_id = glib::timeout_add_local(std::time::Duration::from_millis(100), move || {
        let video_sink = match video_sink_weak.upgrade() {
            Some(video_sink) => video_sink,
            None => return glib::Continue(true),
        };

        let position = video_sink
            .query_position::<gst::ClockTime>()
            .unwrap_or(gst::ClockTime::ZERO);
        position_label.set_text(&format!("Position: {:.1}", position));

        glib::Continue(true)
    });

    let video_src_pad_weak = video_src_pad.downgrade();
    let drop_id = RefCell::new(None);
    drop_button.connect_toggled(move |drop_button| {
        let video_src_pad = match video_src_pad_weak.upgrade() {
            Some(video_src_pad) => video_src_pad,
            None => return,
        };

        let drop = drop_button.is_active();
        if drop {
            let mut drop_id = drop_id.borrow_mut();
            if drop_id.is_none() {
                *drop_id = video_src_pad
                    .add_probe(gst::PadProbeType::BUFFER, |_, _| gst::PadProbeReturn::Drop);
            }
        } else if let Some(drop_id) = drop_id.borrow_mut().take() {
            video_src_pad.remove_probe(drop_id);
        }
    });

    let app_weak = app.downgrade();
    window.connect_delete_event(move |_, _| {
        let app = match app_weak.upgrade() {
            Some(app) => app,
            None => return Inhibit(false),
        };

        app.quit();
        Inhibit(false)
    });

    let bus = pipeline.bus().unwrap();
    let app_weak = app.downgrade();
    bus.add_watch_local(move |_, msg| {
        use gst::MessageView;

        let app = match app_weak.upgrade() {
            Some(app) => app,
            None => return glib::Continue(false),
        };

        match msg.view() {
            MessageView::Eos(..) => app.quit(),
            MessageView::Error(err) => {
                println!(
                    "Error from {:?}: {} ({:?})",
                    msg.src().map(|s| s.path_string()),
                    err.error(),
                    err.debug()
                );
                app.quit();
            }
            _ => (),
        };

        glib::Continue(true)
    })
    .expect("Failed to add bus watch");

    pipeline.set_state(gst::State::Playing).unwrap();

    // Pipeline reference is owned by the closure below, so will be
    // destroyed once the app is destroyed
    let timeout_id = RefCell::new(Some(timeout_id));
    app.connect_shutdown(move |_| {
        pipeline.set_state(gst::State::Null).unwrap();

        bus.remove_watch().unwrap();

        if let Some(timeout_id) = timeout_id.borrow_mut().take() {
            timeout_id.remove();
        }
    });
}

fn main() {
    gst::init().unwrap();
    gtk::init().unwrap();

    gstfallbackswitch::plugin_register_static().expect("Failed to register fallbackswitch plugin");

    let app = gtk::Application::new(None, gio::ApplicationFlags::FLAGS_NONE);

    app.connect_activate(create_ui);
    app.run();
}


text:
<?php
use yii\helpers\Html;
use yii\web\View;

/* @var $this yii\web\View */
/* @var $user app\modules\user\models\User */


text:
class MergeRequestBasicSerializer < BaseSerializer
  entity MergeRequestBasicEntity
end


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

<zorba:iterators
  xmlns:zorba="http://www.zorba-xquery.com"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.zorba-xquery.com ../runtime.xsd">

<zorba:header>
    <zorba:include form="Quoted">zorbatypes/integer.h</zorba:include>
    <zorba:include form="Quoted">zorbatypes/schema_types.h</zorba:include>
</zorba:header>

<!--
/*******************************************************************************
* zorba-math:sqrt
********************************************************************************/
-->
<zorba:iterator name="SqrtIterator" arity="unary">

  <zorba:description author="Zorba Team">math:sqrt</zorba:description>

  <zorba:function>
    <zorba:signature localname="sqrt" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:exp
********************************************************************************/
-->
<zorba:iterator name="ExpIterator" arity="unary">

  <zorba:description author="Zorba Team">math:exp</zorba:description>

  <zorba:function>
    <zorba:signature localname="exp" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:exp10
********************************************************************************/
-->
  <zorba:iterator name="Exp10Iterator" arity="unary">

    <zorba:description author="Zorba Team">math:exp10</zorba:description>

    <zorba:function>
      <zorba:signature localname="exp10" prefix="math">
        <zorba:param>xs:double?</zorba:param>
        <zorba:output>xs:double?</zorba:output>
      </zorba:signature>
    </zorba:function>

  </zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:log
********************************************************************************/
-->
<zorba:iterator name="LogIterator" arity="unary">

  <zorba:description author="Zorba Team">math:log</zorba:description>

  <zorba:function>
    <zorba:signature localname="log" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

  <!--
/*******************************************************************************
* zorba-math:log10
********************************************************************************/
-->
  <zorba:iterator name="Log10Iterator" arity="unary">

    <zorba:description author="Zorba Team">math:log10</zorba:description>

    <zorba:function>
      <zorba:signature localname="log10" prefix="math">
        <zorba:param>xs:double?</zorba:param>
        <zorba:output>xs:double?</zorba:output>
      </zorba:signature>
    </zorba:function>

  </zorba:iterator>

  <!--
/*******************************************************************************
* zorba-math:sin
********************************************************************************/
-->
<zorba:iterator name="SinIterator" arity="unary">

  <zorba:description author="Zorba Team">math:sin</zorba:description>

  <zorba:function>
    <zorba:signature localname="sin" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:cos
********************************************************************************/
-->
<zorba:iterator name="CosIterator" arity="unary">

  <zorba:description author="Zorba Team">math:cos</zorba:description>

  <zorba:function>
    <zorba:signature localname="cos" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:tan
********************************************************************************/
-->
<zorba:iterator name="TanIterator" arity="unary">

  <zorba:description author="Zorba Team">math:tan</zorba:description>

  <zorba:function>
    <zorba:signature localname="tan" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:asin
********************************************************************************/
-->
<zorba:iterator name="ArcSinIterator" arity="unary">

  <zorba:description author="Zorba Team">math:asin</zorba:description>

  <zorba:function>
    <zorba:signature localname="asin" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:acos
********************************************************************************/
-->
<zorba:iterator name="ArcCosIterator" arity="unary">

  <zorba:description author="Zorba Team">math:acos</zorba:description>

  <zorba:function>
    <zorba:signature localname="acos" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:atan
********************************************************************************/
-->
<zorba:iterator name="ArcTanIterator" arity="unary">

  <zorba:description author="Zorba Team">math:atan</zorba:description>

  <zorba:function>
    <zorba:signature localname="atan" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:atan2
********************************************************************************/
-->
<zorba:iterator name="Atan2Iterator" arity="binary">

  <zorba:description author="Zorba Team">math:atan2</zorba:description>

  <zorba:function>
    <zorba:signature localname="atan2" prefix="math">
      <zorba:param>xs:double</zorba:param>
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:cosh
********************************************************************************/
-->
<zorba:iterator name="CoshIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:cosh</zorba:description>

  <zorba:function>
    <zorba:signature localname="cosh" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:acosh
********************************************************************************/
-->
<zorba:iterator name="AcoshIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:acosh</zorba:description>

  <zorba:function>
    <zorba:signature localname="acosh" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:fmod
********************************************************************************/
-->
<zorba:iterator name="FmodIterator" arity="binary">

  <zorba:description author="Zorba Team">zorba-math:fmod</zorba:description>

  <zorba:function>
    <zorba:signature localname="fmod" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:ldexp
********************************************************************************/
-->
<zorba:iterator name="LdexpIterator" arity="binary">

  <zorba:description author="Zorba Team">zorba-math:ldexp</zorba:description>

  <zorba:function>
    <zorba:signature localname="ldexp" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:param>xs:integer</zorba:param>
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:pow
********************************************************************************/
-->
<zorba:iterator name="PowIterator" arity="binary">

  <zorba:description author="Zorba Team">math:pow</zorba:description>

  <zorba:function>
    <zorba:signature localname="pow" prefix="math">
      <zorba:param>xs:double?</zorba:param>
      <zorba:param>xs:anyAtomicType</zorba:param>
      <zorba:output>xs:double?</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:sinh
********************************************************************************/
-->
<zorba:iterator name="SinhIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:sinh</zorba:description>

  <zorba:function>
    <zorba:signature localname="sinh" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:asinh
********************************************************************************/
-->
<zorba:iterator name="AsinhIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:asinh</zorba:description>

  <zorba:function>
    <zorba:signature localname="asinh" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:tanh
********************************************************************************/
-->
<zorba:iterator name="TanhIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:tanh</zorba:description>

  <zorba:function>
    <zorba:signature localname="tanh" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:atanh
********************************************************************************/
-->
<zorba:iterator name="AtanhIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:atanh</zorba:description>

  <zorba:function>
    <zorba:signature localname="atanh" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:pi
********************************************************************************/
-->
<zorba:iterator name="PiNumberIterator" arity="noary">

  <zorba:description author="Zorba Team">math:pi</zorba:description>

  <zorba:function>
    <zorba:signature localname="pi" prefix="math">
      <zorba:output>xs:double</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:isInf
********************************************************************************/
-->
<zorba:iterator name="IsInfIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:is_inf</zorba:description>

  <zorba:function>
    <zorba:signature localname="is_inf" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:boolean</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:isNaN
********************************************************************************/
-->
<zorba:iterator name="IsNaNIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:is_nan</zorba:description>

  <zorba:function>
    <zorba:signature localname="is_nan" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:boolean</zorba:output>
    </zorba:signature>
  </zorba:function>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:modf
********************************************************************************/
-->
<zorba:iterator name="ModfIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:modf</zorba:description>

  <zorba:function>
    <zorba:signature localname="modf" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double+</zorba:output>
    </zorba:signature>
  </zorba:function>

  <zorba:state generateInit="true" generateReset="true">
    <zorba:member type="xs_double" name="theDoubInteger" defaultValue="numeric_consts<xs_double>::zero()"
                  brief=""/>
  </zorba:state>

</zorba:iterator>

<!--
/*******************************************************************************
* zorba-math:frexp
********************************************************************************/
-->
<zorba:iterator name="FrexpIterator" arity="unary">

  <zorba:description author="Zorba Team">zorba-math:frexp</zorba:description>

  <zorba:function>
    <zorba:signature localname="frexp" prefix="fn-zorba-math">
      <zorba:param>xs:double</zorba:param>
      <zorba:output>xs:double+</zorba:output>
    </zorba:signature>
  </zorba:function>

  <zorba:state generateInit="true" generateReset="true">
    <zorba:member type="xs_integer" name="theIntExponent" defaultValue="numeric_consts<xs_integer>::zero()"
                  brief=""/>
  </zorba:state>

</zorba:iterator>

</zorba:iterators>


text:
<?php

/**
   * Commit record class
   *
   * @package activeCollab.modules.source
   * @subpackage models
   */
class Commit extends ProjectObject {

  /**
   * Permission name
   *
   * @var string
   */
  var $permission_name = 'repository';

  /**
   * Project tab
   *
   * @var string
   */
  var $project_tab = 'source';

  /**
   * Total paths affected
   *
   * @var int
   */
  var $total_paths = 0;

  /**
   * Define fields used by this project object
   *
   * @var array
   */
  var $fields = array(
  'id',
  'type', 'module',
  'project_id', 'parent_id', 'parent_type',
  'body',
  'created_on', 'created_by_name', 'created_by_email',
  'state',
  'visibility',
  'integer_field_1', // revision
  'text_field_1', // paths
  'text_field_2' // diff changes
  );

  /**
   * Field map
   *
   * @var array
   */
  var $field_map = array(
  'revision'  => 'integer_field_1',
  'paths'     => 'text_field_1',
  'diff'      => 'text_field_2'
  );

  /**
   * Repository that commit belongs to
   *
   * @var Repository
   */
  var $repository = null;

  /**
   * Construct a new ticket
   *
   * @param mixed $id
   * @return Ticket
   */
  function __construct($id = null) {
    parent::__construct();
    $this->setModule(SOURCE_MODULE);
  } // __construct

  /**
   * Find project objects in commit message, make them links and
   * save the relations to database
   *
   * @param string $commit_message
   * @return string
   */
  function analyze_message($commit_message, $commit_author, $revision, $repository, $project) {

    $pattern = '/((complete[d]*)[\s]+)?(ticket|milestone|discussion|task)[s]*[\s]+[#]*\d+/i';

    if (preg_match_all($pattern, $commit_message, $matches)) {
      $i = 0;
      $search = array();
      $replace = array();

      $matches_unique = array_unique($matches['0']);

      foreach ($matches_unique as $key => $match) {
        $match_data = preg_split('/[\s,]+/', $match, null, PREG_SPLIT_NO_EMPTY);

        // check if the object got completed by this commit
        $object_completed = false;
        if (strpos(strtolower($match_data['0']), 'complete') !== false) {
          $object_completed = true;
          unset($match_data['0']);
          $match_data = array_values($match_data);
        } // if

        $object_class_name = $match_data['0'];
      	$module_name = Inflector::pluralize($object_class_name);
      	$object_id = trim($match_data['1'], '#');
      	$search[$i] = $match;

      	if (class_exists($module_name) && class_exists($object_class_name)) {
      	  $object = null;

      	  switch (strtolower($module_name)) {
      	  	case 'tickets':
      	  	  $object = Tickets::findByTicketId($project, $object_id);
      	  		break;
      	  	case 'discussions':
      	  	  $object = Discussions::findById($object_id);
      	  	  break;
      	  	case 'milestones':
      	  	  $object = Milestones::findById($object_id);
      	  	  break;
      	  	case 'tasks' :
      	  	  $object = Tasks::findById($object_id);
      	  	  break;
      	  } // switch

      	  if (instance_of($object, $object_class_name)) {
      	    $link_already_created = CommitProjectObjects::count("object_id = '".$object->getId()."' AND revision = '$revision'") > 0;

      	    if (!$link_already_created) {
      	      $comit_project_object = new CommitProjectObject();
      	      $comit_project_object->setProjectId($object->getProjectId());
      	      $comit_project_object->setObjectId($object->getId());
      	      $comit_project_object->setObjectType(ucfirst($object_class_name));
      	      $comit_project_object->setRepositoryId($repository->getId());
      	      $comit_project_object->setRevision($revision);

      	      db_begin_work();
      	      $save = $comit_project_object->save();
      	      if ($save && !is_error($save)) {
      	        db_commit();
      	      } else {
      	        db_rollback();
      	      } // if save

      	    } // if

      	    $replace[$i] = ($object_completed ? 'Completed ' : '') . 'getViewUrl().'">'.$match_data['0'].' '.$match_data['1'].'';

      	    // set the object as completed
      	    if ($object_completed && !instance_of($object, 'Discussion')) {
      	      $completed_by = $repository->getMappedUser($commit_author);
      	      $object->complete($completed_by);
      	    } // if
      	  }
      	  else {
      	    $replace[$i] = ($object_completed ? 'Completed ' : '') . ''.$match_data['0'].' '.$match_data['1'].'';
      	  } // if instance_of

      	  $i++;
      	} // if module loaded
      } // foreach

      return str_ireplace($search, $replace, htmlspecialchars($commit_message)); // linkify

    } // if preg_match

    return $commit_message;
  } // get_project_objects

  /**
   * Return count of affected paths
   *
   * @return integer
   */
  function countPaths() {
    $paths = $this->getPaths();
    return (int) count($pats);
  } // countPaths

  /**
   * Get Author
   *
   * @param Repository $repository
   * @return string
   */
  function getAuthor($repository = null) {
    if (!instance_of($repository, 'Repository') || $repository->isNew()) {
      $repository = Repositories::findById($this->getParentId());
    } // if

    if (!is_foreachable($repository->mapped_users)) {
      $repository->mapped_users = SourceUsers::findByRepository($repository);
    } // if

    if (isset($repository->mapped_users[$this->getCreatedByName()]) && instance_of($repository->mapped_users[$this->getCreatedByName()], 'SourceUser')) {
      $source_user = $repository->mapped_users[$this->getCreatedByName()];
      $system_user = $source_user->system_user;
      if (instance_of($system_user, 'User')) {
        return 'getViewUrl().'">'.$system_user->getDisplayName(true).'';
      } // if
    } // if

    return $this->getCreatedByName();
  } // getAuthor

  /**
   * Return commit author (adapted for portal view)
   *
   * @param Repository $repository
   * @return string
   */
  function getPortalAuthor($repository = null) {
  	if(!instance_of($repository, 'Repository') || $repository->isNew()) {
  		$repository = Repositories::findById($this->getParentId());
  		$repository->mapped_users = SourceUsers::findByRepository($repository);
  	} // if

  	if(isset($repository->mapped_users[$this->getCreatedByName()]) && instance_of($repository->mapped_users[$this->getCreatedByName()], 'SourceUser')) {
  		$source_user = $repository->mapped_users[$this->getCreatedByName()];
  		$system_user = $source_user->system_user;
  		if(instance_of($system_user, 'User')) {
  			return $system_user->getDisplayName(true);
  		} // if
  	} // if

  	return $this->getCreatedByName();
  } // getPortalAuthor

  /**
   * Set createdBy info
   *
   * @param User $created_by
   * @return null
   */
  function setCreatedBy($created_by) {
    $this->setCreatedById($created_by->getId());
    $this->setCreatedByName($created_by->getName());
    $this->setCreatedByEmail($created_by->getEmail());
  } // setCreatedBy

  /**
   * Get CreatedBy information
   *
   * @param Repository $repository
   * @return User
   */
  function getCreatedBy($repository = null) {
    if (is_null($repository)) {
      $repository = Repositories::findById($this->getParentId());
      $repository->mapped_users = SourceUsers::findByRepository($repository);
    } // if

    if (isset($repository->mapped_users[$this->getCreatedByName()]) && instance_of($repository->mapped_users[$this->getCreatedByName()], 'SourceUser')) {
      $source_user = $repository->mapped_users[$this->getCreatedByName()];
      if (instance_of($source_user->system_user, 'User')) {
        return $source_user->system_user;
      } // if
    } // if

    return parent::getCreatedBy();
  } // getCreatedBy

  /**
   * Return object name
   *
   * @return string
   */
  function getName() {
    return lang('Revision #:num', array('num' => $this->getRevision()));
  } // getName

  /**
   * Set diff
   *
   * @param array $value
   * @return boolean
   */
  function setDiff($value) {
    return $this->setTextField2(serialize($value));
  } // set diff

  /**
   * Get diff
   *
   * @param null
   * @return array
   */
  function getDiff() {
    return unserialize($this->getTextField2());
  } // get diff

  /**
   * Get commit revision
   *
   * @return null
   */
  function getRevision() {
    return $this->getIntegerField1();
  } // get revision

  /**
   * Set revision
   *
   * @param integer $value
   * @return null
   */
  function setRevision($value) {
    return $this->setIntegerField1($value);
  } // set revision

  /**
   * Set paths
   *
   * @param array $value
   * @return boolean
   */
  function setPaths($value) {
    return $this->setTextField1(serialize($value));
  } // set paths

  /**
   * Get commit paths
   *
   * @return array
   */
  function getPaths() {
    return unserialize($this->getTextField1());
  } // get paths

  /**
   * Get commit message
   *
   * @return string
   */
  function getMessage() {
    return $this->getBody();
  } // getMessage

  /**
   * Set commit message
   *
   * @param string $value
   * @return boolean
   */
  function setMessage($value) {
    return $this->setBody($value);
  } // setMessage

  /**
   * Get View URL
   *
   * @return string
   */
  function getViewUrl() {
    return assemble_url('repository_commit', array('project_id'=>$this->getProjectId(), 'repository_id'=>$this->getParentId(), 'r'=>$this->getRevision()));
  } // getViewUrl

  /**
   * Return portal revision view URL
   *
   * @param Portal $portal
   * @return string
   */
  function getPortalViewUrl($portal) {
  	return assemble_url('portal_repository_commit', array('portal_name' => $portal->getSlug(), 'repository_id' => $this->getParentId(), 'r' => $this->getRevision()));
  } // getPortalViewUrl

  /**
   * Get Edit URL
   *
   * Basically, commits are history entries and are not meant to be edited, but the method is here for
   * possible compatibility issues with project object model
   *
   * @return string
   */
  function getEditUrl() {
    return '';
  } // getEditUrl

  // ---------------------------------------------------
  //  System
  // ---------------------------------------------------

  function validate(&$errors) {
    return parent::validate($errors, true);
  }

  /**
   * Save into database
   *
   * @return boolean
   */
  function save() {
    $save = parent::save();
    return $save;
  } // save

} // Ticket

?>


text:
package com.google.cloud.bigtable.grpc.io;

import io.grpc.Call;
import io.grpc.Channel;
import io.grpc.MethodDescriptor;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

/**
 * Manages a set of ClosableChannels and uses them in a round robin.
 */
public class ChannelPool extends Channel {

  protected static final Logger log = Logger.getLogger(ChannelPool.class.getName());

  private final Channel[] channels;
  private final AtomicInteger requestCount = new AtomicInteger();

  public ChannelPool(Channel[] channels) {
    this.channels = channels;
  }

  @Override
  public <RequestT, ResponseT> Call<RequestT, ResponseT> newCall(
      MethodDescriptor<RequestT, ResponseT> methodDescriptor) {
    int currentRequestNum = requestCount.getAndIncrement();
    int index = Math.abs(currentRequestNum % channels.length);
    return channels[index].newCall(methodDescriptor);
  }
}


text:
import { browser, by, element } from 'protractor';

export class EdutivePage {
  navigateTo() {
    return browser.get('/');
  }

  getParagraphText() {
    return element(by.css('app-root h1')).getText();
  }
}


text:
package org.apache.gora.oracle.util;

import java.io.IOException;
import java.io.OutputStream;

public class FixedByteArrayOutputStream extends OutputStream {

  private int i;
  byte out[];

  public FixedByteArrayOutputStream(byte out[]) {
    this.out = out;
  }

  @Override
  public void write(int b) throws IOException {
    out[i++] = (byte) b;
  }

  @Override
  public void write(byte b[], int off, int len) throws IOException {
    System.arraycopy(b, off, out, i, len);
    i += len;
  }

}


text:
namespace remoting {

using protocol::AuthenticationMethod;

ChromotingClient::ChromotingClient(
    ClientContext* client_context,
    ClientUserInterface* user_interface,
    VideoRenderer* video_renderer,
    scoped_ptr<AudioPlayer> audio_player)
    : task_runner_(client_context->main_task_runner()),
      user_interface_(user_interface),
      video_renderer_(video_renderer),
      host_capabilities_received_(false) {
  if (audio_player) {
    audio_decode_scheduler_.reset(new AudioDecodeScheduler(
        client_context->main_task_runner(),
        client_context->audio_decode_task_runner(),
        audio_player.Pass()));
  }
}

ChromotingClient::~ChromotingClient() {}

void ChromotingClient::SetProtocolConfigForTests(
    scoped_ptr<protocol::CandidateSessionConfig> config) {
  connection_.set_candidate_config(config.Pass());
}

void ChromotingClient::Start(
    SignalStrategy* signal_strategy,
    scoped_ptr<protocol::Authenticator> authenticator,
    scoped_ptr<protocol::TransportFactory> transport_factory,
    const std::string& host_jid,
    const std::string& capabilities) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  local_capabilities_ = capabilities;

  connection_.set_client_stub(this);
  connection_.set_clipboard_stub(this);
  connection_.set_video_stub(video_renderer_);
  connection_.set_audio_stub(audio_decode_scheduler_.get());

  connection_.Connect(signal_strategy, transport_factory.Pass(),
                       authenticator.Pass(), host_jid, this);
}

void ChromotingClient::SetCapabilities(
    const protocol::Capabilities& capabilities) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  // Only accept the first |protocol::Capabilities| message.
  if (host_capabilities_received_) {
    LOG(WARNING) << "protocol::Capabilities has been received already.";
    return;
  }

  host_capabilities_received_ = true;
  if (capabilities.has_capabilities())
    host_capabilities_ = capabilities.capabilities();

  VLOG(1) << "Host capabilities: " << host_capabilities_;

  // Calculate the set of capabilities enabled by both client and host and pass
  // it to the webapp.
  user_interface_->SetCapabilities(
      IntersectCapabilities(local_capabilities_, host_capabilities_));
}

void ChromotingClient::SetPairingResponse(
    const protocol::PairingResponse& pairing_response) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  user_interface_->SetPairingResponse(pairing_response);
}

void ChromotingClient::DeliverHostMessage(
    const protocol::ExtensionMessage& message) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  user_interface_->DeliverHostMessage(message);
}

void ChromotingClient::InjectClipboardEvent(
    const protocol::ClipboardEvent& event) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  user_interface_->GetClipboardStub()->InjectClipboardEvent(event);
}

void ChromotingClient::SetCursorShape(
    const protocol::CursorShapeInfo& cursor_shape) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  user_interface_->GetCursorShapeStub()->SetCursorShape(cursor_shape);
}

void ChromotingClient::OnConnectionState(
    protocol::ConnectionToHost::State state,
    protocol::ErrorCode error) {
  DCHECK(task_runner_->BelongsToCurrentThread());
  VLOG(1) << "ChromotingClient::OnConnectionState(" << state << ")";

  if (state == protocol::ConnectionToHost::AUTHENTICATED) {
    OnAuthenticated();
  } else if (state == protocol::ConnectionToHost::CONNECTED) {
    OnChannelsConnected();
  }
  user_interface_->OnConnectionState(state, error);
}

void ChromotingClient::OnConnectionReady(bool ready) {
  VLOG(1) << "ChromotingClient::OnConnectionReady(" << ready << ")";
  user_interface_->OnConnectionReady(ready);
}

void ChromotingClient::OnRouteChanged(const std::string& channel_name,
                                      const protocol::TransportRoute& route) {
  VLOG(0) << "Using " << protocol::TransportRoute::GetTypeString(route.type)
          << " connection for " << channel_name << " channel";
  user_interface_->OnRouteChanged(channel_name, route);
}

void ChromotingClient::OnAuthenticated() {
  DCHECK(task_runner_->BelongsToCurrentThread());

  // Initialize the decoder.
  video_renderer_->Initialize(connection_.config());
  if (connection_.config().is_audio_enabled())
    audio_decode_scheduler_->Initialize(connection_.config());

}

void ChromotingClient::OnChannelsConnected() {
  DCHECK(task_runner_->BelongsToCurrentThread());

  // Negotiate capabilities with the host.
  VLOG(1) << "Client capabilities: " << local_capabilities_;

  protocol::Capabilities capabilities;
  capabilities.set_capabilities(local_capabilities_);
  connection_.host_stub()->SetCapabilities(capabilities);
}

}  // namespace remoting


text:
// This file is automatically generated.

package adila.db;

/*
 * LG G5 SE
 *
 * DEVICE: alicee
 * MODEL: LG-H840
 */
final class alicee_lg2dh840 {
    public static final String DATA = "LG|G5 SE|";
}


text:
<?php
/**
 * This file is part of VinceTBootstrapFormBundle for Symfony2
 *
 * @category VinceT
 * @package  VinceTBootstrapFormBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/BootstrapFormBundle
 */

namespace VinceT\BootstrapFormBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

/**
 * KnobType
 *
 * @category VinceT
 * @package  VinceTBootstrapFormBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/BootstrapFormBundle
 */
class KnobType extends AbstractType
{

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        // style
        if ( !isset($view->vars['attr']['style']) ) {
            $view->vars['attr']['style'] = '';
        }
        if ( $options['hide_box_shadow'] ) {
            $view->vars['attr']['style'] .= ';box-shadow:none;';
        }
        // class
        if ( !isset($view->vars['attr']['class']) ) {
            $view->vars['attr']['class'] = '';
        }
        $view->vars['attr']['class'] .= ' knob';
        $view->vars['attr']['data-width'] = $options['width'];
        $view->vars['attr']['data-height'] = $options['height'];
        $view->vars['attr']['data-displayInput'] = $options['displayInput'];
        $view->vars['attr']['data-displayPrevious'] = $options['displayPrevious'];
        $view->vars['attr']['data-cursor'] = $options['cursor'];
        $view->vars['attr']['data-readonly'] = $options['readonly'];

        if ( $options['thickness'] ) {
            $view->vars['attr']['data-thickness'] = $options['thickness'];
        }
        if ( $options['fgColor'] ) {
            $view->vars['attr']['data-fgColor'] = $options['fgColor'];
        }
        if ( $options['angleOffset'] ) {
            $view->vars['attr']['data-angleOffset'] = $options['angleOffset'];
        }
        if ( $options['linecap'] ) {
            $view->vars['attr']['data-linecap'] = $options['linecap'];
        }
        if ( $options['angleArc'] ) {
            $view->vars['attr']['data-angleArc'] = $options['angleArc'];
        }
        if ( $options['step'] ) {
            $view->vars['attr']['data-step'] = $options['step'];
        }
        if ( $options['min'] ) {
            $view->vars['attr']['data-min'] = $options['min'];
        }
        if ( $options['max'] ) {
            $view->vars['attr']['data-max'] = $options['max'];
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'width' => 200,
            'height' => 200,
            'displayInput' => true,
            'cursor' => 0,
            'thickness' => 0.35,
            'fgColor' => '#87CEEB',
            'displayPrevious' => false,
            'linecap' => 'butt',
            'angleOffset' => null,
            'angleArc' => null,
            'step' => 1,
            'min' => 0,
            'max' => 100,
            'readonly' => false,
            'hide_box_shadow' => true,
        ));

        $resolver->setAllowedValues('displayInput', [true, false]);
        $resolver->setAllowedValues('displayPrevious', [true, false]);
    }

    public function getParent()
    {
        return NumberType::class;
    }

    public function getName()
    {
        return 'knob';
    }
}


text:
class Lifestylechallenge < ActiveRecord::Base
end


text:
<?xml version="1.0" encoding="utf-8"?>
<metadata>
	<layout title="COM_JDOWNLOADS_JD_MENU_CREATE_DOWNLOAD_LAYOUT" option="COM_JDOWNLOADS_JD_MENU_CREATE">
		<message>
			<![CDATA[COM_JDOWNLOADS_JD_MENU_CREATE_DOWNLOAD_LAYOUT_DESC]]>
		</message>
	</layout>

    <fieldset addfieldpath="/administrator/components/com_jdownloads/models/fields"></fieldset>
    <fields name="params">
		<fieldset name="basic">
			<field name="enable_category"
				type="radio"
				default="0"
				label="COM_JDOWNLOADS_FE_CREATE_DOWNLOAD_CATEGORY_LABEL"
				description="COM_JDOWNLOADS_FE_CREATE_DOWNLOAD_ARTICLE_CATEGORY_DESC">
					<option value="1">COM_JDOWNLOADS_YES</option>
					<option value="0">COM_JDOWNLOADS_NO</option>
			</field>
			<field name="catid"
				type="jdCategorySelect"
				label="COM_JDOWNLOADS_CHOOSE_CATEGORY_LABEL"
				description="COM_JDOWNLOADS_CHOOSE_CATEGORY_DESC" />
		</fieldset>
	</fields>
</metadata>