text:
@implementation DataStore

@synthesize managedObjectContext = _managedObjectContext;

+ (instancetype)sharedDataStore {
    static DataStore *_sharedDataStore = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedDataStore = [[DataStore alloc] init];
    });

    return _sharedDataStore;
}

- (void)fetchData
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Visit"];
    self.locations = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];

}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

-(void)generateTestData{
    NSManagedObjectContext *objectContext = [DataStore sharedDataStore].managedObjectContext;
    Visit *fakeVisit = [NSEntityDescription insertNewObjectForEntityForName:@"Visit" inManagedObjectContext:objectContext];
    fakeVisit.arrivalDate = [NSDate date];
    [[DataStore sharedDataStore]fetchData];
}

#pragma mark - Core Data Stack

// Managed Object Context property getter. This is where we've dropped our "boilerplate" code.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CLVisit.sqlite"];

    NSError *error = nil;

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CLVisit" withExtension:@"momd"];
    NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];

    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end


text:
"""Linux specific tests.  These are implicitly run by test_psutil.py."""

from __future__ import division
import unittest
import subprocess
import sys
import time
import os

from test_psutil import sh, get_test_subprocess
from psutil._compat import PY3
import psutil

TOLERANCE = 200 * 1024  # 200 KB

class LinuxSpecificTestCase(unittest.TestCase):

    def assert_eq_w_tol(self, first, second, tolerance):
        difference = abs(first - second)
        if difference <= tolerance:
            return
        msg = '%r != %r within %r delta (%r difference)' \
              % (first, second, tolerance, difference)
        raise AssertionError(msg)

    def test_disks(self):
        # test psutil.disk_usage() and psutil.disk_partitions()
        # against "df -a"
        def df(path):
            out = sh('df -P -B 1 "%s"' % path).strip()
            lines = out.split('\n')
            lines.pop(0)
            line = lines.pop(0)
            dev, total, used, free = line.split()[:4]
            if dev == 'none':
                dev = ''
            total, used, free = int(total), int(used), int(free)
            return dev, total, used, free

        for part in psutil.disk_partitions(all=False):
            usage = psutil.disk_usage(part.mountpoint)
            dev, total, used, free = df(part.mountpoint)
            self.assertEqual(part.device, dev)
            self.assertEqual(usage.total, total)
            # 10 MB tollerance
            if abs(usage.free - free) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % (usage.free, free))
            if abs(usage.used - used) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % (usage.used, used))

    def test_memory_maps(self):
        sproc = get_test_subprocess()
        time.sleep(1)
        p = psutil.Process(sproc.pid)
        maps = p.get_memory_maps(grouped=False)
        pmap = sh('pmap -x %s' % p.pid).split('\n')
        del pmap[0]; del pmap[0]  # get rid of header
        while maps and pmap:
            this = maps.pop(0)
            other = pmap.pop(0)
            addr, _, rss, dirty, mode, path = other.split(None, 5)
            if not path.startswith('[') and not path.endswith(']'):
                self.assertEqual(path, os.path.basename(this.path))
            self.assertEqual(int(rss) * 1024, this.rss)
            # test only rwx chars, ignore 's' and 'p'
            self.assertEqual(mode[:3], this.perms[:3])

    def test_vmem_total(self):
        lines = sh('free').split('\n')[1:]
        total = int(lines[0].split()[1]) * 1024
        self.assertEqual(total, psutil.virtual_memory().total)

    def test_vmem_used(self):
        lines = sh('free').split('\n')[1:]
        used = int(lines[0].split()[2]) * 1024
        self.assert_eq_w_tol(used, psutil.virtual_memory().used, TOLERANCE)

    def test_vmem_free(self):
        lines = sh('free').split('\n')[1:]
        free = int(lines[0].split()[3]) * 1024
        self.assert_eq_w_tol(free, psutil.virtual_memory().free, TOLERANCE)

    def test_vmem_buffers(self):
        lines = sh('free').split('\n')[1:]
        buffers = int(lines[0].split()[5]) * 1024
        self.assert_eq_w_tol(buffers, psutil.virtual_memory().buffers, TOLERANCE)

    def test_vmem_cached(self):
        lines = sh('free').split('\n')[1:]
        cached = int(lines[0].split()[6]) * 1024
        self.assert_eq_w_tol(cached, psutil.virtual_memory().cached, TOLERANCE)

    def test_swapmem_total(self):
        lines = sh('free').split('\n')[1:]
        total = int(lines[2].split()[1]) * 1024
        self.assertEqual(total, psutil.swap_memory().total)

    def test_swapmem_used(self):
        lines = sh('free').split('\n')[1:]
        used = int(lines[2].split()[2]) * 1024
        self.assert_eq_w_tol(used, psutil.swap_memory().used, TOLERANCE)

    def test_swapmem_free(self):
        lines = sh('free').split('\n')[1:]
        free = int(lines[2].split()[3]) * 1024
        self.assert_eq_w_tol(free, psutil.swap_memory().free, TOLERANCE)

if __name__ == '__main__':
    test_suite = unittest.TestSuite()
    test_suite.addTest(unittest.makeSuite(LinuxSpecificTestCase))
    unittest.TextTestRunner(verbosity=2).run(test_suite)

redpajama_set_name: RedPajamaGithub


text:
jQuery.fn.mousehold=function(timeout,f){if(timeout&&typeof timeout=='function'){f=timeout;timeout=100;}
if(f&&typeof f=='function'){var timer=0;var fireStep=0;return this.each(function(){jQuery(this).mousedown(function(){fireStep=1;var ctr=0;var t=this;timer=setInterval(function(){ctr++;f.call(t,ctr);fireStep=2;},timeout);})
clearMousehold=function(){clearInterval(timer);if(fireStep==1)f.call(this,1);fireStep=0;}
jQuery(this).mouseout(clearMousehold);jQuery(this).mouseup(clearMousehold);})}}

angle = 60;
distance = 10;
iterations = 6;
speed = 10;
mode = "normal";
startPosX = 500;
startPosY = 800;

var turtle = new turtle(startPosX, startPosY, angle);
var ctx = new draw("canvas");
var fractal = "sierpinski";

createSierpinski(mode, false);

$("#danceFractal").click(function(){
	alert("feature not implemented");
});
$("#fractal").on('change', function(){
	changeFractal();
});
$("#distance").on('change', function(){
	changeDistance();
});
$("#generations").on('change', function(){
	changeGenerations();
});
$("#mode").on('change', function(){
	changeMode();
});
$("#angleMin").mousehold(function(){
	lowerAngle();
});
$("#anglePlus").mousehold(function(){
	higherAngle();
});
function createFractal(reset){
	reset = (typeof reset === "undefined") ? false : reset;
	checkDrawReady();
	if (drawready == true){
		turtle.resetTurtle();
		if(fractal == "sierpinski"){
			if(reset == true){
				angle = 60;
				distance = 10;
				iterations = 6;
				speed = 20;
				startPosX = 500;
				startPosY = 800;
				turtle.resetTurtle();
			}
			createSierpinski(mode, true);
		} else if (fractal == "plant"){
			if(reset == true){
				angle = 25;
				distance = 3.5;
				iterations = 6;
				speed = 5;
				startPosX = 950;
				startPosY = 800;
				turtle.resetTurtle();
			}
			createPlant(mode, true);
		} else if (fractal == "dragoncurve"){
			if(reset == true){
				angle = 90;
				distance = 10;
				iterations = 10;
				speed = 5;
				startPosX = 500;
				startPosY = 425;
				turtle.resetTurtle();
			}
			createDragoncurve(mode, true);
		}
		updateControls();
	} else{
		if (reset == true){
			setTimeout(function(){
				createFractal(true);
			}, 0);
		} else{
			setTimeout(function(){
				createFractal();
			}, 0);
		}
	}
}
function checkboxLiveCheck(){
	if(mode == "normal"){
		$(".livechk").attr("disabled", true);
	} else{
		$(".livechk").removeAttr("disabled");
	}
}
function changeFractal(){
	fractal = $("#fractal").val();
	checkDrawReady();
	createFractal(true);
}
function changeDistance(){
	distance = $("#distance").val();
	chkbox = $("#distanceLive").is(":checked");
	if(chkbox == false || mode == "normal"){
		checkDrawReady();
		createFractal();
	}
	updateControls();
}
function changeMode(){
	mode = $("#mode").val();
	checkDrawReady();
	createFractal();
	updateControls();
}
function changeGenerations(){
	iterations = $("#generations").val();
	checkDrawReady();
	createFractal();
	updateControls();
}
function lowerAngle(){
	angle = angle - 1;
	updateControls();
	chkbox = $("#angleLive").is(":checked");
	if(chkbox == false || mode == "normal"){
		checkDrawReady();
		createFractal();
	}
}
function higherAngle(){
	angle = angle + 1;
	updateControls();
	chkbox = $("#angleLive").is(":checked");
	if(chkbox == false || mode == "normal"){
		checkDrawReady();
		createFractal();
	}
}
function checkDrawReady(){
	if(!drawready){
		breakloop = true;
	} else{
		return false;
	}
}
function updateControls(){
	$("#generations").val(iterations);
	$("#angle").html(angle + "°");
	$("#distance").val(distance);
	checkboxLiveCheck();
}
function capitaliseFirstLetter(string)
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

$(document).ready(function(){
	updateControls();
});


text:
#known-errors

This article lists the common error messages which may occur when working with Telerik UI for ASP.NET AJAX, and their causes and solutions.

* The `SyntaxError` in Internet Explorer, `Uncaught SyntaxError: Failed to execute 'insertRule' on 'CSSStyleSheet': Failed to parse the rule'` in Chrome, or `SyntaxError: An invalid or illegal string was specified` in FireFox occur.

	The cause for this error is the commented CSS rules in the `<head>` of your page, for example, `/* .someClass { display: none; } */`.

	The AjaxManager and Ajaxpanel update the `<head>` of the page to enable controls to register stylesheets and scripts during an AJAX request. Such commented rules cannot be parsed by the engine.

	To solve this issue, use any of the following approaches:

	* Set the `EnablePageHeadUpdate` property of the Ajax control to `false`.

	* Remove the commented CSS rule or move it to a separate stylesheet file.

	* Place the styles settings in external CSS files.

* `Sys.WebForms.PageRequestManagerParserErrorException` occurs.

	A possible cause for this error is the usage of the AjaxPanel and AjaxManager to AJAX-enable the same control at the same time. For more information on the issue, refer to the article on [using controls wrapped in an AjaxPanel and added to the AjaxManager settings]({%slug ajaxmanager/troubleshooting/controls-wrapped-in-ajaxpanel-and-added-to-ajaxmanager-settings%}).

* `The state information is invalid for this page and might be corrupted` error occurs.

	Firefox version 1.5 and later use in-memory caching for entire web pages, including their JavaScript states, for a single browser session. Going backward and forward between visited pages requires no page loading and the JavaScript states are preserved. This feature, referred to by some as bfcache (for "Back-Forward Cache"), makes page navigation very fast. The caching state is preserved until the user closes the browser. For more information and a workaround, refer to the article on [using Ajax, ViewState, and Firefox]({%slug ajaxpanel/troubleshooting/firefox-specifics%}).

* `Unexpected AJAX response was received from the server` error occurs in a dialog.

	The possible causes for this issue may be any of the following:

	* Using `Server.Transfer()`—Some controls may use this method internally, for example, the `asp:LoginView` control. To redirect to another page in an AJAX-enabled application, use the approaches from the article on [redirecting to another page]({%slug ajaxpanel/how-to/redirecting-to-another-page%}). To solve this issue, utilize `Response.Redirect`. You can also try using the `Redirect` method of the Ajax control you use.

	* Using a custom HTTP handler

	* Incorrect loading of an AJAX-enabled user control. To solve the issue, refer to the article on [loading user controls]({%slug ajaxpanel/how-to/load-user-controls%}).

	If the suggested solutions do not fix the issue, disable AJAX as suggested in the error message. Verify that you don't get a server-side exception or any other undesired behavior by setting the `EnableAJAX` property to `false`. This approach will help you verify whether the error is related to using AJAX and, if not, to fix any server-side errors if any are thrown.

#end


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Zjs Tests</title>
    <link rel="stylesheet" href="../node_modules/mocha/mocha.css">


text:
namespace QtNodes
{

class NodeState;
class NodeDataModel;
class Node;

class NODE_EDITOR_PUBLIC NodeGeometry
{
public:

  NodeGeometry(std::unique_ptr<NodeDataModel> const &dataModel);

public:
  unsigned int
  height() const { return _height; }

  void
  setHeight(unsigned int h) { _height = h; }

  unsigned int
  width() const { return _width; }

  void
  setWidth(unsigned int w) { _width = w; }

  unsigned int
  entryHeight() const { return _entryHeight; }
  void
  setEntryHeight(unsigned int h) { _entryHeight = h; }

  unsigned int
  entryWidth() const { return _entryWidth; }

  void
  setEntryWidth(unsigned int w) { _entryWidth = w; }

  unsigned int
  spacing() const { return _spacing; }

  void
  setSpacing(unsigned int s) { _spacing = s; }

  bool
  hovered() const { return _hovered; }

  void
  setHovered(unsigned int h) { _hovered = h; }

  unsigned int
  nSources() const;

  unsigned int
  nSinks() const;

  QPointF const&
  draggingPos() const
  { return _draggingPos; }

  void
  setDraggingPosition(QPointF const& pos)
  { _draggingPos = pos; }

public:

  QRectF
  entryBoundingRect() const;

  QRectF
  boundingRect() const;

  /// Updates size unconditionally
  void
  recalculateSize() const;

  /// Updates size if the QFontMetrics is changed
  void
  recalculateSize(QFont const &font) const;

  // TODO removed default QTransform()
  QPointF
  portScenePosition(PortIndex index,
                    PortType portType,
                    QTransform const & t = QTransform()) const;

  PortIndex
  checkHitScenePoint(PortType portType,
                     QPointF point,
                     QTransform const & t = QTransform()) const;

  QRect
  resizeRect() const;

  /// Returns the position of a widget on the Node surface
  QPointF
  widgetPosition() const;

  /// Returns the maximum height a widget can be without causing the node to grow.
  int
  equivalentWidgetHeight() const;

  unsigned int
  validationHeight() const;

  unsigned int
  validationWidth() const;

  static
  QPointF
  calculateNodePositionBetweenNodePorts(PortIndex targetPortIndex, PortType targetPort, Node* targetNode,
                                        PortIndex sourcePortIndex, PortType sourcePort, Node* sourceNode,
                                        Node& newNode);
private:

  unsigned int
  captionHeight() const;

  unsigned int
  captionWidth() const;

  unsigned int
  portWidth(PortType portType) const;

private:

  // some variables are mutable because
  // we need to change drawing metrics
  // corresponding to fontMetrics
  // but this doesn't change constness of Node

  mutable unsigned int _width;
  mutable unsigned int _height;
  unsigned int _entryWidth;
  mutable unsigned int _inputPortWidth;
  mutable unsigned int _outputPortWidth;
  mutable unsigned int _entryHeight;
  unsigned int _spacing;

  bool _hovered;

  unsigned int _nSources;
  unsigned int _nSinks;

  QPointF _draggingPos;

  std::unique_ptr<NodeDataModel> const &_dataModel;

  mutable QFontMetrics _fontMetrics;
  mutable QFontMetrics _boldFontMetrics;
};
}


text:
tags:
  - v1
---

There are a small set of breaking changes between v1 and v2.
Converting is relatively straightforward and typically takes less than
an hour. Specific steps are included in
[Migration Guide: v1 to v2](../migrate-v1-to-v2.md).


text:
/*
 * bin.h
 *
 */

#ifndef __glubin_h_
#define __glubin_h_

#include "myassert.h"
#include "arc.h"
#include "defines.h"

class Bin
{ /* a linked list of jordan arcs */
private:
    Arc_ptr head;/*first arc on list */
    Arc_ptr		current;	/* current arc on list */
public:
    			Bin();
			~Bin();
    inline Arc_ptr	firstarc( void );
    inline Arc_ptr	nextarc( void );
    inline Arc_ptr	removearc( void );
    inline int		isnonempty( void ) { return (head ? 1 : 0); }
    inline void		addarc( Arc_ptr );
    void 		remove_this_arc( Arc_ptr );
    int			numarcs( void );
    void 		adopt( void );
    void		markall( void );
    void		show( char * );
    void		listBezier( void );
};

/*----------------------------------------------------------------------------
 * Bin::addarc - add an Arc_ptr to head of linked list of Arc_ptr
 *----------------------------------------------------------------------------
 */

inline void
Bin::addarc( Arc_ptr jarc )
{
   jarc->link = head;
   head = jarc;
}

/*----------------------------------------------------------------------------
 * Bin::removearc - remove first Arc_ptr from bin
 *----------------------------------------------------------------------------
 */

inline Arc_ptr
Bin::removearc( void )
{
    Arc_ptr jarc = head;

    if( jarc ) head = jarc->link;
    return jarc;
}

/*----------------------------------------------------------------------------
 * BinIter::nextarc - return current arc in bin and advance pointer to next arc
 *----------------------------------------------------------------------------
 */

inline Arc_ptr
Bin::nextarc( void )
{
    Arc_ptr jarc = current;

#ifdef DEBUG
    assert( jarc->check() != 0 );
#endif

    if( jarc ) current = jarc->link;
    return jarc;
}

/*----------------------------------------------------------------------------
 * BinIter::firstarc - set current arc to first arc of bin advance to next arc
 *----------------------------------------------------------------------------
 */

inline Arc_ptr
Bin::firstarc( void )
{
    current = head;
    return nextarc( );
}

#endif /* __glubin_h_ */


text:
import jwt_token from "jsonwebtoken";
import config from "../../config/environment"
import { compose } from "compose-middleware"
const AUTHORIZE_URL = "http://newers-world-oauth.qa2.tothenew.net/oauth/authorize?client_id=e6d6a83e-6c7a-11e7-9394-406186be844b";
const AUTH_HRMS_TOKEN_COOKIE = 'nw_dev_oauthToken';

/**
 * it extracts the token from headers
 * verifies the token received from client side in order to authenticate and authorize the user,
 * if authenticated decodes the employeeId from the token and adds it in req object
 * if token is not verified send an error otherwise calls the next middleware
 * if not token then also it calls the next middleware
 * @param req
 * @param res
 * @param next
 */
const verifyTsmsToken = (req, res, next) => {
  //to verify token
  const token = req.headers.authorization;
    if (token){
    jwt_token.verify(token, config.token.SecretKey,(err, decode) => {
      if (err) {
        res.status(500).send("invalid token");
      }
      else {
        const decodeData = jwt_token.decode(token);
        req.employeeId = decodeData.employeeId;
          next();
      }
    })
  } else {
    next();
  }
};

/**
 *exclude Callback url to check cookie existing condition
 *if cookie exists call employee detail API with token in cookie
 *if employee sign in first time call authorize api for google sign in

 * @param req
 * @param res
 * @param next
 */
const authChecker = (req, res, next) => {
  const url = req.originalUrl;
  if (url.indexOf('/api/oauthServerCallback') != -1) {
    return next();
  }
  if (req.cookies[AUTH_HRMS_TOKEN_COOKIE]) {
      next();
  } else {
      res.redirect(AUTHORIZE_URL)
  }
};

const composeMiddlewares = (compose([
  verifyTsmsToken,
  authChecker
]));

module.exports = composeMiddlewares;


text:
<?xml version="1.0" encoding="UTF-8"?>
<monster name="Elf" nameDescription="an elf" race="blood" experience="42" speed="170" manacost="320">
	<health now="100" max="100"/>
	<look type="62" corpse="6003"/>
	<targetchange interval="4000" chance="0"/>
	<flags>
		<flag summonable="1"/>
		<flag attackable="1"/>
		<flag hostile="1"/>
		<flag illusionable="1"/>
		<flag convinceable="1"/>
		<flag pushable="1"/>
		<flag canpushitems="0"/>
		<flag canpushcreatures="0"/>
		<flag targetdistance="1"/>
		<flag staticattack="90"/>
		<flag runonhealth="0"/>
	</flags>
	<attacks>
		<attack name="melee" interval="2000" skill="10" attack="15"/>
		<attack name="physical" interval="2000" chance="10" range="7" min="-0" max="-25">
			<attribute key="shootEffect" value="arrow"/>
		</attack>
	</attacks>
	<defenses armor="10" defense="10"/>
	<elements>
		<element holyPercent="20"/>
		<element deathPercent="-1"/>
	</elements>
	<immunities>
		<immunity invisible="1"/>
	</immunities>
	<voices interval="5000" chance="10">
		<voice sentence="Ulathil beia Thratha!"/>
		<voice sentence="Bahaha aka!"/>
		<voice sentence="You are not welcome here."/>
		<voice sentence="Flee as long as you can."/>
		<voice sentence="Death to the defilers!"/>
	</voices>
	<loot>
		<item id="2148" countmax="30" chance="44000"/><!-- gold coin -->
		<item id="2544" countmax="3" chance="7060"/><!-- arrow -->
		<item id="8839" countmax="2" chance="20000"/><!-- plum -->
		<item id="2397" chance="10800"/><!-- longsword -->
		<item id="2643" chance="11410"/><!-- leather boots -->
		<item id="2510" chance="9300"/><!-- plate shield -->
		<item id="2484" chance="8960"/><!-- studded armor -->
		<item id="2482" chance="13500"/><!-- studded helmet -->
		<item id="5921" chance="940"/><!-- heaven blossom -->
		<item id="10552" chance="2100"/><!-- elvish talisman -->
	</loot>
</monster>


text:
namespace SlimMessageBus.Host.Collections;

public interface IRuntimeTypeCache
{
    bool IsAssignableFrom(Type from, Type to);
    TaskOfTypeCache GetTaskOfType(Type type);
    /// <summary>
    /// Cache for generic methods that match this signature <see cref="Func{TResult}"/>.
    /// </summary>
    IReadOnlyCache<(Type ClassType, string MethodName, Type GenericArgument), Func<object, object>> GenericMethod { get; }
}


text:
package pl.asie.charset.lib.capability;

import pl.asie.charset.api.audio.IAudioSource;

public class DefaultAudioSource implements IAudioSource {
}


text:
#import "CSXNodeContentLayout+CSXLayoutObject.h"

static NSString * const CSXNodeContentLayoutTypeAttributeName = @"type";
static NSString * const CSXNodeContentLayoutContentElementName = @"content";

static NSString * const CSXNodeContentLayoutSetterElementName = @"setter";
static NSString * const CSXNodeContentLayoutGetterElementName = @"getter";
static NSString * const CSXNodeContentLayoutClassElementName = @"class";

@implementation CSXNodeContentLayout (CSXLayoutObject)
/* MARK: Various Attributes */
+ (CSXNodeLayout *)typeAttributeLayout {
    CSXNodeLayout *layout;
    CSXNodeContentLayout *content;

    layout = [CSXNodeLayout new];
    content = [CSXNodeContentLayout new];

    layout.name = CSXNodeContentLayoutTypeAttributeName;
    layout.required = YES;

    content.contentType = CSXNodeContentTypeString;
    content.getter = @selector(contentTypeIdentifier);
    content.setter = @selector(setContentTypeIdentifier:);

    layout.contentLayout = content;
    [content release];

    return [layout autorelease];
}

/* MARK: Content Element */
+ (CSXElementLayout *)getterElementLayout {
    CSXElementLayout *layout;
    CSXNodeContentLayout *content;

    layout = [CSXElementLayout new];
    content = [CSXNodeContentLayout new];

    layout.name = CSXNodeContentLayoutGetterElementName;
    layout.required = NO;
    layout.unique = YES;
    layout.empty = NO;

    content.contentType = CSXNodeContentTypeString;
    content.getter = @selector(getterString);
    content.setter = @selector(setGetterString:);

    layout.contentLayout = content;
    [content release];

    return [layout autorelease];
}

+ (CSXElementLayout *)setterElementLayout {
    CSXElementLayout *layout;
    CSXNodeContentLayout *content;

    layout = [CSXElementLayout new];
    content = [CSXNodeContentLayout new];

    layout.name = CSXNodeContentLayoutSetterElementName;
    layout.required = NO;
    layout.unique = YES;
    layout.empty = NO;

    content.contentType = CSXNodeContentTypeString;
    content.getter = @selector(setterString);
    content.setter = @selector(setSetterString:);

    layout.contentLayout = content;
    [content release];

    return [layout autorelease];
}

+ (CSXElementLayout *)classElementLayout {
    CSXElementLayout *layout;
    CSXNodeContentLayout *content;

    layout = [CSXElementLayout new];
    content = [CSXNodeContentLayout new];

    layout.name = CSXNodeContentLayoutClassElementName;
    layout.required = NO;
    layout.unique = YES;
    layout.empty = NO;

    content.contentType = CSXNodeContentTypeString;
    content.getter = @selector(customClassString);
    content.setter = @selector(setCustomClassString:);

    layout.contentLayout = content;
    [content release];

    return [layout autorelease];
}

+ (CSXElementLayout *)contentElementLayout {
    CSXElementLayout *layout;
    CSXNodeContentLayout *content;

    layout = [CSXElementLayout new];
    content = [CSXNodeContentLayout new];

    layout.name = CSXNodeContentLayoutContentElementName;
    layout.required = YES;
    layout.unique = YES;
    layout.empty = NO;

    content.contentType = CSXNodeContentTypeCustom;
    content.getter = @selector(contentLayout);
    content.setter = @selector(setContentLayout:);
    content.customClass = [CSXNodeContentLayout class];

    layout.contentLayout = content;
    [content release];

    layout.attributes = [NSArray arrayWithObjects:
                         [self typeAttributeLayout],
                         nil];
    layout.subelements = [NSArray arrayWithObjects:
                          [self getterElementLayout],
                          [self setterElementLayout],
                          [self classElementLayout],
                          nil];

    return [layout autorelease];
}
@end


text:
package commands

import (
	"fmt"
	"net/url"
	"strings"

	"github.com/github/hub/v2/github"
	"github.com/github/hub/v2/utils"
)

var cmdBrowse = &Command{
	Run:   browse,
	Usage: "browse [-uc] [[<USER>/]<REPOSITORY>|--] [<SUBPAGE>]",
	Long: `Open a GitHub repository in a web browser.

## Options:
	-u, --url
		Print the URL instead of opening it.

	-c, --copy
		Put the URL in clipboard instead of opening it.

	[<USER>/]<REPOSITORY>
		Defaults to repository in the current working directory.

	<SUBPAGE>
		One of "wiki", "commits", "issues", or other (default: "tree").

## Examples:
		$ hub browse
		> open https://github.com/REPO

		$ hub browse -- issues
		> open https://github.com/REPO/issues

		$ hub browse jingweno/gh
		> open https://github.com/jingweno/gh

		$ hub browse gh wiki
		> open https://github.com/USER/gh/wiki

## See also:

hub-compare(1), hub(1)
`,
}

func init() {
	CmdRunner.Use(cmdBrowse)
}

func browse(command *Command, args *Args) {
	var (
		dest    string
		subpage string
		path    string
		project *github.Project
		branch  *github.Branch
		err     error
	)

	if !args.IsParamsEmpty() {
		dest = args.RemoveParam(0)
	}

	if !args.IsParamsEmpty() {
		subpage = args.RemoveParam(0)
	}

	if args.Terminator {
		subpage = dest
		dest = ""
	}

	localRepo, _ := github.LocalRepo()
	if dest != "" {
		project = github.NewProject("", dest, "")
		branch = localRepo.MasterBranch()
	} else if subpage != "" && subpage != "commits" && subpage != "tree" && subpage != "blob" && subpage != "settings" {
		project, err = localRepo.MainProject()
		branch = localRepo.MasterBranch()
		utils.Check(err)
	} else {
		currentBranch, err := localRepo.CurrentBranch()
		if err != nil {
			currentBranch = localRepo.MasterBranch()
		}

		var owner string
		mainProject, err := localRepo.MainProject()
		if err == nil {
			host, err := github.CurrentConfig().PromptForHost(mainProject.Host)
			if err != nil {
				utils.Check(github.FormatError("in browse", err))
			} else {
				owner = host.User
			}
		}

		branch, project, _ = localRepo.RemoteBranchAndProject(owner, currentBranch.IsMaster())
		if branch == nil {
			branch = localRepo.MasterBranch()
		}
	}

	if project == nil {
		utils.Check(command.UsageError(""))
	}

	if subpage == "commits" {
		path = fmt.Sprintf("commits/%s", branchInURL(branch))
	} else if subpage == "tree" || subpage == "" {
		if !branch.IsMaster() {
			path = fmt.Sprintf("tree/%s", branchInURL(branch))
		}
	} else {
		path = subpage
	}

	pageURL := project.WebURL("", "", path)

	args.NoForward()
	flagBrowseURLPrint := args.Flag.Bool("--url")
	flagBrowseURLCopy := args.Flag.Bool("--copy")
	printBrowseOrCopy(args, pageURL, !flagBrowseURLPrint && !flagBrowseURLCopy, flagBrowseURLCopy)
}

func branchInURL(branch *github.Branch) string {
	parts := strings.Split(branch.ShortName(), "/")
	newPath := make([]string, len(parts))
	for i, s := range parts {
		newPath[i] = url.QueryEscape(s)
	}
	return strings.Join(newPath, "/")
}


text:
namespace base {
class SingleThreadTaskRunner;
}

namespace winhttp {

// Implements a network fetcher in terms of WinHTTP. The class is ref-counted
// as it is accessed from the main thread and the worker threads in WinHTTP.
class NetworkFetcher : public base::RefCountedThreadSafe<NetworkFetcher> {
 public:
  using FetchCompleteCallback = base::OnceCallback<void(int response_code)>;
  using FetchStartedCallback =
      base::OnceCallback<void(int response_code, int64_t content_length)>;
  using FetchProgressCallback = base::RepeatingCallback<void(int64_t current)>;

  NetworkFetcher(const HINTERNET& session_handle,
                 scoped_refptr<ProxyConfiguration> proxy_configuration);
  NetworkFetcher(const NetworkFetcher&) = delete;
  NetworkFetcher& operator=(const NetworkFetcher&) = delete;

  void Close();

  void PostRequest(
      const GURL& url,
      const std::string& post_data,
      const std::string& content_type,
      const base::flat_map<std::string, std::string>& post_additional_headers,
      FetchStartedCallback fetch_started_callback,
      FetchProgressCallback fetch_progress_callback,
      FetchCompleteCallback fetch_complete_callback);

  // Downloads the content of the |url| to a file identified by |file_path|.
  // The content is written to the file as it is being retrieved from the
  // network.
  void DownloadToFile(const GURL& url,
                      const base::FilePath& file_path,
                      FetchStartedCallback fetch_started_callback,
                      FetchProgressCallback fetch_progress_callback,
                      FetchCompleteCallback fetch_complete_callback);

  HRESULT QueryHeaderString(const std::wstring& name,
                            std::wstring* value) const;
  HRESULT QueryHeaderInt(const std::wstring& name, int* value) const;
  std::string GetResponseBody() const;
  HRESULT GetNetError() const;
  base::FilePath GetFilePath() const;

  // Returns the number of bytes retrieved from the network. This may be
  // different than the content length if an error occurred.
  int64_t GetContentSize() const;

 private:
  friend class base::RefCountedThreadSafe<NetworkFetcher>;
  using WriteDataCallback = base::RepeatingCallback<void()>;

  ~NetworkFetcher();

  static void __stdcall WinHttpStatusCallback(HINTERNET handle,
                                              DWORD_PTR context,
                                              DWORD status,
                                              void* info,
                                              DWORD info_len);

  // Invoked by the last WinHTTPstatus status callback.
  void HandleClosing();

  DWORD_PTR context() const { return reinterpret_cast<DWORD_PTR>(this); }

  HRESULT BeginFetch(
      const std::string& data,
      base::flat_map<std::string, std::string> additional_headers);
  ScopedHInternet Connect();
  ScopedHInternet OpenRequest();
  HRESULT SendRequest(const std::string& data);
  void SendRequestComplete();
  HRESULT ReceiveResponse();
  void HeadersAvailable();
  HRESULT ReadData();
  void ReadDataComplete(size_t num_bytes_read);
  void RequestError(DWORD error);
  void CompleteFetch();

  void WriteDataToMemory();
  void WriteDataToFile();
  bool WriteDataToFileBlocking();
  void WriteDataToFileComplete(bool is_eof);

  SEQUENCE_CHECKER(sequence_checker_);
  scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_;

  const raw_ref<const HINTERNET>
      session_handle_;  // Owned by NetworkFetcherFactory.
  scoped_refptr<ProxyConfiguration> proxy_configuration_;
  ScopedHInternet connect_handle_;
  ScopedHInternet request_handle_;

  // Keeps an outstanding reference count on itself as long as there is a
  // valid request handle and the context for the handle is set to this
  // instance.
  scoped_refptr<NetworkFetcher> self_;

  GURL url_;
  bool is_https_ = false;
  std::string host_;
  int port_ = 0;
  std::string path_for_request_;

  base::WStringPiece verb_;
  std::string request_data_;
  // The value of Content-Type header, e.g. "application/json".
  std::string content_type_;
  WriteDataCallback write_data_callback_;
  HRESULT net_error_ = S_OK;
  std::vector<char> read_buffer_;
  int response_code_ = 0;
  std::string post_response_body_;
  base::FilePath file_path_;
  base::File file_;
  int64_t content_size_ = 0;

  FetchStartedCallback fetch_started_callback_;
  FetchProgressCallback fetch_progress_callback_;
  FetchCompleteCallback fetch_complete_callback_;
};

}  // namespace winhttp

#endif  // COMPONENTS_WINHTTP_NETWORK_FETCHER_H_


text:
![](https://github.com/pddg/go-ghq-alfred/workflows/test/badge.svg?branch=master)

Search local repos with ghq in Alfred Workflow.

## Environment

* Alfred 3.4 (or later)
* [ghq](https://github.com/motemen/ghq)

## Usage

This tool is a CLI tool. Output JSON strings.

```bash
$ ./go-alfred-ghq '{query}' $(ghq list -p)
```

## In Alfred

This workflow start with `ghq {query}` in alfred.

Filtering the result of `ghq list -p` with `{query}` and show them.

### Preparing

You should specify path to `ghq`. Open this workflow settings, and edit environment variables. Default is `/usr/local/bin/ghq`.

And I recommend you to specify a editor and terminal app. Default is `Visual Studio Code.app` and `iTerm.app`

### Modifier key options

* **Enter**: Open repository in Finder.
* **Shift + Enter**: Open repository in your default browser.
* **Command + Enter**: Same as Enter only.
* **Option + Enter**: Search "user/repo" in google.
* **Fn + Enter**: Open repository in your terminal.
* **Control + Enter**: Open repository in your editor.

## Build

My environment is as follows.

* Go 1.9
* Glide 0.12.3

```bash
$ glide update
$ go test $(glide novendor) -v
$ go build .
```

## Attributes

Icons provided by www.flaticon.com.

### github and git logo

Icon made by Freepik from www.flaticon.com

### bitbucket logo

Icon made by Swifticons from www.flaticon.com

## Author

pudding

## License

MIT


text:
package exnihiloadscensio.barrel;

import javax.annotation.Nullable;

import exnihiloadscensio.networking.MessageBarrelModeUpdate;
import exnihiloadscensio.networking.MessageFluidUpdate;
import exnihiloadscensio.networking.PacketHandler;
import exnihiloadscensio.registries.BarrelLiquidBlacklistRegistry;
import exnihiloadscensio.registries.BarrelModeRegistry;
import exnihiloadscensio.registries.BarrelModeRegistry.TriggerType;
import exnihiloadscensio.tiles.TileBarrel;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;

public class BarrelFluidHandler extends FluidTank {

	private TileBarrel barrel;

	public BarrelFluidHandler(TileBarrel barrel) {
		this(Fluid.BUCKET_VOLUME);
		this.barrel = barrel;
	}

    public BarrelFluidHandler(int capacity) {
        super(capacity);
    }

    public BarrelFluidHandler(@Nullable FluidStack fluidStack, int capacity) {
        super(fluidStack, capacity);
    }

    public BarrelFluidHandler(Fluid fluid, int amount, int capacity)  {
        super(fluid, amount, capacity);
    }

    @Override
    public boolean canFillFluidType(FluidStack fluid) {
        if(fluid == null || fluid.getFluid() == null || BarrelLiquidBlacklistRegistry.isBlacklisted(barrel.getTier(), fluid.getFluid().getName()))
            return false;

    	for (IBarrelMode mode : BarrelModeRegistry.getModes(TriggerType.FLUID))	{
    		if (mode.isTriggerFluidStack(fluid))
    			return true;
    	}
        return false;
    }

    @Override
    public boolean canFill() {
    	return barrel.getMode() == null ? true : barrel.getMode().canFillWithFluid(barrel);
    }

    @Override
    public int fill(FluidStack resource, boolean doFill) {
    	if (barrel.getMode() != null && !barrel.getMode().canFillWithFluid(barrel))
    		return 0;

    	int amount = super.fill(resource, doFill);
    	if (amount > 0) {
    		PacketHandler.sendToAllAround(new MessageFluidUpdate(fluid, barrel.getPos()), barrel);
        	if (this.fluid != null && this.barrel.getMode() == null) {
        		this.barrel.setMode("fluid");
        		PacketHandler.sendToAllAround(new MessageBarrelModeUpdate(barrel.getMode().getName(), barrel.getPos()), barrel);
        	}
    	}
    	return amount;
    }

    @Override
    public FluidStack drain(FluidStack resource, boolean doDrain) {
    	FluidStack stack = super.drain(resource, doDrain);
    	if (stack != null && stack.amount > 0) {
    		PacketHandler.sendToAllAround(new MessageFluidUpdate(fluid, barrel.getPos()), barrel);
    	}
    	if (fluid == null && barrel.getMode() != null && barrel.getMode().getName().equals("fluid")) {
    		barrel.setMode("null");
    		PacketHandler.sendToAllAround(new MessageBarrelModeUpdate("null", barrel.getPos()), barrel);
    	}
    	return stack;
    }

    @Override
    public FluidStack drain(int maxDrain, boolean doDrain) {
    	FluidStack stack = super.drain(maxDrain, doDrain);
    	if (stack != null && stack.amount > 0) {
    		PacketHandler.sendToAllAround(new MessageFluidUpdate(fluid, barrel.getPos()), barrel);
    	}
    	if (fluid == null && barrel.getMode() != null && barrel.getMode().getName().equals("fluid")) {
    		barrel.setMode("null");
    		PacketHandler.sendToAllAround(new MessageBarrelModeUpdate("null", barrel.getPos()), barrel);
    	}
    	return stack;
    }

    @Override
    protected void onContentsChanged() {

    }

    public void setBarrel(TileBarrel barrel) {
    	this.barrel = barrel;
    }

}


text:
using System;
using Sitecore.Pipelines;

namespace Ignition.Foundation.Core.GlassMapper.Pipelines
{
	public class GetGlassLoadersPipeline
	{
		public static void Run(GetGlassLoadersPipelineArgs args)
		{
			if (args == null) throw new ArgumentNullException(nameof(args));

			var pipeline = CorePipelineFactory.GetPipeline("getGlassLoaders", Constants.GlassMapperPipelineGroupName);
			pipeline.Run(args);
		}
	}
}


text:
<site name="Telegram" homepage="https://telegram.org/">
	<example>https://t.me/telegram/83</example>

	<tags><tag>social</tag></tags>

	<host>t.me</host>
	<extract>@//t.me/(?!addstickers/|joinchat/)(?'id'\w+/\d+)@</extract>
	<iframe width="500" height="96" onload="let c=new MessageChannel;c.port1.onmessage=e=>this.style.height=e.data+'px';this.contentWindow.postMessage('s9e:init','*',[c.port2])" data-s9e-livepreview-ignore-attrs="style">
		<src><![CDATA[
			<xsl:text>https://s9e.github.io/iframe/2/telegram.min.html#</xsl:text>
			<xsl:value-of select="@id"/>
			<xsl:if test="$MEDIAEMBED_THEME = 'dark'">#theme=dark</xsl:if>
		]]></src>
	</iframe>
</site>


text:
<?php

set_time_limit(0);

$deps = array(
    array('symfony', 'git://github.com/symfony/symfony.git', isset($_ENV['SYMFONY_VERSION']) ? $_ENV['SYMFONY_VERSION'] : 'v2.0.9'),
    array('Doctrine\Common', 'git://github.com/doctrine/common.git', isset($_ENV['DOCTRINE_COMMON_VERSION']) ? $_ENV['DOCTRINE_COMMON_VERSION'] : '2.1.4'),
    array('Markdown', 'git://github.com/wolfie/php-markdown.git', 'd464071334'),
    array('Zend', 'git://github.com/zendframework/zf2.git', 'master'),
    array('ZendPdf', 'git://github.com/zendframework/ZendPdf.git', 'master'),
    array('Imagine', 'git://github.com/avalanche123/Imagine.git', 'v0.2.6'),
    array('PHPPdf', 'git://github.com/psliwa/PHPPdf.git', 'origin/1.1.x'),
);

foreach ($deps as $dep) {
    list($name, $url, $rev) = $dep;

    echo "> Installing/Updating $name\n";

    $installDir = __DIR__.'/'.$name;
    if (!is_dir($installDir)) {
        system(sprintf('git clone %s %s', $url, $installDir));
    }

    system(sprintf('cd %s && git fetch origin && git reset --hard %s', $installDir, $rev));
}


text:
require 'automatic/command_line/trips'
require 'automatic/command_line/vehicles'

module Automatic
  module CommandLine
  end
end


text:
<?php
declare(strict_types=1);

namespace Upgate\LaravelJsonRpc\Exception;

abstract class JsonRpcException extends \RuntimeException
{

    public function __construct(string $message = "", int $code = 0, \Exception $previous = null)
    {
        parent::__construct(
            $message ?: $this->getDefaultMessage(),
            intval($code ?: $this->getDefaultCode()),
            $previous
        );
    }

    abstract protected function getDefaultMessage(): string;

    abstract protected function getDefaultCode(): int;

    public function getExtras(): array {
        return [];
    }

}


text:
See the [access](http://haraka.github.io/manual/plugins/access.html) plugin
for upgrade instructions.

mail\_from.access
===================

This plugin will evaluate the address against a set of white and black lists.
The lists are applied in the following way:

mail\_from.access.whitelist          (pass)
mail\_from.access.whitelist\_regex   (pass)
mail\_from.access.blacklist          (block)
mail\_from.access.blacklist\_regex   (block)

Configuration mail\_from.access.ini
-------------------------------------

General configuration file for this plugin.

* mail\_from.access.general.deny\_msg

  Text to send the user on reject (text).

Configuration mail\_from.access.whitelist
-------------------------------------------

The whitelist is mostly to counter blacklist entries that match more than
what one would want.  This file should be used for a specific address,
one per line, that should bypass blacklist checks.
NOTE: We heavily suggest tailoring blacklist entries to be as accurate as
possible and never using whitelists.  Nevertheless, if you need whitelists,
here they are.

Configuration mail\_from.access.whitelist\_regex
-------------------------------------------------

Does the same thing as the whitelist file, but each line is a regex.
Each line is also anchored for you, meaning '^' + regex + '$' is added for
you.  If you need to get around this restriction, you may use a '.*' at
either the start or the end of your regex.  This should help prevent people
from writing overly permissive rules on accident.

Configuration mail\_from.access.blacklist
-------------------------------------------

This file should be used for a specific address, one per line, that should
fail on connect.

Configuration mail\_from.access.blacklist\_regex
-------------------------------------------------

Does the same thing as the blacklist file, but each line is a regex.
Each line is also anchored for you, meaning '^' + regex + '$' is added for
you.  If you need to get around this restriction, you may use a '.*' at
either the start or the end of your regex.  This should help prevent people
from writing overly permissive rules on accident.


text:
#ifndef _INC_EAPPAPIS
#define _INC_EAPPAPIS
#if (_WIN32_WINNT >= 0x0600)
#include <eaptypes.h>
#include <eaphostpeertypes.h>
#ifdef __cplusplus
extern "C" {
#endif

DWORD APIENTRY EapHostPeerGetResult(
  EAP_SESSIONID sessionHandle,
  EapHostPeerMethodResultReason reason,
  EapHostPeerMethodResult *ppResult,
  EAP_ERROR **ppEapError
);

DWORD WINAPI EapHostPeerProcessReceivedPacket(
  EAP_SESSIONID sessionHandle,
  DWORD cbReceivePacket,
  const BYTE *pReceivePacket,
  EapHostPeerResponseAction *pEapOutput,
  EAP_ERROR **ppEapError
);

VOID APIENTRY EapHostPeerFreeEapError(
  EAP_ERROR *ppEapError
);

DWORD APIENTRY EapHostPeerClearConnection(
  GUID *pConnectionId,
  EAP_ERROR **ppEapError
);

DWORD APIENTRY EapHostPeerEndSession(
  EAP_SESSIONID sessionHandle,
  EAP_ERROR **ppEapError
);

DWORD APIENTRY EapHostPeerGetAuthStatus(
  EAP_SESSIONID sessionHandle,
  EapHostPeerAuthParams authParam,
  DWORD *pcbAuthData,
  BYTE **ppAuthData,
  EAP_ERROR **ppEapError
);

DWORD APIENTRY EapHostPeerGetResponseAttributes(
  EAP_SESSIONID sessionHandle,
  EapAttributes *pAttribs,
  EAP_ERROR **ppEapError
);

DWORD WINAPI EapHostPeerGetSendPacket(
  EAP_SESSIONID sessionHandle,
  DWORD *pcbSendPacket,
  BYTE **ppSendPacket,
  EAP_ERROR **ppEapError
);

DWORD APIENTRY EapHostPeerGetUIContext(
  EAP_SESSIONID sessionHandle,
  DWORD *pdwSizeOfUIContextData,
  BYTE **ppUIContextData,
  EAP_ERROR **ppEapError
);

DWORD APIENTRY EapHostPeerSetResponseAttributes(
  EAP_SESSIONID sessionHandle,
  const EapAttributes *pAttribs,
  EapHostPeerResponseAction *pEapOutput,
  EAP_ERROR **ppEapError
);

DWORD APIENTRY EapHostPeerSetUIContext(
  EAP_SESSIONID sessionHandle,
  DWORD dwSizeOfUIContextData,
  const BYTE *pUIContextData,
  EapHostPeerResponseAction *pEapOutput,
  EAP_ERROR **ppEapError
);

typedef VOID ( CALLBACK *NotificationHandler )(
  GUID connectionId,
  VOID *pContextData
);

DWORD APIENTRY EapHostPeerBeginSession(
  DWORD dwFlags,
  EAP_METHOD_TYPE eapType,
  const EapAttributes *pAttributeArray,
  HANDLE hTokenImpersonateUser,
  DWORD dwSizeOfConnectionData,
  const BYTE *pConnectionData,
  DWORD dwSizeOfUserData,
  const BYTE *pUserData,
  DWORD dwMaxSendPacketSize,
  const GUID *pConnectionId,
  NotificationHandler func,
  VOID *pContextData,
  EAP_SESSIONID *pSessionId,
  EAP_ERROR **ppEapError
);

VOID WINAPI  EapHostPeerFreeRuntimeMemory(
  BYTE *pData
);

DWORD WINAPI EapHostPeerGetIdentity(
  DWORD dwVersion,
  DWORD dwFlags,
  EAP_METHOD_TYPE eapMethodType,
  DWORD dwSizeofConnectionData,
  const BYTE *pConnectionData,
  DWORD dwSizeofUserData,
  const  BYTE *pUserData,
  HANDLE hTokenImpersonateUser,
  WINBOOL *pfInvokeUI,
  DWORD *pdwSizeofUserDataOut,
  BYTE **ppUserDataOut,
  LPWSTR *ppwszIdentity,
  EAP_ERROR **ppEapError,
  BYTE **ppvReserved
);

DWORD WINAPI EapHostPeerInitialize(void);
void WINAPI EapHostPeerUninitialize(void);

#ifdef __cplusplus
}
#endif
#endif /*(_WIN32_WINNT >= 0x0600)*/
#endif /*_INC_EAPPAPIS*/


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface org.springframework.http.codec.CodecConfigurer.CustomCodecs (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.springframework.http.codec.CodecConfigurer.CustomCodecs

Packages that use CodecConfigurer.CustomCodecs

Package
Description

org.springframework.http.codec

Provides implementations of Encoder
 and Decoder for web use.

Uses of CodecConfigurer.CustomCodecs in org.springframework.http.codec

Methods in org.springframework.http.codec that return CodecConfigurer.CustomCodecs

Modifier and Type
Method and Description

CodecConfigurer.CustomCodecs
CodecConfigurer.customCodecs()

Register custom HTTP message readers or writers in addition to the ones
 registered by default.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes


text:
package net.lacolaco.smileessence.util;

import android.os.AsyncTask;
import net.lacolaco.smileessence.logging.Logger;

public abstract class BackgroundTask<Result, Progress> {
    private Consumer<Result> then;
    private Consumer<Progress> progress;
    private Consumer<Exception> fail;
    private Runnable finish;
    private Exception exception;
    private final InnerAsyncTask task;

    public BackgroundTask() {
        this.task = new InnerAsyncTask();
    }

    public BackgroundTask<Result, Progress> onDone(Consumer<Result> cb) {
        this.then = cb;
        return this;
    }

    public BackgroundTask<Result, Progress> onProgress(Consumer<Progress> cb) {
        this.progress = cb;
        return this;
    }

    public BackgroundTask<Result, Progress> onFail(Consumer<Exception> cb) {
        this.fail = cb;
        return this;
    }

    public BackgroundTask<Result, Progress> onFinish(Runnable cb) {
        this.finish = cb;
        return this;
    }

    public BackgroundTask<Result, Progress> onDoneUI(Consumer<Result> cb) {
        return onDone(r -> new UIHandler().post(() -> cb.accept(r)));
    }

    public BackgroundTask<Result, Progress> onProgressUI(Consumer<Progress> cb) {
        return onProgress(p -> new UIHandler().post(() -> cb.accept(p)));
    }

    public BackgroundTask<Result, Progress> onFailUI(Consumer<Exception> cb) {
        return onFail(e -> new UIHandler().post(() -> cb.accept(e)));
    }

    public BackgroundTask<Result, Progress> onFinishUI(Runnable cb) {
        return onFinish(() -> new UIHandler().post(cb::run));
    }

    public boolean cancel() {
        return task.cancel(true);
    }

    public final BackgroundTask<Result, Progress> execute() {
        task.execute();
        return this;
    }

    public final Result getImmediately() throws Exception {
        Result result = task.get();
        if (exception == null) {
            return result;
        } else {
            throw exception;
        }
    }

    protected void fail(Exception ex) {
        exception = ex;
        ex.printStackTrace();
        Logger.error(ex);

        if (!task.isCancelled() && fail != null) {
            fail.accept(ex);
        }
    }

    protected void progress(Progress value) {
        if (!task.isCancelled() && exception == null && progress != null) {
            progress.accept(value);
        }
    }

    protected abstract Result doInBackground() throws Exception;

    private class InnerAsyncTask extends AsyncTask<Void, Progress, Result> {
        @Override
        protected final void onPostExecute(Result result) {
            if (!isCancelled() && exception == null && then != null) {
                then.accept(result);
            }
            if (finish != null) {
                finish.run();
            }
        }

        @Override
        protected Result doInBackground(Void... params) {
            try {
                return BackgroundTask.this.doInBackground();
            } catch (Exception ex) {
                fail(ex);
                return null;
            }
        }
    }
}


text:
namespace Poker
{
    /// <summary>
    /// ICard interface. Describes all methods and properties needed for an object to be considered a card.
    /// </summary>
    public interface ICard
    {
        /// <summary>
        /// Gets the card face.
        /// </summary>
        /// <value>The card's face.</value>
        CardFace Face { get; }

        /// <summary>
        /// Gets the card suit.
        /// </summary>
        /// <value>The card's suite.</value>
        CardSuit Suit { get; }

        /// <summary>
        /// String representation of the card.
        /// </summary>
        /// <returns>String with the card face and suit.</returns>
        string ToString();
    }
}


text:
import scipy.spatial as _spatial
import numpy as _np
from .. import point

def _unstack_as_numpy_array(points):
    return _np.array([[p.x, p.y] for p in points])

def distance(points):
    """From an array of `Point`s compute the distances"""
    return _spatial.distance.pdist(_unstack_as_numpy_array(points))


text:
$(function() {
    var $popup_title = $('#admin_modal_title');
    var $popup_contents = $('#admin_modal_contents');
    $('a.admin_modal').click(function () {
        var link = this;
        $popup_title.html('');
        $popup_contents.html('Loading...');
        $.get(link.href, function (data) {
            $popup_title.html($(link).html());
            $popup_contents.html(data);
            var csrf_exists = $popup_contents.find('form > input[name="_session_id"]').length;
            if (!csrf_exists) {
              var cval = $.cookie('_session_id');
              var csrf_input = $('<input name="_session_id" type="hidden" value="'+cval+'">');
              $popup_contents.find('form').append(csrf_input);
            }
        });
    });
});


text:
package com.vityuk.ginger.proxy;

import com.vityuk.ginger.InvalidParameterTypeException;
import com.vityuk.ginger.InvalidReturnTypeException;
import com.vityuk.ginger.Localizable;
import com.vityuk.ginger.PluralCount;
import com.vityuk.ginger.Select;
import com.vityuk.ginger.provider.LocalizationProvider;
import com.vityuk.ginger.util.GingerUtils;
import com.vityuk.ginger.util.MiscUtils;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.FixedValue;
import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.NoOp;
import org.apache.commons.lang3.ArrayUtils;

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

public class CglibProxyBuilder implements ProxyBuilder {

    @Override
    public <T> T createProxy(Class<T> localizable, LocalizationProvider localizationProvider) {
        Method[] methods = localizable.getDeclaredMethods();

        List<Callback> callbacks = new ArrayList<Callback>(methods.length + 1);
        final Map<Method, Integer> method2CallbackIndex = new HashMap<Method, Integer>(methods.length);

        callbacks.add(NoOp.INSTANCE);
        for (Method localizableMethod : methods) {
            callbacks.add(createCallback(localizationProvider, localizableMethod));
            method2CallbackIndex.put(localizableMethod, callbacks.size() - 1);
        }

        CallbackFilter callbackFilter = new CallbackFilter() {
            @Override
            public int accept(Method method) {
                Integer index = method2CallbackIndex.get(method);
                return index == null ? 0 : index;
            }
        };

        Enhancer enhancer = new Enhancer();
        enhancer.setInterfaces(new Class[]{localizable});
        enhancer.setCallbackFilter(callbackFilter);
        enhancer.setCallbacks(callbacks.toArray(new Callback[callbacks.size()]));
        enhancer.setUseFactory(false);

        @SuppressWarnings("unchecked")
        T instance = (T) enhancer.create();
        return instance;
    }

    private Callback createCallback(LocalizationProvider localizationProvider, Method method) {
        String key = GingerUtils.createKeyFromMethod(method);
        Class<?> type = method.getReturnType();
        if (GingerUtils.isConstantMethod(method)) {
            return getConstantCallback(localizationProvider, method, type, key);
        } else {
            return getMessageCallback(localizationProvider, method, type, key);
        }
    }

    private Callback getMessageCallback(LocalizationProvider localizationProvider, Method method, Class<?> type, String key) {
        if (type != String.class) {
            throw new InvalidReturnTypeException(type, method);
        }

        int selectorParameterIndex = GingerUtils.indexOfParameterAnnotation(method, Select.class);
        if (selectorParameterIndex != -1) {
            return createSelectorMessageLookupCallback(localizationProvider, method, key, selectorParameterIndex);
        }

        int pluralCountParameterIndex = GingerUtils.indexOfParameterAnnotation(method, PluralCount.class);
        if (pluralCountParameterIndex != -1) {
            return createPluralMessageLookupCallback(localizationProvider, method, key, pluralCountParameterIndex);
        }

        return new MessageLookupCallback(localizationProvider, key);
    }

    private Callback createSelectorMessageLookupCallback(LocalizationProvider localizationProvider, Method method, String key, int parameterIndex) {
        Class<?> parameterType = method.getParameterTypes()[parameterIndex];
        if (parameterType.isPrimitive() || MiscUtils.isWrapperType(parameterType)) {
            // TODO: consider more informative exception
            throw new InvalidParameterTypeException(parameterType, method);
        }
        return new SelectorMessageLookupCallback(localizationProvider, key, parameterIndex);
    }

    private Callback createPluralMessageLookupCallback(LocalizationProvider localizationProvider, Method method, String key, int parameterIndex) {
        Class<?> parameterType = method.getParameterTypes()[parameterIndex];
        if (!GingerUtils.isIntNumericType(parameterType)) {
            // TODO: consider more informative exception
            throw new InvalidParameterTypeException(parameterType, method);
        }
        return new PluralMessageLookupCallback(localizationProvider, key, parameterIndex);
    }

    private Callback getConstantCallback(LocalizationProvider localizationProvider, Method method, Class<?> type, String key) {
        if (type == String.class) {
            return new StringConstantLookupCallback(localizationProvider, key);
        }
        if (type == Boolean.class) {
            return new BooleanConstantLookupCallback(localizationProvider, key);
        }
        if (type == Integer.class) {
            return new IntegerConstantLookupCallback(localizationProvider, key);
        }
        if (type == Long.class) {
            return new LongConstantLookupCallback(localizationProvider, key);
        }
        if (type == Float.class) {
            return new FloatConstantLookupCallback(localizationProvider, key);
        }
        if (type == Double.class) {
            return new DoubleConstantLookupCallback(localizationProvider, key);
        }
        if (type == List.class) {
            // TODO: generics support
            return new StringListConstantLookupCallback(localizationProvider, key);
        }
        if (type == Map.class) {
            // TODO: generics support
            return new StringMapConstantLookupCallback(localizationProvider, key);
        }

        throw new InvalidReturnTypeException(type, method);
    }

    private static abstract class AbstractLookupCallback implements Callback {
        protected final LocalizationProvider localizationProvider;
        protected final String key;

        public AbstractLookupCallback(LocalizationProvider localizationProvider, String key) {
            this.localizationProvider = localizationProvider;
            this.key = key;
        }
    }

    private static abstract class AbstractConstantLookupCallback extends AbstractLookupCallback implements FixedValue {
        public AbstractConstantLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }
    }

    private static class StringConstantLookupCallback extends AbstractConstantLookupCallback {
        public StringConstantLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }

        @Override
        public Object loadObject() throws Exception {
            return localizationProvider.getString(key);
        }
    }

    private static class BooleanConstantLookupCallback extends AbstractConstantLookupCallback {
        public BooleanConstantLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }

        @Override
        public Object loadObject() throws Exception {
            return localizationProvider.getBoolean(key);
        }
    }

    private static class IntegerConstantLookupCallback extends AbstractConstantLookupCallback {
        public IntegerConstantLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }

        @Override
        public Object loadObject() throws Exception {
            return localizationProvider.getInteger(key);
        }
    }

    private static class LongConstantLookupCallback extends AbstractConstantLookupCallback {
        public LongConstantLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }

        @Override
        public Object loadObject() throws Exception {
            return localizationProvider.getLong(key);
        }
    }

    private static class FloatConstantLookupCallback extends AbstractConstantLookupCallback {
        public FloatConstantLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }

        @Override
        public Object loadObject() throws Exception {
            return localizationProvider.getFloat(key);
        }
    }

    private static class DoubleConstantLookupCallback extends AbstractConstantLookupCallback {
        public DoubleConstantLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }

        @Override
        public Object loadObject() throws Exception {
            return localizationProvider.getDouble(key);
        }
    }

    private static class StringListConstantLookupCallback extends AbstractConstantLookupCallback {
        public StringListConstantLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }

        @Override
        public Object loadObject() throws Exception {
            return localizationProvider.getStringList(key);
        }
    }

    private static class StringMapConstantLookupCallback extends AbstractConstantLookupCallback {
        public StringMapConstantLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }

        @Override
        public Object loadObject() throws Exception {
            return localizationProvider.getStringMap(key);
        }
    }

    private static class MessageLookupCallback extends AbstractLookupCallback implements InvocationHandler {
        public MessageLookupCallback(LocalizationProvider localizationProvider, String key) {
            super(localizationProvider, key);
        }

        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            return localizationProvider.getMessage(key, objects);
        }
    }

    private static class SelectorMessageLookupCallback extends AbstractLookupCallback implements InvocationHandler {
        private final int selectorParameterIndex;

        public SelectorMessageLookupCallback(LocalizationProvider localizationProvider, String key,
                                             int selectorParameterIndex) {
            super(localizationProvider, key);
            this.selectorParameterIndex = selectorParameterIndex;
        }

        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            String selector = extractSelector(objects);
            Object[] parameters = extractParameters(objects);
            return localizationProvider.getSelectedMessage(key, selector, parameters);
        }

        private String extractSelector(Object[] objects) {
            return String.valueOf(objects[selectorParameterIndex]);
        }

        private Object[] extractParameters(Object[] objects) {
            return ArrayUtils.remove(objects, selectorParameterIndex);
        }
    }

    private static class PluralMessageLookupCallback extends AbstractLookupCallback implements InvocationHandler {
        private final int pluralCountParameterIndex;

        public PluralMessageLookupCallback(LocalizationProvider localizationProvider, String key,
                                           int pluralCountParameterIndex) {
            super(localizationProvider, key);
            this.pluralCountParameterIndex = pluralCountParameterIndex;
        }

        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            Number pluralCount = extractPluralCount(objects);
            Object[] parameters = extractParameters(objects);
            return localizationProvider.getPluralMessage(key, pluralCount, parameters);
        }

        private Number extractPluralCount(Object[] objects) {
            return (Number) objects[pluralCountParameterIndex];
        }

        private Object[] extractParameters(Object[] objects) {
            return ArrayUtils.remove(objects, pluralCountParameterIndex);
        }
    }
}


text:
require "spec_helper"

describe DecimalDollars::Money do
  let(:money) { described_class.new(1.2345) }

  describe "#+" do
    it "adds a value and return Money object" do
      expect(money + 1.01).to be_an_instance_of(described_class)
    end
  end

  describe "#-" do
    it "subtracts a value and return Money object" do
      expect(money - 1.01).to be_an_instance_of(described_class)
    end
  end

  describe "#*" do
    it "is multipliable by a value and returns Money object" do
      expect(money * 1.01).to be_an_instance_of(described_class)
    end

    it "raises an ArgumentError if a Money object is passed" do
      expect {
        money * described_class.new(2)
      }.to raise_error(ArgumentError, 'Money cannot be multiplied by Money')
    end
  end

  describe "#/" do
    it "is divisible by a value and return Money object" do
      expect(money / 1.01).to be_an_instance_of(described_class)
    end
  end

  describe "#**" do
    it "raises a RuntimeError" do
      expect {
        money ** 2
      }.to raise_error(RuntimeError, 'Money cannot be raised to any power')
    end
  end

  describe "#round_float" do
    it "rounds correctly" do
      expect(described_class.new(1.251).to_f).to  eq(1.25)
      expect(described_class.new(1.255).to_f).to  eq(1.25)
      expect(described_class.new(1.2551).to_f).to eq(1.26)
      expect(described_class.new(1.2555).to_f).to eq(1.26)
      expect(described_class.new(1.2556).to_f).to eq(1.26)
      expect(described_class.new(1.256).to_f).to  eq(1.26)
    end
  end
end


text:
<?php

use Faker\Generator as Faker;

$factory->define(App\Role::class, function (Faker $faker) {
    $name         = $faker->unique()->randomElement(['Manager', 'Operator', 'Customer']);
    $slug         = str_slug($name, '-');
    $permissions  = [
        'metric-ticket'  => null,
        'list-ticket'    => null,
        'show-ticket'    => null,
        'delete-ticket'  => null,
        'create-ticket'  => null,
        'edit-profile'   => null,
        'see-auxiliares' => null
    ];

    switch($name) {
        case 'Manager':
            $permissions['metric-ticket']  = true;
            $permissions['list-ticket']    = true;
            $permissions['show-ticket']    = true;
            $permissions['delete-ticket']  = true;
            $permissions['create-ticket']  = true;
            $permissions['edit-profile']   = true;
            $permissions['see-auxiliares'] = true;
            break;
        case 'Operator':
            $permissions['metric-ticket']  = true;
            $permissions['list-ticket']    = true;
            $permissions['show-ticket']    = true;
            $permissions['delete-ticket']  = true;
            $permissions['create-ticket']  = false;
            $permissions['edit-profile']   = true;
            $permissions['see-auxiliares'] = false;
            break;
        case 'Customer':
            $permissions['metric-ticket']  = false;
            $permissions['list-ticket']    = false;
            $permissions['show-ticket']    = true;
            $permissions['delete-ticket']  = false;
            $permissions['create-ticket']  = true;
            $permissions['edit-profile']   = true;
            $permissions['see-auxiliares'] = false;
            break;
    }

    return [
        'name'        => $name,
        'slug'        => $slug,
        'permissions' => $permissions
    ];
});


text:
/* $PostgreSQL: pgsql/src/tutorial/funcs_new.c,v 1.13 2007/02/27 23:48:10 tgl Exp $ */

/******************************************************************************
  These are user-defined functions that can be bound to a Postgres backend
  and called by Postgres to execute SQL functions of the same name.

  The calling format for these functions is defined by the CREATE FUNCTION
  SQL statement that binds them to the backend.

  NOTE: this file shows examples of "new style" function call conventions.
  See funcs.c for examples of "old style".
*****************************************************************************/

#include "postgres.h"			/* general Postgres declarations */

#include "executor/executor.h"	/* for GetAttributeByName() */
#include "utils/geo_decls.h"	/* for point type */

PG_MODULE_MAGIC;

/* These prototypes just prevent possible warnings from gcc. */

Datum		add_one(PG_FUNCTION_ARGS);
Datum		add_one_float8(PG_FUNCTION_ARGS);
Datum		makepoint(PG_FUNCTION_ARGS);
Datum		copytext(PG_FUNCTION_ARGS);
Datum		concat_text(PG_FUNCTION_ARGS);
Datum		c_overpaid(PG_FUNCTION_ARGS);

/* By Value */

PG_FUNCTION_INFO_V1(add_one);

Datum
add_one(PG_FUNCTION_ARGS)
{
	int32		arg = PG_GETARG_INT32(0);

	PG_RETURN_INT32(arg + 1);
}

/* By Reference, Fixed Length */

PG_FUNCTION_INFO_V1(add_one_float8);

Datum
add_one_float8(PG_FUNCTION_ARGS)
{
	/* The macros for FLOAT8 hide its pass-by-reference nature */
	float8		arg = PG_GETARG_FLOAT8(0);

	PG_RETURN_FLOAT8(arg + 1.0);
}

PG_FUNCTION_INFO_V1(makepoint);

Datum
makepoint(PG_FUNCTION_ARGS)
{
	Point	   *pointx = PG_GETARG_POINT_P(0);
	Point	   *pointy = PG_GETARG_POINT_P(1);
	Point	   *new_point = (Point *) palloc(sizeof(Point));

	new_point->x = pointx->x;
	new_point->y = pointy->y;

	PG_RETURN_POINT_P(new_point);
}

/* By Reference, Variable Length */

PG_FUNCTION_INFO_V1(copytext);

Datum
copytext(PG_FUNCTION_ARGS)
{
	text	   *t = PG_GETARG_TEXT_P(0);

	/*
	 * VARSIZE is the total size of the struct in bytes.
	 */
	text	   *new_t = (text *) palloc(VARSIZE(t));

	SET_VARSIZE(new_t, VARSIZE(t));

	/*
	 * VARDATA is a pointer to the data region of the struct.
	 */
	memcpy((void *) VARDATA(new_t),		/* destination */
		   (void *) VARDATA(t), /* source */
		   VARSIZE(t) - VARHDRSZ);		/* how many bytes */
	PG_RETURN_TEXT_P(new_t);
}

PG_FUNCTION_INFO_V1(concat_text);

Datum
concat_text(PG_FUNCTION_ARGS)
{
	text	   *arg1 = PG_GETARG_TEXT_P(0);
	text	   *arg2 = PG_GETARG_TEXT_P(1);
	int32		arg1_size = VARSIZE(arg1) - VARHDRSZ;
	int32		arg2_size = VARSIZE(arg2) - VARHDRSZ;
	int32		new_text_size = arg1_size + arg2_size + VARHDRSZ;
	text	   *new_text = (text *) palloc(new_text_size);

	SET_VARSIZE(new_text, new_text_size);
	memcpy(VARDATA(new_text), VARDATA(arg1), arg1_size);
	memcpy(VARDATA(new_text) + arg1_size, VARDATA(arg2), arg2_size);
	PG_RETURN_TEXT_P(new_text);
}

/* Composite types */

PG_FUNCTION_INFO_V1(c_overpaid);

Datum
c_overpaid(PG_FUNCTION_ARGS)
{
	HeapTupleHeader t = PG_GETARG_HEAPTUPLEHEADER(0);
	int32		limit = PG_GETARG_INT32(1);
	bool		isnull;
	int32		salary;

	salary = DatumGetInt32(GetAttributeByName(t, "salary", &isnull));
	if (isnull)
		PG_RETURN_BOOL(false);

	/*
	 * Alternatively, we might prefer to do PG_RETURN_NULL() for null salary
	 */

	PG_RETURN_BOOL(salary > limit);
}


text:
package com.github.gfranks.collapsible.calendar.model;

import com.github.gfranks.collapse.calendar.CalendarManager;

import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class CalendarManagerTest {

    Formatter formatter;
    CalendarManager mCalendarManager;

    @Before
    public void setUp() throws Exception {

        formatter = mock(Formatter.class);

        mCalendarManager = new CalendarManager(LocalDate.now(),
                CalendarManager.State.MONTH, LocalDate.now().minusDays(1),
                LocalDate.now().plusMonths(3), formatter);

    }

    @Test
    public void testSelectDay() throws Exception {

        LocalDate select = LocalDate.now().plusDays(1);

        boolean result = mCalendarManager.selectDay(select);

        assertTrue(result);
        assertTrue(mCalendarManager.getUnits().isSelected());

    }

    @Test
    public void testSelectDayOutOfRange() throws Exception {

        LocalDate select = LocalDate.now().plusMonths(2);

        boolean result = mCalendarManager.selectDay(select);

        assertTrue(result);
        assertFalse(mCalendarManager.getUnits().isSelected());

    }

    @Test
    public void testSelectDayWeek() throws Exception {

        mCalendarManager.toggleView();

        LocalDate select = LocalDate.now().plusMonths(2);

        boolean result = mCalendarManager.selectDay(select);
        assertTrue(result);
        assertFalse(mCalendarManager.getUnits().isSelected());
        assertEquals(select.withDayOfMonth(1), mCalendarManager.getActiveMonth());

    }

    @Test
    public void testSelectDaySame() throws Exception {

        LocalDate selected = mCalendarManager.getSelectedDay();

        boolean result = mCalendarManager.selectDay(selected);

        assertFalse(result);
        assertEquals(selected, mCalendarManager.getSelectedDay());
        assertTrue(mCalendarManager.getUnits().isSelected());

    }

    @Test
    public void testGetHeaderText() throws Exception {

        LocalDate date = LocalDate.now();
        RangeUnit unit = mock(RangeUnit.class);
        when(unit.getType()).thenReturn(CalendarUnit.TYPE_WEEK);
        when(unit.getFrom()).thenReturn(date);
        when(unit.getTo()).thenReturn(date);

        when(formatter.getHeaderText(eq(CalendarUnit.TYPE_WEEK), eq(date), eq(date))).thenReturn("header");
        mCalendarManager.setUnit(unit);

        String header = mCalendarManager.getHeaderText();
        assertEquals("header", header);

    }

    @Test
    public void testSetUnit() throws Exception {

        RangeUnit unit = mock(RangeUnit.class);
        mCalendarManager.setUnit(unit);

        assertTrue(unit == mCalendarManager.getUnits());

    }

    @Test
    public void testSetUnitNull() throws Exception {

        CalendarUnit unit = mCalendarManager.getUnits();
        mCalendarManager.setUnit(null);

        assertTrue(unit == mCalendarManager.getUnits());

    }

    @Test
    public void testHasNext() throws Exception {

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.hasNext()).thenReturn(true);

        mCalendarManager.setUnit(unit);

        boolean result = mCalendarManager.hasNext();
        assertTrue(result);

        verify(unit).hasNext();

    }

    @Test
    public void testHasPrev() throws Exception {

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.hasPrev()).thenReturn(true);

        mCalendarManager.setUnit(unit);

        boolean result = mCalendarManager.hasPrev();
        assertTrue(result);

        verify(unit).hasPrev();

    }

    @Test
    public void testNext() throws Exception {

        LocalDate from = LocalDate.now().plusWeeks(1);

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.next()).thenReturn(true);
        when(unit.getFrom()).thenReturn(from);

        mCalendarManager.setUnit(unit);

        boolean result = mCalendarManager.next();

        assertTrue(result);

        InOrder order = inOrder(unit);
        order.verify(unit).next();
        order.verify(unit).select(mCalendarManager.getSelectedDay());

        assertEquals(from.withDayOfMonth(1), mCalendarManager.getActiveMonth());

    }

    @Test
    public void testPrev() throws Exception {

        LocalDate to = LocalDate.now().plusWeeks(1);

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.prev()).thenReturn(true);
        when(unit.getTo()).thenReturn(to);

        mCalendarManager.setUnit(unit);

        boolean result = mCalendarManager.prev();

        assertTrue(result);

        InOrder order = inOrder(unit);
        order.verify(unit).prev();
        order.verify(unit).select(mCalendarManager.getSelectedDay());

        assertEquals(to.withDayOfMonth(1), mCalendarManager.getActiveMonth());

    }

    @Test
    public void testToggleViewMonthInView() throws Exception {

        LocalDate selected = mCalendarManager.getSelectedDay();

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.isInView(selected)).thenReturn(true);
        mCalendarManager.setUnit(unit);

        mCalendarManager.toggleView();

        Week week = new Week(selected, LocalDate.now(), mCalendarManager.getMinDate(), mCalendarManager.getMaxDate());
        week.select(selected);

        assertEquals(week, mCalendarManager.getUnits());
        assertEquals(CalendarManager.State.WEEK, mCalendarManager.getState());
        assertEquals(selected.withDayOfMonth(1), mCalendarManager.getActiveMonth());

    }

    @Test
    public void testToggleViewMonthNotInView() throws Exception {

        LocalDate selected = mCalendarManager.getSelectedDay();
        LocalDate from = selected.plusMonths(1);

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.isInView(selected)).thenReturn(false);
        when(unit.getFrom()).thenReturn(from);
        when(unit.getFirstDateOfCurrentMonth(any(LocalDate.class))).thenReturn(from);
        mCalendarManager.setUnit(unit);

        mCalendarManager.toggleView();

        Week week = new Week(from, LocalDate.now(), mCalendarManager.getMinDate(), mCalendarManager.getMaxDate());
        week.select(selected);

        assertEquals(week, mCalendarManager.getUnits());
        assertEquals(from.withDayOfMonth(1), mCalendarManager.getActiveMonth());

    }

    @Test
    public void testToggleViewWeekInView() throws Exception {

        mCalendarManager.toggleView(); // initial state week

        LocalDate currentMonth = mCalendarManager.getActiveMonth();
        LocalDate selected = mCalendarManager.getSelectedDay();

        mCalendarManager.toggleView();

        Month month = new Month(currentMonth, LocalDate.now(), mCalendarManager.getMinDate(), mCalendarManager.getMaxDate());
        month.select(selected);

        assertEquals(month, mCalendarManager.getUnits());
        assertEquals(CalendarManager.State.MONTH, mCalendarManager.getState());

    }

    @Test
    public void testToggleToWeek() throws Exception {

        LocalDate from = mCalendarManager.getUnits().getFrom();

        mCalendarManager.toggleToWeek(2);

        Week week = new Week(from.plusDays(2 * 7), LocalDate.now(), mCalendarManager.getMinDate(), mCalendarManager.getMaxDate());
        week.select(mCalendarManager.getSelectedDay());

        assertEquals(week, mCalendarManager.getUnits());

    }

    @Test
    public void testGetWeekInViewInRange() throws Exception {

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.isInView(any(LocalDate.class))).thenReturn(true);
        when(unit.isIn(any(LocalDate.class))).thenReturn(true);
        when(unit.getWeekInMonth(mCalendarManager.getSelectedDay())).thenReturn(12);

        mCalendarManager.setUnit(unit);

        assertEquals(12, mCalendarManager.getWeekOfMonth());

    }

    @Test
    public void testGetWeekInViewAfter() throws Exception {

        LocalDate from = mCalendarManager.getSelectedDay().plusDays(1);

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.isInView(any(LocalDate.class))).thenReturn(true);
        when(unit.isIn(any(LocalDate.class))).thenReturn(false);
        when(unit.getFrom()).thenReturn(from);
        when(unit.getWeekInMonth(from)).thenReturn(12);

        mCalendarManager.setUnit(unit);

        assertEquals(12, mCalendarManager.getWeekOfMonth());

    }

    @Test
    public void testGetWeekInViewBefore() throws Exception {

        LocalDate from = mCalendarManager.getSelectedDay().minusDays(1);
        LocalDate to = mCalendarManager.getSelectedDay().plusDays(1);

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.isInView(any(LocalDate.class))).thenReturn(true);
        when(unit.isIn(any(LocalDate.class))).thenReturn(false);
        when(unit.getFrom()).thenReturn(from);
        when(unit.getTo()).thenReturn(to);
        when(unit.getWeekInMonth(to)).thenReturn(12);

        mCalendarManager.setUnit(unit);

        assertEquals(12, mCalendarManager.getWeekOfMonth());

    }

    @Test
    public void testGetWeekOfMonthNotInView() throws Exception {

        LocalDate now = LocalDate.now();

        RangeUnit unit = mock(RangeUnit.class);
        when(unit.isInView(any(LocalDate.class))).thenReturn(false);
        when(unit.getFirstDateOfCurrentMonth(mCalendarManager.getActiveMonth())).thenReturn(now);
        when(unit.getFirstWeek(now)).thenReturn(43);

        mCalendarManager.setUnit(unit);

        assertEquals(43, mCalendarManager.getWeekOfMonth());

    }

    @Test
    public void testInit() throws Exception {

        LocalDate now = LocalDate.now();
        LocalDate min = now.minusDays(3);
        LocalDate max = min.plusMonths(3);

        mCalendarManager.init(now, min, max);

        assertEquals(now, mCalendarManager.getSelectedDay());
        assertEquals(min, mCalendarManager.getMinDate());
        assertEquals(max, mCalendarManager.getMaxDate());
        assertEquals(now.withDayOfMonth(1), mCalendarManager.getActiveMonth());

        CalendarUnit unit = new Month(now, now, min, max);
        unit.setSelected(true);

        assertEquals(unit, mCalendarManager.getUnits());

    }

    @Test
    public void testInitWeek() throws Exception {

        LocalDate now = LocalDate.now();
        LocalDate min = now.minusDays(3);
        LocalDate max = min.plusMonths(3);

        CalendarManager manager = new CalendarManager(now,
                CalendarManager.State.WEEK, min, max);

        CalendarUnit unit = new Week(now, now, min, max);
        unit.setSelected(true);

        assertEquals(unit, manager.getUnits());

    }

    @Test
    public void testSetMinDate() throws Exception {

        LocalDate min = LocalDate.now().minusMonths(1);
        mCalendarManager.setMinDate(min);

        assertEquals(min, mCalendarManager.getMinDate());

    }

    @Test
    public void testSetMaxDate() throws Exception {

        LocalDate max = LocalDate.now().plusMonths(1);
        mCalendarManager.setMaxDate(max);

        assertEquals(max, mCalendarManager.getMaxDate());

    }
}


text:
package fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.library;

import java.util.List;

import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Element;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.AbstractDoubleEvaluator;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.EvaluationContext;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.Evaluator;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.Function;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.FunctionLibrary;
import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.Library;
import fr.inra.maiage.bibliome.alvisnlp.core.module.ModuleException;
import fr.inra.maiage.bibliome.alvisnlp.core.module.NameUsage;
import fr.inra.maiage.bibliome.util.pairing.AlignmentProbability;
import fr.inra.maiage.bibliome.util.pairing.AlignmentScore;
import fr.inra.maiage.bibliome.util.pairing.ClassicAlignmentScore;
import fr.inra.maiage.bibliome.util.pairing.NeedlemanWunsch;

@Library("align")
public abstract class AlignmentLibrary extends FunctionLibrary {
	@Function
	public static Evaluator score(Evaluator gap, Evaluator match, Evaluator a, Evaluator b) {
		return new NeedlemanWunschEvaluator(false, gap, match, a, b);
	}

	@Function
	public static Evaluator proba(Evaluator gap, Evaluator match, Evaluator a, Evaluator b) {
		return new NeedlemanWunschEvaluator(true, gap, match, a, b);
	}

	private static final class NeedlemanWunschEvaluator extends AbstractDoubleEvaluator {
		private final boolean probability;
		private final Evaluator gap;
		private final Evaluator match;
		private final Evaluator a;
		private final Evaluator b;
		private final ComparatorContext comparatorContext;

		private NeedlemanWunschEvaluator(boolean probability, Evaluator gap, Evaluator match, Evaluator a, Evaluator b, ComparatorContext comparatorContext) {
			super();
			this.probability = probability;
			this.gap = gap;
			this.match = match;
			this.a = a;
			this.b = b;
			this.comparatorContext = comparatorContext;
		}

		private NeedlemanWunschEvaluator(boolean probability, Evaluator gap, Evaluator match, Evaluator a, Evaluator b) {
			this(probability, gap, match, a, b, new ComparatorContext());
		}

		@Override
		public double evaluateDouble(EvaluationContext ctx, Element elt) {
			List<Element> a = this.a.evaluateList(ctx, elt);
			List<Element> b = this.b.evaluateList(ctx, elt);
			AlignmentScore<Element,Element> alignmentScore = getScore(ctx, elt);
			NeedlemanWunsch<Element,Element> matrix = new NeedlemanWunsch<Element,Element>(a, b, alignmentScore);
			matrix.solve();
			return matrix.getScore();
		}

		@Override
		public void collectUsedNames(NameUsage nameUsage, String defaultType) throws ModuleException {
			gap.collectUsedNames(nameUsage, defaultType);
			match.collectUsedNames(nameUsage, defaultType);
			a.collectUsedNames(nameUsage, defaultType);
			b.collectUsedNames(nameUsage, defaultType);
		}

		private AlignmentScore<Element,Element> getScore(EvaluationContext ctx, Element elt) {
			double gap = this.gap.evaluateDouble(ctx, elt);
			if (probability)
				return new ProbabilityScore(ctx, gap);
			return new AdditiveScore(ctx, gap);
		}

		private final class ProbabilityScore extends AlignmentProbability<Element,Element> {
			private final EvaluationContext ctx;
			private final double gapValue;

			private ProbabilityScore(EvaluationContext ctx, double gap) {
				super(true);
				this.ctx = ctx;
				this.gapValue = gap;
			}

			@Override
			public double getScore(Element a, Element b) {
				return comparatorContext.evaluateDouble(match, ctx, a, b);
			}

			@Override
			public double getGap() {
				return gapValue;
			}
		}

		private final class AdditiveScore extends ClassicAlignmentScore<Element,Element> {
			private final EvaluationContext ctx;
			private final double gapValue;

			private AdditiveScore(EvaluationContext ctx, double gap) {
				super(0);
				this.ctx = ctx;
				this.gapValue = gap;
			}

			@Override
			public double getScore(Element a, Element b) {
				return comparatorContext.evaluateDouble(match, ctx, a, b);
			}

			@Override
			public double getGap() {
				return gapValue;
			}
		}
	}
}


text:
namespace k52
{
namespace parallel
{

WorkerStatistics::WorkerStatistics()
    : counted_(0)
    , errors_(0)
    , id_()
{
}

WorkerStatistics::WorkerStatistics(int counted, int errors, int id)
    : counted_(counted)
    , errors_(errors)
    , id_(id)
{
}

void WorkerStatistics::IncreaseCounted()
{
    ++counted_;
}

void WorkerStatistics::IncreaseErrors()
{
    errors_++; // encoding issue with prefix increment
}

int WorkerStatistics::get_counted() const
{
    return counted_;
}

int WorkerStatistics::get_errors() const
{
    return errors_;
}

int WorkerStatistics::get_id() const
{
    return id_;
}

} // namespace parallel
} // namespace k52