text:
package io.branch.referral.network;

import android.text.TextUtils;
import androidx.annotation.Nullable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;

import io.branch.referral.Branch;
import io.branch.referral.BranchError;
import io.branch.referral.Defines;
import io.branch.referral.PrefHelper;
import io.branch.referral.ServerResponse;

/**
 *

 * Abstract class for Branch remote interface. This class provides the abstraction layer for network operations between
 * Branch SDK and remote Branch servers. Extend this class for creating custom network interface.
 * Class provide abstract method for implementing RESTful requests to Branch server
 *
 * see {@link #doRestfulGet(String)}
 * {@link #doRestfulPost(String, JSONObject)}
 * {@link io.branch.referral.network.BranchRemoteInterface.BranchResponse}
 * {@link BranchRemoteException}
 *

 */
public abstract class BranchRemoteInterface {
    /**
     * Key for adding retry numbers for the request. This will help better network issue analysis and debugging.
     * Add the retry number to the GET Request as a query param and as a JSon key value for post
     */
    public static final String RETRY_NUMBER = "retryNumber";

    //----------- Abstract methods-----------------------//

    /**
     *

     * Abstract method to implement the network layer to do a RESTful GET to Branch servers.
     * This method is called whenever Branch SDK want to make a GET request to Branch servers.
     * Please note that this methods always called on the background thread and no need for thread switching for the network operations.
     *
     * @param url The url end point
     * @return {@link io.branch.referral.network.BranchRemoteInterface.BranchResponse} with the get result data and http status code
     * @throws BranchRemoteException Branch remote exception is thrown when there is an error in communicating to the Branch servers
     *                               BranchRemoteException contains the corresponding BranchError code for the error {@link BranchError#ERR_BRANCH_NO_CONNECTIVITY } | {@link BranchError#ERR_BRANCH_REQ_TIMED_OUT}
     *                               see {@link io.branch.referral.network.BranchRemoteInterface.BranchRemoteException}
     *                               {@link io.branch.referral.network.BranchRemoteInterface.BranchResponse}
     *
     *                               NOTE: For better debugging purpose conside adding {@link #RETRY_NUMBER} as a query params if you implement multiple retries for your request
     *

     */
    public abstract BranchResponse doRestfulGet(String url) throws BranchRemoteException;

    /**
     *

     * Abstract method to implement the network layer to do a RESTful GET to Branch servers.
     * This method is called whenever Branch SDK want to make a GET request to Branch servers.
     * Please note that this methods always called on the background thread and no need for thread switching to execute network operations.
     *
     * @param url     The url end point
     * @param payload The JSon object payload for the post request
     * @return {@link io.branch.referral.network.BranchRemoteInterface.BranchResponse} with the get result data and http status code
     * @throws BranchRemoteException Branch remote exception is thrown when there is an error in communicating to the Branch servers
     *                               BranchRemoteException contains the corresponding BranchError code for the error {@link BranchError#ERR_BRANCH_NO_CONNECTIVITY } | {@link BranchError#ERR_BRANCH_REQ_TIMED_OUT}
     *                               see {@link io.branch.referral.network.BranchRemoteInterface.BranchRemoteException}
     *                               {@link io.branch.referral.network.BranchRemoteInterface.BranchResponse}
     *
     *                               NOTE: For better debugging purpose conside adding {@link #RETRY_NUMBER} as a JSon keyvalue  if you implement multiple retries for your request
     *

     */
    public abstract BranchResponse doRestfulPost(String url, JSONObject payload) throws BranchRemoteException;

    //--------- public methods-----------------//

    /**
     * Method for handling the RESTful POST operations to Branch Servers. Internally calls abstract method {@link #doRestfulGet(String)}
     *
     * @param url       The url end point
     * @param params    {@link JSONObject with parameters to the GET call}
     * @param tag       {@link String} Tag for identifying the request for analytical or debugging purpose
     * @param branchKey {@link String} Branch key
     * @return {@link ServerResponse} object representing the result of RESTful GET to Branch Server
     */
    public final ServerResponse make_restful_get(String url, JSONObject params, String tag, String branchKey) {
        String modifiedUrl = url;
        params = params != null ? params : new JSONObject();
        if (addCommonParams(params, branchKey)) {
            modifiedUrl += this.convertJSONtoString(params);
        } else {
            return new ServerResponse(tag, BranchError.ERR_BRANCH_KEY_INVALID, "");
        }

        long reqStartTime = System.currentTimeMillis();
        PrefHelper.Debug("getting " + modifiedUrl);

        try {
            BranchResponse response = doRestfulGet(modifiedUrl);
            return processEntityForJSON(response, tag, response.requestId);
        } catch (BranchRemoteException branchError) {
            if (branchError.branchErrorCode == BranchError.ERR_BRANCH_REQ_TIMED_OUT) {
                return new ServerResponse(tag, BranchError.ERR_BRANCH_REQ_TIMED_OUT, "");
            } else { // All other errors are considered as connectivity error
                return new ServerResponse(tag, BranchError.ERR_BRANCH_NO_CONNECTIVITY, "");
            }
        } finally {
            // Add total round trip time
            if (Branch.getInstance() != null) {
                int brttVal = (int) (System.currentTimeMillis() - reqStartTime);
                Branch.getInstance().addExtraInstrumentationData(tag + "-" + Defines.Jsonkey.Branch_Round_Trip_Time.getKey(), String.valueOf(brttVal));
            }
        }
    }

    /**
     * Method for handling the RESTful POST operations to Branch Servers. Internally calls abstract method {@link #doRestfulPost(String, JSONObject)}
     *
     * @param url       The url end point
     * @param body      {@link JSONObject with parameters to the POST call}
     * @param tag       {@link String} Tag for identifying the request for analytical or debugging purpose
     * @param branchKey {@link String} Branch key
     * @return {@link ServerResponse} object representing the result of RESTful POST to Branch Server
     */
    public final ServerResponse make_restful_post(JSONObject body, String url, String tag, String branchKey) {
        long reqStartTime = System.currentTimeMillis();
        body = body != null ? body : new JSONObject();

        if (!addCommonParams(body, branchKey)) {
            return new ServerResponse(tag, BranchError.ERR_BRANCH_KEY_INVALID, "");
        }
        PrefHelper.Debug("posting to " + url);
        PrefHelper.Debug("Post value = " + body.toString());

        try {
            BranchResponse response = doRestfulPost(url, body);
            return processEntityForJSON(response, tag, response.requestId);
        } catch (BranchRemoteException branchError) {
            if (branchError.branchErrorCode == BranchError.ERR_BRANCH_REQ_TIMED_OUT) {
                return new ServerResponse(tag, BranchError.ERR_BRANCH_REQ_TIMED_OUT, "");
            } else { // All other errors are considered as connectivity error
                return new ServerResponse(tag, BranchError.ERR_BRANCH_NO_CONNECTIVITY, "");
            }
        } finally {
            if (Branch.getInstance() != null) {
                int brttVal = (int) (System.currentTimeMillis() - reqStartTime);
                Branch.getInstance().addExtraInstrumentationData(tag + "-" + Defines.Jsonkey.Branch_Round_Trip_Time.getKey(), String.valueOf(brttVal));
            }
        }
    }

    //----------- private methods----------------------------//

    /**
     *
Converts resultant output object from Branch Remote server into a {@link ServerResponse} object by
     * reading the content supplied in the raw server response, and creating a {@link JSONObject}
     * that contains the same data. This data is then attached as the post data of the
     * {@link ServerResponse} object returned.

     *
     * @param response Branch server response received containing response data with headers and response code
     * @param tag            A {@link String} value containing the tag value to be applied to the
     *                       resultant {@link ServerResponse} object.
     * @return A {@link ServerResponse} object representing the resultant output object from Branch Remote server
     * response in Branch SDK terms.
     * see HTTP/1.1: Status Codes
     */
    private ServerResponse processEntityForJSON(BranchResponse response, String tag, String requestId) {
        String responseString = response.responseData;

        int statusCode = response.responseCode;

        ServerResponse result = new ServerResponse(tag, statusCode, requestId);
        if(!TextUtils.isEmpty(requestId)){
            PrefHelper.Debug(String.format(Locale.getDefault(), "Server returned: [%s] Status: [%d]; Data: %s", requestId, statusCode, responseString));
        } else {
            PrefHelper.Debug(String.format("returned %s", responseString));
        }

        if (responseString != null) {
            try {
                JSONObject jsonObj = new JSONObject(responseString);
                result.setPost(jsonObj);
            } catch (JSONException ex) {
                try {
                    JSONArray jsonArray = new JSONArray(responseString);
                    result.setPost(jsonArray);
                } catch (JSONException ex2) {
                    PrefHelper.Debug("JSON exception: " + ex2.getMessage());
                }
            }
        }
        return result;
    }

    private boolean addCommonParams(JSONObject post, String branch_key) {
        try {
            if (!post.has(Defines.Jsonkey.UserData.getKey())) { // user data already has the sdk in it as part of v2 request
                post.put(Defines.Jsonkey.SDK.getKey(), "android" + Branch.getSdkVersionNumber());
            }
            if (!branch_key.equals(PrefHelper.NO_STRING_VALUE)) {
                post.put(Defines.Jsonkey.BranchKey.getKey(), branch_key);
                return true;
            }
        } catch (JSONException ignore) {
        }
        return false;
    }

    private String convertJSONtoString(JSONObject json) {
        StringBuilder result = new StringBuilder();
        if (json != null) {
            JSONArray names = json.names();
            if (names != null) {
                boolean first = true;
                int size = names.length();
                for (int i = 0; i < size; i++) {
                    try {
                        String key = names.getString(i);

                        if (first) {
                            result.append("?");
                            first = false;
                        } else {
                            result.append("&");
                        }

                        String value = json.getString(key);
                        result.append(key).append("=").append(value);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            }
        }

        return result.toString();
    }

    //-------------- Supporting classes -----------------------//

    /**
     *

     * Class for providing result of RESTful operation against Branch Remote server
     *

     */
    public static class BranchResponse {
        private final String responseData;
        private final int responseCode;
        String requestId;

        /**
         * Creates a BranchResponse object with response data and status code
         *
         * @param responseData The data returned by branch server. Nullable in case of errors.(Note :please see {@link io.branch.referral.network.BranchRemoteInterface.BranchRemoteException} for a better handling of errors)
         * @param responseCode Standard Http Response code (rfc2616 http error codes)
         */
        public BranchResponse(@Nullable String responseData, int responseCode) {
            this.responseData = responseData;
            this.responseCode = responseCode;
        }
    }

    /**
     * Exception thrown when there is an error while doing a restful operation with Branch Remote server
     * see {@link #doRestfulGet(String)} and {@link #doRestfulPost(String, JSONObject)}
     */
    public static class BranchRemoteException extends Exception {
        private int branchErrorCode = BranchError.ERR_BRANCH_NO_CONNECTIVITY;

        /**
         * Creates BranchRemoteException
         *
         * @param errorCode Error code for operation failure. Should be one of
         *                  {@link BranchError#ERR_BRANCH_REQ_TIMED_OUT} | {@link BranchError#ERR_BRANCH_NO_CONNECTIVITY}
         */
        public BranchRemoteException(int errorCode) {
            branchErrorCode = errorCode;
        }
    }

}


text:
from os.path import join
from mklib import Task, File
from mklib.sh import touch

class answer(Task):
    "touch answer.tmp"
    results = ["answer.tmp"]
    def make(self):
        touch(join(self.dir, "answer.tmp"))

class answer_tmp(File):
    path = "answer.tmp"
    deps = ["question.txt"]

redpajama_set_name: RedPajamaGithub


text:
package org.knowm.proprioceptron.thematrix;

import com.jme3.math.Vector3f;

/**
 * a wrapper class for all of the variables that the the character should be able to sense about a particular pill.
 *
 * @author Moobear
 * @create Oct 12, 2012
 */
public class PillPerceptionState {

  private final Vector3f relativePosition;
  private final float distLeftEye;
  private final float distRightEye;
  private final float distHead;
  private final boolean wasCollision;
  private final boolean isBlue;

  public PillPerceptionState(Vector3f relativePosition, float distLeftEye, float distRightEye, float distHead, boolean isBlue, boolean wasCollision) {

    this.relativePosition = relativePosition;
    this.distLeftEye = distLeftEye;
    this.distRightEye = distRightEye;
    this.distHead = distHead;
    this.wasCollision = wasCollision;
    this.isBlue = isBlue;
  }

  public Vector3f getRelativePosition() {

    return relativePosition;
  }

  public float getDistLeftEye() {

    return distLeftEye;
  }

  public float getDistRightEye() {

    return distRightEye;
  }

  public float getDistHead() {

    return distHead;
  }

  public boolean isWasCollision() {

    return wasCollision;
  }

  @Override
  public String toString() {

    return (isBlue ? "\nBluePill" : "\nRedPill") + "\nLeft eye distance: " + distLeftEye + "\nRight eye distance: " + distRightEye + "\ndistance to forehead: " + distHead + "\nCollision? " + wasCollision;
  }
}


text:
<?php

namespace Popov\Importer;

class Observable implements ObservableInterface
{
    protected $events = [];

    public function trigger($eventName, $target = null, $params = [])
    {
        foreach ($this->events[$eventName] as $listener) {
            $listener($target, $params);
        }
    }

    /**
     * @inheritDoc
     */
    public function attach($eventName, callable $listener)
    {
        $this->events[$eventName][] = $listener;

        return $listener;
    }

    /**
     * @inheritDoc
     */
    public function detach(callable $listener, $eventName)
    {
        foreach ($this->events[$eventName] as $i => $callback) {
            if ($callback === $listener) {
                unset($this->events[$eventName][$i]);
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using ATMobile.Enums;
using ATMobile.Objects;
using LiteDB;

namespace ATMobile.Daos
{
    public class ChartEntryDao : AbstractDao<ChartEntry>
    {
        public ChartEntryDao (LiteDatabase _db)
            : base (_db)
        {
        }

        public override string CollectionName {
            get {
                return "ChartEntries";
            }
        }

        public override void BuildIndexes ()
        {

        }

        public List<ChartEntry> GetChartEntriesForEnds (Guid _endParentId, Guid _archerId)
        {
            Query query =
                    Query.And (
                        Query.EQ ("ParentId", _endParentId),
                        Query.EQ ("ArcherId", _archerId));

            return m_Collection.Find (query).OrderBy (r => r.Sequence).ToList ();
        }

        public List<ChartEntry> GetChartEntriesForRounds (Guid _tournamentId, Guid _archerId)
        {
            Query query =
                    Query.And (
                        Query.EQ ("ParentId", _tournamentId),
                        Query.EQ ("ArcherId", _archerId));

            return m_Collection.Find (query).OrderBy (r => r.Sequence).ToList ();
        }

        public List<ChartEntry> GetChartEntriesForPractices (DateTime _startDate, DateTime _endDate, Guid _archerId)
        {
            Query query =
                Query.And (
                    Query.And (
                        Query.Between ("Date", _endDate, _endDate),
                        Query.EQ ("ChartEntryType", (int)ChartEntryTypes.Practice)),
                    Query.EQ ("ArcherId", _archerId));
            return m_Collection.Find (query).OrderBy (r => r.Date).ToList ();
        }

        public List<ChartEntry> GetChartEntriesForTournaments (DateTime _startDate, DateTime _endDate, Guid _archerId)
        {
            Query query =
                Query.And (
                    Query.And (
                        Query.Between ("Date", _endDate, _endDate),
                        Query.EQ ("ChartEntryType", (int)ChartEntryTypes.Tournament)),
                    Query.EQ ("ArcherId", _archerId));
            return m_Collection.Find (query).OrderBy (r => r.Date).ToList ();
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Parser\TokenParser\Chainable;

use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Parser\ChainableTokenParserInterface;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Token;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\TokenType;

/**
 * @covers \Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Parser\TokenParser\Chainable\EscapedValueTokenParser
 */
class EscapedValueTokenParserTest extends \PHPUnit_Framework_TestCase
{
    public function testIsAChainableTokenParser()
    {
        $this->assertTrue(is_a(EscapedValueTokenParser::class, ChainableTokenParserInterface::class, true));
    }

    /**
     * @expectedException \DomainException
     */
    public function testIsNotClonable()
    {
        clone new EscapedValueTokenParser();
    }

    /**
     * @dataProvider provideTokens
     */
    public function testCanParseEscapedTokens(Token $token, bool $expected)
    {
        $parser = new EscapedValueTokenParser();
        $actual = $parser->canParse($token);

        $this->assertEquals($expected, $actual);
    }

    /**
     * @expectedException \Nelmio\Alice\Throwable\Exception\FixtureBuilder\ExpressionLanguage\ParseException
     * @expectedExceptionMessage Could not parse the token "" (type: ESCAPED_VALUE_TYPE).
     */
    public function testThrowsAnExceptionIfAMalformedTokenIsGiven()
    {
        $token = new Token('', new TokenType(TokenType::ESCAPED_VALUE_TYPE));

        $parser = new EscapedValueTokenParser();
        $parser->parse($token);
    }

    public function testReturnsEscapedValue()
    {
        $token = new Token('\<', new TokenType(TokenType::ESCAPED_VALUE_TYPE));
        $expected = '<';

        $parser = new EscapedValueTokenParser();
        $actual = $parser->parse($token);

        $this->assertEquals($expected, $actual);
    }

    public function testTheEscapedValueIsDetokenizedBeforeBeingReturned()
    {
        $token = new Token('\<aliceTokenizedFunction(FUNCTION_START__foo__IDENTITY_OR_FUNCTION_END)>', new TokenType(TokenType::ESCAPED_VALUE_TYPE));
        $expected = '<foo()>';

        $parser = new EscapedValueTokenParser();
        $actual = $parser->parse($token);

        $this->assertEquals($expected, $actual);
    }

    public function provideTokens()
    {
        return [
            [
                new Token('', new TokenType(TokenType::DYNAMIC_ARRAY_TYPE)),
                false,
            ],
            [
                new Token('', new TokenType(TokenType::ESCAPED_VALUE_TYPE)),
                true,
            ],
        ];
    }
}


text:
/* jQuery Image Magnify script v1.1
* This notice must stay intact for usage
* Author: Dynamic Drive at http://www.dynamicdrive.com/
* Visit http://www.dynamicdrive.com/ for full source code

* Nov 16th, 09 (v1.1): Adds ability to dynamically apply/reapply magnify effect to an image, plus magnify to a specific width in pixels.
* Feb 8th, 11 (v1.11): Fixed bug that caused script to not work in newever versions of jQuery (ie: v1.4.4)
*/

jQuery.noConflict()

jQuery.imageMagnify={
	dsettings: {
		magnifyby: 3, //default increase factor of enlarged image
		duration: 500, //default duration of animation, in millisec
		imgopacity: 0.2 //opacify of original image when enlarged image overlays it
 	},
	cursorcss: 'url(magnify.cur), -moz-zoom-in', //Value for CSS's 'cursor' attribute, added to original image
	zIndexcounter: 100,

	refreshoffsets:function($window, $target, warpshell){
		var $offsets=$target.offset()
		var winattrs={x:$window.scrollLeft(), y:$window.scrollTop(), w:$window.width(), h:$window.height()}
		warpshell.attrs.x=$offsets.left //update x position of original image relative to page
		warpshell.attrs.y=$offsets.top
		warpshell.newattrs.x=winattrs.x+winattrs.w/2-warpshell.newattrs.w/2
		warpshell.newattrs.y=winattrs.y+winattrs.h/2-warpshell.newattrs.h/2
		if (warpshell.newattrs.x<winattrs.x+5){ //no space to the left?
			warpshell.newattrs.x=winattrs.x+5
		}
		else if (warpshell.newattrs.x+warpshell.newattrs.w > winattrs.x+winattrs.w){//no space to the right?
			warpshell.newattrs.x=winattrs.x+5
		}
		if (warpshell.newattrs.y<winattrs.y+5){ //no space at the top?
			warpshell.newattrs.y=winattrs.y+5
		}
	},

	magnify:function($, $target, options){
		var setting={} //create blank object to store combined settings
		var setting=jQuery.extend(setting, this.dsettings, options)
		var attrs=(options.thumbdimensions)? {w:options.thumbdimensions[0], h:options.thumbdimensions[1]} : {w:$target.outerWidth(), h:$target.outerHeight()}
		var newattrs={}
		newattrs.w=(setting.magnifyto)? setting.magnifyto : Math.round(attrs.w*setting.magnifyby)
		newattrs.h=(setting.magnifyto)? Math.round(attrs.h*newattrs.w/attrs.w) : Math.round(attrs.h*setting.magnifyby)
		$target.css('cursor', jQuery.imageMagnify.cursorcss)
		if ($target.data('imgshell')){
			$target.data('imgshell').$clone.remove()
			$target.css({opacity:1}).unbind('click.magnify')
		}
		var $clone=$target.clone().css({position:'absolute', left:0, top:0, visibility:'hidden', border:'1px solid gray', cursor:'pointer'}).appendTo(document.body)
		$clone.data('$relatedtarget', $target) //save $target image this enlarged image is associated with
		$target.data('imgshell', {$clone:$clone, attrs:attrs, newattrs:newattrs})
		$target.bind('click.magnify', function(e){ //action when original image is clicked on
			var $this=$(this).css({opacity:setting.imgopacity})
			var imageinfo=$this.data('imgshell')
			jQuery.imageMagnify.refreshoffsets($(window), $this, imageinfo) //refresh offset positions of original and warped images
			var $clone=imageinfo.$clone
			$clone.stop().css({zIndex:++jQuery.imageMagnify.zIndexcounter, left:imageinfo.attrs.x, top:imageinfo.attrs.y, width:imageinfo.attrs.w, height:imageinfo.attrs.h, opacity:0, visibility:'visible', display:'block'})
			.animate({opacity:1, left:imageinfo.newattrs.x, top:imageinfo.newattrs.y, width:imageinfo.newattrs.w, height:imageinfo.newattrs.h}, setting.duration,
			function(){ //callback function after warping is complete
				//none added
			}) //end animate
		}) //end click
		$clone.click(function(e){ //action when magnified image is clicked on
			var $this=$(this)
			var imageinfo=$this.data('$relatedtarget').data('imgshell')
			jQuery.imageMagnify.refreshoffsets($(window), $this.data('$relatedtarget'), imageinfo) //refresh offset positions of original and warped images
			$this.stop().animate({opacity:0, left:imageinfo.attrs.x, top:imageinfo.attrs.y, width:imageinfo.attrs.w, height:imageinfo.attrs.h},  setting.duration,
			function(){
				$this.hide()
				$this.data('$relatedtarget').css({opacity:1}) //reveal original image
			}) //end animate
		}) //end click
	}
};

jQuery.fn.imageMagnify=function(options){
	var $=jQuery
	return this.each(function(){ //return jQuery obj
		var $imgref=$(this)
		if (this.tagName!="IMG")
			return true //skip to next matched element
		if (parseInt($imgref.css('width'))>0 && parseInt($imgref.css('height'))>0 || options.thumbdimensions){ //if image has explicit width/height attrs defined
			jQuery.imageMagnify.magnify($, $imgref, options)
		}
		else if (this.complete){ //account for IE not firing image.onload
			jQuery.imageMagnify.magnify($, $imgref, options)
		}
		else{
			$(this).bind('load', function(){
				jQuery.imageMagnify.magnify($, $imgref, options)
			})
		}
	})
};

jQuery.fn.applyMagnifier=function(options){ //dynamic version of imageMagnify() to apply magnify effect to an image dynamically
	var $=jQuery
	return this.each(function(){ //return jQuery obj
		var $imgref=$(this)
		if (this.tagName!="IMG")
			return true //skip to next matched element

	})

};

//** The following applies the magnify effect to images with class="magnify" and optional "data-magnifyby" and "data-magnifyduration" attrs
//** It also looks for links with attr rel="magnify[targetimageid]" and makes them togglers for that image

jQuery(document).ready(function($){
	var $targets=$('.magnify')
	$targets.each(function(i){
		var $target=$(this)
		var options={}
		if ($target.attr('data-magnifyto'))
			options.magnifyto=parseFloat($target.attr('data-magnifyto'))
		if ($target.attr('data-magnifyby'))
			options.magnifyby=parseFloat($target.attr('data-magnifyby'))
		if ($target.attr('data-magnifyduration'))
			options.duration=parseInt($target.attr('data-magnifyduration'))
		$target.imageMagnify(options)
	})
	var $triggers=$('a[rel^="magnify["]')
	$triggers.each(function(i){
		var $trigger=$(this)
		var targetid=$trigger.attr('rel').match(/\[.+\]/)[0].replace(/[\[\]']/g, '') //parse 'id' from rel='magnify[id]'
		$trigger.data('magnifyimageid', targetid)
		$trigger.click(function(e){
			$('#'+$(this).data('magnifyimageid')).trigger('click.magnify')
			e.preventDefault()
		})
	})
})


text:
package tpe.oo.abstrakt;

/**
 * Ein Kreis.
 */
public class Kreis {

    /** Radius des Kreises. */
    private double radius;

    /**
     * Legt einen neuen Kreis an.
     *
     * @param radius Radius des Kreises.
     */
    public Kreis(double radius) {
        this.radius = radius;
    }

    /**
     * Berechnet die Fläche.
     *
     * @return die Fläche.
     */
    public double flaeche() {
        return Math.PI * radius * radius;
    }
}


text:
////////////////////////////////////////////////////////////////////////////////
//
//  EXPANZ
//  Copyright 2008-2011 EXPANZ
//  All Rights Reserved.
//
//  NOTICE: Expanz permits you to use, modify, and distribute this file
//  in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////

#import "xcode_ClassDefinition.h"

@implementation xcode_ClassDefinition

@synthesize className = _className;
@synthesize header = _header;
@synthesize source = _source;

/* ================================================= Class Methods ================================================== */
+ (ClassDefinition*) classDefinitionWithName:(NSString*)fileName {
    return [[ClassDefinition alloc] initWithName:fileName];
}

+ (ClassDefinition*) classDefinitionWithName:(NSString*)className language:(ClassDefinitionLanguage)language {
    return [[ClassDefinition alloc] initWithName:className language:language];
}

/* ================================================== Initializers ================================================== */
- (id) initWithName:(NSString*)className {
    return [self initWithName:className language:ObjectiveC];
}

- (id) initWithName:(NSString*)className language:(ClassDefinitionLanguage)language {
    self = [super init];
    if (self) {
        _className = [className copy];
        if (!(language == ObjectiveC || language == ObjectiveCPlusPlus)) {
            [NSException
                    raise:NSInvalidArgumentException format:@"Language must be one of ObjectiveC, ObjectiveCPlusPlus"];
        }
        _language = language;
    }
    return self;
}

/* ================================================ Interface Methods =============================================== */
- (BOOL) isObjectiveC {
    return _language == ObjectiveC;
}

- (BOOL) isObjectiveCPlusPlus {
    return _language == ObjectiveCPlusPlus;
}

- (NSString*) headerFileName {
    return [_className stringByAppendingString:@".h"];

}

- (NSString*) sourceFileName {
    NSString* sourceFileName = nil;
    if ([self isObjectiveC]) {
        sourceFileName = [_className stringByAppendingString:@".m"];
    }
    else if ([self isObjectiveCPlusPlus]) {
        sourceFileName = [_className stringByAppendingString:@".mm"];
    }
    return sourceFileName;
}

@end


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Password Reset Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are the default lines which match reasons
    | that are given by the password broker for a password update attempt
    | has failed, such as for an invalid token or invalid new password.
    |
    */

    "password" => "كلمة المرور يجب أن تكون على الأقل 6 أحرف وتتطابق التأكيد.",
    "user"     => "لا يمكن إيجاد مستخدم بهذا البريد الالكترني.",
    "token"    => "رمز إعادة تعين كلمة المرور غير صالح.",
    "sent"     => "تم ارسال مذكر كلمة المرور!",
    "reset"    => "تم اعادة تعين كلمة المرور!",

];


text:
PORT=46576
TIMEOUT=30
MAX_RETRIES=5

if [ -z "$VIRTUAL_ENV" ]; then
    echo "ERROR: You are not running within a virtual environment" >&2
    exit 1
fi

mkdir -p artefacts
mkdir -p output; rm -Rf output/*

python create_pages.py --path-prefix "${PATH_PREFIX}"

python ./test/features/support/test_server.py $PORT >> /dev/null 2>&1 &

server_pid=$!
echo pid of server is $server_pid

python create_treemap_fallbacks.py "http://localhost:${PORT}/" $TIMEOUT $MAX_RETRIES

kill $server_pid

cd output/treemaps
tar -zcvf "../../artefacts/${TREEMAP_ARTEFACT_NAME}" .

cd ../../
rm -Rf output


text:
 * [ ] Provide (prototype) documentation in the following formats: REPL using @doc, html, as well as pdf
 * [ ] Copyright information (BSD 2-clause) in each file
 * [ ] Build a (user)sysimage to speed up starting time

## Orders in number fields

 * [ ] implement Montes--Nart algorithm
 * [ ] composite Dedekind criterion
 * [ ] composite Round Two algorithm
 * [ ] implement information about containment (O_1 \sub O_2)
 * [ ] save prime factors of discriminant
 * [x] `princ_gen` should be cached
 * [ ] Clean up uniformizer (p-uniformizer? strong uniformizer?)
 * [x] Residue fields of degree one
 * [ ] Parent checks for `(::Order)(::NumFieldElem)`.
 * [ ] Coercion of nf_elem in NfOrd

## Number fields
 * [ ] Overhaul the morphisms
 * [ ] Test functionality for non-monic defining polynomials
 * [x] Torsion unit functionality for number fields
 * [ ] Better algorithm for normal closure
 * [ ] weak and strong approximation
 * [ ] `absolute_field` is inconsistent and needs keyword for `simplify`
 * [ ] Remove the type `nf_elem_or_fac_elem`
 * [ ] Clean up the clever `princ_gen_special` code
 * [ ] Implement Arakelov and/or divisor type
 * [ ] Finite places
 * [ ] Need `is_maximal_order_known` and `isautomorphism_group_known`
 * [x] `relative_extension`
 * [ ] `is_locally_power` (at given primes or up to given bound)
 * [x] Frobenius automorphism of a field at a prime ideal
 * [ ] Redo the `automorphism_group` properly.
 * [ ] `coeff(z, i)` and `coefficients(z)` "inconsistencies"

 ## Renaming

 * [x] `DiagonalGroup` and `AbelianGroup` to `abelian_group`.
 * [x] `princ_gen` to `principal_generator`
 * [ ] `nf` to `number_field`
 * [x] Group algebra renaming
 * [ ] Make `has*` and `*_known` consistent.

 ## Misc
 * [ ] `exp_map_unit_grp_mod`
 * [ ] `charpoly` should have `parent = ` keyword.
 * [ ] Squarefree factorization over number fields (?)
 * [ ] Make FF robust for the use of `fmpz`.
 * [ ] `next_prime(::fmpz, ::Bool)`
 * [x] `round(::Type{fmpq}, ::fmpz)` is doing funky things. Also needs the `RoundUp/RoundDown` versions.
 * [x] Parent checks for factored elements
 * [ ] Primitive element for all finite fields


text:
import gulp from 'gulp';

import getServer from './src';

gulp.task('server', (cb) => {
  getServer().listen(process.env.PORT || 3000, cb);
});


text:
package system

type platformStatT struct {
}

// Flags return file flags if supported or zero otherwise
func (s StatT) Flags() uint32 {
	_ = s.platformStatT // Silence warnings that StatT.platformStatT is unused (on these platforms)
	return 0
}


text:
package org.auraframework.impl.javascript.provider;

import java.io.IOException;

import org.auraframework.builder.ComponentDefRefBuilder;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.ProviderDef;
import org.auraframework.def.RootDefinition;
import org.auraframework.impl.system.DefinitionImpl;
import org.auraframework.instance.ComponentConfig;
import org.auraframework.throwable.quickfix.QuickFixException;
import org.auraframework.util.json.Json;

/**
 */
public class JavascriptProviderDef extends DefinitionImpl<ProviderDef> implements ProviderDef {
    /**
     */
    private static final long serialVersionUID = -3839367107553671775L;
    private final String code;

    protected JavascriptProviderDef(Builder builder) {
        super(builder);
        this.code = builder.code;
    }

    @Override
    public void serialize(Json json) throws IOException {
        json.writeMapBegin();
        json.writeMapEntry("code", code);
        json.writeMapEnd();
    }

    public static class Builder extends DefinitionImpl.BuilderImpl<ProviderDef> {

        public Builder() {
            super(ProviderDef.class);
        }

        public String code;

        @Override
        public JavascriptProviderDef build() {
            return new JavascriptProviderDef(this);
        }
    }

    @Override
    public boolean isLocal() {
        return false;
    }

    @Override
    public ComponentConfig provide(DefDescriptor<? extends RootDefinition> intfDescriptor) throws QuickFixException {
        return null;
    }

    @Override
    public ComponentConfig provide(ComponentDefRefBuilder ref) throws QuickFixException {
        return null;
    }

    @Override
    public boolean supportsRefProvide() {
        return false;
    }
}


text:
package services;

import domain.ReferenceRate;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class BfsCrossReferenceRatesRetrieverTest {

    @Mock
    private IReferenceRateQueryService referenceRateQueryService;

    @InjectMocks
    private BfsCrossReferenceRatesRetriever crossReferenceRatesRetriever;

    @Before
    public void setUp() {
        mockRefRate("EUR/GBP");
        mockRefRate("EUR/USD");
        mockRefRate("USD/JPY");
        mockRefRate("GBP/JPY");
        mockRefRate("CHF/RUB");
        mockRefRate("USD/CHF");

        mockRefRates("EUR", "EUR/GBP", "EUR/USD");
        mockRefRates("USD", "EUR/USD", "USD/JPY", "USD/CHF");
        mockRefRates("JPY", "USD/JPY", "GBP/JPY");
        mockRefRates("GBP", "EUR/GBP", "GBP/JPY");
        mockRefRates("CHF", "CHF/RUB", "USD/CHF");
    }

    private void mockRefRate(String ccyPair) {
        when(referenceRateQueryService.getReferenceRate(getFirstCcy(ccyPair), getSecondCcy(ccyPair)))
                .thenReturn(createRefRate(ccyPair));
    }

    private void mockRefRates(String fromCcy, String... ccyPairs) {
        when(referenceRateQueryService.getAllAvailableReferenceRate(fromCcy))
                .thenReturn(Stream
                                .of(ccyPairs)
                                .map(this::createRefRate)
                                .collect(Collectors.toList()));
    }

    private ReferenceRate createRefRate(String ccyPair) {
        return new ReferenceRate(getFirstCcy(ccyPair), getSecondCcy(ccyPair), BigDecimal.ONE);
    }

    private String getFirstCcy(String ccyPair) {
        return ccyPair.substring(0, 3);
    }

    private String getSecondCcy(String ccyPair) {
        return ccyPair.substring(ccyPair.length() - 3, ccyPair.length());
    }

    @Test
    public void testRetrieveCrossReferenceRates_NotFound() {
        List<String> expectedResults = Collections.emptyList();
        verifyResults(expectedResults, crossReferenceRatesRetriever.retrieveCrossReferenceRates("EUR", "CAD"));
    }

    @Test
    public void testRetrieveCrossReferenceRates_NoCrossesRequired() {
        List<String> expectedResults = Collections.singletonList("EUR/GBP");
        verifyResults(expectedResults, crossReferenceRatesRetriever.retrieveCrossReferenceRates("EUR", "GBP"));
    }

    @Test
    public void testRetrieveCrossReferenceRates_ShorterDistanceReturned() {
        List<String> expectedResults = Arrays.asList("USD/CHF", "EUR/USD");
        verifyResults(expectedResults, crossReferenceRatesRetriever.retrieveCrossReferenceRates("EUR", "CHF"));
    }

    @Test
    public void testRetrieveCrossReferenceRates_LongestPath() {
        List<String> expectedResults = Arrays.asList("CHF/RUB", "USD/CHF", "EUR/USD");
        verifyResults(expectedResults, crossReferenceRatesRetriever.retrieveCrossReferenceRates("EUR", "RUB"));
    }

    private void verifyResults(List<String> expectedResults, List<ReferenceRate> results) {
        System.out.println("Expected: " + expectedResults);
        System.out.println("Actual: " + results);

        assertEquals(expectedResults.size(), results.size());
        IntStream
                .range(0, expectedResults.size())
                .forEach(index -> assertEquals(expectedResults.get(index), results.get(index).getCcyPair()));
    }
}


text:
<?php

namespace Usuarios\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;

class UsuarioTable extends AbstractTableGateway {

    protected $table = 'tab_usuario';

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
    }

    public function save(Entity\Usuario $usuario) {
        $data = array(
            'id_rol_usuario' => $usuario->getIdRolUsuario(),
            'nombre' => $usuario->getNombre(),
        );
        $id = (int) $usuario->getId();
        if ($id == 0) {
            $data['id_empleado'] = $usuario->getIdEmpleado();
            $data['password'] = $usuario->getPassword();
            if (!$this->insert($data)){
                return false;
            }else{
                return $this->getLastInsertValue();
            }
        }else{
            if (!$this->update($data, array('id' => $id))){
                return false;
            }else{
                return $id;
            }
        }
    }

    public function fetchAll() {

        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from($this->table)
            ->join('tab_empleado', 'tab_empleado.id = tab_usuario.id_empleado',
              array('empleado' => 'nombre'))
            ->join('cat_rol_usuario', 'cat_rol_usuario.id = tab_usuario.id_rol_usuario',
              array('rol' => 'nombre'));

//        echo $select->getSqlString();
        $statement = $sql->prepareStatementForSqlObject($select);
        $resultSet = $statement->execute();

        $entities = array();
        foreach ($resultSet as $row) {
            $entity = new Entity\Usuario(array(
                'id' => $row["id"],
                'id_rol_usuario' => $row["id_rol_usuario"],
                'nombre' => $row["nombre"],
                'empleado' => $row["empleado"],
                'rol' => $row["rol"],
            ));
            $entities[] = $entity->toArray();
        }
        return $entities;
    }

    public function fetch($id) {

        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from($this->table)
        ->join('tab_empleado', 'tab_empleado.id = tab_usuario.id_empleado',
          array('empleado' => 'nombre'))
        ->join('cat_rol_usuario', 'cat_rol_usuario.id = tab_usuario.id_rol_usuario',
          array('rol' => 'nombre'));

        $where = new  Where();
        $where->equalTo('tab_usuario.id', $id) ;
        $select->where($where);

        $statement = $sql->prepareStatementForSqlObject($select);
        $resultSet = $statement->execute();

        foreach ($resultSet as $row) {
            $entity = new Entity\Usuario(array(
              'id' => $row["id"],
              'id_rol_usuario' => $row["id_rol_usuario"],
              'nombre' => $row["nombre"],
              'empleado' => $row["empleado"],
              'rol' => $row["rol"],
            ));
            $entity = $entity->toArray();
        }

        if(isset($entity)){
            return $entity;
        }else{
            return 0;
        }

    }

    public function fetchByName($nombre) {

        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from($this->table)
          ->join('tab_empleado', 'tab_empleado.id = tab_usuario.id_empleado',
            array('id_tipo_empleado' => 'id_tipo_empleado'));

        $where = new  Where();
        $where->equalTo('tab_usuario.nombre', $nombre) ;
        $select->where($where);

        $statement = $sql->prepareStatementForSqlObject($select);
        $resultSet = $statement->execute();

        foreach ($resultSet as $row) {
            $entity = new Entity\Usuario(array(
              'id' => $row["id"],
              'id_rol_usuario' => $row["id_rol_usuario"],
              'nombre' => $row["nombre"],
              'id_tipo_empleado' => $row["id_tipo_empleado"],
            ));
        }

        if(isset($entity)){
            return $entity->toArray();
        }else{
            return 0;
        }

    }

    public function removeUsuario($id) {
        return $this->delete(array('id' => (int) $id));
    }

    public function fetchAllByIdRolesUsuario($ids) {

        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from($this->table);

        $where = new  Where();
        $where->in('tab_usuario.id_rol_usuario', $ids);
        $select->where($where);

        $statement = $sql->prepareStatementForSqlObject($select);
        $resultSet = $statement->execute();

        $entities = array();
        foreach ($resultSet as $row) {
            $entity = new Entity\Usuario(array(
              'id' => $row["id"],
              'id_rol_usuario' => $row["id_rol_usuario"],
              'nombre' => $row["nombre"],
            ));
            $entities[] = $entity->toArray();
        }
        return $entities;
    }

}


text:
'''
Functions for helping with serialization and deserialization of
Bokeh objects.

Certain NumPy array dtypes can be serialized to a binary format for
performance and efficiency. The list of supported dtypes is:

{binary_array_types}

'''

#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import annotations

import logging # isort:skip
log = logging.getLogger(__name__)

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Standard library imports
import datetime as dt
import uuid
from functools import lru_cache
from threading import Lock
from typing import TYPE_CHECKING, Any, Type

# External imports
import numpy as np

# Bokeh imports
from ..core.types import ID
from ..settings import settings
from .strings import format_docstring

if TYPE_CHECKING:
    import numpy.typing as npt
    import pandas as pd
    from typing_extensions import TypeGuard

#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------

@lru_cache(None)
def _compute_datetime_types() -> set[type]:
    import pandas as pd

    result = {dt.time, dt.datetime, np.datetime64}
    result.add(pd.Timestamp)
    result.add(pd.Timedelta)
    result.add(pd.Period)
    result.add(type(pd.NaT))
    return result

def __getattr__(name: str) -> Any:
    if name == "DATETIME_TYPES":
        return _compute_datetime_types()
    raise AttributeError

BINARY_ARRAY_TYPES = {
    np.dtype(np.bool_),
    np.dtype(np.uint8),
    np.dtype(np.int8),
    np.dtype(np.uint16),
    np.dtype(np.int16),
    np.dtype(np.uint32),
    np.dtype(np.int32),
    #np.dtype(np.uint64),
    #np.dtype(np.int64),
    np.dtype(np.float32),
    np.dtype(np.float64),
}

NP_EPOCH = np.datetime64(0, 'ms')
NP_MS_DELTA = np.timedelta64(1, 'ms')

DT_EPOCH = dt.datetime.utcfromtimestamp(0)

__doc__ = format_docstring(__doc__, binary_array_types="\n".join(f"* ``np.{x}``" for x in BINARY_ARRAY_TYPES))

__all__ = (
    'array_encoding_disabled',
    'convert_date_to_datetime',
    'convert_datetime_array',
    'convert_datetime_type',
    'convert_timedelta_type',
    'is_datetime_type',
    'is_timedelta_type',
    'make_globally_unique_id',
    'make_id',
    'transform_array',
    'transform_series',
)

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

def is_datetime_type(obj: Any) -> TypeGuard[dt.time | dt.datetime | np.datetime64]:
    ''' Whether an object is any date, time, or datetime type recognized by
    Bokeh.

    Arg:
        obj (object) : the object to test

    Returns:
        bool : True if ``obj`` is a datetime type

    '''
    _dt_tuple = tuple(_compute_datetime_types())

    return isinstance(obj, _dt_tuple)

def is_timedelta_type(obj: Any) -> TypeGuard[dt.timedelta | np.timedelta64]:
    ''' Whether an object is any timedelta type recognized by Bokeh.

    Arg:
        obj (object) : the object to test

    Returns:
        bool : True if ``obj`` is a timedelta type

    '''
    return isinstance(obj, (dt.timedelta, np.timedelta64))

def convert_date_to_datetime(obj: dt.date) -> float:
    ''' Convert a date object to a datetime

    Args:
        obj (date) : the object to convert

    Returns:
        datetime

    '''
    return (dt.datetime(*obj.timetuple()[:6], tzinfo=None) - DT_EPOCH).total_seconds() * 1000

def convert_timedelta_type(obj: dt.timedelta | np.timedelta64) -> float:
    ''' Convert any recognized timedelta value to floating point absolute
    milliseconds.

    Arg:
        obj (object) : the object to convert

    Returns:
        float : milliseconds

    '''
    if isinstance(obj, dt.timedelta):
        return obj.total_seconds() * 1000.
    elif isinstance(obj, np.timedelta64):
        return float(obj / NP_MS_DELTA)

    raise ValueError(f"Unknown timedelta object: {obj!r}")

# The Any here should be pd.NaT | pd.Period but mypy chokes on that for some reason
def convert_datetime_type(obj: Any | pd.Timestamp | pd.Timedelta | dt.datetime | dt.date | dt.time | np.datetime64) -> float:
    ''' Convert any recognized date, time, or datetime value to floating point
    milliseconds since epoch.

    Arg:
        obj (object) : the object to convert

    Returns:
        float : milliseconds

    '''
    import pandas as pd

    # Pandas NaT
    if obj is pd.NaT:
        return np.nan

    # Pandas Period
    if isinstance(obj, pd.Period):
        return obj.to_timestamp().value / 10**6.0

    # Pandas Timestamp
    if isinstance(obj, pd.Timestamp):
        return obj.value / 10**6.0

    # Pandas Timedelta
    elif isinstance(obj, pd.Timedelta):
        return obj.value / 10**6.0

    # Datetime (datetime is a subclass of date)
    elif isinstance(obj, dt.datetime):
        diff = obj.replace(tzinfo=None) - DT_EPOCH
        return diff.total_seconds() * 1000

    # XXX (bev) ideally this would not be here "dates are not datetimes"
    # Date
    elif isinstance(obj, dt.date):
        return convert_date_to_datetime(obj)

    # NumPy datetime64
    elif isinstance(obj, np.datetime64):
        epoch_delta = obj - NP_EPOCH
        return float(epoch_delta / NP_MS_DELTA)

    # Time
    elif isinstance(obj, dt.time):
        return (obj.hour * 3600 + obj.minute * 60 + obj.second) * 1000 + obj.microsecond / 1000.

    raise ValueError(f"unknown datetime object: {obj!r}")

def convert_datetime_array(array: npt.NDArray[Any]) -> npt.NDArray[np.floating[Any]]:
    ''' Convert NumPy datetime arrays to arrays to milliseconds since epoch.

    Args:
        array : (obj)
            A NumPy array of datetime to convert

            If the value passed in is not a NumPy array, it will be returned as-is.

    Returns:
        array

    '''
    # not quite correct, truncates to ms..
    if array.dtype.kind == 'M':
        return array.astype('datetime64[us]').astype('int64') / 1000.0

    elif array.dtype.kind == 'm':
        return array.astype('timedelta64[us]').astype('int64') / 1000.0

    # XXX (bev) special case dates, not great
    elif array.dtype.kind == 'O' and len(array) > 0 and isinstance(array[0], dt.date):
        try:
            return array.astype('datetime64[us]').astype('int64') / 1000.0
        except Exception:
            pass

    return array

def make_id() -> ID:
    ''' Return a new unique ID for a Bokeh object.

    Normally this function will return simple monotonically increasing integer
    IDs (as strings) for identifying Bokeh objects within a Document. However,
    if it is desirable to have globally unique for every object, this behavior
    can be overridden by setting the environment variable ``BOKEH_SIMPLE_IDS=no``.

    Returns:
        str

    '''
    global _simple_id

    if settings.simple_ids():
        with _simple_id_lock:
            _simple_id += 1
            return ID(f"p{_simple_id}")
    else:
        return make_globally_unique_id()

def make_globally_unique_id() -> ID:
    ''' Return a globally unique UUID.

    Some situations, e.g. id'ing dynamically created Divs in HTML documents,
    always require globally unique IDs.

    Returns:
        str

    '''
    return ID(str(uuid.uuid4()))

def array_encoding_disabled(array: npt.NDArray[Any]) -> bool:
    ''' Determine whether an array may be binary encoded.

    The NumPy array dtypes that can be encoded are:

    {binary_array_types}

    Args:
        array (np.ndarray) : the array to check

    Returns:
        bool

    '''

    # disable binary encoding for non-supported dtypes
    return array.dtype not in BINARY_ARRAY_TYPES

array_encoding_disabled.__doc__ = format_docstring(
    array_encoding_disabled.__doc__,
    binary_array_types="\n    ".join(f"* ``np.{x}``" for x in BINARY_ARRAY_TYPES),
)

def transform_array(array: npt.NDArray[Any]) -> npt.NDArray[Any]:
    ''' Transform a ndarray into a serializable ndarray.

    Converts un-serializable dtypes and returns JSON serializable
    format

    Args:
        array (np.ndarray) : a NumPy array to be transformed

    Returns:
        ndarray

    '''
    array = convert_datetime_array(array)

    # XXX: as long as we can't support 64-bit integers, try to convert
    # to 32-bits. If not possible, let the serializer convert to a less
    # efficient representation and/or deal with any error messaging.
    def _cast_if_can(array: npt.NDArray[Any], dtype: Type[Any]) -> npt.NDArray[Any]:
        info = np.iinfo(dtype)

        if np.any((array < info.min) | (info.max < array)):
            return array
        else:
            return array.astype(dtype, casting="unsafe")

    if array.dtype == np.dtype(np.int64):
        array = _cast_if_can(array, np.int32)
    elif array.dtype == np.dtype(np.uint64):
        array = _cast_if_can(array, np.uint32)

    if isinstance(array, np.ma.MaskedArray):
        array = array.filled(np.nan)  # type: ignore # filled is untyped
    if not array.flags["C_CONTIGUOUS"]:
        array = np.ascontiguousarray(array)

    return array

def transform_series(series: pd.Series[Any] | pd.Index) -> npt.NDArray[Any]:
    ''' Transforms a Pandas series into serialized form

    Args:
        series (pd.Series) : the Pandas series to transform

    Returns:
        ndarray

    '''
    import pandas as pd

    # not checking for pd here, this function should only be called if it
    # is already known that series is a Pandas Series type
    if isinstance(series, pd.PeriodIndex):
        vals = series.to_timestamp().values  # type: ignore
    else:
        vals = series.values
    return vals

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

_simple_id = 999
_simple_id_lock = Lock()

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------


text:
<?php

namespace freestyle;

/**
 * classMapLoader
 * Class map autoloader
 * ::create(array(class => file), __DIR__, 'name\\space')
 *
 * @package freestyle
 * @subpackage loader
 * @author olamedia
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 */
class classMapLoader{
	protected $_map = array();
	protected $_path = null;
	protected $_namespace = null;
	public function __construct($map = array(), $path = null, $namespace = null){
		$this->_map = $map;
		$this->_path = $path;
		$this->_namespace = $namespace;
		autoloadManager::getInstance()->registerClassLoader(array($this, 'loadClass'));
	}
	public static function create(){
		$args = \func_get_args();
		$class = new \ReflectionClass(\get_called_class());
		$constructor = $class->getConstructor();
		if ($constructor->isPublic()){
			$instance = $class->newInstanceArgs($args);
		}else{
			$constructor->setAccessible(true);
			$instance = $class->newInstanceWithoutConstructor();
			$constructor->invokeArgs($instance, $args);
		}
		return $instance;
	}
	public function loadClass($class){
		if ($this->_namespace !== null){
			if (\substr($class, 0, \strlen($this->_namespace)+1) != $this->_namespace.'\\'){
				return false;
			}
		}
		$left = (null === $this->_namespace)?$class:\substr($class, \strlen($this->_namespace)+1);
		if (isset($this->_map[$left])){
			$fn = (string) ($this->_path === null?'':$this->_path.\DIRECTORY_SEPARATOR).$this->_map[$left];
			if (\is_file($fn)){
				include $fn;
				autoloadManager::getInstance()->cache($class, $fn);
				unset($this->_map[$left]);
				return true;
			}else{
				require $fn;
				\clearstatcache(true);
				throw new \Exception('File not found "'.$fn.'". Class: "'.$class.'".');
			}
		}
		return false;
	}
}


text:
<?php
/**
 * The template for displaying Search Results pages.
 *
 * @package WordPress
 * @subpackage Starkers
 * @since Starkers 3.0
 */

get_header(); ?>

<?php if ( have_posts() ) : ?>

<?php printf( __( 'Search Results for: %s', 'twentyten' ), '' . get_search_query() . '' ); ?>

				<?php
				/* Run the loop for the search to output the results.
				 * If you want to overload this in a child theme then include a file
				 * called loop-search.php and that will be used instead.
				 */
				 get_template_part( 'loop', 'search' );
				?>
<?php else : ?>

<?php _e( 'Nothing Found', 'twentyten' ); ?>

<?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'twentyten' ); ?>

					<?php get_search_form(); ?>
<?php endif; ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>


text:
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var gutil = require('gulp-util');
var eslint = require('gulp-eslint');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var del = require('del');
require('babel-core/register');

var webpackConfig = require('./webpack.config.js');

gulp.task('lint', function () {
  return gulp.src(['src/**/*.js'])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('mocha', function() {
  return gulp.src(['test/**/*.js'], { read: false })
    .pipe(mocha({ reporter: 'list' }))
    .on('error', gutil.log);
});

gulp.task('webpack', function(callback) {
  // run webpack
  webpack(webpackConfig, function(err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);
    gutil.log('[webpack]', stats.toString({}));
    callback();
  });
});

gulp.task('devserver', function() {
  // Start a webpack-dev-server
  var compiler = webpack(webpackConfig);

  new WebpackDevServer(compiler, {
    // server and middleware options
  }).listen(8080, 'localhost', function(err) {
    if (err) throw new gutil.PluginError('webpack-dev-server', err);
    // Server listening
    gutil.log('[webpack-dev-server]',
      'http://localhost:8080/webpack-dev-server/index.html');
  });
});

gulp.task('watch', function() {
  gulp.watch(['src/**', 'test/**'], ['mocha', 'lint', 'webpack']);
});

gulp.task('clean', function(callback) {
  del([
    'dist/**/*'
  ], callback);
});

gulp.task('dev', ['devserver'], function() {
  gulp.watch(['src/**', 'test/**'], ['mocha', 'lint']);
});

gulp.task('test', ['mocha', 'lint']);

gulp.task('default', ['mocha', 'lint', 'webpack']);


text:
<?php

namespace User\Service;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
class Acl implements ServiceLocatorAwareInterface
{
    use ServiceLocatorAwareTrait;

    public function isAllowed($userId,$controller,$action)
    {
        $userDao = $this->getServiceLocator()->get('User\Dao\UserDao');
        $user = $userDao->getById($userId);
        $aclActions = [];
        if(null!==$user->getRole()){
             $aclActions = $user->getRole()->getAclActions()->getValues();
        }

        $controllers = [];
        for ($i = 0; $i < sizeof($aclActions); $i ++) {

               if ($controller == $aclActions[$i]->getAction()->getResource()->getResource()){
                    $actionInDataBase = $aclActions[$i]->getAction()->getAction();

                    if($action == $actionInDataBase || $actionInDataBase == "all" ){
                        return true;
                    }
               }
        }
        return false;
    }
}


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: ./core/src/java/org/apache/lucene/search/similarities/BasicModelG.java
//

#include "J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelG")
#ifdef RESTRICT_OrgApacheLuceneSearchSimilaritiesBasicModelG
#define INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelG 0
#else
#define INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelG 1
#endif
#undef RESTRICT_OrgApacheLuceneSearchSimilaritiesBasicModelG

#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif

#if !defined (OrgApacheLuceneSearchSimilaritiesBasicModelG_) && (INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelG || defined(INCLUDE_OrgApacheLuceneSearchSimilaritiesBasicModelG))
#define OrgApacheLuceneSearchSimilaritiesBasicModelG_

#define RESTRICT_OrgApacheLuceneSearchSimilaritiesBasicModel 1
#define INCLUDE_OrgApacheLuceneSearchSimilaritiesBasicModel 1
#include "org/apache/lucene/search/similarities/BasicModel.h"

@class OrgApacheLuceneSearchSimilaritiesBasicStats;

/*!
 @brief Geometric as limiting form of the Bose-Einstein model.The formula used in Lucene differs
  slightly from the one in the original paper: F is increased by 1
  and N is increased by F.
 */
@interface OrgApacheLuceneSearchSimilaritiesBasicModelG : OrgApacheLuceneSearchSimilaritiesBasicModel

#pragma mark Public

/*!
 @brief Sole constructor: parameter-free
 */
- (instancetype __nonnull)init;

- (jfloat)scoreWithOrgApacheLuceneSearchSimilaritiesBasicStats:(OrgApacheLuceneSearchSimilaritiesBasicStats *)stats
                                                     withFloat:(jfloat)tfn;

- (NSString *)description;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchSimilaritiesBasicModelG)

FOUNDATION_EXPORT void OrgApacheLuceneSearchSimilaritiesBasicModelG_init(OrgApacheLuceneSearchSimilaritiesBasicModelG *self);

FOUNDATION_EXPORT OrgApacheLuceneSearchSimilaritiesBasicModelG *new_OrgApacheLuceneSearchSimilaritiesBasicModelG_init(void) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT OrgApacheLuceneSearchSimilaritiesBasicModelG *create_OrgApacheLuceneSearchSimilaritiesBasicModelG_init(void);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneSearchSimilaritiesBasicModelG)

#endif

#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelG")


text:
from django.contrib.auth import get_user_model
from django.contrib.sites.managers import CurrentSiteManager
from django.contrib.sites.models import Site
from django.db import models
from django.dispatch import receiver
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from social_graph import Graph
from notifications.models import Event, NotificationTemplateConfig
from content_interactions.mixins import (
    LikableMixin,
    DenounceTargetMixin,
    CommentTargetMixin,
    ShareToSocialNetworkTargetMixin
)
from content_interactions_stats.mixins import StatsMixin
from mixins import ShareToSocialGroupTargetMixin
from signals import (
    follower_relationship_created,
    follower_relationship_destroyed,
    friend_request_created,
    friendship_created,
    social_group_created,
    social_group_membership_request_created,
    social_group_member_added,
    social_group_post_created,
    social_group_post_deleted,
    profile_comment_created,
)
from utils import (
    followed_by_edge,
    follower_of_edge,
    friendship_edge,
    integrated_by_edge,
    member_of_edge,
    generate_sha1,
    group_post_event_type
)

graph = Graph()

class SocialNetworkUserManager(object):

    def followed_by_users(self, user):
        follower_of = follower_of_edge()
        count = graph.edge_count(user, follower_of)
        ids = [node.pk for node, attributes, time in graph.edge_range(user, follower_of, 0, count)]
        return self.get_queryset().filter(pk__in=ids)

    def members_of(self, group):
        integrated_by = integrated_by_edge()
        count = graph.edge_count(group, integrated_by)
        ids = [node.pk for node, attributes, time in graph.edge_range(group, integrated_by, 0, count)]
        return self.get_queryset().filter(pk__in=ids)

class SocialNetworkUserMixin(models.Model):
    objects = SocialNetworkUserManager()

    class Meta:
        abstract = True

    @models.permalink
    def get_request_friendship_url(self):
        return 'user:request_friendship', [self.username]

    def get_site(self):
        return Site.objects.get_current()

    def followers(self):
        return graph.edge_count(self, followed_by_edge(), self.get_site())

    def follower_list(self):
        count = self.followers()
        return [node for node, attributes, time in graph.edge_range(self, followed_by_edge(), 0, count, self.get_site())]

    def following(self):
        return graph.edge_count(self, follower_of_edge(), self.get_site())

    def following_list(self):
        count = self.following()
        return [node for node, attributes, time in graph.edge_range(self, follower_of_edge(), 0, count, self.get_site())]

    def followed_by(self, user):
        return graph.edge_get(self, followed_by_edge(), user, self.get_site()) is not None

    def follow(self, user):
        _edge = graph.edge(self, user, follower_of_edge(), self.get_site(), {})
        if _edge:
            follower_relationship_created.send(sender=self.__class__, followed=user, user=self)
        return _edge

    def stop_following(self, user):
        _deleted = graph.no_edge(self, user, follower_of_edge(), self.get_site())
        if _deleted:
            follower_relationship_destroyed.send(sender=self.__class__, followed=user, user=self)
        return _deleted

    def friend_of(self, user):
        return graph.edge_get(self, friendship_edge(), user, self.get_site()) is not None

    def friends(self):
        return graph.edge_count(self, friendship_edge(), self.get_site())

    def friend_list(self):
        return [node for node, attributes, time in graph.edge_range(self, friendship_edge(), self.get_site())]

    def make_friend_of(self, user):
        _edge = graph.edge(self, user, friendship_edge(), self.get_site(), {})
        if _edge:
            friendship_created.send(sender=self.__class__, friend=user, user=self)
        return _edge

    def social_groups(self):
        return graph.edge_count(self, member_of_edge(), self.get_site())

    def social_group_list(self):
        count = self.social_groups()
        return [group for group, attributes, time in graph.edge_range(self, member_of_edge(), 0, count, self.get_site())]

    def specific_role_social_group_list(self, role):
        count = self.social_groups()
        return [group for group, attributes, time in graph.edge_range(self, member_of_edge(), 0, count, self.get_site())
                if attributes['role'] == role]

    def is_member_of(self, group):
        return graph.edge_get(group, integrated_by_edge(), self, group.site) is not None

    def is_admin_of(self, group):
        return self in group.administrators.all()

    def is_creator_of(self, group):
        return self == group.creator

    def join(self, group):
        return group.add_member(self)

from django.contrib.auth.models import User, UserManager
# modify user class
bases = list(User.__bases__)
bases.insert(0, SocialNetworkUserMixin)
User.__bases__ = tuple(bases)

# modify user class
bases = list(UserManager.__bases__)
bases.insert(0, SocialNetworkUserManager)
UserManager.__bases__ = tuple(bases)

class FriendRequest(models.Model):
    from_user = models.ForeignKey(User, related_name='user_outgoing_friend_requests', verbose_name=_(u'requester'))
    to_user = models.ForeignKey(User, related_name='user_incoming_friend_requests', verbose_name=_(u'receiver'))
    message = models.TextField(blank=True, verbose_name=_(u'message'))
    accepted = models.BooleanField(default=False, verbose_name=_(u'accepted'), blank=True)
    denied = models.BooleanField(default=False, verbose_name=_(u'denied'), blank=True)

    class Meta:
        verbose_name = _(u'friend request')
        verbose_name_plural = _(u'friend requests')

    def __unicode__(self):
        return u"%s" % self.to_user.get_full_name() or self.to_user.get_username()

    def accept(self, by_user):
        if by_user != self.to_user or self.denied or self.accepted:
            return False
        if self.to_user.make_friend_of(self.from_user):
            self.accepted = True
            self.save()
            return True
        else:
            raise Exception("A problem has occurred while trying to create a friendship edge.")

    def deny(self, by_user):
        if by_user != self.to_user or self.accepted or self.denied:
            return False
        self.denied = True
        self.save()
        return True

@receiver(models.signals.post_save, sender=FriendRequest, dispatch_uid='post_save_friend_request')
def post_save_friend_request(sender, instance, created, **kwargs):
    if created:
        friend_request_created.send(
            sender=FriendRequest,
            user=instance.from_user,
            instance=instance,
            receiver=instance.to_user
        )

class SocialGroupManagerMixin(object):

    def integrated_by(self, user):
        member_of = member_of_edge()
        count = graph.edge_count(user, member_of)
        ids = [node.pk for node, attributes, time in graph.edge_range(user, member_of, 0, count)]
        return self.get_queryset().filter(pk__in=ids)

class SocialGroupManager(SocialGroupManagerMixin, models.Manager):
    pass

class SocialGroupCurrentSiteManager(SocialGroupManagerMixin, CurrentSiteManager):
    pass

class SocialGroup(models.Model, LikableMixin, DenounceTargetMixin, ShareToSocialNetworkTargetMixin,
                  ShareToSocialGroupTargetMixin):
    creator = models.ForeignKey(User, related_name='created_groups', verbose_name=_(u'creator'))
    name = models.CharField(_(u'name'), max_length=255)
    slug = models.SlugField(_(u'slug'), max_length=255)
    description = models.TextField(_(u'description'))
    closed = models.BooleanField(_(u'closed'), default=False)
    administrators = models.ManyToManyField(
        User, related_name='managed_groups', verbose_name=_(u'administrators'), blank=True
    )
    created = models.DateTimeField(_(u'creation date'), auto_now_add=True)

    site = models.ForeignKey(Site, verbose_name=_(u'site'))

    def images_upload(self, filename):
        salt, hash_string = generate_sha1(self.pk)
        return 'site-%s/groups/%s/%s/%s' % (
            self.site.pk, self.creator.pk, hash_string,
            filename)

    image = models.ImageField(verbose_name=_(u'image'), upload_to=images_upload, null=True, blank=True, max_length=500)

    objects = SocialGroupManager()
    on_site = SocialGroupCurrentSiteManager()

    class Meta:
        unique_together = ('slug', 'site')
        verbose_name = _(u'social group')
        verbose_name_plural = _(u'social groups')

    def __init__(self, *args, **kwargs):
        super(SocialGroup, self).__init__(*args, **kwargs)
        if not self.pk and not self.site_id:
            self.site_id = Site.objects.get_current().pk

    @models.permalink
    def get_absolute_url(self):
        return 'group:details', [self.slug]

    @models.permalink
    def get_members_url(self):
        return 'group:members', [self.slug]

    @models.permalink
    def get_feed_url(self):
        return 'group:feed', [self.slug]

    @models.permalink
    def get_requests_url(self):
        return 'group:requests', [self.slug]

    @models.permalink
    def get_membership_buttons_url(self):
        return 'group:membership_buttons', [self.slug]

    @models.permalink
    def get_edit_url(self):
        return 'group:edit', [self.slug]

    @models.permalink
    def get_edit_inline_url(self):
        return 'group:edit_inline', [self.slug]

    @models.permalink
    def get_post_url(self):
        return 'group:post', [self.slug]

    @models.permalink
    def get_comment_url(self):
        return 'group:comment', [self.slug]

    @models.permalink
    def get_comment_inline_url(self):
        return 'group:comment_inline', [self.slug]

    @models.permalink
    def get_post_link_url(self):
        return 'group:post_link', [self.slug]

    @models.permalink
    def get_post_link_inline_url(self):
        return 'group:post_link_inline', [self.slug]

    @models.permalink
    def get_post_photo_url(self):
        return 'group:post_photo', [self.slug]

    @models.permalink
    def get_post_photo_inline_url(self):
        return 'group:post_photo_inline', [self.slug]

    @models.permalink
    def get_join_url(self):
        return 'group:join', [self.slug]

    @models.permalink
    def get_request_membership_url(self):
        return 'group:request_membership', [self.slug]

    @models.permalink
    def get_request_membership_inline_url(self):
        return 'group:request_membership_inline', [self.slug]

    @property
    def picture(self):
        # to satisfy ShareToSocialGroupTargetMixin and ShareToSocialNetworkTargetMixin
        return self.image

    @property
    def members(self):
        return graph.edge_count(self, integrated_by_edge())

    @property
    def member_list(self):
        edge = integrated_by_edge()
        count = graph.edge_count(self, edge)
        return [user for user, attributes, time in graph.edge_range(self, edge, 0, count)]

    def specific_role_member_list(self, role):
        edge = integrated_by_edge()
        count = graph.edge_count(self, edge)
        return [user for user, attributes, time in graph.edge_range(self, edge, 0, count) if attributes['role'] == role]

    @property
    def member_role_list(self):
        edge = integrated_by_edge()
        count = graph.edge_count(self, edge)
        return dict([(user.pk, attributes.get('role', 'member'))
                     for user, attributes, time in graph.edge_range(self, edge, 0, count)])

    def has_admin(self, user):
        return user == self.creator or user in self.administrators.all()

    def has_member(self, user):
        return graph.edge_get(user, member_of_edge(), self) is not None

    def relationship_with(self, user):
        edge = graph.edge_get(user, member_of_edge(), self)
        return user, edge.attributes.get('role', 'member') if edge else None

    def add_member(self, member, acceptor=None):
        if not acceptor:
            acceptor = member
        if self.closed and not self.has_admin(acceptor):
            return False
        _edge = graph.edge(member, self, member_of_edge(), self.site, {'role': 'member'})
        if _edge:
            social_group_member_added.send(
                sender=SocialGroup,
                group=self,
                member=member,
                user=acceptor
            )
            return True
        else:
            raise Exception("A problem has occurred while trying to create a membership edge.")

    def __unicode__(self):
        return u"%s" % self.name

@receiver(models.signals.pre_save, sender=SocialGroup, dispatch_uid='fill_social_group_slug')
def fill_social_group_slug(sender, instance, **kwargs):
    if not instance.pk and not instance.slug:
        instance.slug = slugify(instance.name)
        good_slug = False
        counter = 1
        while not good_slug:
            if instance.__class__.objects.filter(slug=instance.slug, site=instance.site).exists():
                instance.slug = instance.slug[:-1] + '%s' % counter
                counter += 1
            else:
                good_slug = True

@receiver(models.signals.post_save, sender=SocialGroup, dispatch_uid='post_save_social_group')
def post_save_social_group(sender, instance, created, **kwargs):
    if created:
        # add creator to members
        graph.edge(instance.creator, instance, member_of_edge(), instance.site, {'role': 'creator'})
        social_group_created.send(sender=SocialGroup, instance=instance, user=instance.creator)

@receiver(models.signals.m2m_changed, sender=SocialGroup.administrators.through, dispatch_uid='post_m2m_changed_social_group')
def post_m2m_changed_social_group(sender, instance, action, reverse, model, pk_set, **kwargs):
    if action not in ('post_add', 'post_remove', 'post_clear'):
        return
    member_of = member_of_edge()
    if not reverse:  # the call has modified the direct relationship SocialGroup.administrators
        group = instance
        if action == 'post_clear':
            for admin in group.specific_role_member_list('admin'):
                graph.no_edge(admin, group, member_of, group.site)
        else:
            admins = model.objects.filter(pk__in=list(pk_set))
            if action == 'post_add':
                for admin in admins:
                    graph.edge(admin, group, member_of, group.site, {'role': 'admin'})
            elif action == 'post_remove':
                for admin in admins:
                    graph.no_edge(admin, group, member_of, group.site)
    else:  # the call has modified the reverse relationship: User.groups_administrated_by
        admin = instance
        if action == 'post_clear':
            for group in admin.specific_role_social_group_list('admin'):
                graph.no_edge(admin, group, member_of, group.site)
        else:
            groups = model.objects.filter(pk__in=list(pk_set))
            if action == 'post_add':
                for group in groups:
                    graph.edge(admin, group, member_of, group.site, {'role': 'admin'})
            elif action == 'post_remove':
                for group in groups:
                    graph.no_edge(admin, group, member_of, group.site)

class GroupMembershipRequest(models.Model):
    requester = models.ForeignKey(User, related_name='requested_group_memberships', verbose_name=_(u'requester'))
    group = models.ForeignKey(SocialGroup, related_name='aspirants', verbose_name=_(u'group'))
    message = models.TextField(blank=True, verbose_name=_(u'message'))
    accepted = models.BooleanField(default=False, verbose_name=_(u'accepted'), blank=True)
    denied = models.BooleanField(default=False, verbose_name=_(u'denied'), blank=True)
    acceptor = models.ForeignKey(
        User, related_name='accepted_group_memberships', verbose_name=_(u'decider'), null=True, blank=True
    )

    class Meta:
        verbose_name = _(u'group membership request')
        verbose_name_plural = _(u'group membership requests')

    @models.permalink
    def get_accept_url(self):
        return 'group:accept_request', [], {'slug': self.group.slug, 'pk': self.pk}

    @models.permalink
    def get_deny_url(self):
        return 'group:deny_request', [], {'slug': self.group.slug, 'pk': self.pk}

    def accept(self, by_user):
        if not self.group.has_admin(by_user) or self.denied or self.accepted:
            return False
        if self.group.add_member(self.requester, by_user):
            self.accepted = True
            self.acceptor = by_user
            self.save()
            return True
        else:
            return False

    def deny(self, by_user):
        if not self.group.has_admin(by_user) or self.accepted or self.denied:
            return False
        self.denied = True
        self.acceptor = by_user
        self.save()
        return True

@receiver(models.signals.post_save, sender=GroupMembershipRequest, dispatch_uid='post_save_group_membership_request')
def post_save_group_membership_request(sender, instance, created, **kwargs):
    if created:
        social_group_membership_request_created.send(
            sender=GroupMembershipRequest,
            instance=instance,
            user=instance.requester,
            group=instance.group
        )

class GroupPost(models.Model):
    creator = models.ForeignKey(User, related_name='posts', verbose_name=_(u'creator'))
    group = models.ForeignKey(SocialGroup, related_name='posts', verbose_name=_(u'group'))
    comment = models.TextField(_(u'comment'), help_text=_(u"Share something with the group"))
    url = models.URLField(_(u'url'), blank=True, help_text=_(u"Enter a link"))

    def images_upload(self, filename):
        group_salt, group_hash_string = generate_sha1(self.group.pk)
        salt, hash_string = generate_sha1(self.pk)
        return 'site-%s/groups/%s/%s/%s/%s/%s' % (
            self.group.site.pk, self.group.creator.pk, group_hash_string, self.creator.pk, hash_string,
            filename)

    image = models.ImageField(_(u'cover image'), upload_to=images_upload, null=True, blank=True, max_length=500)

    class Meta(object):
        verbose_name = _(u'group post')
        verbose_name_plural = _(u'group posts')

    @models.permalink
    def get_edit_url(self):
        return 'group:edit_post', [], {'slug': self.group.slug, 'pk': self.pk}

    @models.permalink
    def get_delete_url(self):
        return 'group:delete_post', [], {'slug': self.group.slug, 'pk': self.pk}

@receiver(models.signals.post_save, sender=GroupPost, dispatch_uid='post_save_group_post')
def post_save_group_post(sender, instance, created, **kwargs):
    if created:
        social_group_post_created.send(sender=GroupPost, user=instance.creator, instance=instance)
    else:
        import datetime
        feed_item = GroupFeedItem.objects.get(event__target_pk=instance.pk)
        feed_item.event.date = datetime.datetime.now()
        feed_item.event.save()

@receiver(models.signals.post_delete, sender=GroupPost, dispatch_uid='post_delete_group_post')
def post_delete_group_post(sender, instance, **kwargs):
    social_group_post_deleted.send(sender=GroupPost, instance=instance)

@receiver(social_group_post_created, sender=GroupPost, dispatch_uid='social_network_group_post')
def social_network_group_post(instance, user, **kwargs):
    from notifications import create_event
    create_event(user, group_post_event_type(), instance, _(u'A new post has been added to a group'))

@receiver(social_group_post_deleted, sender=GroupPost, dispatch_uid='social_network_group_post_deleted')
def social_network_group_post_deleted(instance, **kwargs):
    feed_item = GroupFeedItem.objects.get(event__target_pk=instance.pk)
    feed_item.erased = True
    feed_item.save()

class GroupFeedItemQuerySet(models.query.QuerySet):

    def active(self):
        return self.filter(erased=False)

class GroupFeedItemManagerMixin(object):

    def active(self):
        return self.get_queryset().active()

class GroupFeedItemManager(GroupFeedItemManagerMixin, models.Manager):

    def get_queryset(self):
        return GroupFeedItemQuerySet(self.model, using=self._db).active()

class GroupFeedItemCurrentSiteManager(GroupFeedItemManagerMixin, CurrentSiteManager):

    def get_queryset(self):
        if not self._CurrentSiteManager__is_validated:
            self._validate_field_name()
        return GroupFeedItemQuerySet(
            self.model, using=self._db
        ).filter(**{self._CurrentSiteManager__field_name + '__id__exact': Site.objects.get_current().pk}).active()

class GroupFeedItem(LikableMixin, DenounceTargetMixin, CommentTargetMixin, ShareToSocialNetworkTargetMixin,
                    ShareToSocialGroupTargetMixin, StatsMixin, models.Model):
    group = models.ForeignKey(SocialGroup, related_name='feed_items')
    event = models.ForeignKey(Event, related_name='feed_items')
    template_config = models.ForeignKey(NotificationTemplateConfig)
    erased = models.BooleanField(default=False, blank=True)

    site = models.ForeignKey(Site)

    objects = GroupFeedItemManager()
    on_site = GroupFeedItemCurrentSiteManager()
    historical = models.Manager()

    class Meta(object):
        verbose_name = _(u'group feed item')
        verbose_name_plural = _(u'group feed item')
        ordering = ('-event__date',)

    def __init__(self, *args, **kwargs):
        super(GroupFeedItem, self).__init__(*args, **kwargs)
        if not self.pk and not self.site_id:
            self.site_id = self.event.site_id or Site.objects.get_current().pk

    def creator_by(self, user):
        return isinstance(user, GroupFeedItem) and self.event.user.pk == user.pk

    @property
    def picture(self):
        # to satisfy ShareToSocialNetworkTargetMixin and ShareToSocialGroupTargetMixin
        try:
            return self.event.target_object.image
        except Exception:
            return None

    @property
    def url(self):
        # to satisfy ShareToSocialNetworkTargetMixin and ShareToSocialGroupTargetMixin
        try:
            return self.event.target_object.url or self.group.get_absolute_url()
        except Exception:
            return ""

class FeedComment(models.Model):
    creator = models.ForeignKey(User, related_name='feed_comments', verbose_name=_(u'creator'))
    receiver = models.ForeignKey(User, related_name='feed_received_comments', verbose_name=_(u'receiver'))
    comment = models.TextField(_(u'comment'))

    class Meta(object):
        verbose_name = _(u'profile comment')
        verbose_name_plural = _(u'profile comments')

@receiver(models.signals.post_save, sender=FeedComment, dispatch_uid='post_save_feed_comment')
def post_save_feed_comment(sender, instance, created, **kwargs):
    if created:
        profile_comment_created.send(sender=FeedComment, user=instance.creator, instance=instance)


text:
using System;
using System.IO;
using System.Threading.Tasks;

namespace Xamarin.Forms
{
	internal interface IIsolatedStorageFile
	{
		Task CreateDirectoryAsync(string path);
		Task<bool> GetDirectoryExistsAsync(string path);
		Task<bool> GetFileExistsAsync(string path);

		Task<DateTimeOffset> GetLastWriteTimeAsync(string path);

		Task<Stream> OpenFileAsync(string path, FileMode mode, FileAccess access);
		Task<Stream> OpenFileAsync(string path, FileMode mode, FileAccess access, FileShare share);
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gbif.registry.ws.it.collections.resource;

import org.gbif.api.model.collections.search.CollectionsSearchResponse;
import org.gbif.api.vocabulary.Country;
import org.gbif.registry.search.dataset.service.collections.CollectionsSearchService;
import org.gbif.registry.ws.client.collections.CollectionsSearchClient;
import org.gbif.registry.ws.it.fixtures.RequestTestFixture;
import org.gbif.registry.ws.it.fixtures.TestConstants;
import org.gbif.ws.client.filter.SimplePrincipalProvider;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.web.server.LocalServerPort;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;

public class CollectionsSearchResourceTest extends BaseResourceIT {

  @MockBean private CollectionsSearchService collectionsSearchService;

  private final CollectionsSearchClient collectionsSearchClient;

  @Autowired
  public CollectionsSearchResourceTest(
      SimplePrincipalProvider simplePrincipalProvider,
      RequestTestFixture requestTestFixture,
      @LocalServerPort int localServerPort) {
    super(simplePrincipalProvider, requestTestFixture);
    this.collectionsSearchClient =
        prepareClient(
            TestConstants.TEST_GRSCICOLL_ADMIN, localServerPort, CollectionsSearchClient.class);
  }

  @Test
  public void searchTest() {
    String q = "foo";
    boolean highlight = true;
    int limit = 10;

    CollectionsSearchResponse response = new CollectionsSearchResponse();
    response.setCode("c1");
    response.setInstitutionKey(UUID.randomUUID());
    CollectionsSearchResponse.Match match = new CollectionsSearchResponse.Match();
    match.setField("field1");
    match.setSnippet("snippet");
    response.setMatches(Collections.singleton(match));

    when(collectionsSearchService.search(q, highlight, null, null, Country.SPAIN, limit))
        .thenReturn(Collections.singletonList(response));

    List<CollectionsSearchResponse> responseReturned =
        collectionsSearchClient.searchCollections(q, highlight, null, null, Country.SPAIN, limit);
    assertEquals(1, responseReturned.size());
    assertEquals(response, responseReturned.get(0));
  }
}


text:
#ifndef _WX_XH_SLIDR_H_
#define _WX_XH_SLIDR_H_

#include "wx/xrc/xmlres.h"

#if wxUSE_XRC && wxUSE_SLIDER

class WXDLLIMPEXP_XRC wxSliderXmlHandler : public wxXmlResourceHandler
{
public:
    wxSliderXmlHandler();
    virtual wxObject *DoCreateResource();
    virtual bool CanHandle(wxXmlNode *node);

    DECLARE_DYNAMIC_CLASS(wxSliderXmlHandler)
};

#endif // wxUSE_XRC && wxUSE_SLIDER

#endif // _WX_XH_SLIDR_H_


text:
namespace marian {
namespace io {

bool isNpz(const std::string& fileName) {
  return fileName.size() >= 4
         && fileName.substr(fileName.length() - 4) == ".npz";
}

bool isBin(const std::string& fileName) {
  return fileName.size() >= 4
         && fileName.substr(fileName.length() - 4) == ".bin";
}

void getYamlFromNpz(YAML::Node& yaml,
                    const std::string& varName,
                    const std::string& fileName) {
  auto item = cnpy::npz_load(fileName, varName);
  if(item->size() > 0)
    yaml = YAML::Load(item->data());
}

void getYamlFromBin(YAML::Node& yaml,
                    const std::string& varName,
                    const std::string& fileName) {
  auto item = binary::getItem(fileName, varName);
  if(item.size() > 0)
    yaml = YAML::Load(item.data());
}

void getYamlFromModel(YAML::Node& yaml,
                      const std::string& varName,
                      const std::string& fileName) {
  if(io::isNpz(fileName)) {
    io::getYamlFromNpz(yaml, varName, fileName);
  } else if(io::isBin(fileName)) {
    io::getYamlFromBin(yaml, varName, fileName);
  } else {
    ABORT("Unknown model file format for file {}", fileName);
  }
}

void getYamlFromModel(YAML::Node& yaml,
                      const std::string& varName,
                      const void* ptr) {
  auto item = binary::getItem(ptr, varName);
  if(item.size() > 0)
    yaml = YAML::Load(item.data());
}

void addMetaToItems(const std::string& meta,
                    const std::string& varName,
                    std::vector<io::Item>& items) {
  Item item;
  item.name = varName;

  // increase size by 1 to add \0
  item.shape = Shape({(int)meta.size() + 1});

  item.bytes.resize(item.shape.elements());
  std::copy(meta.begin(), meta.end(), item.bytes.begin());
  // set string terminator
  item.bytes.back() = '\0';

  item.type = Type::int8;

  items.push_back(item);
}

void loadItemsFromNpz(const std::string& fileName, std::vector<Item>& items) {
  auto numpy = cnpy::npz_load(fileName);
  for(auto it : numpy) {
    Shape shape;
    shape.resize(it.second->shape.size());
    for(size_t i = 0; i < it.second->shape.size(); ++i)
      shape.set(i, (size_t)it.second->shape[i]);

    Item item;
    item.name = it.first;
    item.shape = shape;

    char npzType = it.second->type;
    int wordSize = it.second->word_size;
    if     (npzType == 'f' && wordSize == 2) item.type = Type::float16;
    else if(npzType == 'f' && wordSize == 4) item.type = Type::float32;
    else if(npzType == 'f' && wordSize == 8) item.type = Type::float64;
    else if(npzType == 'i' && wordSize == 1) item.type = Type::int8;
    else if(npzType == 'i' && wordSize == 2) item.type = Type::int16;
    else if(npzType == 'i' && wordSize == 4) item.type = Type::int32;
    else if(npzType == 'i' && wordSize == 8) item.type = Type::uint64;
    else if(npzType == 'u' && wordSize == 1) item.type = Type::uint8;
    else if(npzType == 'u' && wordSize == 2) item.type = Type::uint16;
    else if(npzType == 'u' && wordSize == 4) item.type = Type::uint32;
    else if(npzType == 'u' && wordSize == 8) item.type = Type::uint64;
    else ABORT("Numpy item '{}' type '{}' with size {} not supported", it.first, npzType, wordSize);

    item.bytes.swap(it.second->bytes);
    items.emplace_back(std::move(item));
  }
}

std::vector<Item> loadItems(const std::string& fileName) {
  std::vector<Item> items;
  if(isNpz(fileName)) {
    loadItemsFromNpz(fileName, items);
  } else if(isBin(fileName)) {
    binary::loadItems(fileName, items);
  } else {
    ABORT("Unknown model file format for file {}", fileName);
  }

  return items;
}

std::vector<Item> loadItems(const void* ptr) {
  std::vector<Item> items;
  binary::loadItems(ptr, items, false);
  return items;
}

std::vector<Item> mmapItems(const void* ptr) {
  std::vector<Item> items;
  binary::loadItems(ptr, items, true);
  return items;
}

// @TODO: make cnpy and our wrapper talk to each other in terms of types
// or implement our own saving routines for npz based on npy, probably better.
void saveItemsNpz(const std::string& fileName, const std::vector<Item>& items) {
  std::vector<cnpy::NpzItem> npzItems;
  for(auto& item : items) {
    std::vector<unsigned int> shape(item.shape.begin(), item.shape.end());
    char type;

    if     (item.type == Type::float16) type = cnpy::map_type(typeid(float)); // becomes 'f', correct size is given below
    else if(item.type == Type::float32) type = cnpy::map_type(typeid(float));
    else if(item.type == Type::float64) type = cnpy::map_type(typeid(double));
    else if(item.type == Type::int8)    type = cnpy::map_type(typeid(int8_t));
    else if(item.type == Type::int16)   type = cnpy::map_type(typeid(int16_t));
    else if(item.type == Type::int32)   type = cnpy::map_type(typeid(int32_t));
    else if(item.type == Type::int64)   type = cnpy::map_type(typeid(int64_t));
    else if(item.type == Type::uint8)   type = cnpy::map_type(typeid(uint8_t));
    else if(item.type == Type::uint16)  type = cnpy::map_type(typeid(uint16_t));
    else if(item.type == Type::uint32)  type = cnpy::map_type(typeid(uint32_t));
    else if(item.type == Type::uint64)  type = cnpy::map_type(typeid(uint64_t));
    else ABORT("Other types ({}) not supported", item.type);

    npzItems.emplace_back(item.name, item.bytes, shape, type, sizeOf(item.type));
  }
  cnpy::npz_save(fileName, npzItems);
}

void saveItems(const std::string& fileName, const std::vector<Item>& items) {
  if(isNpz(fileName)) {
    saveItemsNpz(fileName, items);
  } else if(isBin(fileName)) {
    binary::saveItems(fileName, items);
  } else {
    ABORT("Unknown file format for file {}", fileName);
  }
}

}  // namespace io
}  // namespace marian


text: Web tool for processing MRS data