text:
require 'spec_helper'

describe "GameHelper" do
  before do
    allow($stdout).to receive(:write)
  end
  let(:beginner) {0}
  let(:intermediate) {1}
  let(:advanced) {2}
  let(:num_of_players) {2}
  let(:max_guess) {12}

  subject do
    MasterMind::Tobi::GameHelper.new
  end

  describe "GameHelper#user_choice" do
    it "exits when user chooses to" do
      allow(subject).to receive(:gets).and_return('q')
      expect{subject.user_choice}.to raise_error SystemExit
    end

    it "processes user's level correctly" do
      allow(subject).to receive(:gets).and_return('b')
      expect(subject.ask_level).to eql(beginner)

      allow(subject).to receive(:gets).and_return('i')
      expect(subject.ask_level).to eql(intermediate)

      allow(subject).to receive(:gets).and_return('a')
      expect(subject.ask_level).to eql(advanced)
    end

    it "allows user select to play and play single-player smoothly" do
      Object.any_instance.stub(:gets) {
        @counter ||= 0
        response = ''

        if @counter == 0
          response = 'r'
        elsif @counter == 1
          response = 'er'
        elsif @counter == 2
          response = 'p'
        elsif @counter == 3
          response = 'g'
        elsif @counter == 4
          response = 'b'
        elsif @counter == 5
          response = 's'
        elsif @counter >= 6 && @counter < (max_guess + 1 + 6)
          response = 'JJJJ'
        elsif @counter >= 19
          response = 'q'
        end
        @counter += 1
        response
      }
      expect{subject.user_choice}.to raise_error SystemExit
    end

    it "allows user select to play and play multi-player smoothly" do
      Object.any_instance.stub(:gets) {
        @counter ||= 0
        response = ''

        if @counter == 0
          response = 'p'
        elsif @counter == 1
          response = 'g'
        elsif @counter == 2
          response = 'b'
        elsif @counter == 3
          response = 'other'
        elsif @counter == 4
          response = 'm'
        elsif @counter == 5
          response = 'no'
        elsif @counter == 6
          response = num_of_players.to_s
        elsif @counter > 7 && @counter < (max_guess*2 + 1 + 7)
          response = 'JJJJJ'
        else
          response = 'q'
        end
        @counter += 1
        response
      }
      expect{subject.user_choice}.to raise_error SystemExit
    end
  end
end


text:
/* glibconfig.h
 *
 * This is a generated file.  Please modify 'configure.ac'
 */

#ifndef __GLIBCONFIG_H__
#define __GLIBCONFIG_H__

#include <glib/gmacros.h>

#include <limits.h>
#include <float.h>
#define GLIB_HAVE_ALLOCA_H
#define GLIB_HAVE_SYS_POLL_H

/* Specifies that GLib's g_print*() functions wrap the
 * system printf functions.  This is useful to know, for example,
 * when using glibc's register_printf_function().
 */
#define GLIB_USING_SYSTEM_PRINTF

G_BEGIN_DECLS

#define G_MINFLOAT	FLT_MIN
#define G_MAXFLOAT	FLT_MAX
#define G_MINDOUBLE	DBL_MIN
#define G_MAXDOUBLE	DBL_MAX
#define G_MINSHORT	SHRT_MIN
#define G_MAXSHORT	SHRT_MAX
#define G_MAXUSHORT	USHRT_MAX
#define G_MININT	INT_MIN
#define G_MAXINT	INT_MAX
#define G_MAXUINT	UINT_MAX
#define G_MINLONG	LONG_MIN
#define G_MAXLONG	LONG_MAX
#define G_MAXULONG	ULONG_MAX

typedef signed char gint8;
typedef unsigned char guint8;
typedef signed short gint16;
typedef unsigned short guint16;
#define G_GINT16_MODIFIER "h"
#define G_GINT16_FORMAT "hi"
#define G_GUINT16_FORMAT "hu"
typedef signed int gint32;
typedef unsigned int guint32;
#define G_GINT32_MODIFIER ""
#define G_GINT32_FORMAT "i"
#define G_GUINT32_FORMAT "u"
#define G_HAVE_GINT64 1          /* deprecated, always true */

typedef signed long gint64;
typedef unsigned long guint64;

#define G_GINT64_CONSTANT(val)	(val##L)
#define G_GUINT64_CONSTANT(val)	(val##UL)
#define G_GINT64_MODIFIER "l"
#define G_GINT64_FORMAT "li"
#define G_GUINT64_FORMAT "lu"

#define GLIB_SIZEOF_VOID_P 8
#define GLIB_SIZEOF_LONG   8
#define GLIB_SIZEOF_SIZE_T 8

typedef signed long gssize;
typedef unsigned long gsize;
#define G_GSIZE_MODIFIER "l"
#define G_GSSIZE_FORMAT "li"
#define G_GSIZE_FORMAT "lu"

#define G_MAXSIZE	G_MAXULONG
#define G_MINSSIZE	G_MINLONG
#define G_MAXSSIZE	G_MAXLONG

typedef gint64 goffset;
#define G_MINOFFSET	G_MININT64
#define G_MAXOFFSET	G_MAXINT64

#define G_GOFFSET_MODIFIER      G_GINT64_MODIFIER
#define G_GOFFSET_FORMAT        G_GINT64_FORMAT
#define G_GOFFSET_CONSTANT(val) G_GINT64_CONSTANT(val)

#define GPOINTER_TO_INT(p)	((gint)  (glong) (p))
#define GPOINTER_TO_UINT(p)	((guint) (gulong) (p))

#define GINT_TO_POINTER(i)	((gpointer) (glong) (i))
#define GUINT_TO_POINTER(u)	((gpointer) (gulong) (u))

typedef signed long gintptr;
typedef unsigned long guintptr;

#define G_GINTPTR_MODIFIER      "l"
#define G_GINTPTR_FORMAT        "li"
#define G_GUINTPTR_FORMAT       "lu"

#ifdef NeXT /* @#%@! NeXTStep */
# define g_ATEXIT(proc)	(!atexit (proc))
#else
# define g_ATEXIT(proc)	(atexit (proc))
#endif

#define g_memmove(dest,src,len) G_STMT_START { memmove ((dest), (src), (len)); } G_STMT_END

#define GLIB_MAJOR_VERSION 2
#define GLIB_MINOR_VERSION 32
#define GLIB_MICRO_VERSION 4

#define G_OS_UNIX

#define G_VA_COPY	va_copy
#define G_VA_COPY_AS_ARRAY 1

#ifdef	__cplusplus
#define	G_HAVE_INLINE	1
#else	/* !__cplusplus */
#define G_HAVE_INLINE 1
#define G_HAVE___INLINE 1
#define G_HAVE___INLINE__ 1
#endif	/* !__cplusplus */

#ifdef	__cplusplus
#define G_CAN_INLINE	1
#else	/* !__cplusplus */
#define G_CAN_INLINE	1
#endif

#ifndef __cplusplus
# define G_HAVE_ISO_VARARGS 1
#endif
#ifdef __cplusplus
# define G_HAVE_ISO_VARARGS 1
#endif

/* gcc-2.95.x supports both gnu style and ISO varargs, but if -ansi
 * is passed ISO vararg support is turned off, and there is no work
 * around to turn it on, so we unconditionally turn it off.
 */
#if __GNUC__ == 2 && __GNUC_MINOR__ == 95
#  undef G_HAVE_ISO_VARARGS
#endif

#define G_HAVE_GNUC_VARARGS 1
#define G_HAVE_GROWING_STACK 1

#if defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590)
#define G_GNUC_INTERNAL __attribute__((visibility("hidden")))
#elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550)
#define G_GNUC_INTERNAL __hidden
#elif defined (__GNUC__) && defined (G_HAVE_GNUC_VISIBILITY)
#define G_GNUC_INTERNAL __attribute__((visibility("hidden")))
#else
#define G_GNUC_INTERNAL
#endif

#define G_THREADS_ENABLED
#define G_THREADS_IMPL_POSIX

#define G_ATOMIC_LOCK_FREE

#define GINT16_TO_LE(val)	((gint16) (val))
#define GUINT16_TO_LE(val)	((guint16) (val))
#define GINT16_TO_BE(val)	((gint16) GUINT16_SWAP_LE_BE (val))
#define GUINT16_TO_BE(val)	(GUINT16_SWAP_LE_BE (val))
#define GINT32_TO_LE(val)	((gint32) (val))
#define GUINT32_TO_LE(val)	((guint32) (val))
#define GINT32_TO_BE(val)	((gint32) GUINT32_SWAP_LE_BE (val))
#define GUINT32_TO_BE(val)	(GUINT32_SWAP_LE_BE (val))
#define GINT64_TO_LE(val)	((gint64) (val))
#define GUINT64_TO_LE(val)	((guint64) (val))
#define GINT64_TO_BE(val)	((gint64) GUINT64_SWAP_LE_BE (val))
#define GUINT64_TO_BE(val)	(GUINT64_SWAP_LE_BE (val))
#define GLONG_TO_LE(val)	((glong) GINT64_TO_LE (val))
#define GULONG_TO_LE(val)	((gulong) GUINT64_TO_LE (val))
#define GLONG_TO_BE(val)	((glong) GINT64_TO_BE (val))
#define GULONG_TO_BE(val)	((gulong) GUINT64_TO_BE (val))
#define GINT_TO_LE(val)		((gint) GINT32_TO_LE (val))
#define GUINT_TO_LE(val)	((guint) GUINT32_TO_LE (val))
#define GINT_TO_BE(val)		((gint) GINT32_TO_BE (val))
#define GUINT_TO_BE(val)	((guint) GUINT32_TO_BE (val))
#define GSIZE_TO_LE(val)	((gsize) GUINT64_TO_LE (val))
#define GSSIZE_TO_LE(val)	((gssize) GINT64_TO_LE (val))
#define GSIZE_TO_BE(val)	((gsize) GUINT64_TO_BE (val))
#define GSSIZE_TO_BE(val)	((gssize) GINT64_TO_BE (val))
#define G_BYTE_ORDER G_LITTLE_ENDIAN

#define GLIB_SYSDEF_POLLIN =1
#define GLIB_SYSDEF_POLLOUT =4
#define GLIB_SYSDEF_POLLPRI =2
#define GLIB_SYSDEF_POLLHUP =16
#define GLIB_SYSDEF_POLLERR =8
#define GLIB_SYSDEF_POLLNVAL =32

#define G_MODULE_SUFFIX "so"

typedef int GPid;

#define GLIB_SYSDEF_AF_UNIX 1
#define GLIB_SYSDEF_AF_INET 2
#define GLIB_SYSDEF_AF_INET6 30

#define GLIB_SYSDEF_MSG_OOB 1
#define GLIB_SYSDEF_MSG_PEEK 2
#define GLIB_SYSDEF_MSG_DONTROUTE 4

G_END_DECLS

#endif /* __GLIBCONFIG_H__ */

redpajama_set_name: RedPajamaGithub


text:
function  [y] = UGM_Decode_AlphaBetaSwap(nodePot, edgePot, edgeStruct, decodeFunc,y)
% INPUT
% nodePot(node,class)
% edgePot(class,class,edge) where e is referenced by V,E (must be the same
% between feature engine and inference engine)
%
% OUTPUT
% nodeLabel(node)

[nNodes,maxStates] = size(nodePot);
nEdges = size(edgePot,3);
edgeEnds = edgeStruct.edgeEnds;
V = edgeStruct.V;
E = edgeStruct.E;
nStates = edgeStruct.nStates;
maxState = max(nStates);

% Initialize
if nargin < 4
    decodeFunc = @UGM_Decode_GraphCut;
end
if nargin < 5
    [junk y] = max(nodePot,[],2);
end
pot = UGM_LogConfigurationPotential(y,nodePot,edgePot,edgeStruct.edgeEnds);

% Do Alpha-Beta swaps until convergence
while 1
    y_old = y;

    for s1 = 1:maxState
        for s2 = s1+1:maxState
            swapPositions = find(y==s1 | y==s2);
            if ~isempty(swapPositions)
                % Find optimal re-arrangement of nodes assigned to s1 or s2
                fprintf('Swapping %d and %d, ',s1,s2);
                clamped = y;
                clamped(swapPositions) = 0;
                [clampedNP,clampedEP,clampedES] = UGM_makeClampedPotentials(nodePot,edgePot,edgeStruct,clamped);

                % Remove all other labels
                clampedNP = clampedNP(:,[s1 s2]);
                clampedEP = clampedEP([s1 s2],[s1 s2],:);
                clampedES.nStates = 2*ones(size(nStates));

                ytmp = decodeFunc(clampedNP,clampedEP,clampedES);

                clampedY = zeros(size(ytmp));
                clampedY(ytmp==1) = s1;
                clampedY(ytmp==2) = s2;

                y2 = y;
                y(swapPositions) = clampedY;

                fprintf('logPot = %f, changes = %d\n',UGM_LogConfigurationPotential(y,nodePot,edgePot,edgeEnds),sum(y2~=y));
            %imagesc(reshape(y,384,288)');title('ICM');colormap gray;drawnow
            end
        end
	end

	if all(y==y_old)
        break;
	end
	pot_old = pot;
    pot = UGM_LogConfigurationPotential(y,nodePot,edgePot,edgeStruct.edgeEnds);
    if pot-pot_old == 0
        break;
    end
end


text:
from google.appengine.api import urlfetch
from main_exception import SafeRequestHandler

import jsonUtil
import logging
import key

import requests
import json

json_headers = {'Content-type': 'application/json'}

def setGetStartedButton():
    from main import tell_admin
    response_data = {
        "get_started": {
            "payload":"START"
        }
    }
    response_data_str = json.dumps(response_data)

    try:
        logging.info('sending menu with json: {}'.format(response_data))
        resp = requests.post(key.FACEBOOK_PROFILE_API_URL, data=response_data_str, headers=json_headers)
        logging.info('responding to request: {}'.format(resp.text))
        tell_admin('Response to GetStartedButton: {}'.format(resp.text))
        return resp.status_code == 200
    except:
        report_exception()

def setFB_Menu():
    setMenu(['INIZIO','IMPOSTAZIONI','AIUTO','STOP'])

def setMenu(menu_items):
    from main import tell_admin
    response_data = {
        "persistent_menu": [
            {
                "locale": "default",
                "composer_input_disabled": False, #Set to true to disable user input in the menu. This means users will only be able to interact with your bot via the menu, postbacks, buttons, and webviews.
                "call_to_actions": [
                    {
                        "title": "Opzioni",
                        "type": "nested",
                        "call_to_actions": [
                            {
                                "type": "postback",
                                "title": i,
                                "payload": i,
                            }
                            for i in menu_items
                        ]
                    },
                    {
                        "title": "Links",
                        "type": "nested",
                        "call_to_actions": [
                            {
                                "type": "web_url",
                                "title": "Telegram bot",
                                "url": "https://t.me/PickMeUp_bot",
                                "webview_height_ratio": "tall"  # compact, tall, full
                            },
                            {
                                "type": "web_url",
                                "title": "Website",
                                "url": "http://pickmeup.trentino.it",
                                "webview_height_ratio": "tall"  # compact, tall, full
                            }

                        ]
                    },

                ]
            },
            #{
            #    "locale": "default",
            #    "composer_input_disabled": False #Set to true to disable user input in the menu. This means users will only be able to interact with your bot via the menu, postbacks, buttons, and webviews.
            #}
        ]
    }
    response_data_str = json.dumps(response_data)

    try:
        logging.info('sending menu with json: {}'.format(response_data))
        resp = requests.post(key.FACEBOOK_PROFILE_API_URL, data=response_data_str, headers=json_headers)
        logging.info('responding to request: {}'.format(resp.text))
        tell_admin('Response to set persisten menu: {}'.format(resp.text))
        return resp.status_code == 200
    except:
        report_exception()

def sendMsgRequest(p, request_data):
    if key.APPLICATION == 'tiramisu-telegram':
        return
    request_data_str = json.dumps(request_data)
    try:
        logging.info('responding to request with message: {}'.format(request_data))
        resp = requests.post(key.FACEBOOK_MSG_API_URL, data=request_data_str, headers=json_headers)
        logging.info('responding to request: {}'.format(resp.text))
        logging.info('status code: {}'.format(resp.status_code))
        code = resp.status_code
        if code == 403:
            # Disabled user
            p.setEnabled(False, put=True)
            # logging.info('Disabled user: ' + p.getFirstNameLastNameUserName())
        return code == 200
    except:
        report_exception()

def sendMessage(p, msg):
    msg = msg.replace('*','')
    request_data = {
        "recipient": {
            "id": p.chat_id
        },
        "message": {
            "text": msg,
        }
    }
    logging.info('message request (simple): {}'.format(request_data))
    return sendMsgRequest(p, request_data)

# max 11 reply_items
def sendMessageWithQuickReplies(p, msg, reply_items):
    msg = msg.replace('*', '')
    request_data = {
        "recipient": {
            "id": p.chat_id
        },
        "message": {
            "text": msg,
            "quick_replies": [
                {
                    "content_type": "text",
                    "title": i,
                    "payload": i
                }
                for i in reply_items
            ]
        }
    }
    logging.info('message request with quick replies: {}'.format(request_data))
    return sendMsgRequest(p, request_data)

# max 3 button_items
def sendMessageWithButtons(p, msg, button_items):
    msg = msg.replace('*', '')
    request_data = {
        "recipient": {
            "id": p.chat_id
        },
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "button",
                    "text": msg,
                    "buttons": [
                        {
                            "type": "postback",
                            "title": i,
                            "payload": i
                        }
                        for i in button_items
                    ]
                }
            }
        }
    }
    logging.info('message request with buttons: {}'.format(request_data))
    return sendMsgRequest(p, request_data)

def sendMessageWithList(p, msg, button_items):
    from main import tell_admin
    msg = msg.replace('*', '')
    request_data = {
        "recipient": {
            "id": p.chat_id
        },
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "list",
                    "top_element_style": "compact", # large, compact
                    "elements": [
                        {
                            "title": i,
                            "subtitle": i,
                            "default_action": {
                                "type": "postback",
                                "payload": i
                            }
                        }
                        for i in button_items
                    ]
                }
            }
        }
    }
    logging.info('message request with list: {}'.format(request_data))
    request_data_str = json.dumps(request_data)
    try:
        logging.info('responding to request with message: {}'.format(request_data))
        resp = requests.post(key.FACEBOOK_MSG_API_URL, data=request_data_str, headers=json_headers)
        tell_admin('response to request with list: {}'.format(resp.text))
        logging.info('status code: {}'.format(resp.status_code))
        code = resp.status_code
        if code == 403:
            # Disabled user
            p.setEnabled(False, put=True)
            # logging.info('Disabled user: ' + p.getFirstNameLastNameUserName())
        return code == 200
    except:
        report_exception()

def sendPhotoUrl(p, url):
    request_data = {
        "recipient": {
            "id": p.chat_id
        },
        "message": {
            "attachment": {
                "type": "file",
                "payload": {
                    "url": url
                }
            }
        }
    }
    logging.info('send photo (url) request: {}'.format(request_data))
    return sendMsgRequest(p, request_data)

def sendPhotoData(p, file_data, filename):
    request_data = {
        "recipient": json.dumps(
            {
                "id": p.chat_id
            }
        ),
        "message": json.dumps(
            {
                "attachment": {
                    "type": "image",
                    "payload": {}
                }
            }
        )
    }

    files = {
        "filedata": (filename, file_data, 'image/png')
    }

    try:
        logging.info('sending photo data: {}'.format(request_data))
        resp = requests.post(key.FACEBOOK_MSG_API_URL, data=request_data, files=files)
        logging.info('responding to photo request: {}'.format(resp.text))
        return resp.status_code == 200
    except:
        report_exception()

def getUserInfo(user_id):
    url = key.FACEBOOK_BASE_API + \
          '/{}?fields=first_name,last_name,profile_pic,locale,timezone,gender' \
          '&access_token={}'.format(user_id, key.FACEBOOK_PAGE_ACCESS_TOKEN)
    logging.debug('Sending user info request: {}'.format(url))
    r = requests.get(url)
    json = r.json()
    first_name = json.get('first_name', None)
    last_name = json.get('last_name', None)
    logging.debug('Getting first name = {} and last name = {}'.format(first_name, last_name))
    return first_name, last_name

class WebhookHandler(SafeRequestHandler):

    # to confirm the webhook url
    def get(self):
        #urlfetch.set_default_fetch_deadline(60)
        logging.info('verification request: {}'.format(self.request.body))
        verify_token = self.request.get('hub.verify_token')
        if verify_token == key.FACEBOOK_VERIFY_TOKEN:
            challenge = self.request.get('hub.challenge')
            self.response.write(challenge)
        else:
            self.response.http_status_message(403)

    # to handle user interaction
    def post(self):
        from main import dealWithUserInteraction
        #urlfetch.set_default_fetch_deadline(60)
        body = jsonUtil.json_loads_byteified(self.request.body)
        logging.info('request body: {}'.format(body))
        messaging = body['entry'][0]['messaging'][0]
        chat_id = messaging['sender']['id']
        text = messaging.get('message', {}).get('text', '')
        if text=='':
            text = messaging.get('postback', {}).get('payload', '')
        #attachment = messaging.get('message', {}).get('attachments', [{}])[0]
        #voice_url = attachment.get('payload',{}).get('url',None) if attachment.get('type',None)=='audio' else None
        location = messaging.get('message', {}).get('attachments', [{}])[0].get('payload', {}).get('coordinates', None)
        # {"lat": 46.0, "long": 11.1}
        if location:
            location = {'latitude': location['lat'], 'longitude': location['long'] }

        # we need this as fb is send all sort of notification when user is active without sending any message
        if text=='' and location is None:
            return

        name, last_name = getUserInfo(chat_id)

        dealWithUserInteraction(chat_id, name=name, last_name=last_name, username=None,
                                application='messenger', text=text,
                                location=location, contact=None, photo=None, document=None, voice=None)

def report_exception():
    from main import tell_admin
    import traceback
    msg = "❗ Detected Exception: " + traceback.format_exc()
    tell_admin(msg)
    logging.error(msg)


text:
Command line tool for creating a manifest file to go with a release bundle. For more information on the internals of this tool, have a look at the [Manifest library](/lib/manifest).
###[Canonical Generator](/client/canonical-main)
Command line tool for generating the canonical form of Snomed. See [algorithm details](/lib/canonical) for more information.
###[Canonical Maven MOJO Plugin](/client/canonical-plugin)
Maven MOJO build plugin for generating the canonical form of Snomed. See [algorithm details](/lib/canonical) for more information.
###[Closure Generator](/client/closure-main)
Command line tool for creating the transitive closure of isA relationships. See [algorithm details](/lib/closure) for more information.
###[Closure Maven MOJO Plugin](/client/closure-plugin)
Maven MOJO build plugin for creating the transitive closure of isA relationships. See [algorithm details](/lib/closure) for more information.
###[Snomed Diff Tool](/client/diff-main)
Command line tool for comparing two snomed releases.
###[Database Import Tool](/client/import-main)
Command line tool for importing Snomed to a relational database. See [algorithm details](/lib/importexport) for more information.
###[RDF Schema Generator](/client/rdfs-export-main)
Command line tool for converting Snomed to RDF Schema. See [algorithm details](/lib/importexport) for more information.


text:
var geometries = require('../core/geometry').geometries;
var geometryNames = require('../core/geometry').geometryNames;
var registerComponent = require('../core/component').registerComponent;
var THREE = require('../lib/three');

var dummyGeometry = new THREE.Geometry();

/**
 * Geometry component. Combined with material component to make a mesh in 3D object.
 * Extended with registered geometries.
 */
module.exports.Component = registerComponent('geometry', {
  schema: {
    buffer: {default: true},
    primitive: {default: 'box', oneOf: geometryNames},
    skipCache: {default: false}
  },

  init: function () {
    this.geometry = null;
  },

  /**
   * Talk to geometry system to get or create geometry.
   */
  update: function (previousData) {
    var data = this.data;
    var el = this.el;
    var mesh;
    var system = this.system;

    // Dispose old geometry if we created one.
    if (this.geometry) {
      system.unuseGeometry(previousData);
      this.geometry = null;
    }

    // Create new geometry.
    this.geometry = system.getOrCreateGeometry(data);

    // Set on mesh. If mesh does not exist, create it.
    mesh = el.getObject3D('mesh');
    if (mesh) {
      mesh.geometry = this.geometry;
    } else {
      mesh = new THREE.Mesh();
      mesh.geometry = this.geometry;
      el.setObject3D('mesh', mesh);
    }
  },

  /**
   * Tell geometry system that entity is no longer using the geometry.
   * Unset the geometry on the mesh
   */
  remove: function () {
    this.system.unuseGeometry(this.data);
    this.el.getObject3D('mesh').geometry = dummyGeometry;
    this.geometry = null;
  },

  /**
   * Update geometry component schema based on geometry type.
   *
   * @param {object} data - New data passed by Component.
   */
  updateSchema: function (data) {
    var newGeometryType = data.primitive;
    var currentGeometryType = this.data && this.data.primitive;
    var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;

    // Geometry has no schema.
    if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
    // Nothing has changed.
    if (currentGeometryType && currentGeometryType === newGeometryType) { return; }

    this.extendSchema(schema);
  }
});


text:
import React from 'react';

const safeClone = ( child, props ) =>
  child && typeof child.type === 'function'
    ? React.cloneElement( child, props )
    : child;

const cloneChildren = ( children, props ) =>
  <span>{ React.Children.map( children, child => safeClone( child, props ) ) }</span>;

export const createChildren = ( components, props, index = 0 ) => {
  if ( components[ index ] ) {
    return React.createElement( components[ index ], props, createChildren( components, props, index + 1 ) );
  } else {
    const { children, ...rest } = props;
    return children && React.Children.count( children ) > 1
      ? cloneChildren( children, rest )
      : safeClone( children, rest );
  }
};

export const Children = ({ children, ...props }) => { // eslint-disable-line
  return children && typeof children.type === 'function'
    ? React.cloneElement( children, props )
    : children;
};


text:
const   Augmented = require("augmentedjs");
        Augmented.Presentation = require("augmentedjs-presentation"),
        CONSTANTS = require("./constants.js");

module.exports = Augmented.Presentation.DialogView.extend({
    style: "form",
    el: CONSTANTS.VIEW_MOUNT.EDIT_DIALOG,
    buttons: {
        "cancel": "cancel",
        "ok" : "ok",
        "delete": "del"
    },
    ok: function() {
        this.trigger(CONSTANTS.MESSAGES.SAVE);
        this.close();
    },
    del: function() {
        this.trigger(CONSTANTS.MESSAGES.DELETE);
        this.close();
    }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<dispatchers method="POST">
	<dispatcher id="pay.usr">
		<url-pattern>/pay/usr/.*</url-pattern>
		<handler>jframe.pay.http.usr.UsrHandler</handler>
	</dispatcher>

	<dispatcher id="pay.ord">
		<url-pattern>/pay/ord/.*</url-pattern>
		<handler>jframe.pay.http.ord.OrderHandler</handler>
	</dispatcher>

	<dispatcher id="void" method="POST|HEAD|GET">
		<url-pattern>/.*</url-pattern>
		<handler>jframe.pay.http.handler.VoidHandler</handler>
	</dispatcher>
</dispatchers>


text:
require( "DotaHS_AI_FollowerBase" )

--
-- TODO:
--

--------------------------------------------------------------------------------
-- CONSTANTS
--------------------------------------------------------------------------------
OBJECTIVE_TYPE_APHOTIC_SHIELD	= "aphoticShield"

--------------------------------------------------------------------------------
-- AI / Abaddon
--------------------------------------------------------------------------------
if AI_Abaddon == nil then
	AI_BehaviorTreeBuilder_Abaddon = class({}, nil, AI_BehaviorTreeBuilder)

	AI_Abaddon = class({}, nil, AI_FollowerBase)

	AI_Abaddon.btreeBuilderClass = AI_BehaviorTreeBuilder_Abaddon

	-- Hero specific properties
	AI_Abaddon.unitClassname	= "npc_dota_hero_abaddon"
	AI_Abaddon.unitShortname	= "Abaddon"

	AI_Abaddon.vAbilityNameList = {
		"abaddon_death_coil",		-- 1
		"abaddon_aphotic_shield",	-- 2
		"abaddon_frostmourne",		-- 3
		"abaddon_borrowed_time",	-- 4
		"attribute_bonus",			-- 5
	}
	AI_Abaddon.vAbilityUpgradeSequence = {
		2, 1, 2, 3, 2,
		4, 2, 1, 1, 1,
		4, 3, 3, 3, 5,
		4, 5, 5, 5, 5,
		5, 5, 5, 5, 5,
	}

	AI_Abaddon.vItemPropertyRating = {
		damage	= 4,
		str		= 5,
		agi		= 1,
		int		= 1,
		as		= 2,
		armor	= 4,
		mr		= 3,
		hp		= 3,
		mana	= 2,
		hpreg	= 4,
		manareg	= 2,
		ms		= 2,
	}
end

--------------------------------------------------------------------------------
function AI_Abaddon:constructor( unit )
	AI_FollowerBase.constructor( self, unit )

	-- Abilities
	self.ABILITY_death_coil		= self.vAbilities["abaddon_death_coil"]
	self.ABILITY_aphotic_shield	= self.vAbilities["abaddon_aphotic_shield"]
end

--------------------------------------------------------------------------------
function AI_Abaddon:GetObjectiveTypeToClassMap()
	local types = AI_FollowerBase.GetObjectiveTypeToClassMap( self )

	-- Register additional objective types
	types[OBJECTIVE_TYPE_APHOTIC_SHIELD]	= AI_Objective_AphoticShield

	return types
end

--------------------------------------------------------------------------------
function AI_Abaddon:GetObjectiveTypesToShow()
	return { OBJECTIVE_TYPE_APHOTIC_SHIELD }
end

--------------------------------------------------------------------------------
-- CONDITIONS
--------------------------------------------------------------------------------
function AI_Abaddon:COND_ReadyForDeathCoil()
	if not self.ABILITY_death_coil:IsFullyCastable() then
		return false
	end

	local range = self.ABILITY_death_coil:GetCastRange()
	local allies = self:FriendlyHeroesInRange( range )

	local lowestHealthPercent = 100
	local lowestHealthAlly = nil
	for _,v in ipairs(allies) do
		if v:entindex() ~= self.entity:entindex() then
			-- Other hero
			if v:IsAlive() then
				local healthPercent = v:GetHealthPercent()
				if healthPercent < lowestHealthPercent then
					lowestHealthPercent = healthPercent
					lowestHealthAlly = v
				end
			end
		end
	end

	if lowestHealthPercent > self.entity:GetHealthPercent() * 0.75 then
		return false
	end

	self.targetDeathCoil = lowestHealthAlly

	return true
end

--------------------------------------------------------------------------------
function AI_Abaddon:COND_ReadyForAphoticShield()
	if not self.ABILITY_aphotic_shield:IsFullyCastable() then
		return false
	end

	-- Collect objectives
	local range = self.ABILITY_aphotic_shield:GetCastRange()
	local allies = self:FriendlyHeroesInRange( range )
	self:RegisterUnitsAsObjectives( OBJECTIVE_TYPE_APHOTIC_SHIELD, allies )

	-- Choose target
	local objective = self.vBestObjectives[OBJECTIVE_TYPE_APHOTIC_SHIELD]

	if not objective or not objective:IsAcceptable() then
		return false
	end

	return true
end

--------------------------------------------------------------------------------
-- ACTIONS
--------------------------------------------------------------------------------
function AI_Abaddon:ACT_CastDeathCoil()
	if not self.targetDeathCoil:IsAlive() then
		return BH_FAILURE
	end

	return self:GetCastingAbilityState( self.ABILITY_death_coil, function ()
		self:CreateOrder( DOTA_UNIT_ORDER_CAST_TARGET, self.targetDeathCoil, self.ABILITY_death_coil )
	end )
end

--------------------------------------------------------------------------------
function AI_Abaddon:ACT_CastAphoticShield()
	local objective = self.vBestObjectives[OBJECTIVE_TYPE_APHOTIC_SHIELD]
	if not objective:IsAcceptable() then
		return BH_FAILURE
	end

	return self:GetCastingAbilityState( self.ABILITY_aphotic_shield, function ()
		self:CreateOrder( DOTA_UNIT_ORDER_CAST_TARGET, objective.entity, self.ABILITY_aphotic_shield )
	end )
end

--------------------------------------------------------------------------------
-- Behavior Tree Builder
--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Abaddon:ARRAY_DecisionMakingChildren()
	local array = AI_BehaviorTreeBuilder.ARRAY_DecisionMakingChildren( self )

	-- Modify
	self:InsertBefore( array, "Flee", self:NODE_AphoticShield() )
	self:InsertBefore( array, "Combat", self:NODE_DeathCoil() )

	return array
end

--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Abaddon:NODE_DeathCoil()
	return SequenceNode( "Death Coil", {
		ConditionNode( "Ready?", "COND_ReadyForDeathCoil" ),
		ActionNode( "Cast Death Coil", "ACT_CastDeathCoil" ),
	} )
end

--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Abaddon:NODE_AphoticShield()
	return SequenceNode( "Aphotic Shield", {
		ConditionNode( "Ready?", "COND_ReadyForAphoticShield" ),
		ActionNode( "Cast Aphotic Shield", "ACT_CastAphoticShield" ),
		Action_Wait( 0.25 ),
	} )
end

--------------------------------------------------------------------------------
-- Objective : AphoticShield
--------------------------------------------------------------------------------
AI_Objective_AphoticShield = class({}, nil, AI_Objective)

AI_Objective_AphoticShield.minimumEnemies = 3

--------------------------------------------------------------------------------
function AI_Objective_AphoticShield:constructor( entity, AI )
	AI_Objective.constructor( self, entity, AI )
end

--------------------------------------------------------------------------------
function AI_Objective_AphoticShield:Evaluate()

	local radius = DotaHS_GetAbilitySpecialValue( self.AI.ABILITY_aphotic_shield, "radius" )
	local enemies = self.AI:FindEnemiesInRange( radius, self.entity:GetAbsOrigin() )
	self.nEnemiesInRange = #enemies

	-- Reset
	self.scoreE = 0
	self.scoreH = 0

	-- Update
	if self:IsAcceptable() then
	--	self.scoreE = self.nEnemiesInRange
		self.scoreH = self:GetHealthScore()
		self.score = self.scoreE + self.scoreH
	else
		self.score = -999999
	end

	return self.score
end

--------------------------------------------------------------------------------
function AI_Objective_AphoticShield:IsAcceptable()
	if not self.entity:IsAlive()	then return false end
	if self.entity:IsMagicImmune()	then return false end

	if self.nEnemiesInRange < self.minimumEnemies then
		return false
	end

	return true
end

--------------------------------------------------------------------------------
function AI_Objective_AphoticShield:GetDebugTextLines()
	return { }
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>RetroStore - Sign up</title>

    <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
    <link rel="manifest" href="/favicon/manifest.json">
    <link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#5bbad5">
    <meta name="theme-color" content="#ffffff">

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

    <link href="css/modern-business.css" rel="stylesheet">

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

        </button>

              Home

              Apps

              Contact

              Sign-up

Sign Up

          Home

Sign Up

Sign up for RetroStore

            If you want to publish apps through RetroStore you can contact us, we are happy
            to add your application to the catalogue.
            We are also planning to open up our developer portal so you can manage your apps
            yourself. For this we want to see how many people would be interested to test it.
            If you are, please let us know at info@retrostore.org

Note: You do not need an account if you want to access RetroStore through one of the
            clients that use it.

Copyright © RetroStore 2018


text:
using Emgu.CV.OCR;

using System.Drawing;

namespace ScreenTranslator.WinFroms
{
    partial class frmMainWindow
    {
        /// <summary>
        /// Variable del diseñador necesaria.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Limpiar los recursos que se estén usando.
        /// </summary>
        /// <param name="disposing">true si los recursos administrados se deben desechar; false en caso contrario.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Código generado por el Diseñador de Windows Forms

        /// <summary>
        /// Método necesario para admitir el Diseñador. No se puede modificar
        /// el contenido de este método con el editor de código.
        /// </summary>
        private void InitializeComponent()
        {
            this.picCaptureArea = new System.Windows.Forms.PictureBox();
            this.rtxCapturedText = new System.Windows.Forms.RichTextBox();
            this.btnRead = new System.Windows.Forms.Button();
            this.btnTranslate = new System.Windows.Forms.Button();
            this.splSeparator = new System.Windows.Forms.SplitContainer();
            this.cmbTo = new System.Windows.Forms.ComboBox();
            this.cmbFrom = new System.Windows.Forms.ComboBox();
            this.From = new System.Windows.Forms.Label();
            this.lblTo = new System.Windows.Forms.Label();
            this.grbControls = new System.Windows.Forms.GroupBox();
            ((System.ComponentModel.ISupportInitialize)(this.picCaptureArea)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.splSeparator)).BeginInit();
            this.splSeparator.Panel1.SuspendLayout();
            this.splSeparator.Panel2.SuspendLayout();
            this.splSeparator.SuspendLayout();
            this.grbControls.SuspendLayout();
            this.SuspendLayout();
            //
            // picCaptureArea
            //
            this.picCaptureArea.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));
            this.picCaptureArea.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.picCaptureArea.Dock = System.Windows.Forms.DockStyle.Fill;
            this.picCaptureArea.Location = new System.Drawing.Point(0, 0);
            this.picCaptureArea.Name = "picCaptureArea";
            this.picCaptureArea.Size = new System.Drawing.Size(455, 174);
            this.picCaptureArea.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.picCaptureArea.TabIndex = 0;
            this.picCaptureArea.TabStop = false;
            //
            // rtxCapturedText
            //
            this.rtxCapturedText.Dock = System.Windows.Forms.DockStyle.Fill;
            this.rtxCapturedText.Location = new System.Drawing.Point(0, 0);
            this.rtxCapturedText.Name = "rtxCapturedText";
            this.rtxCapturedText.Size = new System.Drawing.Size(455, 210);
            this.rtxCapturedText.TabIndex = 4;
            this.rtxCapturedText.Text = "";
            //
            // btnRead
            //
            this.btnRead.Location = new System.Drawing.Point(24, 25);
            this.btnRead.Name = "btnRead";
            this.btnRead.Size = new System.Drawing.Size(75, 23);
            this.btnRead.TabIndex = 5;
            this.btnRead.Text = "Read";
            this.btnRead.UseVisualStyleBackColor = true;
            this.btnRead.Click += new System.EventHandler(this.btnRead_Click);
            //
            // btnTranslate
            //
            this.btnTranslate.Location = new System.Drawing.Point(359, 25);
            this.btnTranslate.Name = "btnTranslate";
            this.btnTranslate.Size = new System.Drawing.Size(75, 23);
            this.btnTranslate.TabIndex = 6;
            this.btnTranslate.Text = "Translate";
            this.btnTranslate.UseVisualStyleBackColor = true;
            this.btnTranslate.Click += new System.EventHandler(this.btnTranslate_Click);
            //
            // splSeparator
            //
            this.splSeparator.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splSeparator.Location = new System.Drawing.Point(0, 0);
            this.splSeparator.Name = "splSeparator";
            this.splSeparator.Orientation = System.Windows.Forms.Orientation.Horizontal;
            //
            // splSeparator.Panel1
            //
            this.splSeparator.Panel1.Controls.Add(this.picCaptureArea);
            //
            // splSeparator.Panel2
            //
            this.splSeparator.Panel2.Controls.Add(this.rtxCapturedText);
            this.splSeparator.Size = new System.Drawing.Size(455, 388);
            this.splSeparator.SplitterDistance = 174;
            this.splSeparator.TabIndex = 7;
            //
            // cmbTo
            //
            this.cmbTo.FormattingEnabled = true;
            this.cmbTo.Location = new System.Drawing.Point(267, 27);
            this.cmbTo.Name = "cmbTo";
            this.cmbTo.Size = new System.Drawing.Size(74, 21);
            this.cmbTo.TabIndex = 7;
            //
            // cmbFrom
            //
            this.cmbFrom.FormattingEnabled = true;
            this.cmbFrom.Location = new System.Drawing.Point(154, 27);
            this.cmbFrom.Name = "cmbFrom";
            this.cmbFrom.Size = new System.Drawing.Size(74, 21);
            this.cmbFrom.TabIndex = 8;
            //
            // From
            //
            this.From.AutoSize = true;
            this.From.Location = new System.Drawing.Point(118, 30);
            this.From.Name = "From";
            this.From.Size = new System.Drawing.Size(30, 13);
            this.From.TabIndex = 9;
            this.From.Text = "From";
            //
            // lblTo
            //
            this.lblTo.AutoSize = true;
            this.lblTo.Location = new System.Drawing.Point(241, 30);
            this.lblTo.Name = "lblTo";
            this.lblTo.Size = new System.Drawing.Size(20, 13);
            this.lblTo.TabIndex = 10;
            this.lblTo.Text = "To";
            //
            // grbControls
            //
            this.grbControls.Controls.Add(this.btnTranslate);
            this.grbControls.Controls.Add(this.lblTo);
            this.grbControls.Controls.Add(this.cmbFrom);
            this.grbControls.Controls.Add(this.btnRead);
            this.grbControls.Controls.Add(this.cmbTo);
            this.grbControls.Controls.Add(this.From);
            this.grbControls.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.grbControls.Location = new System.Drawing.Point(0, 320);
            this.grbControls.Name = "grbControls";
            this.grbControls.Size = new System.Drawing.Size(455, 68);
            this.grbControls.TabIndex = 11;
            this.grbControls.TabStop = false;
            //
            // frmMainWindow
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(455, 388);
            this.Controls.Add(this.grbControls);
            this.Controls.Add(this.splSeparator);
            this.MinimumSize = new System.Drawing.Size(471, 427);
            this.Name = "frmMainWindow";
            this.Opacity = 0.8D;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "ScreenTranslator";
            this.TransparencyKey = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));
            this.Load += new System.EventHandler(this.frmMainWindow_Load);
            ((System.ComponentModel.ISupportInitialize)(this.picCaptureArea)).EndInit();
            this.splSeparator.Panel1.ResumeLayout(false);
            this.splSeparator.Panel1.PerformLayout();
            this.splSeparator.Panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.splSeparator)).EndInit();
            this.splSeparator.ResumeLayout(false);
            this.grbControls.ResumeLayout(false);
            this.grbControls.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.PictureBox picCaptureArea;
        private System.Windows.Forms.RichTextBox rtxCapturedText;
        private System.Windows.Forms.Button btnRead;
        private System.Windows.Forms.Button btnTranslate;
        private System.Windows.Forms.SplitContainer splSeparator;
        private System.Windows.Forms.Label lblTo;
        private System.Windows.Forms.Label From;
        private System.Windows.Forms.ComboBox cmbFrom;
        private System.Windows.Forms.ComboBox cmbTo;
        private System.Windows.Forms.GroupBox grbControls;
    }
}


text:
package org.xbib.content.json.pointer;

import java.nio.CharBuffer;
import java.util.Arrays;
import java.util.List;

/**
 * One JSON Pointer reference token.
 * This class represents one reference token. It has no publicly available
 * constructor; instead, it has static factory methods used to generate tokens
 * depending on whether the input is a decoded (raw) token or an encoded
 * (cooked) one, or even an integer.
 * The only characters to encode in a raw token are {@code /} (which becomes
 * {@code ~1}) and {@code ~} (which becomes {@code ~0}).
 * Note that a reference token may be empty and empty object member names
 * are legal.
 */
public final class ReferenceToken {
    /**
     * The escape character in a cooked token.
     */
    private static final char ESCAPE = '~';

    /**
     * List of encoding characters in a cooked token.
     */
    private static final List<Character> ENCODED = Arrays.asList('0', '1');

    /**
     * List of sequences to encode in a raw token.
     * This list and {@link #ENCODED} have matching indices on purpose.
     */
    private static final List<Character> DECODED = Arrays.asList('~', '/');

    /**
     * The cooked representation of that token.
     *
     * @see #toString()
     */
    private final String cooked;

    /**
     * The raw representation of that token.
     *
     * @see #hashCode()
     * @see #equals(Object)
     */
    private final String raw;

    /**
     * The only constructor, private by design.
     *
     * @param cooked the cooked representation of that token
     * @param raw    the raw representation of that token
     */
    private ReferenceToken(final String cooked, final String raw) {
        this.cooked = cooked;
        this.raw = raw;
    }

    /**
     * Generate a reference token from an encoded (cooked) representation.
     *
     * @param cooked the input
     * @return a token
     * @throws JsonPointerException illegal token (bad encode sequence)
     * @throws NullPointerException null input
     */
    public static ReferenceToken fromCooked(final String cooked)
            throws JsonPointerException {
        return new ReferenceToken(cooked, asRaw(cooked));
    }

    /**
     * Generate a reference token from a decoded (raw) representation.
     *
     * @param raw the input
     * @return a token
     * @throws NullPointerException null input
     */
    public static ReferenceToken fromRaw(final String raw) {
        return new ReferenceToken(asCooked(raw), raw);
    }

    /**
     * Generate a reference token from an integer.
     *
     * @param index the integer
     * @return a token
     */
    public static ReferenceToken fromInt(final int index) {
        final String s = Integer.toString(index);
        return new ReferenceToken(s, s);
    }

    /**
     * Decode an encoded token.
     *
     * @param cooked the encoded token
     * @return the decoded token
     * @throws JsonPointerException bad encoded representation
     */
    private static String asRaw(final String cooked)
            throws JsonPointerException {
        final StringBuilder raw = new StringBuilder(cooked.length());

        final CharBuffer buffer = CharBuffer.wrap(cooked);
        boolean inEscape = false;
        char c;

        while (buffer.hasRemaining()) {
            c = buffer.get();
            if (inEscape) {
                appendEscaped(raw, c);
                inEscape = false;
                continue;
            }
            if (c == ESCAPE) {
                inEscape = true;
                continue;
            }
            raw.append(c);
        }

        if (inEscape) {
            throw new JsonPointerException("empty escape");
        }

        return raw.toString();
    }

    /**
     * Append a decoded sequence to a {@link StringBuilder}.
     *
     * @param sb the string builder to append to
     * @param c  the escaped character
     * @throws JsonPointerException illegal escaped character
     */
    private static void appendEscaped(final StringBuilder sb, final char c)
            throws JsonPointerException {
        final int index = ENCODED.indexOf(c);
        if (index == -1) {
            throw new JsonPointerException("illegal escape");
        }

        sb.append(DECODED.get(index));
    }

    /**
     * Encode a raw token.
     *
     * @param raw the raw representation
     * @return the cooked, encoded representation
     */
    private static String asCooked(final String raw) {
        final StringBuilder cooked = new StringBuilder(raw.length());

        final CharBuffer buffer = CharBuffer.wrap(raw);
        char c;
        int index;

        while (buffer.hasRemaining()) {
            c = buffer.get();
            index = DECODED.indexOf(c);
            if (index != -1) {
                cooked.append('~').append(ENCODED.get(index));
            } else {
                cooked.append(c);
            }
        }

        return cooked.toString();
    }

    /**
     * Get the raw representation of that token as a string.
     *
     * @return the raw representation (for traversing purposes)
     */
    public String getRaw() {
        return raw;
    }

    @Override
    public int hashCode() {
        return raw.hashCode();
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final ReferenceToken other = (ReferenceToken) obj;
        return raw.equals(other.raw);
    }

    @Override
    public String toString() {
        return cooked;
    }
}


text:
#ifndef _CIPHER_HMAC_ALL_H
#define _CIPHER_HMAC_ALL_H
#ifdef  __cplusplus
extern "C" {
#endif /* __cplusplus */

#define   SHA1_DIGEST_SIZE  20
#define SHA224_DIGEST_SIZE  28
#define SHA256_DIGEST_SIZE  32
#define SHA384_DIGEST_SIZE  48
#define SHA512_DIGEST_SIZE  64
#define    MD5_DIGEST_SIZE  16
    void hmac_md5(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha1(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha224(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha256(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha384(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha512(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);

#ifdef  __cplusplus
}
#endif /* __cplusplus */
#endif /* _CIPHER_HMAC_ALL_H */


text:
/* */
"format cjs";
/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */
import { Pipe } from '@angular/core';
import { InvalidPipeArgumentError } from './invalid_pipe_argument_error';
/**
 * \@ngModule CommonModule
 * \@whatItDoes Generic selector that displays the string that matches the current value.
 * \@howToUse `expression | i18nSelect:mapping`
 * \@description
 *
 *  Where `mapping` is an object that indicates the text that should be displayed
 *  for different values of the provided `expression`.
 *  If none of the keys of the mapping match the value of the `expression`, then the content
 *  of the `other` key is returned when present, otherwise an empty string is returned.
 *
 *  ## Example
 *
 * {\@example common/pipes/ts/i18n_pipe.ts region='I18nSelectPipeComponent'}
 *
 *  \@experimental
 */
export var I18nSelectPipe = (function () {
    function I18nSelectPipe() {
    }
    /**
     * @param {?} value
     * @param {?} mapping
     * @return {?}
     */
    I18nSelectPipe.prototype.transform = function (value, mapping) {
        if (value == null)
            return '';
        if (typeof mapping !== 'object' || typeof value !== 'string') {
            throw new InvalidPipeArgumentError(I18nSelectPipe, mapping);
        }
        if (mapping.hasOwnProperty(value)) {
            return mapping[value];
        }
        if (mapping.hasOwnProperty('other')) {
            return mapping['other'];
        }
        return '';
    };
    I18nSelectPipe.decorators = [
        { type: Pipe, args: [{ name: 'i18nSelect', pure: true },] },
    ];
    /** @nocollapse */
    I18nSelectPipe.ctorParameters = function () { return []; };
    return I18nSelectPipe;
}());
function I18nSelectPipe_tsickle_Closure_declarations() {
    /** @type {?} */
    I18nSelectPipe.decorators;
    /**
     * @nocollapse
     * @type {?}
     */
    I18nSelectPipe.ctorParameters;
}
//# sourceMappingURL=i18n_select_pipe.js.map


text:
<?php

namespace Benchmark\Resources;

use Benchmark\Entities\FortuneEntity;
use Benchmark\Entities\Message;
use Hamlet\Database\Database;
use Hamlet\Database\Procedure;
use Hamlet\Http\Requests\Request;
use Hamlet\Http\Responses\Response;
use Hamlet\Http\Responses\SimpleOKResponse;

class FortuneResource extends DbResource
{
    /** @var Procedure */
    private $procedure;

    public function __construct(Database $database)
    {
        parent::__construct($database);
        $query = '
            SELECT id,
                   message
              FROM Fortune
        ';
        $this->procedure = $this->database->prepare($query);
    }

    public function getResponse(Request $request): Response
    {
        $messages = $this->procedure->processAll()
            ->selectAll()->cast(Message::class)
            ->collectAll();

        $messages[] = new Message(0, 'Additional fortune added at request time.');
        usort($messages, function (Message $a, Message $b): int {
            return $a->message() <=> $b->message();
        });
        return new SimpleOKResponse(new FortuneEntity($messages));
    }
}


text:
<?xml version="1.0" ?>
<odoo>

        <record id="account_bank_statement_import_view" model="ir.ui.view">
            <field name="name">Import Bank Statements</field>
            <field name="model">account.bank.statement.import</field>
            <field name="priority">1</field>
            <field name="arch" type="xml">
                <form string="Import Bank Statements">

Select a bank statement file to import

Download a bank statement from your bank and import it here. Supported formats:

                    <field name="data_file" placeholder="Choose a file to import..."/>

                        <button name="import_file" string="_Import" type="object" class="btn-primary" />
                        <button string="Cancel" class="btn-default" special="cancel"/>

                </form>
            </field>
        </record>

        <record id="action_account_bank_statement_import" model="ir.actions.act_window">
            <field name="name">Import</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">account.bank.statement.import</field>
            <field name="view_type">form</field>
            <field name="view_mode">form</field>
            <field name="target">new</field>
            <field name="view_id" ref="account_bank_statement_import_view"/>
        </record>

    <record id="journal_dashboard_view_inherit" model="ir.ui.view">
        <field name="name">account.journal.dashboard.kanban.inherit</field>
        <field name="model">account.journal</field>
        <field name="inherit_id" ref="account.account_journal_dashboard_kanban_view"/>
        <field name="arch" type="xml">
            <xpath expr='//div[@name="bank_journal_default_cta"]' position='inside'>

<button t-if="dashboard.number_to_reconcile == 0" type="object" name="import_statement" class="btn btn-primary btn-sm">Import Statement</button>
                 0" type="object" name="import_statement" class="oe_inline">Import Statement
            </xpath>
            <xpath expr='//div[@name="bank_journal_cta"]' position='inside'>
                <button t-if="dashboard.bank_statements_source == 'file_import' && dashboard.number_to_reconcile == 0" type="object" name="import_statement" class="btn btn-primary btn-sm">Import Statement</button>
                 0" type="object" name="import_statement" class="oe_inline">Import Statement
            </xpath>
            <xpath expr='//div[@name="bank_cash_commands"]' position="after">
                <t t-if="journal_type == 'bank'">
                    Import Statement
                </t>
            </xpath>
        </field>
    </record>
</odoo>


text:
const path = require('path')
const fs = require('fs-extra')
const exec = require('./util/exec')
const logger = require('./util/logger')
const runConfigs = require('./run')
const addComment = require('./add-comment')
const actionInfo = require('./prepare/action-info')()
const { mainRepoDir, diffRepoDir } = require('./constants')
const loadStatsConfig = require('./prepare/load-stats-config')
const {
  cloneRepo,
  checkoutRef,
  mergeBranch,
  getCommitId,
  linkPackages,
  getLastStable,
} = require('./prepare/repo-setup')(actionInfo)

const allowedActions = new Set(['synchronize', 'opened'])

if (!allowedActions.has(actionInfo.actionName) && !actionInfo.isRelease) {
  logger(
    `Not running for ${actionInfo.actionName} event action on repo: ${actionInfo.prRepo} and ref ${actionInfo.prRef}`
  )
  process.exit(0)
}

;(async () => {
  try {
    if (await fs.pathExists(path.join(__dirname, '../SKIP_NEXT_STATS.txt'))) {
      console.log(
        'SKIP_NEXT_STATS.txt file present, exiting stats generation..'
      )
      process.exit(0)
    }

    const { stdout: gitName } = await exec(
      'git config user.name && git config user.email'
    )
    console.log('git author result:', gitName)

    // clone PR/newer repository/ref first to get settings
    if (!actionInfo.skipClone) {
      await cloneRepo(actionInfo.prRepo, diffRepoDir)
      await checkoutRef(actionInfo.prRef, diffRepoDir)
    }

    if (actionInfo.isRelease) {
      process.env.STATS_IS_RELEASE = 'true'
    }

    // load stats config from allowed locations
    const { statsConfig, relativeStatsAppDir } = loadStatsConfig()

    if (actionInfo.isLocal && actionInfo.prRef === statsConfig.mainBranch) {
      throw new Error(
        `'GITHUB_REF' can not be the same as mainBranch in 'stats-config.js'.\n` +
          `This will result in comparing against the same branch`
      )
    }

    if (actionInfo.isLocal) {
      // make sure to use local repo location instead of the
      // one provided in statsConfig
      statsConfig.mainRepo = actionInfo.prRepo
    }

    // clone main repository/ref
    if (!actionInfo.skipClone) {
      await cloneRepo(statsConfig.mainRepo, mainRepoDir)
      await checkoutRef(statsConfig.mainBranch, mainRepoDir)
    }
    /* eslint-disable-next-line */
    actionInfo.commitId = await getCommitId(diffRepoDir)
    let mainNextSwcVersion

    if (!actionInfo.skipClone) {
      if (actionInfo.isRelease) {
        logger('Release detected, resetting mainRepo to last stable tag')
        const lastStableTag = await getLastStable(mainRepoDir, actionInfo.prRef)
        mainNextSwcVersion = {
          '@next/swc-linux-x64-gnu': lastStableTag,
        }
        if (!lastStableTag) throw new Error('failed to get last stable tag')
        console.log('using latestStable', lastStableTag)
        await checkoutRef(lastStableTag, mainRepoDir)

        /* eslint-disable-next-line */
        actionInfo.lastStableTag = lastStableTag
        /* eslint-disable-next-line */
        actionInfo.commitId = await getCommitId(diffRepoDir)

        if (!actionInfo.customCommentEndpoint) {
          /* eslint-disable-next-line */
          actionInfo.commentEndpoint = `https://api.github.com/repos/${statsConfig.mainRepo}/commits/${actionInfo.commitId}/comments`
        }
      } else if (statsConfig.autoMergeMain) {
        logger('Attempting auto merge of main branch')
        await mergeBranch(statsConfig.mainBranch, mainRepoDir, diffRepoDir)
      }
    }

    let mainRepoPkgPaths
    let diffRepoPkgPaths

    // run install/initialBuildCommand
    const repoDirs = [mainRepoDir, diffRepoDir]

    for (const dir of repoDirs) {
      logger(`Running initial build for ${dir}`)
      if (!actionInfo.skipClone) {
        const usePnpm = await fs.pathExists(path.join(dir, 'pnpm-lock.yaml'))
        let buildCommand = `cd ${dir}${
          !statsConfig.skipInitialInstall
            ? usePnpm
              ? ' && pnpm install && pnpm run build'
              : ' && yarn install --network-timeout 1000000'
            : ''
        }`

        if (statsConfig.initialBuildCommand) {
          buildCommand += ` && ${statsConfig.initialBuildCommand}`
        }
        // allow 5 minutes node_modules install + building all packages
        // in case of noisy environment slowing down initial repo build
        await exec(buildCommand, false, { timeout: 5 * 60 * 1000 })
      }

      await fs
        .copy(
          path.join(__dirname, '../native'),
          path.join(dir, 'packages/next-swc/native')
        )
        .catch(console.error)

      logger(`Linking packages in ${dir}`)
      const isMainRepo = dir === mainRepoDir
      const pkgPaths = await linkPackages(
        dir,
        isMainRepo ? mainNextSwcVersion : undefined
      )

      if (isMainRepo) mainRepoPkgPaths = pkgPaths
      else diffRepoPkgPaths = pkgPaths
    }

    // run the configs and post the comment
    const results = await runConfigs(statsConfig.configs, {
      statsConfig,
      mainRepoPkgPaths,
      diffRepoPkgPaths,
      relativeStatsAppDir,
    })
    await addComment(results, actionInfo, statsConfig)
    logger('finished')
    process.exit(0)
  } catch (err) {
    console.error('Error occurred generating stats:')
    console.error(err)
    process.exit(1)
  }
})()


text:
    <button type="button" class="close" ng-click="cancel()">×Cancel</button>

{{params.title}}

    <form name="deleteForm" novalidate>

This action CANNOT be undone. This will permanently delete '{{params.key}}'. Please type in '{{params.key}}' to confirm deletion.

        <input type="text" class="form-control" ng-model="confirmKey" match="params.key" required>
    </form>

    <button type="button" class="btn btn-danger" ng-disabled="deleteForm.$pristine || deleteForm.$invalid" ng-click="delete()">Delete Permanently</button>


text:
require "thor/group"
require "yaml"

class GatewayGenerator < ActiveMerchantGenerator
  source_root File.expand_path("..", __FILE__)

  def generate
    template "templates/gateway.rb", gateway_file
    template "templates/gateway_test.rb", gateway_test_file
    template "templates/remote_gateway_test.rb", remote_gateway_test_file

    before = (next_identifier ? /(?:\n#[^\n]*)*\n#{next_identifier}:\s*\n/ : /\z/)
    p before
    inject_into_file(fixtures_file, <<EOYAML, before: before)

# Working credentials, no need to replace
#{identifier}:
  some_credential: SOMECREDENTIAL
  another_credential: ANOTHERCREDENTIAL
EOYAML
  end

  protected

  def gateway_file
    "lib/active_merchant/billing/gateways/#{identifier}.rb"
  end

  def gateway_test_file
    "test/unit/gateways/#{identifier}_test.rb"
  end

  def remote_gateway_test_file
    "test/remote/gateways/remote_#{identifier}_test.rb"
  end

  def fixtures_file
    "test/fixtures.yml"
  end

  def next_identifier
    fixtures = (YAML.load(File.read(fixtures_file)).keys + [identifier]).uniq.sort
    fixtures[fixtures.sort.index(identifier)+1]
  end
end


text:
    <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
    <title>isPositionVisible</title>
    <link href="../../images/logo-icon.svg" rel="icon" type="image/svg">

    <link href="../../styles/style.css" rel="Stylesheet">
    <link href="../../styles/logo-styles.css" rel="Stylesheet">
    <link href="../../styles/jetbrains-mono.css" rel="Stylesheet">
    <link href="../../styles/main.css" rel="Stylesheet">

zircon.core/org.hexworks.zircon.internal.util/isPositionVisible

<button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button>

is<wbr></wbr>Position<wbr></wbr>Visible

fun AnyGameAreaState.isPositionVisible(position3D: Position3D): Boolean
Content copied to clipboard

Sources

<a data-name="%5Borg.hexworks.zircon.internal.util%2F%2FisPositionVisible%2Forg.hexworks.zircon.internal.game.GameAreaState%5Borg.hexworks.zircon.api.data.Tile%2Corg.hexworks.zircon.api.data.Block%5Borg.hexworks.zircon.api.data.Tile%5D%5D%23org.hexworks.zircon.api.data.Position3D%2FPointingToDeclaration%2F%5D%2FSource%2F-755115832" anchor-label="https://github.com/Hexworks/zircon/tree/master/zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/util/Extensions.kt#L16" id="%5Borg.hexworks.zircon.internal.util%2F%2FisPositionVisible%2Forg.hexworks.zircon.internal.game.GameAreaState%5Borg.hexworks.zircon.api.data.Tile%2Corg.hexworks.zircon.api.data.Block%5Borg.hexworks.zircon.api.data.Tile%5D%5D%23org.hexworks.zircon.api.data.Position3D%2FPointingToDeclaration%2F%5D%2FSource%2F-755115832" data-filterable-set=":zircon.core:dokkaHtml/commonMain">

(source)

Link copied to clipboard

© 2020 CopyrightSponsored and developed by dokka


text:
import type { GatsbyConfig } from "gatsby"

const config: GatsbyConfig = {
  siteMetadata: {
    title: `using-gatsby-script`,
    siteUrl: `https://www.yourdomain.tld`,
  },
  plugins: [],
  /**
   * Add the CDN URL for the `marked` module to the Partytown proxy allowlist
   * so we can load it with the `off-main-thread` strategy.
   *
   * This is required, otherwise the request will 404.
   */
  partytownProxiedURLs: [`https://cdn.jsdelivr.net/npm/marked/marked.min.js`],
}

export default config


text:
const os = require('os')
const path = require('path')
const HappyPack = require('happypack')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  devtool: 'source-map',
  mode: 'development',
  context: __dirname,
  entry: './entry.ts',
  output: {
    path: path.join(__dirname, 'dist')
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  module: {
    rules: [
      {
        test: /\.(t|j)sx?$/,
        use: 'happypack/loader?id=ts',
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    new HappyPack({
      id: 'ts',
      loaders: [
        {
          loader: 'ts-loader',
          options: {
            happyPackMode: true,
            transpileOnly: true,
          },
        },
      ],
      threadPool: HappyPack.ThreadPool({ size: os.cpus().length }),
    }),
    new HtmlWebpackPlugin({
      title: `Layout Dev Tool`,
      inject: true,
    }),
  ]
}


text:
module Fog
  module Compute
    class Cloudstack

      class Real
        # Updates a port forwarding rule.  Only the private port and the virtual machine can be updated.
        #
        # {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.4/root_admin/updatePortForwardingRule.html]
        def update_port_forwarding_rule(*args)
          options = {}
          if args[0].is_a? Hash
            options = args[0]
            options.merge!('command' => 'updatePortForwardingRule')
          else
            options.merge!('command' => 'updatePortForwardingRule',
            'id' => args[0])
          end
          request(options)
        end
      end

    end
  end
end


text:
class StringUtil {
    static withoutTrailingDigits (s) {
        let i = s.length - 1;
        while ((i >= 0) && ('0123456789'.indexOf(s.charAt(i)) > -1)) i--;
        return s.slice(0, i + 1);
    }

    static unusedName (name, existingNames) {
        if (existingNames.indexOf(name) < 0) return name;
        name = StringUtil.withoutTrailingDigits(name);
        let i = 2;
        while (existingNames.indexOf(name + i) >= 0) i++;
        return name + i;
    }

    /**
     * Split a string on the first occurrence of a split character.
     * @param {string} text - the string to split.
     * @param {string} separator - split the text on this character.
     * @returns {[string, string]} - the two parts of the split string, or [text, null] if no split character found.
     * @example
     * // returns ['foo', 'tar.gz']
     * splitFirst('foo.tar.gz', '.');
     * @example
     * // returns ['foo', null]
     * splitFirst('foo', '.');
     * @example
     * // returns ['foo', '']
     * splitFirst('foo.', '.');
     */
    static splitFirst (text, separator) {
        const index = text.indexOf(separator);
        if (index >= 0) {
            return [text.substring(0, index), text.substring(index + 1)];
        }
        return [text, null];

    }
}

module.exports = StringUtil;


text:
raise LoadError, "Ruby 1.9.1 only" if RUBY_VERSION < '1.9.1'

require 'sinatra/base'
require 'fiber'

$LOAD_PATH << File.dirname(__FILE__) + '/../lib'

require 'rack/fiber_pool'

# rackup -s thin app.rb
# http://localhost:9292/test
class App < Sinatra::Base

  use Rack::FiberPool

  set :root, File.dirname(__FILE__)

  get '/test' do
    content_type "text/plain"
    body "Hello world from #{Fiber.current}"
  end

end


text:
/**
 * This package contains various views which we use to build user interfaces
 * for editing avro schema based databases.
 */
package interdroid.vdb.avro.view;


text:
[`ScrollView`](scrollview.html)是一个通用的可滚动的容器,你可以在其中放入多个组件和视图,而且这些组件并不需要是同类型的。ScrollView不仅可以垂直滚动,还能水平滚动(通过`horizontal`属性来设置)。

下面的示例代码创建了一个垂直滚动的`ScrollView`,其中还混杂了图片和文字组件。

注:下面的这个`./img/favicon.png`并不实际存在,请自己准备图片素材,并改为相对应的正确路径,具体请参考[图片文档](images.html)。

```ReactNativeWebPlayer
import React, { Component } from 'react';
import{ AppRegistry, ScrollView, Image, Text, View } from 'react-native'

class IScrolledDownAndWhatHappenedNextShockedMe extends Component {
  render() {
      return(
        <ScrollView>
          <Text style={ {fontSize:96} }>Scroll me plz</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={ {fontSize:96} }>If you like</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={ {fontSize:96} }>Scrolling down</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={ {fontSize:96} }>What's the best</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={ {fontSize:96} }>Framework around?</Text>
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Image source={require('./img/favicon.png')} />
          <Text style={ {fontSize:80} }>React Native</Text>
        </ScrollView>
    );
  }
}

// 注册应用(registerComponent)后才能正确渲染
// 注意:只把应用作为一个整体注册一次,而不是每个组件/模块都注册
AppRegistry.registerComponent(
  'IScrolledDownAndWhatHappenedNextShockedMe',
  () => IScrolledDownAndWhatHappenedNextShockedMe);
```

`ScrollView`适合用来显示数量不多的滚动元素。放置在`ScollView`中的所有组件都会被渲染,哪怕有些组件因为内容太长被挤出了屏幕外。如果你需要显示较长的滚动列表,那么应该使用功能差不多但性能更好的`ListView`组件。下面我们来看看[如何使用ListView](using-a-listview.html)。


text:
describe('jasmine-node-flat', function(){
  it('should pass', function(){
    expect(1+2).toEqual(3);
  });
});

describe('Testing some characters', function()  {
    var chars = ['&', '\'', '"', '<', '>'];
    for(var i = 0; i < chars.length; i+=1)  {
        currentChar = chars[i];
        it('should reject ' + currentChar, (function(currentChar)  {
            expect(false).toEqual(false);
        })(currentChar));
    }
});

describe('Testing waitsfor functionality', function() {
    it("Runs and then waitsFor", function() {
        runs(function() {
            1+1;
        });
        waitsFor(function() {
            return true === false;
        }, "the impossible", 1000);
        runs(function() {
            expect(true).toBeTruthy();
        });
    });
});

describe('root', function () {

  describe('nested', function () {

    xit('nested statement', function () {
      expect(1).toBeTruthy();
    });

  });

  it('root statement', function () {
    expect(1).toBeTruthy();
  });

});

describe("Top level describe block", function() {
  it("first it block in top level describe", function() {
    expect(true).toEqual(true);
  });
  describe("Second level describe block", function() {
    it("first it block in second level describe", function() {
      expect(true).toBe(true);
    });
  });
  it("second it block in top level describe", function() {
    expect(true).toEqual(true);
  });
});

describe('async', function () {

    var request = function (str, func) {
        func('1', '2', 'hello world');
    };

    it("should respond with hello world", function(done) {
        request("http://localhost:3000/hello", function(error, response, body){
            expect(body).toEqual("hello world");
            done();
        });
    });

    it("should respond with hello world", function(done) {
        request("http://localhost:3000/hello", function(error, response, body){
            expect(body).toEqual("hello world");
            done();
        });
    }, 250); // timeout after 250 ms

});


text:
package gov.va.oia.terminology.converters.sharedUtils;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import org.ihtsdo.otf.tcc.api.uuid.UuidT5Generator;

public class UuidFromName
{

	/**
	 * This is how to get a UUID that the WB expects from a string in a pom....
	 * @param args
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 */
	public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException
	{
		System.out.println(UuidT5Generator.get(UuidT5Generator.PATH_ID_FROM_FS_DESC, "VA JIF Terminology Workbench development path"));
		System.out.println(UuidT5Generator.get(UuidT5Generator.PATH_ID_FROM_FS_DESC, "VA JIF Terminology Workbench development origin"));
		System.out.println(UuidT5Generator.get(UuidT5Generator.PATH_ID_FROM_FS_DESC, "VA JIF Terminology Workbench release candidate path"));
		System.out.println(UuidT5Generator.get(UuidT5Generator.PATH_ID_FROM_FS_DESC, "Project Refsets"));

	}

}


text:
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed 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.

package google.registry.model.rde;

import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.rde.RdeMode.FULL;
import static google.registry.model.rde.RdeRevision.getNextRevision;
import static google.registry.model.rde.RdeRevision.saveRevision;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.junit.jupiter.api.Assertions.assertThrows;

import google.registry.model.EntityTestCase;
import org.joda.time.DateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/** Unit tests for {@link RdeRevision}. */
public class RdeRevisionTest extends EntityTestCase {

  public RdeRevisionTest() {
    super(JpaEntityCoverageCheck.ENABLED);
  }

  @BeforeEach
  void beforeEach() {
    fakeClock.setTo(DateTime.parse("1984-12-18TZ"));
  }

  @Test
  void testGetNextRevision_objectDoesntExist_returnsZero() {
    tm().transact(
            () -> assertThat(getNextRevision("torment", fakeClock.nowUtc(), FULL)).isEqualTo(0));
  }

  @Test
  void testGetNextRevision_objectExistsAtZero_returnsOne() {
    save("sorrow", fakeClock.nowUtc(), FULL, 0);
    tm().transact(
            () -> assertThat(getNextRevision("sorrow", fakeClock.nowUtc(), FULL)).isEqualTo(1));
  }

  @Test
  void testSaveRevision_objectDoesntExist_newRevisionIsZero_nextRevIsOne() {
    tm().transact(() -> saveRevision("despondency", fakeClock.nowUtc(), FULL, 0));
    tm().transact(
            () ->
                assertThat(getNextRevision("despondency", fakeClock.nowUtc(), FULL)).isEqualTo(1));
  }

  @Test
  void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() {
    IllegalArgumentException thrown =
        assertThrows(
            IllegalArgumentException.class,
            () -> tm().transact(() -> saveRevision("despondency", fakeClock.nowUtc(), FULL, 1)));
    assertThat(thrown)
        .hasMessageThat()
        .isEqualTo(
            "Couldn't find existing RDE revision despondency_1984-12-18_full "
                + "when trying to save new revision 1");
  }

  @Test
  void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() {
    save("melancholy", fakeClock.nowUtc(), FULL, 0);
    IllegalArgumentException thrown =
        assertThrows(
            IllegalArgumentException.class,
            () -> tm().transact(() -> saveRevision("melancholy", fakeClock.nowUtc(), FULL, 0)));
    assertThat(thrown).hasMessageThat().contains("object already created");
  }

  @Test
  void testSaveRevision_objectExistsAtZero_newRevisionIsOne_nextRevIsTwo() {
    DateTime startOfDay = fakeClock.nowUtc().withTimeAtStartOfDay();
    save("melancholy", startOfDay, FULL, 0);
    fakeClock.advanceOneMilli();
    tm().transact(() -> saveRevision("melancholy", startOfDay, FULL, 1));
    tm().transact(() -> assertThat(getNextRevision("melancholy", startOfDay, FULL)).isEqualTo(2));
  }

  @Test
  void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() {
    save("melancholy", fakeClock.nowUtc(), FULL, 0);
    IllegalArgumentException thrown =
        assertThrows(
            IllegalArgumentException.class,
            () -> tm().transact(() -> saveRevision("melancholy", fakeClock.nowUtc(), FULL, 2)));
    assertThat(thrown)
        .hasMessageThat()
        .contains("RDE revision object should be at revision 1 but was");
  }

  @Test
  void testSaveRevision_negativeRevision_throwsIae() {
    IllegalArgumentException thrown =
        assertThrows(
            IllegalArgumentException.class,
            () -> tm().transact(() -> saveRevision("melancholy", fakeClock.nowUtc(), FULL, -1)));
    assertThat(thrown).hasMessageThat().contains("Negative revision");
  }

  @Test
  void testSaveRevision_callerNotInTransaction_throwsIse() {
    IllegalStateException thrown =
        assertThrows(
            IllegalStateException.class, () -> saveRevision("frenzy", fakeClock.nowUtc(), FULL, 1));
    assertThat(thrown).hasMessageThat().contains("transaction");
  }

  public static void save(String tld, DateTime date, RdeMode mode, int revision) {
    RdeRevision object = RdeRevision.create(tld, date.toLocalDate(), mode, revision);
    tm().transact(() -> tm().put(object));
  }
}


text:
require "i18n"
require "ibandit/version"
require "ibandit/errors"
require "ibandit/constants"
require "ibandit/iban"
require "ibandit/german_details_converter"
require "ibandit/sweden/local_details_converter"
require "ibandit/sweden/validator"
require "ibandit/sweden/bank_lookup"
require "ibandit/iban_splitter"
require "ibandit/iban_assembler"
require "ibandit/pseudo_iban_assembler"
require "ibandit/pseudo_iban_splitter"
require "ibandit/local_details_cleaner"
require "ibandit/check_digit"

I18n.load_path += Dir[File.expand_path("../config/locales/*.{rb,yml}",
                                       __dir__)]

module Ibandit
  class << self
    attr_accessor :bic_finder, :modulus_checker

    def find_bic(country_code, national_id)
      raise NotImplementedError, "BIC finder is not defined" unless @bic_finder

      @bic_finder.call(country_code, national_id)
    end

    def structures
      @structures ||= YAML.safe_load(
        File.read(File.expand_path("../data/structures.yml", __dir__)),
        permitted_classes: [Range, Symbol],
      )
    end

    def translate(key, options = {})
      I18n.translate(key, scope: [:ibandit], **options)
    end
  end
end


text:
module CreateTriggerMenuMixin
  def create_metric_alert_item
    cmi = Java::javafx::scene::control::MenuItem.new 'New trigger...'
    cmi.on_action do
      item = tree_view.selectionModel.selectedItem
      stage = tree_view.scene.window

      type = item.raw_item.type.downcase
      id = item.raw_item.hawkular_metric_id
      if type != 'availability'
        text = "define trigger \"trigger-#{id}\"\n (threshold #{type} \"#{id}\" \n > XXX )"
      else
        text = "define trigger \"trigger-#{id}\"\n (availability  \"#{id}\" \n is XXX )"
      end

      ::HawkHelper.run_synth_metric_popup stage, :TRIGGER, text
    end
    cmi
  end
end


text:
package org.juice4j.caching;

/**
 * Defines a common behavior to the generation of cache element key component strings.
 * @see {@link ElementKeyGenerator} - documentation about this API
 * @param <T> Type of the object expected to be parsed into a component key string.
 * @author Rafael Noronha
 */
public interface ElementKeyComponentGenerator<TK> {

	/**
	 * Returns a static representation for the key component generated by this object.
	 * @return The static representation string.
	 */
	String staticRepresentation();

	/**
	 * Generates a string for this element key component.
	 * @param obj Object that will be parsed into a string.
	 * @return Generated string.
	 */
	String generate(TK typedKeyObject);
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CopyToClipboard = void 0;

var _react = _interopRequireDefault(require("react"));

var _copyToClipboard = _interopRequireDefault(require("copy-to-clipboard"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var CopyToClipboard =
/*#__PURE__*/
function (_React$PureComponent) {
  _inherits(CopyToClipboard, _React$PureComponent);

  function CopyToClipboard() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, CopyToClipboard);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(CopyToClipboard)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_this), "onClick", function (event) {
      var _this$props = _this.props,
          text = _this$props.text,
          onCopy = _this$props.onCopy,
          children = _this$props.children,
          options = _this$props.options;

      var elem = _react["default"].Children.only(children);

      var result = (0, _copyToClipboard["default"])(text, options);

      if (onCopy) {
        onCopy(text, result);
      } // Bypass onClick if it was present

      if (elem && elem.props && typeof elem.props.onClick === 'function') {
        elem.props.onClick(event);
      }
    });

    return _this;
  }

  _createClass(CopyToClipboard, [{
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          _text = _this$props2.text,
          _onCopy = _this$props2.onCopy,
          _options = _this$props2.options,
          children = _this$props2.children,
          props = _objectWithoutProperties(_this$props2, ["text", "onCopy", "options", "children"]);

      var elem = _react["default"].Children.only(children);

      return _react["default"].cloneElement(elem, _objectSpread({}, props, {
        onClick: this.onClick
      }));
    }
  }]);

  return CopyToClipboard;
}(_react["default"].PureComponent);

exports.CopyToClipboard = CopyToClipboard;

_defineProperty(CopyToClipboard, "defaultProps", {
  onCopy: undefined,
  options: undefined
});


text:
package org.cloudcompaas.sla.wsag.monitor.selfmanagement;

import org.ogf.graap.wsag.server.accounting.IAccountingContext;

/**
 * @author angarg12
 *
 */
public interface ICorrectiveAction {
	public String getActionName();
	public void apply(IAccountingContext context);
	public int getThreshold();
}


text:
EditSearchEngineController::EditSearchEngineController(
    const TemplateURL* template_url,
    EditSearchEngineControllerDelegate* edit_keyword_delegate,
    Profile* profile)
    : template_url_(template_url),
      edit_keyword_delegate_(edit_keyword_delegate),
      profile_(profile) {
  DCHECK(profile_);
}

bool EditSearchEngineController::IsTitleValid(
    const string16& title_input) const {
  return !CollapseWhitespace(title_input, true).empty();
}

bool EditSearchEngineController::IsURLValid(
    const std::string& url_input) const {
  std::string url = GetFixedUpURL(url_input);
  if (url.empty())
    return false;

  // Use TemplateURLRef to extract the search placeholder.
  TemplateURLRef template_ref(url, 0, 0);
  if (!template_ref.IsValid())
    return false;

  if (!template_ref.SupportsReplacement()) {
    // If this is the default search engine, there must be a search term
    // placeholder.
    if (template_url_ ==
        profile_->GetTemplateURLModel()->GetDefaultSearchProvider())
      return false;
    return GURL(url).is_valid();
  }

  // If the url has a search term, replace it with a random string and make
  // sure the resulting URL is valid. We don't check the validity of the url
  // with the search term as that is not necessarily valid.
  return GURL(template_ref.ReplaceSearchTerms(TemplateURL(), ASCIIToUTF16("a"),
      TemplateURLRef::NO_SUGGESTIONS_AVAILABLE, string16())).is_valid();
}

bool EditSearchEngineController::IsKeywordValid(
    const string16& keyword_input) const {
  string16 keyword_input_trimmed(CollapseWhitespace(keyword_input, true));
  if (keyword_input_trimmed.empty())
    return false;  // Do not allow empty keyword.
  const TemplateURL* turl_with_keyword =
      profile_->GetTemplateURLModel()->GetTemplateURLForKeyword(
          keyword_input_trimmed);
  return (turl_with_keyword == NULL || turl_with_keyword == template_url_);
}

void EditSearchEngineController::AcceptAddOrEdit(
    const string16& title_input,
    const string16& keyword_input,
    const std::string& url_input) {
  std::string url_string = GetFixedUpURL(url_input);
  DCHECK(!url_string.empty());

  const TemplateURL* existing =
      profile_->GetTemplateURLModel()->GetTemplateURLForKeyword(
          keyword_input);
  if (existing &&
      (!edit_keyword_delegate_ || existing != template_url_)) {
    // An entry may have been added with the same keyword string while the
    // user edited the dialog, either automatically or by the user (if we're
    // confirming a JS addition, they could have the Options dialog open at the
    // same time). If so, just ignore this add.
    // TODO(pamg): Really, we should modify the entry so this later one
    // overwrites it. But we don't expect this case to be common.
    CleanUpCancelledAdd();
    return;
  }

  if (!edit_keyword_delegate_) {
    // Confiming an entry we got from JS. We have a template_url_, but it
    // hasn't yet been added to the model.
    DCHECK(template_url_);
    // const_cast is ugly, but this is the same thing the TemplateURLModel
    // does in a similar situation (updating an existing TemplateURL with
    // data from a new one).
    TemplateURL* modifiable_url = const_cast<TemplateURL*>(template_url_);
    modifiable_url->set_short_name(title_input);
    modifiable_url->set_keyword(keyword_input);
    modifiable_url->SetURL(url_string, 0, 0);
    // TemplateURLModel takes ownership of template_url_.
    profile_->GetTemplateURLModel()->Add(modifiable_url);
    UserMetrics::RecordAction(UserMetricsAction("KeywordEditor_AddKeywordJS"),
                              profile_);
  } else {
    // Adding or modifying an entry via the Delegate.
    edit_keyword_delegate_->OnEditedKeyword(template_url_,
                                            title_input,
                                            keyword_input,
                                            url_string);
  }
}

void EditSearchEngineController::CleanUpCancelledAdd() {
  if (!edit_keyword_delegate_ && template_url_) {
    // When we have no Delegate, we know that the template_url_ hasn't yet been
    // added to the model, so we need to clean it up.
    delete template_url_;
    template_url_ = NULL;
  }
}

std::string EditSearchEngineController::GetFixedUpURL(
    const std::string& url_input) const {
  std::string url;
  TrimWhitespace(TemplateURLRef::DisplayURLToURLRef(UTF8ToUTF16(url_input)),
                 TRIM_ALL, &url);
  if (url.empty())
    return url;

  // Parse the string as a URL to determine the scheme. If we need to, add the
  // scheme. As the scheme may be expanded (as happens with {google:baseURL})
  // we need to replace the search terms before testing for the scheme.
  TemplateURL t_url;
  t_url.SetURL(url, 0, 0);
  std::string expanded_url =
      t_url.url()->ReplaceSearchTerms(t_url, ASCIIToUTF16("x"), 0, string16());
  url_parse::Parsed parts;
  std::string scheme(
      URLFixerUpper::SegmentURL(expanded_url, &parts));
  if (!parts.scheme.is_valid()) {
    scheme.append("://");
    url.insert(0, scheme);
  }

  return url;
}


text:
package org.kie.remote.command;

import java.io.Serializable;
import java.util.UUID;

public class HaltCommand extends AbstractCommand implements VisitableCommand, Serializable {

    public HaltCommand() {
        super(UUID.randomUUID().toString());
    }

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

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

    @Override
    public String toString() {
        return "Halt of " + getId();
    }

}


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

    angular.module('calendar')
    .config(runConfig);

    /* @ngInject */
    function runConfig($routeProvider) {
        $routeProvider.otherwise( { redirectTo: '/events' } );
    }

})();


text:
Abductive Event Calculus Planners
This is the companion website to my paper An Abductive Event Calculus Planner. The website contains the following.

	Version 4.2 of the planner. This is the bare, uncommented, pure but inefficient version given in the appendix of the paper.

	Version 1.9a of the planner. This is the faster version that was used for the benchmarks described in Section 6 of the paper. It's reasonably efficient at partial-order planning, but doesn't handle hierarchical planning well.
	Version 1.15 of the planner. This version of the planner uses an iterative deepening search strategy, and has special code for hierarchical decomposition. It's less efficient for straight partial-order planning than Version 1.9a.
	Code for each of the examples given in the paper. The mail delivery example only works with Version 1.15 of the planner. The other two examples work with all three versions.

	The shopping trip example
	The plant safety example
	The mail delivery example

	Code for the two benchmark examples described in Section 7 of the paper.

	Test A
	Test B

All the code is written in LPA MacProlog 32, but should be easy to port to other Prolog systems.

Click here to get to my home page.