text:
from setuptools import setup, Command

import os, sys, re

class RunTestsCommand(Command):
    description = "Test command to run testr in virtualenv"
    user_options = [
        ('coverage', 'c',
         "Generate code coverage report"),
        ]
    boolean_options = ['coverage']
    def initialize_options(self):
        self.coverage = False
    def finalize_options(self):
        pass
    def run(self):
        logfname = 'test.log'
        args = '-V'
        if self.coverage:
            logfname = 'coveragetest.log'
            args += ' -c'
        rc_sig = os.system('./run_tests.sh %s' % args)
        if rc_sig >> 8:
            os._exit(rc_sig>>8)
        with open(logfname) as f:
            if not re.search('\nOK', ''.join(f.readlines())):
                os._exit(1)

setup(
    name='vnc_api',
    version='0.1dev',
    packages=['vnc_api',
              'vnc_api.gen',
              'vnc_api.gen.heat',
              'vnc_api.gen.heat.resources',
              'vnc_api.gen.heat.template',
              'vnc_api.gen.heat.env',
             ],
    long_description="VNC API Library Package",
    package_data={'': ['*.yaml', '*.env']},
    install_requires=[
        'requests>=1.1.0'
    ],
    cmdclass={
       'run_tests': RunTestsCommand,
    },
)

redpajama_set_name: RedPajamaGithub


text:
const Promise = require('bluebird');

const { ActionTransport } = require('@microfleet/plugin-router');

const redisKey = require('../../utils/key');
const handlePipeline = require('../../utils/pipeline-error');
const { checkMFA } = require('../../utils/mfa');
const {
  USERS_DATA,
  USERS_MFA_FLAG,
  USERS_MFA_RECOVERY,
  MFA_TYPE_REQUIRED,
} = require('../../constants');

async function removeData(userId) {
  return this.redis
    .pipeline()
    .del(redisKey(userId, USERS_MFA_RECOVERY))
    .hdel(redisKey(userId, USERS_DATA), USERS_MFA_FLAG)
    .exec()
    .then(handlePipeline)
    .return({ enabled: false });
}

/**
 * @api {amqp} <prefix>.detach Detach
 * @apiVersion 1.0.0
 * @apiName Detach
 * @apiGroup Users
 *
 * @apiDescription Allows to detach secret key and recovery code from user's account,
 * basically disables MFA.
 *
 * @apiHeader (Authorization) {String} Authorization JWT :accessToken
 * @apiHeaderExample Authorization-Example:
 *     "Authorization: JWT my.reallyniceandvalid.jsonwebtoken"
 * @apiHeader (Authorization) {String} X-Auth-TOTP TOTP or recoveryCode
 * @apiHeaderExample X-Auth-TOTP-Example:
 *     "X-Auth-TOTP: 123456"
 *
 * @apiParam (Payload) {String} username - id of the user
 * @apiParam (Payload) {Number} totp - 6 chars time-based one time password or
 * 8 characters hex recovery code
 * @apiParam (Payload) {String} [remoteip] - security logging feature, not used
 *
 */
function detach({ locals }) {
  const { username } = locals;
  const { redis } = this;

  return Promise
    .bind({ redis }, username)
    .then(removeData);
}

detach.mfa = MFA_TYPE_REQUIRED;
detach.allowed = checkMFA;
detach.auth = 'httpBearer';
detach.transports = [ActionTransport.http, ActionTransport.amqp, ActionTransport.internal];
detach.transportOptions = {
  [ActionTransport.http]: {
    methods: ['post'],
  },
};

module.exports = detach;


text:
`<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Home | Takon Seek</title>
    <link href="<?php echo base_url('assets/multicolor'); ?>/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?php echo base_url('assets/multicolor'); ?>/css/font-awesome.min.css" rel="stylesheet">
    <link href="<?php echo base_url('assets/multicolor'); ?>/css/lightbox.css" rel="stylesheet">
    <link href="<?php echo base_url('assets/multicolor'); ?>/css/animate.min.css" rel="stylesheet">
	<link href="<?php echo base_url('assets/multicolor'); ?>/css/main.css" rel="stylesheet">
	<link href="<?php echo base_url('assets/multicolor'); ?>/css/responsive.css" rel="stylesheet">
    <link href="<?php echo base_url('assets/css'); ?>/chat.css" rel="stylesheet">
    <link href="<?php echo base_url('assets/css'); ?>/navbar.css" rel="stylesheet">

    <!--[if lt IE 9]>
	    <script src="js/html5shiv.js"></script>
	    <script src="js/respond.min.js"></script>
    <![endif]-->
    <link rel="shortcut icon" href="<?php echo base_url('assets/multicolor'); ?>/images/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="<?php echo base_url('assets/multicolor'); ?>/images/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="<?php echo base_url('assets/multicolor'); ?>/images/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="<?php echo base_url('assets/multicolor'); ?>/mages/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="<?php echo base_url('assets/multicolor'); ?>/images/ico/apple-touch-icon-57-precomposed.png">
    <script type="text/javascript">var switchTo5x=true;</script>
    <script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
    <script type="text/javascript">stLight.options({publisher: "7e8eb33b-fbe0-4915-9b93-09490e3d10df", doNotHash: false, doNotCopy: false, hashAddressBar: false});</script>
</head><!--/head-->
<body>


text:
var request = require('request')

var host = 'http://115.159.119.199:8080/'

exports.page = {
	index: function(req, res) {
		res.render('./binding')
	}
}

exports.api = {
	state: function(req, res) {
        var url = host + 'userInfo?openId=' + req.query.openId
		request(url, function(error, response, body) {
			if (!error && response.statusCode == 200) {
				res.json(JSON.parse(body))
			} else{
                res.json(JSON.parse(error))
            }
		})
	},
	bind: function(req, res) {
        request.post({
            url: host + 'bindUser',
            form: req.body
        }, function(error, response, body) {
            if (!error && response.statusCode == 200) {
				res.json(JSON.parse(body))
			} else{
                res.json(JSON.parse(error))
            }
        })
	}
}


text:
'use strict';

/**
 * Module dependencies
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Document Schema
 */
var DocumentSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },

  values: {
    type: Array,
    default: []
  },

  form: {
    type: Schema.ObjectId,
    ref: 'Form'
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

mongoose.model('Document', DocumentSchema);


text:
using UnityEngine;
using System.Collections;

public class GameInput : MonoBehaviour {

	public Signal leftSignal;
	public Signal rightSignal;

	void Start(){
		Input.simulateMouseWithTouches = true;
	}

	void Update () {
		bool leftKey = Input.GetKey(KeyCode.LeftArrow);
		bool rightKey = Input.GetKey(KeyCode.RightArrow);

		if(Input.GetMouseButtonDown(0) || Input.GetMouseButton(0)){
			float mouseX = Input.mousePosition.x;
			float thisScreenX = Camera.main.WorldToScreenPoint(this.transform.position).x;
			if(Mathf.Abs(mouseX - thisScreenX) > 20){
				if(thisScreenX > mouseX){
					leftKey = true;
				}else{
					rightKey = true;
				}
			}
		}

		if(leftKey && !rightKey)
			leftSignal.Invoke();
		else if(rightKey && !leftKey)
			rightSignal.Invoke();
	}
}


text:
using UnityEngine;
using System.Collections;

public class Potion : MonoBehaviour {

	public enum Effect{
		Health,
		Poison
	};

	//public Effect potionEffect;
	public float EffectDuration;
	public float Health = 0;
	public bool CanAddExtraHealth = false;
	public float Energy = 0;
	public bool CanAddExtraEnergy = false;
	public float MovementVelocity = 0;
	public float AttackDamage = 0;
	public float AttackSpeed = 0;
	public float AttackDefense = 0;
	public float MagicAttack = 0;
	public float MagicDefense = 0;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:background="#ccaaaa"
              android:layout_height="wrap_content"
              android:orientation="vertical">

    <TextView
        style="@style/TextAppearance.AppCompat.Display3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="16dp"
        android:text="Header View"/>
</LinearLayout>


text:
package com.github.benmanes.caffeine.cache.testing;

import static java.util.Objects.requireNonNull;

import java.util.concurrent.TimeUnit;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.testing.CacheSpec.CacheExecutor;
import com.github.benmanes.caffeine.cache.testing.CacheSpec.CacheWeigher;
import com.github.benmanes.caffeine.cache.testing.CacheSpec.Expire;
import com.github.benmanes.caffeine.cache.testing.CacheSpec.InitialCapacity;
import com.github.benmanes.caffeine.cache.testing.CacheSpec.Listener;
import com.github.benmanes.caffeine.cache.testing.CacheSpec.MaximumSize;
import com.github.benmanes.caffeine.cache.testing.CacheSpec.ReferenceType;

/**
 * A factory that constructs a {@link Cache} from the {@link CacheContext}.
 *
 * @author ben.manes@gmail.com (Ben Manes)
 */
public final class CacheFromContext {

  private CacheFromContext() {}

  @SuppressWarnings("unchecked")
  public static <K, V> LoadingCache<K, V> newLoadingCache(CacheContext context) {
    requireNonNull(context.loader);
    return (LoadingCache<K, V>) newCache(context);
  }

  /**
   * Creates a new cache based on the context's configuration and update's the context's reference.
   */
  public static <K, V> Cache<K, V> newCache(CacheContext context) {
    switch (context.implementation()) {
      case Caffeine:
        return newCaffeineCache(context);
      case Guava:
        return GuavaLocalCache.newGuavaCache(context);
      default:
        throw new IllegalStateException();
    }
  }

  private static <K, V> Cache<K, V> newCaffeineCache(CacheContext context) {
    Caffeine<Object, Object> builder = Caffeine.newBuilder();
    if (context.initialCapacity != InitialCapacity.DEFAULT) {
      builder.initialCapacity(context.initialCapacity.size());
    }
    if (context.isRecordingStats()) {
      builder.recordStats();
    }
    if (context.maximumSize != MaximumSize.DISABLED) {
      if (context.weigher == CacheWeigher.DEFAULT) {
        builder.maximumSize(context.maximumSize.max());
      } else {
        builder.weigher(context.weigher);
        builder.maximumWeight(context.maximumWeight());
      }
    }
    if (context.afterAccess != Expire.DISABLED) {
      builder.expireAfterAccess(context.afterAccess.timeNanos(), TimeUnit.NANOSECONDS);
    }
    if (context.afterWrite != Expire.DISABLED) {
      builder.expireAfterWrite(context.afterWrite.timeNanos(), TimeUnit.NANOSECONDS);
    }
    if (context.refresh != Expire.DISABLED) {
      builder.refreshAfterWrite(context.refresh.timeNanos(), TimeUnit.NANOSECONDS);
    }
    if (context.expires() || context.refreshes()) {
      builder.ticker(context.ticker());
    }
    if (context.keyStrength == ReferenceType.WEAK) {
      builder.weakKeys();
    } else if (context.keyStrength == ReferenceType.SOFT) {
      throw new IllegalStateException();
    }
    if (context.valueStrength == ReferenceType.WEAK) {
      builder.weakValues();
    } else if (context.valueStrength == ReferenceType.SOFT) {
      builder.softValues();
    }
    if (context.cacheExecutor != CacheExecutor.DEFAULT) {
      builder.executor(context.executor);
    }
    if (context.removalListenerType != Listener.DEFAULT) {
      builder.removalListener(context.removalListener);
    }
    if (context.isAsync()) {
      context.asyncCache = builder.buildAsync(context.loader);
      context.cache = context.asyncCache.synchronous();
    } else if (context.loader == null) {
      context.cache = builder.build();
    } else {
      context.cache = builder.build(context.loader);
    }

    @SuppressWarnings("unchecked")
    Cache<K, V> castedCache = (Cache<K, V>) context.cache;
    return castedCache;
  }
}


text:
title: Annotations and Destinations
page_title: Annotations and Destinations | RadPdfProcessing for ASP.NET AJAX Documentation
description: Annotations and Destinations
slug: radpdfprocessing-model-annotations-and-destinations
tags: annotations,and,destinations
published: True
position: 7
---

# Annotations and Destinations

The abstract __Annotation__ element associates an object with a location on a [RadFixedPage]({%slug radpdfprocessing-model-radfixedpage%}). Annotation exposes the following properties:

* __Rect__: The rectangle which defines the location of the annotation on the page.

* __Type__: Property of type [AnnotationType](http://www.telerik.com/help/wpf/t_telerik_windows_Documents_fixed_model_annotations_annotationtype.html) which determines the type of the annotation. The only supported type is __Link__.

This article will get you familiar with the following concepts:

* [Link](#link)

* [Destination](#destination)

* [Action](#action)

## Link

The __Link__ class inherits the abstract __Annotation__ class and is the only supported type of annotation in the document model. Link annotations represents either a hypertext link to a destination elsewhere in the document or an action to be performed. For this reason there are two separate constructors in the [Link class](http://www.telerik.com/help/wpf/t_telerik_windows_documents_fixed_model_annotations_link.html) - one requiring a __Destination__ object and one requiring an __Action__ object.

__Link__ exposes the following properties:

* __Destination__: A destination to be displayed when the annotation is activated. __Example 1__ demonstrates how you can create a Link using a previously created __Destination__ and add the Link in RadFixedPage's Annotations collection.

#### __[C#] Example 1: Add Link to Destination__

{{region radpdfprocessing-model-annotations-and-destinations_0}}
    Link linkWithDestination = new Link(destination);
    page.Annotations.Add(linkWithDestination);
{{endregion}}

* __Action__: An action to be performed when the annotation is activated. __Example 2__ demonstrates how you can create a Link using a previously created __Action__ and add the Link in RadFixedPage's Annotations collection.

#### __[C#] Example 2: Add Link with Action__

{{region radpdfprocessing-model-annotations-and-destinations_1}}
    Link linkWithAction = new Link(action);
    page.Annotations.Add(linkWithAction);
{{endregion}}

>importantIn __Example 1__ the *action* object should be from the Telerik.Windows.Documents.Fixed.Model.Actions.Action type.

## Destination

The abstract __Destination__ class defines a particular view of a document, consisting of the following items:

* The page which needs to be displayed.

* The location on that page.

* The magnification (zoom) factor which should be uses when displaying the page.

The __Destination__ class itself only exposes a __Page__ property specifying the page of the destination. The other properties of the view are determined by the classes that inherit __Destination__.

* __Location__: Exposes __Left__, __Top__ and __Zoom__ properties. Displays the specified page, positioned with the (Left, Top) position at the upper-left corner of the window and the contents of the page magnified by the factor Zoom.

* __PageFit__: Displays the specified page with its contents magnified just enough to fit the entire page within the window both horizontally and vertically.

* __PageHorizontalFit__: Exposes __Top__ property. Displays the specified page with the vertical coordinate Top positioned at the top edge of the window and the contents of the page magnified just enough to fit the entire width of the page within the window.

* __PageVerticalFit__: Exposes __Left__ property. Displays the specified page with the horizontal coordinate Left positioned at the left edge of the window and the contents of the page magnified just enough to fit the entire height of the page within the window.

* __RectangleFit__: Exposes __Left__, __Top__, __Right__ and __Bottom__ properties. Displays the specified page with its contents magnified just enough to fit the rectangle specified by the coordinates Left, Bottom, Right and Top entirely within the window both horizontally and vertically.

* __BoundingRectangleFit__: Displays the specified page with its contents magnified just enough to fit its bounding box entirely within the window both horizontally and vertically.

* __BoundingRectangleHorizontalFit__: Exposes __Top__ property. Displays the specified page with the vertical coordinate Top positioned at the top edge of the window and the contents of the page magnified just enough to fit the entire width of its bounding box within the window.

* __BoundingRectangleVerticalFit__: Exposes __Left__ property. Displays the specified page with the horizontal coordinate Left positioned at the left edge of the window and the contents of the page magnified just enough the fit the entire height of its bounding box within the window.

__Example 3__ shows how you can create a Location object, associate it with a Link and add it to a RadFixedPage.

#### __[C#] Example 3: Add Link with Location__

{{region radpdfprocessing-model-annotations-and-destinations_2}}
    Location location = new Location();
    location.Left = 225;
    location.Top = 500;
    location.Zoom = 4;
    location.Page = secondPage;

    var link = firstPage.Annotations.AddLink(location);
    link.Rect = new Rect(10, 10, 50, 50);
{{endregion}}

## Action

The abstract __Action__ class defines a behavior for an annotation. Action is inherited from the following classes:

* __GoToAction__: Associates the action with a __Destination__. The GoToAction class exposes the following properties:

 * __Destination__: The associated destination.

* __UriAction__: Associates the action with an Uri. The UriAction class exposes the following properties:

 * __Uri__: The associated Uri.

 * __IncludeMouseCoordinates__: Specifies weather to include the mouse coordinates as query parameters in the Uri.

__Example 4__ demonstrates how to create an action of type __GoToAction__, associate it with a Link and add it to a RadFixedPage. The *location* object can be of type Location like the one in __Example 3__.

#### __[C#] Example 4: Add Link with Action__

{{region radpdfprocessing-model-annotations-and-destinations_3}}
    GoToAction goToAction = new GoToAction();
    goToAction.Destination = location;

    var goToLink = firstPage.Annotations.AddLink(goToAction);
    goToLink.Rect = new Rect(10, 10, 50, 50);

    UriAction uriAction = new UriAction();
    uriAction.Uri = new Uri(@"http://www.telerik.com");

    var uriLink = firstPage.Annotations.AddLink(uriAction);
    uriLink.Rect = new Rect(70, 10, 50, 50);
{{endregion}}

# See Also

 * [RadFixedPage]({%slug radpdfprocessing-model-radfixedpage%})
 * [AnnotationType API Reference](http://www.telerik.com/help/wpf/t_telerik_windows_Documents_fixed_model_annotations_annotationtype.html)
 * [Link API Reference](http://www.telerik.com/help/wpf/t_telerik_windows_documents_fixed_model_annotations_link.html)


text:
var _ = require('underscore');
var Strength = require('../../models/strength');
var fs = require('fs');
var path = require('path');

//addStar
exports.new = function(req, res){
  res.render('admin/strengthForm', {
    title: '新增实力',
    strength: {}
  })
};

exports.list = function(req, res){
  Strength
      .find({})
      .sort('meta.createAt')
      .exec(function(err, strength){
          if (err) {
              console.log(err);
          };

          var onitems = 0;

          for(var i = 0; i < strength.length; i++){
            strength[i].displayindex && onitems++;
          }

          res.render('admin/strengthList', {
              title: '实力列表',
              strength: strength,
              onitems: onitems
          });
      })
};

exports.del = function(req, res){
  var delList = (req.body.delList).split(',');

  if (delList.length > 0) {
    Strength.remove({ _id: { $in: delList } }, function(err, strength){
      if (err) {
          console.log(err)
      }else{
          res.json({success: 1});
      }
    });
  }
};
exports.update = function(req, res){
    var id = req.params.id;

    if (id) {
        Strength
          .findOne({_id: id})
          .exec(function(err, strength){
            res.render('admin/strengthForm', {
              title: '更新实力 ' + strength.name,
              strength: strength
            })
          })
    }
};

exports.display = function(req, res){
    var id = req.body.id;
    var on = req.body.on;

    if (id) {
      Strength.findById(id, function(err, strength) {
        if (err) {
            console.log(err);
        };

        strength.displayindex = on;
        strength.save(function(err, strength){
            if (err) {
                console.log(err);
            };

            res.json({success: 1});
        });
      });
    }

};

exports.save = function(req, res){
    var id = req.body.strength._id;
    var strengthObj = req.body.strength;
    var _strength;

    if (id) {
        Strength.findById(id, function(err, strength) {
            if (err) {
                console.log(err);
            };

            _strength = _.extend(strength, strengthObj);
            _strength.save(function(err, strength){

                if (err) {
                    console.log(err);
                };

                res.redirect('/admin/strength/list');
            });
        });
    }
    else{
        _strength = new Strength(strengthObj);

        _strength.save(function(err, strength){

            if (err) {
                console.log(err)
            };

            res.redirect('/admin/strength/list')
        });
    }
};


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical"
        tools:context=".MainActivity"
        android:background="@color/bg">

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            style="?android:progressBarStyleLarge" />

    </FrameLayout>

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:fitsSystemWindows="true" />

</RelativeLayout>


text:
if ("undefined" == typeof jQuery) {
    throw new Error("shiningPhone's JavaScript requires jQuery");
}

!(function($, window, document, undefined) {

    // Create the defaults once
    var pluginName = "shiningPhone",
        defaults = {
            phone: '',
            // In sec
            animateTime: 10,
            infinite: true
        };

    // The actual plugin constructor
    function Plugin(element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.allPhones = ['galaxy_s_4', 'iPhone_5_black', 'iPhone_5_s_gold', 'iPhone_5_white'];
        this.$phone = null;
        this.init();

    }

    Plugin.prototype = {

        init: function() {
            this.animateCount = 0;
            var elem = this.element;
            $(elem).css('background', 'url("images/shining_' + this.getRandomInt(0, 9) + '.jpg") no-repeat')
                .css('background-size', '1500px 1000px');
            var $phone = $('

');
            var matchedPhones = [];

            var _this = this;
            this.allPhones.forEach(function(phone) {
                if (phone.toUpperCase().indexOf(_this.settings.phone.toUpperCase()) != -1) {
                    matchedPhones.push(phone);
                }
            });
            if (matchedPhones.length === 0) {
                matchedPhones = this.allPhones;
            }

            var phone = matchedPhones[this.getRandomInt(0, matchedPhones.length - 1)];
            $phone.css('background', 'url("images/' + phone + '.png") no-repeat')
                .css('width', '234px')
                .css('height', '483px')
                .css('background-size', '100% 100%')
                .css('position', 'absolute')
                .css('left', '0')
                .css('right', '0')
                .css('margin', '250px 590px')
                .appendTo(elem);
            this.$phone = $phone;
            this.tilt($phone);
        },

        getRandomInt: function(min, max) {
            return Math.floor(Math.random() * (max - min + 1) + min);
        },
        tilt: function($phone) {
            $('#tiltStyle_' + (this.animateCount - 1)).remove();
            var rotateXStart = this.getRandomRotate('x');
            var rotateYStart = this.getRandomRotate('y');
            var rotateXMiddle = this.getRandomRotate('x');
            var rotateYMiddle = this.getRandomRotate('y');
            var rotateXEnd = this.getRandomRotate('x');
            var rotateYEnd = this.getRandomRotate('y');
            var tilt = '0%{ ' + this.setRotate(0) + '; }' +
                '10%{ ' + this.setRotate(rotateXStart + rotateYStart) + '; }' +
                '40%{ ' + this.setRotate(rotateXMiddle + rotateYMiddle) + '; }' +
                '80%{ ' + this.setRotate(rotateXEnd + rotateYEnd) + '; }' +
                '100%{ ' + this.setRotate(0) + '; }';
            var animateName = 'tilt_' + this.animateCount;
            var style = '@keyframes ' + animateName + ' {' + tilt + '}';
            var prefixedStyle = this.prefixCss(style);
            var $style = $('').appendTo('head');
            this.animateCount++;
            $phone.css('animation', animateName + ' ' + this.settings.animateTime + 's');
            var _this = this;
            $phone.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(event) {
                $phone.css('animation', '');
                if (_this.settings.infinite) {
                    _this.tilt($phone);
                }

            });
        },
        getRandomRotate: function(axis) {
            return 'perspective(500px) rotate' + axis.toUpperCase() + '(' + this.getRandomInt(-80, 80) + 'deg)';
        },
        setRotate: function(ratation) {
            return 'transform: ' + ratation;
        },
        prefixCss: function(cssRule) {
            cssRules = [];

            if (cssRule.indexOf('transform') != -1) {
                cssRules.push(cssRule.replace(/transform/g, '-webkit-transform'));
                cssRules.push(cssRule.replace(/transform/g, '-moz-transform'));
                cssRules.push(cssRule.replace(/transform/g, '-o-transform'));
                cssRules.push(cssRule);
            }

            if (cssRule.indexOf('@keyframes') != -1) {
                cssRules[0] = cssRules[0].replace(/@keyframes/g, '@-webkit-keyframes');
                cssRules[1] = cssRules[1].replace(/@keyframes/g, '@-moz-keyframes');
                cssRules[2] = cssRules[2].replace(/@keyframes/g, '@-o-keyframes');
            }

            var cssRulesString = '';
            cssRules.forEach(function(prefixedCssRule) {
                cssRulesString += prefixedCssRule + ' ';
            });

            return cssRulesString;
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // Preventing against multiple instantiations
    $.fn[pluginName] = function(options) {
        this.each(function() {
            if (!$.data(this, "plugin_ " + pluginName)) {
                $.data(this, "plugin_ " + pluginName, new Plugin(this, options));
            }
        });

        // Chain jQuery functions
        return this;
    };

})(jQuery, window, document);


text:
package org.broadleafcommerce.core.web.api.wrapper;

import org.apache.commons.collections4.CollectionUtils;
import org.broadleafcommerce.profile.core.domain.AdditionalFields;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.XmlTransient;

/**
 * Base class for APIWrapper implementations to inject the EntityConfiguration reference.
 */
public abstract class BaseWrapper implements ApplicationContextAware {

    @XmlTransient
    protected ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    /**
     * Utility method.
     * Traverses the domain object's additional fields, and generates a list of MapElementWrappers with them
     * @param model  the domain object
     */
    protected List<MapElementWrapper> createElementWrappers(AdditionalFields model) {

        if (model.getAdditionalFields() != null && !model.getAdditionalFields().isEmpty()) {
            List<MapElementWrapper> mapElementWrappers = new ArrayList<MapElementWrapper>();
            for (String key : model.getAdditionalFields().keySet()) {
                MapElementWrapper mapElementWrapper = new MapElementWrapper();
                mapElementWrapper.setKey(key);
                mapElementWrapper.setValue(model.getAdditionalFields().get(key));
                mapElementWrappers.add(mapElementWrapper);
            }
            return mapElementWrappers;
        }
        return null;

    }

    /**
     * Used method, to be used by Wrappers that implement the WrapperAdditionalFields interface.
     * Transfers the additional fields from the wrapper into the domain object
     * @param model
     * @param me
     */
    public void transferAdditionalFieldsFromWrapper(WrapperAdditionalFields from, AdditionalFields to) {
        Map<String, String> destination = new HashMap<String, String>();
        if (CollectionUtils.isNotEmpty(from.getAdditionalFields())) {
            for (MapElementWrapper elem : from.getAdditionalFields()) {
                destination.put(elem.key, elem.value);
            }
        }
        to.setAdditionalFields(destination);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<module sdkVersion="3.5">
    <!--The "id" identifies your plugin globally. Must be unique, must contain only alphanumeric characters, underlines and dots and must contain at least 5 characters and a maximum of 40. Once set the ID, you should not change it;)-->
    <id>br.com.rrpg.ODAP_SDK3</id>
    <!--"version" is the version of your plugin. When you release a new version of your module, change here =)-->
    <version>1.5</version>
    <name>Fichas Old Dragon </name>
    <description>Pacote com fichas de Old Dragon Aprimorado e suas expansões/cenários</description>
    <author>AlvagorH</author>
    <site>http://www.yourwebsite.com</site>
    <contact>https://www.facebook.com/sean.torres.5/</contact>
	<dataTypes>
        <dataType title="Old Dragon Aprimorado - Ficha de Personagem" name="frmOD" lfmFile="OD/OD.lfm">br.com.RRPG.ODAPM_S3</dataType>
		<dataType title="Senhores da Guerra - Ficha de Personagem" name="frmSdG" lfmFile="SdG/SdG.lfm">br.com.RRPG.SdG_S3</dataType>
		<dataType title="Thordezilhas - Ficha de Personagem" name="frmTSC" lfmFile="TSC/TSC.lfm">dataType="br.com.RRPG.TSC_S3"</dataType>
    </dataTypes>
</module>


text:
<rules
    xmlns="http://namespaces.plone.org/diazo"
    xmlns:css="http://namespaces.plone.org/diazo/css"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    >

    <copy
        attributes="*"
        css:theme="div#wrapper"
        css:content="body"
        />

    <copy
        attributes="*"
        css:theme="div#wrapper"
        content="/html/body/div"
        />

</rules>


text:
#import "NanoStore.h"

/** \cond */

@interface NSFNanoPredicate (Private)
// Just a placeholder.
@end

/** \endcond */


text:
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.ArrayList;

public class ActiveMQServer {
    private static int numberOfClients;

    public static void main(String[] args) throws JMSException {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQGlobals.url);
        Connection connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        numberOfClients = getNumberOfClients(session);
        System.out.println("Number of Clients: " + numberOfClients);

        sort(10000, session);
        sort(20000, session);
        sort(40000, session);
        sort(80000, session);
        sort(160000, session);

        connection.close();
    }

    private static int getNumberOfClients(Session session) throws JMSException {
        Destination clientNumberDestination = session.createQueue(ActiveMQGlobals.clientNumberQueue);
        MessageConsumer consumer = session.createConsumer(clientNumberDestination);

        Message clientNumberMessage = consumer.receive();
        int numberOfClients = 0;
        if(clientNumberMessage instanceof TextMessage) {
            numberOfClients = Integer.parseInt(((TextMessage) clientNumberMessage).getText());
        }

        MessageProducer producer = session.createProducer(clientNumberDestination);
        producer.send(clientNumberMessage);

        // Cleanup
        consumer.close();
        producer.close();

        return numberOfClients;
    }

    private static void sort(int n, Session session) throws JMSException {
        int[] dataSet = Utils.generateRandomDataSet(n);
        sortElements(dataSet, session, n);
    }

    private static void sortElements(int[] dataSet, Session session, int maximum) throws JMSException {
        EventProfiler profiler = new EventProfiler(true);

        int accumulatedValues = 0;
        int valuesPerClient = maximum/numberOfClients;

        profiler.start();
        for (int i = 0; i < numberOfClients; i++) {
            Destination clientTaskQueue = session.createQueue(ActiveMQGlobals.clientTaskQueue + i);
            MessageProducer producer = session.createProducer(clientTaskQueue);
            BytesMessage sortingDataMessage = session.createBytesMessage();

            int min = accumulatedValues;
            int max = accumulatedValues + valuesPerClient;

            accumulatedValues += valuesPerClient;
            ActiveMQSortingData data = new ActiveMQSortingData(min, max, dataSet);
            try {
                byte[] bytes = Utils.serialize(data);
                sortingDataMessage.writeBytes(bytes);
                producer.send(sortingDataMessage);

            } catch (Exception e) {
                e.printStackTrace();
            }

            // Cleanup
            producer.close();
        }

        ArrayList<ActiveMQSortedData> sortedDatas = new ArrayList<ActiveMQSortedData>();
        for (int i = 0; i < numberOfClients; i++) {
            Destination clientResultQueue = session.createQueue(ActiveMQGlobals.clientResultQueue + i);
            MessageConsumer consumer = session.createConsumer(clientResultQueue);
            Message message = consumer.receive();
            consumer.close();

            if(message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage)message;
                byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(bytes);

                try {
                    ActiveMQSortedData sortedData = (ActiveMQSortedData)Utils.deserialize(bytes);
                    sortedDatas.add(sortedData);
                    //System.out.println("Received SortedData with length: " + sortedData.data.length);
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }

        int[] mergedData;
        if(numberOfClients > 1) {
            mergedData = new int[dataSet.length];
            int index = 0;
            for (ActiveMQSortedData sortedData :
                    sortedDatas) {
                int[] data = sortedData.data;
                for (int i = 0; i < data.length; i++) {
                    mergedData[index] = data[i];
                    index++;
                }
            }
        }
        else {
            mergedData = sortedDatas.get(0).data;
        }
        profiler.log("Sorting " + dataSet.length + " elements with " + numberOfClients + " clusters");

        //Utils.printArray(mergedData);
        //boolean isSorted = Utils.isDataSetSorted(mergedData, dataSet.length);
        //System.out.println(isSorted);
    }
}


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

using Newtonsoft.Json;

using Ploeh.AutoFixture;

namespace Draft.Tests
{
    internal static partial class Fixtures
    {

        [SuppressMessage("ReSharper", "InconsistentNaming")]
        public static class Dto
        {

            public const int Json_SimpleDataContract_Id = 1234;

            public const string Json_SimpleDataContract_Name = "Draft";

            public static SimpleDataContractDto SimpleDataContract(int? id = null, string name = null)
            {
                return new SimpleDataContractDto
                {
                    Id = id ?? Fixture.Create<int>(),
                    Name = name ?? Fixture.Create<string>()
                };
            }

            public static readonly string Json_SimpleDataContract = JsonConvert.SerializeObject(SimpleDataContract(Json_SimpleDataContract_Id, Json_SimpleDataContract_Name));

        }

    }
}


text:
import logging
from typing import Optional

from great_expectations.data_context.data_context.abstract_data_context import (
    AbstractDataContext,
)
from great_expectations.data_context.data_context_variables import (
    DataContextVariableSchema,
    FileDataContextVariables,
)
from great_expectations.data_context.types.base import (
    DataContextConfig,
    datasourceConfigSchema,
)
from great_expectations.datasource.datasource_serializer import (
    YAMLReadyDictDatasourceConfigSerializer,
)

logger = logging.getLogger(__name__)

class FileDataContext(AbstractDataContext):
    """
    Extends AbstractDataContext, contains only functionality necessary to hydrate state from disk.

    TODO: Most of the functionality in DataContext will be refactored into this class, and the current DataContext
    class will exist only for backwards-compatibility reasons.
    """

    GE_YML = "great_expectations.yml"

    def __init__(
        self,
        project_config: DataContextConfig,
        context_root_dir: str,
        runtime_environment: Optional[dict] = None,
    ) -> None:
        """FileDataContext constructor

        Args:
            project_config (DataContextConfig):  Config for current DataContext
            context_root_dir (Optional[str]): location to look for the ``great_expectations.yml`` file. If None,
                searches for the file based on conventions for project subdirectories.
            runtime_environment (Optional[dict]): a dictionary of config variables that override both those set in
                config_variables.yml and the environment
        """
        self._context_root_directory = context_root_dir
        self._project_config = self._apply_global_config_overrides(
            config=project_config
        )
        super().__init__(runtime_environment=runtime_environment)

    def _init_datasource_store(self) -> None:
        from great_expectations.data_context.store.datasource_store import (
            DatasourceStore,
        )

        store_name: str = "datasource_store"  # Never explicitly referenced but adheres
        # to the convention set by other internal Stores
        store_backend: dict = {
            "class_name": "InlineStoreBackend",
            "resource_type": DataContextVariableSchema.DATASOURCES,
        }
        runtime_environment: dict = {
            "root_directory": self.root_directory,
            "data_context": self,
            # By passing this value in our runtime_environment,
            # we ensure that the same exact context (memory address and all) is supplied to the Store backend
        }

        datasource_store = DatasourceStore(
            store_name=store_name,
            store_backend=store_backend,
            runtime_environment=runtime_environment,
            serializer=YAMLReadyDictDatasourceConfigSerializer(
                schema=datasourceConfigSchema
            ),
        )
        self._datasource_store = datasource_store

    @property
    def root_directory(self) -> Optional[str]:
        """The root directory for configuration objects in the data context; the location in which
        ``great_expectations.yml`` is located.

        Why does this exist in AbstractDataContext? CloudDataContext and FileDataContext both use it

        """
        return self._context_root_directory

    def _init_variables(self) -> FileDataContextVariables:
        variables = FileDataContextVariables(
            config=self._project_config,
            config_provider=self.config_provider,
            data_context=self,  # type: ignore[arg-type]
        )
        return variables


text:
package mezz.jei.network.packets;

import io.netty.buffer.Unpooled;
import mezz.jei.network.IPacketId;
import mezz.jei.network.PacketHandler;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;

public abstract class PacketJei {
	private final IPacketId id = getPacketId();

	public final FMLProxyPacket getPacket() {
		PacketBuffer packetBuffer = new PacketBuffer(Unpooled.buffer());

		packetBuffer.writeByte(id.ordinal());
		writePacketData(packetBuffer);

		return new FMLProxyPacket(packetBuffer, PacketHandler.CHANNEL_ID);
	}

	public abstract IPacketId getPacketId();

	public abstract void writePacketData(PacketBuffer buf);
}


text:
<?php

/** Applications forms */
namespace Applications\Form;

use Core\Form\SummaryForm;

/**
 * Form for base application data.
 *
 * @author Mathias Gelhausen <gelhausen@cross-solution.de>
 */
class Base extends SummaryForm
{
    /**
     * Label for the form.
     *
     * @var string
     */
    protected $label        = /*@translate*/ 'Cover Letter';

    /**
     * {@inheritDoc}
     */
    protected $baseFieldset = array(
        'type' => 'Applications/BaseFieldset',
        'options' => array(
            'disable_capable' => array(
                'label' => 'Test label base form',
            ),
            'is_disable_capable' => false,
            'is_disable_elements_capable' => true,
        ),
    );

    /**
     * {@inheritDoc}
     */
    protected $displayMode = 'summary';
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ListViewExt">
        <!-- type of data source -->
        <attr name="adapterData" format="enum">
            <!-- do not initialize Adapter (default) -->
            <enum name="none" value="0"/>
            <!-- used with AdapterX -->
            <enum name="array_list" value="1"/>
            <!-- used with AdapterX -->
            <enum name="linked_list" value="2"/>
            <!-- used with CursorAdapterX -->
            <enum name="cursor" value="3"/>
        </attr>
        <!-- used for adapterData="cursor" -->
        <attr name="adapterCursorQuery" format="string|reference"/>
        <!-- used for adapterData="cursor" -->
        <attr name="adapterCursorAutoRequery" format="boolean|reference"/>
        <!-- layout for items -->
        <attr name="adapterLayoutId" format="reference"/>
        <!-- array with the ids of layouts for items -->
        <attr name="adapterLayoutIdsArray" format="reference"/>
        <!-- binder for items -->
        <attr name="adapterBinderClass" format="string|reference"/>
        <!-- view-type resolver for items -->
        <attr name="adapterViewTypeResolverClass" format="string|reference"/>
    </declare-styleable>
</resources>


text:
<!DOCTYPE html>

	<meta charset="utf-8">
    <meta name="referrer" content="origin">
    <meta name="viewport" content="width=device-width">
    <meta name="robots" content="index,nofollow"/>
	<title></title>
	<link rel="shortcut icon" th:href="@{/images/favicon.ico(cacheVersion=${contentCacheVersion})}">
	<link rel="stylesheet" th:href="@{/externlib/cesium/Widgets/widgets.css(cacheVersion=${contentCacheVersion})}" />
	<link rel="stylesheet" th:href="@{/externlib/jquery-ui-1.12.1/jquery-ui.min.css(cacheVersion=${contentCacheVersion})}" />
	<link rel="stylesheet" th:href="@{/externlib/geostats/geostats.css(cacheVersion=${contentCacheVersion})}" />
	<link rel="stylesheet" th:href="@{/externlib/kotSlider/range.css(cacheVersion=${contentCacheVersion})}" />
	<link rel="stylesheet" th:href="@{/externlib/tuidatepicker-4.0.3/tui-date-picker.min.css(cacheVersion=${contentCacheVersion})}" />
	<link rel="stylesheet" th:href="@{/css/{lang}/user-style.css(lang=${lang}, cacheVersion=${contentCacheVersion})}" />
	<link rel="stylesheet" th:href="@{/css/fontawesome-free-5.2.0-web/css/all.css(cacheVersion=${contentCacheVersion})}" />
	<link rel="stylesheet" th:href="@{/externlib/json-viewer/json-viewer.css(cacheVersion=${contentCacheVersion})}" />
	<link rel="stylesheet" th:href="@{/externlib/css-toggle-switch/toggle-switch.css(cacheVersion=${contentCacheVersion})}" />
	<link rel="stylesheet" th:href="@{/externlib/noUiSlider/nouislider.min.css(cacheVersion=${contentCacheVersion})}" />

			<button type="button" id="closeLeftBtn" th:title="#{common.close}" th:text="#{common.close}" style="display:none;"></button>

			<canvas id="analysisGraphic"></canvas>

X

			caRange
			<input id="rangeInput"/>

			saRange
			<input id="timeInput"/>

			<button type="button" style="float: right;width: 20px;">X</button>

				D2D4E1
				D2D4E1
				D2D4E1


text:
<?php
include("DAO/conexao.php");
include("DAO/operacoesDAO.php");
include("DAO/estoqueDAO.php");

$servico['terceiro'] = $_POST['terceiro'];
$servico['data_saida'] = $_POST['data_saida'];
$servico['data_retorno'] = $_POST['data_retorno'];
$servico['descricao'] = $_POST['descricao'];

$baixa['id'] = $_POST['id'];
$baixa['saida'] = $_POST['saida'];

if ($baixa['id']!= "vazio") {
  alteraProdutoSelect($conexao, $baixa);
}

cadastrarServicosTerceiros($conexao, $servico);

header("location: terceiro.service.search.php?status=ok");
die();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace FLocal.Client.Common {
	static class Extensions {

		public static string Join(this IEnumerable<string> value, string separator) {
			return string.Join(separator, value.ToArray());
		}

		public static string GetTextValue(this IEnumerable<XElement> elements) {
			return (from element in elements select element.Value).Join("");
		}

		public static string GetTextValue(this XElement element, XName name) {
			return element.Elements(name).GetTextValue();
		}

	}
}


text:
/*
 * File:   InternalResourceData.cpp
 * Author: ricky
 *
 * Created on 2014年5月14日, 下午 12:13
 */

#include "InternalResourceData.h"

namespace HPHP {
    IMPLEMENT_OBJECT_ALLOCATION(InternalResourceData)
    InternalResourceData::InternalResourceData(void *resource) {
        this->resource = resource;
    }

    void * InternalResourceData::getInternalResourceData() {
        return this->resource;
    }

    void InternalResourceData::setInternalResourceData(void *resource) {
        this->resource = resource;
    }
    void InternalResourceData::setObject(const Object &obj) {
        this->object_data = &obj;
    }

    const Object *InternalResourceData::getObject() {
        return object_data;
    }

    InternalResourceData::~InternalResourceData() {
    }

}


text:
if (AVAHICLIENT_INCLUDE_DIR AND AVAHICLIENT_LIBRARIES)
	# in cache already
	set(AVAHICLIENT_FOUND TRUE)
else (AVAHICLIENT_INCLUDE_DIR AND AVAHICLIENT_LIBRARIES)
	FIND_PATH(AVAHICLIENT_INCLUDE_DIR client.h
	PATHS ${PC_AVAHICLIENT_INCLUDEDIR} ${PC_AVAHICLIENT_INCLUDE_DIRS})
	FIND_LIBRARY(AVAHICLIENT_LIBRARIES NAMES avahi-client
	PATHS ${PC_AVAHICLIENT_LIBDIR} ${PC_AVAHICLIENT_LIBRARY_DIRS})

	#include(FindPackageHandleStandardArgs)
	#FIND_PACKAGE_HANDLE_STANDARD_ARGS(AVAHICLIENT DEFAULT_MSG AVAHICLIENT_LIBRARIES AVAHICLIENT_INCLUDE_DIR)

	MARK_AS_ADVANCED(AVAHICLIENT_INCLUDE_DIR AVAHICLIENT_LIBRARIES)
endif (AVAHICLIENT_INCLUDE_DIR AND AVAHICLIENT_LIBRARIES)


text:
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;
using KPEntity.ORM;
using KPBO;
using Castle.ActiveRecord;

namespace KPBO
{
    /// <summary>
    /// <para>Authors: Juliano Tiago Rinaldi and
    /// Tiago Antonio Jacobi</para>
    /// </summary>
    public class FrwParamListBO : BaseBO<FrwParamList>
    {
        public FrwParamListBO(FrwParamList entity)
            : base(entity)
        {

        }

        /// <summary>
        /// This method is responsible for save and return the Entity,
        /// so if you need to save some extra data you could use this method.
        ///
        /// TODO: This method is Auto-generated by the KP Mapping Generator.
        /// </summary>
        /// <returns>The Entity saved in the database</returns>
        public override FrwParamList SaveEntity()
        {
            // Your code here

            return base.SaveEntity(); // Default framework SaveEntity, it call's the Validate method.
        }

        /// <summary>
        /// This method is responsible for save and return the Entity,
        /// so if you need to save some extra data you could use this method.
        ///
        /// TODO: This method is Auto-generated by the KP Mapping Generator.
        /// </summary>
        /// <returns>True if the Entity is validated and False if not, e.g: if some required field is empty, returns false.</returns>
        public override bool Validate()
        {
            // Your code here

            return base.Validate(); // Default framework validation.
        }
    }
}


text:
<?php

namespace Thomasvvugt\LaraLang;

use Illuminate\Support\Facades\Lang;
use Thomasvvugt\LaraLang\Exceptions\InvalidConfiguration;
use Illuminate\Database\Eloquent\Model;

class Translation extends Model
{
	protected $table = 'translations';

    // Fillable for MassAssignment
    protected $fillable = ['language_id', 'group_id', 'key'];

	public function __construct(array $attributes = []) {
        $this->table = config('laralang.tables.translations');
		parent::__construct($attributes);
	}

	public function language()
	{
		$language_model = config('laralang.models.language');
        if (! is_a(new $language_model, Language::class)) {
            throw InvalidConfiguration::invalidModel($language_model);
        }
		return $this->belongsTo($language_model);
	}

	public static function getTranslationsForGroup(string $locale, string $group, string $namespace): array
    {
    	$result = [];
      if($locale !== null) {
        $language_model = config('laralang.models.language');
        if (! is_a(new $language_model, Language::class)) {
          throw InvalidConfiguration::invalidModel($language_model);
        }
        $language = config('laralang.models.language')::getFromName($locale);

        // Check namespaces
        if($namespace !== null && $namespace != "*") {
          $namespace_model = config('laralang.models.namespace');
          if (! is_a(new $namespace_model, Namespc::class)) {
            throw InvalidConfiguration::invalidModel($namespace_model);
          }
          $namespace = config('laralang.models.namespace')::getFromName($namespace);
        }

        if(isset($group) && $group !== "*") {
          $group_model = config('laralang.models.group');
          if (! is_a(new $group_model, Group::class)) {
            throw InvalidConfiguration::invalidModel($group_model);
          }
          $group = config('laralang.models.group')::getFromName($group);
        }

        if(isset($language)) {
          if(isset($namespace->id)) {
            if(isset($group->id)) {
              $translations = static::where('language_id', $language->id)->where('group_id', $group->id)->where('namespace_id', $namespace->id)->get();
              foreach($translations as $translation)
              {
                $result[$translation->key] = $translation->value;
              }
            } else {
              if($group === "*") {
                $translations = static::where('language_id', $language->id)->get();
                foreach($translations as $translation)
                {
                  $group = Group::getFromID($translation->group_id);
                  $result[$group->name.".".$translation->key] = $translation->value;
                }
              }
            }
          } else {
            if(isset($group->id)) {
              $translations = static::where('language_id', $language->id)->where('group_id', $group->id)->get();
              foreach($translations as $translation)
              {
                $result[$translation->key] = $translation->value;
              }
            } else {
              if($group === "*") {
                $translations = static::where('language_id', $language->id)->get();
                foreach($translations as $translation)
                {
                  $group = Group::getFromID($translation->group_id);
                  $result[$group->name.".".$translation->key] = $translation->value;
                }
              }
            }
          }
        }
      }
      return $result;
    }
}


text:
var React = require('react');
var isEqual = require('lodash/lang/isEqual');
var SpinningIcon = require('./icons/Spinning');
var InfiniteScroll = require('../utils/InfiniteScroll');

var CLASS_ROOT = "table";
var SELECTED_CLASS = CLASS_ROOT + "__row--selected";

var Table = React.createClass({

  propTypes: {
    selection: React.PropTypes.oneOfType([
      React.PropTypes.number,
      React.PropTypes.arrayOf(React.PropTypes.number)
    ]),
    onMore: React.PropTypes.func,
    scrollable: React.PropTypes.bool,
    selectable: React.PropTypes.oneOfType([
      React.PropTypes.bool,
      React.PropTypes.oneOf(['multiple'])
    ]),
    onSelect: React.PropTypes.func
  },

  getDefaultProps: function () {
    return {
      scrollable: false,
      selectable: false
    };
  },

  getInitialState: function () {
    return {
      selection: this._normalizeSelection(this.props.selection),
      rebuildMirror: this.props.scrollable
    };
  },

  componentDidMount: function () {
    this._alignSelection();
    if (this.props.scrollable) {
      this._buildMirror();
      this._alignMirror();
    }
    if (this.props.onMore) {
      this._scroll = InfiniteScroll.startListeningForScroll(this.refs.more, this.props.onMore);
    }
    window.addEventListener('resize', this._onResize);
  },

  componentWillReceiveProps: function (newProps) {
    if (this._scroll) {
      InfiniteScroll.stopListeningForScroll(this._scroll);
      this._scroll = null;
    }
    if (newProps.hasOwnProperty('selection')) {
      this.setState({selection: this._normalizeSelection(newProps.selection)});
    }
    this.setState({rebuildMirror: newProps.scrollable});
  },

  componentDidUpdate: function (prevProps, prevState) {
    if (! isEqual(this.state.selection, prevState.selection)) {
      this._alignSelection();
    }
    if (this.state.rebuildMirror) {
      this._buildMirror();
      this.setState({rebuildMirror: false});
    }
    if (this.props.scrollable) {
      this._alignMirror();
    }
    if (this.props.onMore && !this._scroll) {
      this._scroll = InfiniteScroll.startListeningForScroll(this.refs.more, this.props.onMore);
    }
  },

  componentWillUnmount: function () {
    if (this._scroll) {
      InfiniteScroll.stopListeningForScroll(this._scroll);
    }
    window.removeEventListener('resize', this._onResize);
  },

  _normalizeSelection: function (selection) {
    var result;
    if (undefined === selection || null === selection) {
      result = [];
    } else if (typeof selection === 'number') {
      result = [selection];
    } else {
      result = selection;
    }
    return result;
  },

  _clearSelected: function () {
    var rows = this.refs.table
      .querySelectorAll("." + SELECTED_CLASS);
    for (var i = 0; i < rows.length; i++) {
      rows[i].classList.remove(SELECTED_CLASS);
    }
  },

  _alignSelection: function () {
    this._clearSelected();
    if (null !== this.state.selection) {
      var tbody = this.refs.table.querySelectorAll('tbody')[0];
      this.state.selection.forEach(function (rowIndex) {
        tbody.childNodes[rowIndex].classList.add(SELECTED_CLASS);
      });
    }
  },

  _onClick: function (event) {
    if (!this.props.selectable) {
      return;
    }

    var element = event.target;
    while (element.nodeName !== 'TR') {
      element = element.parentNode;
    }

    var parentElement = element.parentNode;
    if (element && parentElement.nodeName === 'TBODY') {

      var index;
      for (index = 0; index < parentElement.childNodes.length; index++) {
        if (parentElement.childNodes[index] === element) {
          break;
        }
      }

      var selection = this.state.selection.slice(0);
      var selectionIndex = selection.indexOf(index);

      if ('multiple' === this.props.selectable && event.shiftKey) {

        // select from nearest selected item to the currently selected item
        var closestIndex = -1;
        selection.forEach(function (selectIndex, arrayIndex) {
          if (-1 === closestIndex) {
            closestIndex = selectIndex;
          } else if (Math.abs(index - selectIndex) < Math.abs(index - closestIndex)) {
            closestIndex = selectIndex;
          }
        });
        for (var i = index; i !== closestIndex; ) {
          selection.push(i);
          if (closestIndex < index) {
            i -= 1;
          } else {
            i += 1;
          }
        }
        // remove text selection
        window.getSelection().removeAllRanges();

      } else if (('multiple' === this.props.selectable || -1 !== selectionIndex) &&
        (event.ctrlKey || event.metaKey)) {

        // toggle
        if (-1 === selectionIndex) {
          element.classList.add(SELECTED_CLASS);
          selection.push(index);
        } else {
          element.classList.remove(SELECTED_CLASS);
          selection.splice(selectionIndex, 1);
        }

      } else {

        this._clearSelected();
        selection = [index];
        element.classList.add(SELECTED_CLASS);

      }

      this.setState({selection: selection});

      if (this.props.onSelect) {
        // notify caller that the selection has changed
        if (selection.length === 1) {
          selection = selection[0];
        }
        this.props.onSelect(selection);
      }
    }
  },

  _onResize: function () {
    this._alignMirror();
  },

  _buildMirror: function () {
    var tableElement = this.refs.table;
    var cells = tableElement.querySelectorAll('thead tr th');
    var mirrorElement = this.refs.mirror;
    var mirrorRow = mirrorElement.querySelectorAll('thead tr')[0];
    while (mirrorRow.hasChildNodes()) {
      mirrorRow.removeChild(mirrorRow.lastChild);
    }
    for (var i = 0; i < cells.length; i++) {
      mirrorRow.appendChild(cells[i].cloneNode(true));
    }
  },

  _alignMirror: function () {
    if (this.refs.mirror) {
      var tableElement = this.refs.table;
      var cells = tableElement.querySelectorAll('thead tr th');
      var mirrorElement = this.refs.mirror;
      var mirrorCells = mirrorElement.querySelectorAll('thead tr th');

      var rect = tableElement.getBoundingClientRect();
      mirrorElement.style.width = '' + Math.floor(rect.right - rect.left) + 'px';

      var height = 0;
      for (var i = 0; i < cells.length; i++) {
        rect = cells[i].getBoundingClientRect();
        mirrorCells[i].style.width = '' + Math.floor(rect.right - rect.left) + 'px';
        mirrorCells[i].style.height = '' + Math.floor(rect.bottom - rect.top) + 'px';
        height = Math.max(height, Math.floor(rect.bottom - rect.top));
      }
      mirrorElement.style.height = '' + height + 'px';
    }
  },

  render: function () {
    var classes = [CLASS_ROOT];
    if (this.props.selectable) {
      classes.push(CLASS_ROOT + "--selectable");
    }
    if (this.props.scrollable) {
      classes.push(CLASS_ROOT + "--scrollable");
    }
    if (this.props.className) {
      classes.push(this.props.className);
    }

    var mirror = null;
    if (this.props.scrollable) {
      mirror = (

      );
    }

    var more = null;
    if (this.props.onMore) {
      more = (

          <SpinningIcon />

      );
    }

    return (

        {mirror}

          {this.props.children}

        {more}

    );
  }

});

module.exports = Table;


text:
{
  :basic => {
    :visibility => "public",
    :private_project_qty => 1
  },
  :developer => {
    :visibility => "public",
    :private_project_qty => 5
  },
  :consultant => {
    :visibility => "public",
    :private_project_qty => 15
  },
  :corporation => {
    :visibility => "public",
    :private_project_qty => 35
  }
}.each do |plan_name, plan_attributes|
  plan = Plan.find_or_create_by_name(:name => plan_name.to_s)
  plan.update_attributes(plan_attributes)
end


text:
doRunDockerImage(){

	doLog "DEBUG START doRunDockerImage"

	cat doc/txt/url-sniper/funcs/run-docker-image.func.txt

	test -z "$sleep_interval" || sleep "$sleep_interval"
	# add your action implementation code here ...
	# Action !!!

	doLog "DEBUG STOP  doRunDockerImage"
}
# eof func doRunDockerImage

# eof file: src/bash/url-sniper/funcs/run-docker-image.func.sh


text:
'use strict';

var manifoldjs = require('manifoldjs'),
    manifestTools = manifoldjs.manifestTools,
    projectBuilder = manifoldjs.projectBuilder,
    path = require('path'),
    url = require('url');

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('manifoldjs', 'Generate hosted apps across platforms and devices', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      output: 'generatedApps',
      platforms: ['chrome', 'firefox', 'android', 'ios', 'windows10'],
      buildProjects: false
    });

    if (!options.manifestFilePath) {
      return grunt.fail.fatal('Required config properties "manifestFilePath" is missing.');
    }

    if (!grunt.file.exists(options.manifestFilePath) || !grunt.file.isFile(options.manifestFilePath)) {
      return grunt.fail.fatal('"manifestFilePath" config property must target an existing manifest file.');
    }

    if (grunt.util.kindOf(options.platforms) !== 'array') {
      return grunt.fail.fatal('"platforms" config property must be an array.');
    }

    if (grunt.util.kindOf(options.buildProjects) !== 'boolean') {
      return grunt.fail.fatal('"buildProjects" config property must be a boolean.');
    }

    if (grunt.util.kindOf(options.output) !== 'string') {
      return grunt.fail.fatal('"output" config property must be a string.');
    }

    if (!grunt.file.isDir(options.output)) {
      if (grunt.file.exists(options.output)) {
        return grunt.fail.fatal('"output" config property must be a directory.');
      }
    }

    var done = this.async();

    manifestTools.getManifestFromFile(options.manifestFilePath, function (err, manifestInfo) {
      if (err) {
        grunt.fail.fatal('File error or invalid manifest format.');
        return done(false);
      }

      var startUrl = manifestInfo.content.start_url;

      if (startUrl) {
        var parsedSiteUrl = url.parse(startUrl);
        if (!parsedSiteUrl.hostname) {
          if (!options.site) {
            grunt.fail.fatal('You need to have a full url as start_url in the manifest or set the "site" config property.');
            return done(false);
          } else {
            manifestInfo.content.start_url = options.site;
          }
        }
      }

      var outputPath = options.output;

      if (grunt.file.exists(outputPath)) {
        grunt.file.delete(outputPath);
      }

      grunt.file.mkdir(outputPath);

      if (!grunt.file.isPathAbsolute(outputPath) && grunt.file.isPathInCwd(outputPath)) {
        outputPath = path.resolve(process.cwd(), outputPath);
      }

      projectBuilder.createApps(manifestInfo, outputPath, options.platforms, options.buildProjects, function (err) {
        if (err) {
          // Build errors
          grunt.fail.fatal('An error occurs while creating the apps.');
          return done(false);
        }

        grunt.log.writeln('applications created!.');
        done(true);
      });
    });
  });

};


text:
package com.iauto.wlink.core.message;

public interface MessageReceivedHandler {
	void onMessage( String type, String from, String to, byte[] payload );
}


text:
import _plotly_utils.basevalidators

class MinexponentValidator(_plotly_utils.basevalidators.NumberValidator):
    def __init__(
        self,
        plotly_name="minexponent",
        parent_name="layout.polar.angularaxis",
        **kwargs,
    ):
        super(MinexponentValidator, self).__init__(
            plotly_name=plotly_name,
            parent_name=parent_name,
            edit_type=kwargs.pop("edit_type", "plot"),
            min=kwargs.pop("min", 0),
            **kwargs,
        )


text:
Installation
============

.. include:: ../INSTALL


text:
from ncclient.operations.rpc import *
import unittest
from mock import patch
from ncclient import manager
import ncclient.manager
import ncclient.transport
from ncclient.xml_ import *
from ncclient.operations import RaiseMode
from ncclient.capabilities import Capabilities
from xml.sax.saxutils import escape
import sys

if sys.version >= '3':
    patch_str = 'ncclient.operations.rpc.Event.isSet'
else:
    patch_str = 'threading._Event.isSet'

xml1 = """<rpc-reply xmlns:junos="http://xml.juniper.net/junos/12.1X46/junos">
    <ok/>
</rpc-reply>"""

xml2 = """<rpc-reply message-id="urn:uuid:15ceca00-904e-11e4-94ad-5c514f91ab3f">
	<load-configuration-results>
		<rpc-error>
			<error-severity>error</error-severity>
			<error-info>
				<bad-element>system1</bad-element>
			</error-info>
			<error-message>syntax error</error-message>
		</rpc-error>
		<rpc-error>
			<error-severity>error</error-severity>
			<error-info>
				<bad-element>}</bad-element>
			</error-info>
            <error-message>error recovery ignores input until this point</error-message>
		</rpc-error>
	</load-configuration-results>
</rpc-reply>"""

xml3 = """<rpc-reply xmlns:junos="http://xml.juniper.net/junos/12.1X46/junos" attrib1 = "test">
    <software-information>
        <host-name>R1</host-name>
        <product-model>firefly-perimeter</product-model>
        <product-name>firefly-perimeter</product-name>
        <package-information>
            <name>junos</name>
            <comment>JUNOS Software Release [12.1X46-D10.2]</comment>
        </package-information>
    </software-information>
    <rpc-error>
    </rpc-error>
    <cli>
        <banner></banner>
    </cli>
</rpc-reply>"""

xml4 = """<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/14.2I0/junos" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:b19400d6-fa2a-11e4-8f7b-0800278ff596">
<data>
<configuration xmlns="http://xml.juniper.net/xnm/1.1/xnm" junos:changed-seconds="1431599824" junos:changed-localtime="2015-05-14 03:37:04 PDT">
    <system>
        <services>
            <ftp>
                <connection-limit>200</connection-limit>
                <rate-limit>214</rate-limit>
            </ftp>
            <ssh>
                <root-login>allow</root-login>
            </ssh>
            <telnet>
            </telnet>
            <netconf>
                <ssh>
                </ssh>
            </netconf>
        </services>
    </system>
</configuration>
</data>
</rpc-reply>"""

# Huge dummy text configuration to trigger "xml.etree.XMLSyntaxError: xmlSAX2Characters: huge text node"
# - The maximum size of a single text node is `#define XML_MAX_TEXT_LENGTH 10000000`
#   (https://gitlab.gnome.org/GNOME/libxml2/blob/master/include/libxml/parserInternals.h)
# - The text should contain at least one special character that should be escaped (e.g. '>')
huge_configuration_text = "-->\n" + "Huge configuration. " * 500000

xml5_huge = """<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/18.2R1/junos" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:b8b20a95-7822-4c59-97a3-44435d6fc6a7">
<configuration-text xmlns="http://xml.juniper.net/xnm/1.1/xnm">%s</configuration-text>
</rpc-reply>""" % escape(huge_configuration_text)

class TestRPC(unittest.TestCase):

    def test_rpc_reply(self):
        obj = RPCReply(xml4)
        obj.parse()
        self.assertTrue(obj.ok)
        self.assertFalse(obj.error)
        self.assertEqual(xml4, obj.xml)
        self.assertTrue(obj._parsed)

    def test_rpc_reply_huge_text_node_exception(self):
        obj = RPCReply(xml5_huge)
        self.assertRaises(etree.XMLSyntaxError, obj.parse)

    def test_rpc_reply_huge_text_node_workaround(self):
        obj = RPCReply(xml5_huge, huge_tree=True)
        obj.parse()
        self.assertTrue(obj.ok)
        self.assertFalse(obj.error)
        self.assertEqual(xml5_huge, obj.xml)
        self.assertTrue(obj._parsed)

    @patch('ncclient.transport.Session.send')
    @patch(patch_str)
    def test_rpc_send(self, mock_thread, mock_send):
        device_handler, session = self._mock_device_handler_and_session()
        obj = RPC(session, device_handler, raise_mode=RaiseMode.ALL, timeout=0)
        reply = RPCReply(xml1)
        obj._reply = reply
        node = new_ele("commit")
        sub_ele(node, "confirmed")
        sub_ele(node, "confirm-timeout").text = "50"
        sub_ele(node, "log").text = "message"
        result = obj._request(node)
        ele = new_ele("rpc",
                      {"message-id": obj._id},
                      **device_handler.get_xml_extra_prefix_kwargs())
        ele.append(node)
        node = to_xml(ele)
        mock_send.assert_called_once_with(node)
        self.assertEqual(
            result.data_xml,
            (NCElement(
                reply,
                device_handler.transform_reply())).data_xml)
        self.assertEqual(obj.session, session)
        self.assertEqual(reply, obj.reply)

    @patch('ncclient.transport.Session.send')
    @patch(patch_str)
    def test_rpc_async(self, mock_thread, mock_send):
        device_handler, session = self._mock_device_handler_and_session()
        obj = RPC(
            session,
            device_handler,
            raise_mode=RaiseMode.ALL,
            timeout=0,
            async_mode=True)
        reply = RPCReply(xml1)
        obj._reply = reply
        node = new_ele("commit")
        result = obj._request(node)
        self.assertEqual(result, obj)

    @patch('ncclient.transport.Session.send')
    @patch(patch_str)
    def test_rpc_timeout_error(self, mock_thread, mock_send):
        device_handler, session = self._mock_device_handler_and_session()
        obj = RPC(session, device_handler, raise_mode=RaiseMode.ALL, timeout=0)
        reply = RPCReply(xml1)
        obj.deliver_reply(reply)
        node = new_ele("commit")
        sub_ele(node, "confirmed")
        mock_thread.return_value = False
        self.assertRaises(TimeoutExpiredError, obj._request, node)

    @patch('ncclient.transport.Session.send')
    @patch(patch_str)
    def test_rpc_rpcerror(self, mock_thread, mock_send):
        device_handler, session = self._mock_device_handler_and_session()
        obj = RPC(session, device_handler, raise_mode=RaiseMode.ALL, timeout=0)
        reply = RPCReply(xml1)
        obj._reply = reply
        node = new_ele("commit")
        sub_ele(node, "confirmed")

        err = RPCError(to_ele(xml2))
        obj.deliver_error(err)
        self.assertRaises(RPCError, obj._request, node)

    @patch('ncclient.transport.Session.send')
    @patch(patch_str)
    def test_rpc_capability_error(self, mock_thread, mock_send):
        device_handler, session = self._mock_device_handler_and_session()
        session._server_capabilities = [':running']
        obj = RPC(session, device_handler, raise_mode=RaiseMode.ALL, timeout=0)
        obj._assert(':running')
        self.assertRaises(MissingCapabilityError,
            obj._assert, ':candidate')

    @patch('ncclient.transport.Session.send')
    def test_rpc_huge_text_node_exception(self, mock_send):
        device_handler, session = self._mock_device_handler_and_session()
        obj = RPC(session, device_handler, raise_mode=RaiseMode.ALL, timeout=0)

        obj.deliver_reply(xml5_huge)
        node = new_ele("get-configuration", {'format': 'text'})
        self.assertRaises(etree.XMLSyntaxError, obj._request, node)

    @patch('ncclient.transport.Session.send')
    def test_rpc_huge_text_node_workaround(self, mock_send):
        device_handler, session = self._mock_device_handler_and_session()
        obj = RPC(session, device_handler, raise_mode=RaiseMode.ALL, timeout=0, huge_tree=True)
        self.assertTrue(obj.huge_tree)

        obj.deliver_reply(xml5_huge)
        node = new_ele("get-configuration", {'format': 'text'})
        result = obj._request(node)

        self.assertEqual(result.find('configuration-text').text, huge_configuration_text)
        obj.huge_tree = False
        self.assertFalse(obj.huge_tree)

    def _mock_device_handler_and_session(self):
        device_handler = manager.make_device_handler({'name': 'junos'})
        capabilities = Capabilities(device_handler.get_capabilities())
        session = ncclient.transport.Session(capabilities)
        return device_handler, session


text:
---
layout: post
permalink: /allowing-multiple-accounts-email-wordpress
title: "Allow Multiple Accounts with Same Email in WordPress"
category: "How To"
tags: account email multiple-emails registration wordpress
redirect_from:
 - /allowing-multiple-accounts-with-same-email-in-wordpress
---
### Introduction

I was working on a project where a users would register their family to a modified WordPress instance, and fill out additional User Meta. Each family member would have their own user account, but not all the time did each family member have their own email. For this reason, I needed a way to register multiple accounts with the same email. I Googled, but all the results were the same, use a `pre_user_email` hook. The problem with this is, in 3.9, the `pre_user_email` hook was never fired on account registration.

> *Note*: You will want to add this to your `functions.php` file in either your `plugin` or `theme`.

## The Documented Wrong Way

According to the documentation, the following should work out of the box:

    // This hook should run before user email validation
    add_filter( 'pre_user_email', 'skip_email_exist');
    /**
     * [skip_email_exist description]
     * @param [type] $user_email [description]
     * @return [type] [description]
     */
    function skip_email_exist($user_email){

        define( 'WP_IMPORTING', 'SKIP_EMAIL_EXIST' );
        return $user_email;
    }

But in Wordpress 3.9.1 it wasn't working. This function was never called on account registration, only on account import.

## The Right Way

I had to use the `registration_errors` hook to get it working. Here, I was able to unset the `email_exists` key from the `$errors` object and the account was added as expected.

    // Hook run on registration errors
    add_filter( 'registration_errors', 'dtr_registration_errors', 10, 3);
    /**
     * Removes email_exists error
     *
     * @since 1.0
     *
     * @param [type] $errors [description]
     * @param [type] $sanitized_user_login [description]
     * @param [type] $user_email [description]
     * @return [type] [description]
     */
    function dtr_registration_errors ($errors, $sanitized_user_login, $user_email) {

        if( isset($errors->errors['email_exists'])) {
            unset($errors->errors['email_exists']);
        }

        return $errors;
    }

Enjoy.


text:
define( [
		"dojo/_base/declare",
		"dijit/_WidgetBase",
		"dijit/_TemplatedMixin",
		"dojo/_base/lang",
		"dojo/dom-class",
		"dojo/touch",
		"dijit/form/HorizontalSlider",
		"dijit/form/HorizontalRuleLabels",
		"esri/dijit/BasemapGallery" ], function( declare, _WidgetBase, _TemplatedMixin, lang, domClass, touch,
		HorizontalSlider, HorizontalRuleLabels, BasemapGallery ){

		var Widget = declare( [ _WidgetBase, _TemplatedMixin ], {
			declaredClass: "mojo.BasemapSwitch",
			templateString:
				"
" +
					"
" +
						"
Streets
" +
						"
Aerials
" +
						"
Hybrid
" +
						"
Topo
" +
						"

" +
					"
" +
					"
" +
						"
" +
							"

" +
						"
" +
						"
" +
							"

" +
						"
" +
					"
" +
				"
",
			options: {
				map: null,
				aerialsLayers: null,
				selectedBasemap: "streets",
				basemaps: [ ]
			},

			refreshID: null,

			constructor: function( options, srcRefNode ){
				// mix in settings and defaults
				lang.mixin( this.options, options );

				//mix options with properties
				lang.mixin( this, this.options );
			},

			// start widget. called by user
			startup: function( ){
				this._init( );
			},

			// bind listener for touch action
			postCreate: function( ){
				touch.over( this._basemapswitch, lang.hitch( this, this._onMouseover ) );
				touch.out( this._basemapswitch, lang.hitch( this, this._onMouseout ) );
			},

			_init: function( ){
				//add basemap gallery
				this.basemapgallery = new BasemapGallery( {
					showArcGISBasemaps : false,
					basemaps : this.basemaps,
					map : this.map
				} );

				var slider = new HorizontalSlider( {
					name: "slider",
					value: 0,
					minimum: 0,
					maximum: 6,
					discreteValues: 7,
					intermediateChanges: true,
					showButtons: true,
					style: "width:166px;",
					onChange: lang.hitch( this, function( value ) {
						this.basemaps [ 1 ].layers.splice( 0, 1, this.aerialsLayers[ value ] );
						this.basemaps [ 2 ].layers.splice( 0, 1, this.aerialsLayers[ value ] );
						this.basemapgallery.select( this.selectedBasemap );

						var filteredArr = this.basemaps.filter( lang.hitch( this, function( item ) {
						  return item.id == this.selectedBasemap;
						} ) );

						var lyrs = "";
						filteredArr[ 0 ].layers.forEach ( function( layer, i ){
							lyrs += ( lyrs.length === 0 ? "": ",") + layer.url.replace ( "http://gisags03/ArcGIS03/rest/services/", "" ).replace ( "/MapServer", "" ) ;
						} );

						return this.onBaseMapChange( lyrs );
					} )
				}, this._slider ).startup( );

				var sliderLabels = new HorizontalRuleLabels( {
					labels: [ "2022", "2021", "2020", "2019", "2018", "2017", "2016" ],
					style: "font-size:8px;"
				}, this._rulelabel );
			},

			_onClick: function( event ){
				if( event.target.className.indexOf( "selected" ) === -1 ){
					domClass.remove( this["_" + this.selectedBasemap], "selected" );

					if( event.target.className.indexOf( "streets" ) > -1 ){
						this.selectedBasemap = "streets";
						domClass.add( this._aerialslider, "hidden" );
					}else if( event.target.className.indexOf( "aerials" ) > -1 ){
						this.selectedBasemap = "aerials";
						domClass.remove( this._aerialslider, "hidden" );
					}else if( event.target.className.indexOf( "hybrid" ) > -1 ){
						this.selectedBasemap = "hybrid";
						domClass.remove( this._aerialslider, "hidden" );
					}else if( event.target.className.indexOf( "topo" ) > -1 ){
						this.selectedBasemap = "topo";
						domClass.add( this._aerialslider, "hidden" );
					}

					domClass.add( this[ "_" + this.selectedBasemap ], "selected" );
					this.basemapgallery.select( this.selectedBasemap );

					var filteredArr = this.basemaps.filter( lang.hitch( this, function( item ){
					  return item.id == this.selectedBasemap;
					} ) );

					var lyrs = "";

					filteredArr[ 0 ].layers.forEach( function( layer, i ){
						lyrs += ( lyrs.length === 0 ? "": ",") + layer.url.replace ( "http://gisags03/ArcGIS03/rest/services/", "" ).replace ( "/MapServer", "" ) ;
					} );

					return this.onBaseMapChange( lyrs );
				}
			},

			_onMouseover: function( event ){
				if ( this.selectedBasemap === "aerials" || this.selectedBasemap === "hybrid" ){
					if( this.refreshID ){
						this.refreshID = window.clearInterval( this.refreshID );
					}

					//show dashboard
					domClass.remove( this._aerialslider, "hidden");
				}
			},

			_onMouseout: function( event ){
				if( this.selectedBasemap === "aerials" || this.selectedBasemap === "hybrid" ){
					//start timer to hide dashboard
					this.refreshID = self.setInterval( lang.hitch( this, function( ){
					domClass.add( this._aerialslider, "hidden" );
					} ), 2000 );
				}
			},

			onBaseMapChange: { // nothing here: the extension point!
			}
		} );
    return Widget;
} );


text:
package v1

import (
	"context"

	v1pb "go-common/app/interface/live/app-ucenter/api/http/v1"
	"go-common/app/interface/live/app-ucenter/conf"
	"go-common/app/interface/live/app-ucenter/dao"
	"go-common/library/ecode"
)

// TopicService struct
type TopicService struct {
	conf *conf.Config
	// optionally add other properties here, such as dao
	dao *dao.Dao
}

//NewTopicService init
func NewTopicService(c *conf.Config) (s *TopicService) {
	s = &TopicService{
		conf: c,
		dao:  dao.New(c),
	}
	return s
}

// GetTopicList implementation
// 获取话题列表
// `method:"GET" midware:"auth"`
func (s *TopicService) GetTopicList(ctx context.Context, req *v1pb.GetTopicListReq) (resp *v1pb.GetTopicListResp, err error) {
	reply, err := s.dao.GetTopicList(ctx)
	if err != nil {
		err = ecode.CallResourceError
		return
	}
	resp = &v1pb.GetTopicListResp{}
	resp.TopicList = reply
	return
}

// CheckTopic implementation
// 检验话题是否有效
// `method:"GET" midware:"auth"`
func (s *TopicService) CheckTopic(ctx context.Context, req *v1pb.CheckTopicReq) (resp *v1pb.CheckTopicResp, err error) {
	msg := req.Topic
	area := "live_biaoti"
	reply, err := s.dao.CheckMsgIsLegal(ctx, msg, area, 0)
	if err != nil {
		err = ecode.Error(ecode.CallMainFilterError, "出错啦,再试试吧")
		return
	}
	resp = &v1pb.CheckTopicResp{}
	if reply {
		err = ecode.Error(ecode.FILTERNOTPASS, "当前输入的话题里面包含敏感内容~请修改~")
		return
	}
	return
}


text:
#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

#include "dcmtk/dcmdata/dcvras.h"

// ********************************

DcmAgeString::DcmAgeString(const DcmTag &tag,
                           const Uint32 len)
  : DcmByteString(tag, len)
{
    setMaxLength(4);
}

DcmAgeString::DcmAgeString(const DcmAgeString &old)
  : DcmByteString(old)
{
}

DcmAgeString::~DcmAgeString()
{
}

DcmAgeString &DcmAgeString::operator=(const DcmAgeString &obj)
{
    DcmByteString::operator=(obj);
    return *this;
}

OFCondition DcmAgeString::copyFrom(const DcmObject& rhs)
{
  if (this != &rhs)
  {
    if (rhs.ident() != ident()) return EC_IllegalCall;
    *this = OFstatic_cast(const DcmAgeString &, rhs);
  }
  return EC_Normal;
}

// ********************************

DcmEVR DcmAgeString::ident() const
{
    return EVR_AS;
}

OFCondition DcmAgeString::checkValue(const OFString &vm,
                                     const OFBool /*oldFormat*/)
{
    OFString strVal;
    /* get "raw value" without any modifications (if possible) */
    OFCondition l_error = getStringValue(strVal);
    if (l_error.good())
        l_error = DcmAgeString::checkStringValue(strVal, vm);
    return l_error;
}

// ********************************

OFCondition DcmAgeString::checkStringValue(const OFString &value,
                                           const OFString &vm)
{
    return DcmByteString::checkStringValue(value, vm, "as", 1);
}

/*
** CVS/RCS Log:
** $Log: dcvras.cc,v $
** Revision 1.16  2010-10-20 16:44:17  joergr
** Use type cast macros (e.g. OFstatic_cast) where appropriate.
**
** Revision 1.15  2010-10-14 13:14:09  joergr
** Updated copyright header. Added reference to COPYRIGHT file.
**
** Revision 1.14  2010-04-23 14:30:34  joergr
** Added new method to all VR classes which checks whether the stored value
** conforms to the VR definition and to the specified VM.
**
** Revision 1.13  2009-08-03 09:02:59  joergr
** Added methods that check whether a given string value conforms to the VR and
** VM definitions of the DICOM standards.
**
** Revision 1.12  2008-07-17 10:31:32  onken
** Implemented copyFrom() method for complete DcmObject class hierarchy, which
** permits setting an instance's value from an existing object. Implemented
** assignment operator where necessary.
**
** Revision 1.11  2007-06-29 14:17:49  meichel
** Code clean-up: Most member variables in module dcmdata are now private,
**   not protected anymore.
**
** Revision 1.10  2005/12/08 15:41:46  meichel
** Changed include path schema for all DCMTK header files
**
** Revision 1.9  2002/12/06 13:20:48  joergr
** Enhanced "print()" function by re-working the implementation and replacing
** the boolean "showFullData" parameter by a more general integer flag.
** Made source code formatting more consistent with other modules/files.
**
** Revision 1.8  2001/06/01 15:49:14  meichel
** Updated copyright header
**
** Revision 1.7  2000/03/08 16:26:45  meichel
** Updated copyright header.
**
** Revision 1.6  1999/03/31 09:25:46  meichel
** Updated copyright header in module dcmdata
**
** Revision 1.5  1998/11/12 16:48:22  meichel
** Implemented operator= for all classes derived from DcmObject.
**
** Revision 1.4  1997/07/03 15:10:08  andreas
** - removed debugging functions Bdebug() and Edebug() since
**   they write a static array and are not very useful at all.
**   Cdebug and Vdebug are merged since they have the same semantics.
**   The debugging functions in dcmdata changed their interfaces
**   (see dcmdata/include/dcdebug.h)
**
** Revision 1.3  1996/01/05 13:27:45  andreas
** - changed to support new streaming facilities
** - unique read/write methods for file and block transfer
** - more cleanups
**
*/


text:
<?php

namespace SchoolBundle\Repository;

/**
 * ClasseRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ClasseRepository extends \Doctrine\ORM\EntityRepository
{

	public function findById($id)
    {
        $qb = $this->createQueryBuilder('c');

        $qb->where('c.id = :id')
              ->setParameter('id', $id);
        return $qb;
    }

    public function findByEnseignant($id)
    {
        $qb = $this->createQueryBuilder('c');

        $qb->where('c.responsable = :id')
              ->setParameter('id', $id);
        return $qb;
    }
}


text:
package io.agrest.converter.jsonvalue;

import com.fasterxml.jackson.databind.JsonNode;
import io.agrest.AgException;

import java.util.Base64;

public class Base64Converter extends AbstractConverter<byte[]> {

    private static final Base64Converter instance = new Base64Converter();

    public static Base64Converter converter() {
        return instance;
    }

    @Override
    protected byte[] valueNonNull(JsonNode node) {

        if (!node.isTextual()) {
            throw AgException.badRequest("Expected textual value, got: %s", node.asText());
        }

        try {
            return Base64.getDecoder().decode(node.asText());
        } catch (IllegalArgumentException e) {
            throw AgException.badRequest(e, "Failed to decode Base64 value: %s", node.asText());
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Smuuf\Koloader;

class SimpleCache {

	/** @var string Cache directory. **/
	private $directory;

	/** @var string Cache namespace **/
	private $namespace;

	/**
	 * @param string $path Cache directory path.
	 * @param string $namespace Cache namespace.
	 */
	public function __construct(string $path, ?string $namespace = null) {

		$path = rtrim($path, '\\/');
		if (!is_dir($path)) {
			throw new KoloaderException("Passed cache path '$path' is not a directory");
		}

		if (!is_writable($path)) {
			throw new KoloaderException("Cache directory '$path' not writable");
		}

		$this->directory = $path;
		$this->namespace = self::pathalize((string) $namespace);

	}

	public function load(string $key) {
		if (is_file($path = $this->getCachePath($key)) ){
			return json_decode(file_get_contents($path), true);
		}
	}

	public function save(string $key, $value) {
		return file_put_contents(
			$this->getCachePath($key),
			json_encode($value)
		);
	}

	private function getCachePath(string $key) {

		$filename = ($this->namespace ?? '') . ' ' . md5($key);
		return "{$this->directory}/{$filename}";

	}

	private static function pathalize(string $string): string {
		return preg_replace('#[^a-zA-Z0-9._-]#', '_', $string);
	}

}


text:
import EmulationWindow from './EmulationWindow'
export default EmulationWindow


text:
package org.apache.ignite.internal.processors.cache;

import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.binary.BinaryObjectBuilder;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.cache.QueryIndex;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.binary.AbstractBinaryArraysTest;
import org.apache.ignite.internal.binary.BinaryMarshaller;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.marshaller.Marshaller;
import org.apache.ignite.testframework.junits.IgniteTestResources;

/**
 *
 */
@SuppressWarnings("unchecked")
public abstract class IgniteCacheAbstractSqlDmlQuerySelfTest extends AbstractBinaryArraysTest {
    /** */
    protected final Marshaller marsh;

    /**
     *
     */
    IgniteCacheAbstractSqlDmlQuerySelfTest() {
        try {
            marsh = IgniteTestResources.getMarshaller();
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    /**
     * @return whether {@link #marsh} is an instance of {@link BinaryMarshaller} or not.
     */
    protected boolean isBinaryMarshaller() {
        return marsh instanceof BinaryMarshaller;
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        cfg.setPeerClassLoadingEnabled(false);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        startGridsMultiThreaded(3, true);

        ignite(0).createCache(cacheConfig("S2P", true, false).setIndexedTypes(String.class, Person.class));

        if (isBinaryMarshaller())
            ignite(0).createCache(createBinCacheConfig());
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        super.beforeTest();

        // Put to S2P only non binary Persons
        ignite(0).cache("S2P").put("FirstKey", new Person(1, "John", "White"));
        ignite(0).cache("S2P").put("SecondKey", new Person(2, "Joe", "Black"));
        ignite(0).cache("S2P").put("k3", new Person(3, "Sylvia", "Green"));
        ignite(0).cache("S2P").put("f0u4thk3y", new Person(4, "Jane", "Silver"));

        if (isBinaryMarshaller()) {
            ignite(0).cache("S2P-bin").put("FirstKey", createBinPerson(1, "John", "White"));
            ignite(0).cache("S2P-bin").put("SecondKey", createBinPerson(2, "Joe", "Black"));
            ignite(0).cache("S2P-bin").put("k3", createBinPerson(3, "Sylvia", "Green"));
            ignite(0).cache("S2P-bin").put("f0u4thk3y", createBinPerson(4, "Jane", "Silver"));
        }
    }

    /**
     * Create person.
     *
     * @param id ID.
     * @param name Name.
     * @param secondName Second name.
     * @return Person.
     */
    Object createPerson(int id, String name, String secondName) {
        if (!isBinaryMarshaller())
            return new Person(id, name, secondName);
        else
            return createBinPerson(id, name, secondName);
    }

    /**
     * Create binary person.
     *
     * @param id ID.
     * @param name Name.
     * @param secondName Second name.
     * @return Person.
     */
    private Object createBinPerson(int id, String name, String secondName) {
        BinaryObjectBuilder bldr = ignite(0).binary().builder("Person");

        bldr.setField("id", id);
        bldr.setField("firstName", name);
        bldr.setField("secondName", secondName);

        return bldr.build();
    }

    /**
     * @return Cache.
     */
    protected IgniteCache cache() {
        if (!isBinaryMarshaller())
            return ignite(0).cache("S2P");
        else
            return ignite(0).cache("S2P-bin").withKeepBinary();
    }

    /**
     * @param name Cache name.
     * @param partitioned Partition or replicated cache.
     * @param escapeSql whether identifiers should be quoted - see {@link CacheConfiguration#setSqlEscapeAll}
     * @return Cache configuration.
     */
    protected static CacheConfiguration cacheConfig(String name, boolean partitioned, boolean escapeSql) {
        return new CacheConfiguration(DEFAULT_CACHE_NAME)
            .setName(name)
            .setCacheMode(partitioned ? CacheMode.PARTITIONED : CacheMode.REPLICATED)
            .setAtomicityMode(CacheAtomicityMode.ATOMIC)
            .setBackups(1)
            .setSqlEscapeAll(escapeSql);
    }

    /**
     *
     */
    private static CacheConfiguration createBinCacheConfig() {
        CacheConfiguration ccfg = cacheConfig("S2P-bin", true, false);

        QueryEntity e = new QueryEntity(String.class.getName(), "Person");

        LinkedHashMap<String, String> flds = new LinkedHashMap<>();

        flds.put("id", Integer.class.getName());
        flds.put("firstName", String.class.getName());
        flds.put("secondName", String.class.getName());

        e.setFields(flds);

        e.setIndexes(Collections.<QueryIndex>emptyList());

        ccfg.setQueryEntities(Collections.singletonList(e));

        return ccfg;
    }

    /**
     *
     */
    static class Person implements Serializable {
        /** */
        public Person(int id, String name, String secondName) {
            this.id = id;
            this.name = name;
            this.secondName = secondName;
        }

        /** */
        @QuerySqlField
        protected int id;

        /** */
        @QuerySqlField(name = "firstName")
        protected final String name;

        /** */
        @QuerySqlField
        final String secondName;

        /** {@inheritDoc} */
        @Override public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Person person = (Person)o;

            return id == person.id && name.equals(person.name) && secondName.equals(person.secondName);

        }

        /** {@inheritDoc} */
        @Override public int hashCode() {
            int res = id;
            res = 31 * res + name.hashCode();
            res = 31 * res + secondName.hashCode();
            return res;
        }
    }
}