text:
import datetime
from django.utils.translation import get_language
from django.db import models, IntegrityError, transaction

# create profile
from bbeta.bloodon.system.models import Blood
from . import utils
from django.db.models.signals import post_save
from django.contrib.auth.models import *
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.core.urlresolvers import reverse
from datetime import timedelta

from django.db.models import Q
from .utils import random_token

class MyUserManager(BaseUserManager):
    def create_user(self, username, email=None, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(email=MyUserManager.normalize_email(email), username=username)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(username, email, password=password)
        user.is_admin = True
        user.is_active = True
        #user.is_superuser = True
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
        db_index=True,
    )
    username = models.CharField(max_length=35, blank=False)
    is_active = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __unicode__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

class UserProfile(models.Model):
    address_latitude = models.FloatField(blank=True, null=True)
    address_longitude = models.FloatField(blank=True, null=True)
    can_donate = models.BooleanField(default=True)
    is_visible = models.BooleanField(default=True)
    user = models.OneToOneField(MyUser, primary_key=True)
    blood = models.ForeignKey(Blood)
    lang = models.CharField(max_length=3, default=True, blank=True)

class EmailAddressManager(models.Manager):
    def add_email(self, request, user, email, **kwargs):
        confirm = kwargs.pop("confirm", False)
        signup = kwargs.pop("signup", False)
        try:
            email_address = self.create(user=user, email=email, **kwargs)
        except IntegrityError:
            return None
        else:
            if confirm and not email_address.verified:
                email_address.send_confirmation(request,
                                                signup=signup)
            return email_address

    def get_primary(self, user):
        try:
            return self.get(user=user, primary=True)
        except self.model.DoesNotExist:
            return None

    def get_users_for(self, email):
        # this is a list rather than a generator because we probably want to
        # do a len() on it right away
        return [address.user for address in self.filter(verified=True,
                                                        email=email)]

class EmailConfirmationManager(models.Manager):
    def all_expired(self):
        return self.filter(self.expired_q())

    def all_valid(self):
        return self.exclude(self.expired_q())

    def expired_q(self):
        sent_threshold = timezone.now() \
                         - timedelta(days=3)
        return Q(sent__lt=sent_threshold)

    def delete_expired_confirmations(self):
        self.all_expired().delete()

class EmailAddress(models.Model):
    user = models.ForeignKey(MyUser)
    email = models.EmailField(unique=True)
    verified = models.BooleanField(default=False)
    primary = models.BooleanField(default=False)

    objects = EmailAddressManager()

    class Meta:
        verbose_name = _("email address")
        verbose_name_plural = _("email addresses")

    def __str__(self):
        return u"%s (%s)" % (self.email, self.user)

    def set_as_primary(self, conditional=False):
        old_primary = EmailAddress.objects.get_primary(self.user)
        if old_primary:
            if conditional:
                return False
            old_primary.primary = False
            old_primary.save()
        self.primary = True
        self.save()
        utils.user_email(self.user, self.email)
        #B$P
        self.user.save()
        return True

    def send_confirmation(self, request, signup=False):
        confirmation = EmailConfirmation.create(self)
        confirmation.send(request, signup=signup)
        return confirmation

    def change(self, request, new_email, confirm=True):
        """
        Given a new email address, change self and re-confirm.
        """
        with transaction.commit_on_success():
            utils.user_email(self.user, new_email)
            #B$P
            self.user.save()
            self.email = new_email
            self.verified = False
            self.save()
            if confirm:
                self.send_confirmation(request)

class EmailConfirmation(models.Model):
    email_address = models.ForeignKey(EmailAddress)
    created = models.DateTimeField(default=timezone.now)
    sent = models.DateTimeField(null=True)
    key = models.CharField(max_length=64, unique=True)

    objects = EmailConfirmationManager()

    class Meta:
        verbose_name = _("email confirmation")
        verbose_name_plural = _("email confirmations")

    def __str__(self):
        return u"confirmation for %s" % self.email_address

    @classmethod
    def create(cls, email_address):
        key = random_token([email_address.email])
        return cls._default_manager.create(email_address=email_address, key=key)

    def key_expired(self):
        expiration_date = self.sent + datetime.timedelta(days=3)
        return expiration_date <= timezone.now()

    key_expired.boolean = True

    def confirm(self, request):
        if not self.key_expired() and not self.email_address.verified:
            email_address = self.email_address
            email_address.verified = True
            email_address.set_as_primary(conditional=True)
            email_address.save()
            return email_address

    def send(self, request, signup=False, **kwargs):
        #current_site = kwargs["site"] if "site" in kwargs else Site.objects.get_current()
        activate_url = reverse("account_confirm_email", args=[self.key])
        activate_url = request.build_absolute_uri(activate_url)
        ctx = {
            "user": self.email_address.user,
            "activate_url": activate_url,
            #"current_site": current_site,
            "key": self.key,
        }
        if signup:
            email_template = 'account/email/email_confirmation_signup'
        else:
            email_template = 'account/email/email_confirmation'
        from .helper import AccountHelper

        AccountHelper().send_mail(email_template,
                                  self.email_address.email,
                                  ctx)
        self.sent = timezone.now()
        self.save()

MyUser.backend = 'django.contrib.auth.backends.ModelBackend'

def my_callback(sender, instance, created, raw, using, **kwargs):
    if created:
        defaultBloodType = Blood.objects.get(blood='0')
        lang = get_language()
        profile = UserProfile.objects.create(user=instance, blood=defaultBloodType, lang=lang)
        profile.save()

post_save.connect(my_callback, sender=MyUser)


text:
using System;
using Csla;
using Invoices.DataAccess;

namespace Invoices.DataAccess.Firebird
{
    public partial class ProductTypeEditDal
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
[![Codeship Status for FluuxIO/xmpp](https://app.codeship.com/projects/dba7f300-d145-0135-6c51-26e28af241d2/status?branch=master)](https://app.codeship.com/projects/262399) [![GoDoc](https://godoc.org/gosrc.io/xmpp?status.svg)](https://godoc.org/gosrc.io/xmpp) [![GoReportCard](https://goreportcard.com/badge/gosrc.io/xmpp)](https://goreportcard.com/report/fluux.io/xmpp) [![codecov](https://codecov.io/gh/FluuxIO/xmpp/branch/master/graph/badge.svg)](https://codecov.io/gh/FluuxIO/xmpp)

Fluux XMPP is a Go XMPP library, focusing on simplicity, simple automation, and IoT.

The goal is to make simple to write simple adhoc XMPP clients:

- For automation (like for example monitoring of an XMPP service),
- For building connected "things" by plugging them on an XMPP server,
- For writing simple chatbot to control a service or a thing.
- For writing XMPP servers components.

The library is designed to have minimal dependencies. For now, the library does not depends on any other library.

## Usage

Please, check GoDoc for more information: [gosrc.io/xmpp](https://godoc.org/gosrc.io/xmpp)


text:
package ninja.ugly.prevail.event.factory;

import com.google.common.base.Optional;

import ninja.ugly.prevail.event.DeleteEndEvent;
import ninja.ugly.prevail.event.Event;

/**
 * A DeleteEventFactory that just returns DeleteEndEvents at the end of a delete operation.
 * @param <K>
 */
public class DeleteEndEventFactory<K> extends DeleteEventFactory.EmptyDeleteEventFactory<K> {
  @Override
  public <E extends Event> Optional<E> endEvent(K key, int numValuesDeleted) {
    return (Optional<E>) Optional.of(new DeleteEndEvent<K>(key, numValuesDeleted));
  }
}


text:
var activeChannel = ''
function receive_msg(s) {
  console.log(s)
    mainView.chatMod.append(s);
}

function onLoggedIn() {
  loader.source = ""
    loader.sourceComponent = waitingComp
    rootApp.width = 800
}

function channelAdd(ch) {
  console.log(loader.source)
    mainView.channelMod.append({channel: ch})
}

function loginFinish() {
  loader.sourceComponent = undefined
    loader.source = 'main.qml'
    medium.Qjoin('Lobby')
}

function setActiveChannel(ch) {
  activeChannel = ch
}


text:
define({
  "enableUndoRedo": "Iespējot Atsaukt/Atatsaukt",
  "toolbarVisible": "Rīkjosla redzama",
  "toolbarOptions": "Rīkjoslas opcijas",
  "mergeVisible": "Apvienot",
  "cutVisible": "Izgriezt",
  "reshapeVisible": "Pārveidot",
  "back": "Atpakaļ",
  "label": "Slānis",
  "edit": "Rediģējams",
  "update": "Atspējot Atjaunināt ģeometriju",
  "fields": "Lauki",
  "actions": "Darbības",
  "editpageName": "Nosaukums",
  "editpageAlias": "Aizstājvārds",
  "editpageVisible": "Redzams",
  "editpageEditable": "Rediģējams",
  "noLayers": "Nav pieejams neviens rediģējams elementu slānis",
  "configureFields": "Konfigurēt slāņa laukus",
  "useFilterEdit": "Izmantot elementu šablona filtru",
  "display": "Parādīt",
  "autoApplyEditWhenGeometryIsMoved": "Pārvietojot ģeometriju, automātiski lietot rediģēšanu",
  "snappingTolerance": "Iestatīt pielipšanas toleranci pikseļos",
  "popupTolerance": "Iestatīt atribūtu rediģēšanas uznirstošā loga toleranci pikseļos",
  "stickyMoveTolerance": "Iestatīt līpošās pārvietošanas toleranci pikseļos"
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sharp2D.Core.Interfaces;

namespace Sharp2D.Game.Sprites
{
    public abstract class LogicalSprite : Sprite, ILogical
    {
        public abstract void Update();
    }
}


text:
using GraphQL.Types;

namespace GraphQL.Introspection
{
    public class SchemaMetaFieldType : FieldType
    {
        public SchemaMetaFieldType()
        {
            Name = "__schema";
            Type = typeof (__Schema);
            Description = "Access the current type schema of this server.";
            Resolve = context => context.Schema;
        }
    }

    public class __Schema : ObjectGraphType
    {
        public __Schema()
        {
            Name = "__Schema";
            Description = "A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query and mutation operations.";

            Field<NonNullGraphType<ListGraphType<__Type>>>("types", "A list of all types supported by this server.", null, context =>
            {
                return context.Schema.AllTypes;
            });
            Field<NonNullGraphType<__Type>>("queryType", "The type that query operations will be rooted at.", null, context =>
            {
                return context.Schema.Query;
            });
            Field<__Type>("mutationType", "If this server supports mutation, the type that mutation operations will be rooted at.", null, context =>
            {
                return context.Schema.Mutation;
            });
            Field<NonNullGraphType<ListGraphType<__Directive>>>("directives", "A list of all directives supported by this server.", null, context =>
            {
                return context.Schema.Directives;
            });
        }
    }
}


text:
"""
A collection of utilities which also includes the slot grid builder.
"""
from dateutil import rrule
import logging

from django.utils.datastructures import SortedDict

from . import models

LOG = logging.getLogger(__name__)

class PlaceSlot(object):
    """
    A simple object combining a place with a slot.
    """
    def __init__(self, place, slot):
        self.place = place
        self.slot = slot
    def __unicode__(self):
        return u"%s: %s" % (self.slot, self.place.name)

def get_days(start, end):
    "Retuns the dates between start and end."
    return rrule.rrule(rrule.DAILY, dtstart=start, until=end)

class SlotGridElement(object):
    """
    An element within a slotgrid combining slot, place and
    events associated with this combination.
    """

    def __init__(self, slot=None, place=None):
        self.slot = slot is not None and slot or None
        self.place = place is not None and place or None
        self.events = []

    def __unicode__(self):
        return unicode(self.slot.start) + u" - " + unicode(self.slot.end) + " (" + self.place.name + ")"

class SlotGrid(object):
    """
    A slotgrid represents a matrix of slots associated with
    a room. Internally it is a 2dim array where columns are
    associated with place objects.

    If all slots are synchronized then the row dimension
    as a whole has an additional slot association.
    """
    def __init__(self):
        self.grid = []
        self.places = []
        self.slots = []
        self.date = None

    @classmethod
    def create_from_barcamp(cls, barcamp, room_order=None, per_day=False, mark_for_user=None):
        """
        Create a slotgrid from the given barcamp. If the rooms should
        be ordered in a specific fashion, pass them in the right way
        using the room_order argument.

        If a grid should be generated for every day that actually includes
        slots, set per_day to True.

        To, furthermore, set permissions for a given user, pass this user
        using the mark_for_user kwarg.
        """
        if room_order is not None:
            places = room_order
        else:
            places = [x for x in barcamp.places.filter(is_sessionroom=True).order_by('pk')]
        slots = barcamp.slots.all().order_by('start')
        sge_index = {}
        start_grid = {}
        for slot in slots:
            if slot.start not in start_grid:
                start_grid[slot.start] = [None for x in places]
            if slot.place is None:
                start_grid[slot.start] = []
                for place in places:
                    sge = SlotGridElement(slot=slot, place=place)
                    start_grid[slot.start].append(sge)
                    sge_index["%d-%d" % (sge.slot.pk, sge.place.pk)] = sge
            else:
                sge = SlotGridElement(slot=slot, place=slot.place)
                start_grid[slot.start][places.index(slot.place)] = sge
                sge_index["%d-%d" % (sge.slot.pk, sge.place.pk)] = sge

        # Fill the sges with events
        events = models.Talk.objects.filter(barcamp=barcamp,
                timeslot__isnull=False, place__isnull=False)
        if mark_for_user is not None:
            mark_talklist_permissions(events, mark_for_user, barcamp)
        for event in events:
            sge_index["%d-%d" % (event.timeslot.pk, event.place.pk)]\
                    .events.append(event)
        open_elems = [sge for sge in sge_index.values() if len(sge.events) == 0]

        if per_day:
            date_grids = []
            grid = None
            last_date = None
            for k in sorted(start_grid.keys()):
                date = k.date()
                if date != last_date:
                    if grid is not None:
                        date_grids.append(grid)
                    grid = SlotGrid()
                    grid.places = places
                    grid.date = date
                grid.grid.append(start_grid[k])
                last_date = date
            if grid is not None:
                date_grids.append(grid)
            return date_grids, open_elems
        else:
            grid = SlotGrid()
            grid.places = places
            for k in sorted(start_grid.keys()):
                grid.grid.append(start_grid[k])

        return grid, open_elems

def create_slot_grid(barcamp):
    from .models import Talk

    talks = Talk.objects.filter(barcamp=barcamp).select_related().all()
    slots = barcamp.slots.order_by('start').all()
    rooms = barcamp.places.all()
    open_slots = {}

    result = SortedDict() # Grid with slots as first and room as second dim.
    for slot in slots:
        if slot not in result:
            result[slot] = {}
        for room in rooms:
            open_slots['r%d-s%d' % (room.pk, slot.pk)] = PlaceSlot(room, slot)
            result[slot][room] = None

    for talk in talks:
        if talk.timeslot is None or talk.place is None:
            continue
        result[talk.timeslot][talk.place] = talk
        del open_slots['r%d-s%d' % (talk.place.pk, talk.timeslot.pk)]

    return result, open_slots

def mark_talkgrid_permissions(grid, user, barcamp):
    user_talks = hasattr(user, 'talks') and user.talks.all() or []
    for rooms in grid.values():
        for talk in rooms.values():
            if talk is None:
                continue
            _mark_talk_permissions(talk, user, barcamp, user_talks)

def mark_talklist_permissions(talks, user, barcamp):
    user_talks = hasattr(user, 'talks') and user.talks.all() or []
    for talk in talks:
        if talk is None:
            continue
        _mark_talk_permissions(talk, user, barcamp, user_talks)

def _mark_talk_permissions(talk, user, barcamp, user_talks):
    if user.is_superuser or user.is_staff:
        talk.can_edit = True
    elif talk in user_talks:
        talk.can_edit = True
    else:
        talk.can_edit = False


text:
/**
 * chemist controller
 * @return
 */
module.exports = Controller("Home/BaseController", function(){
    "use strict";
    return {
        indexAction: function(){
            var self= this;
//            console.log('session:\n',self.http.cookie)
//            if(self.http.query.drugId){
                var api_url= zyoAPI.chemist_list+ '&city='+(self.http.cookie.usercity||encodeURI('上海'))+'&start=0&rows=10&lat='+(self.http.cookie.userlat||31.313131)+'&lng='+(self.http.cookie.userlng||121.121121)+'&uid=';
                request(api_url, function(error, response, body){
                    console.log('api_url:\n',api_url)
                    var res= JSON.parse(body);
                    self.assign('storeEmployeeList', JSON.stringify(res.data.storeEmployeeList))
                    self.display();
                })
//            }
//            else{
//
//            }
        },
        detailAction: function(){
            var self= this;
            var uid= self.view.tVar.userInfo? JSON.parse(self.view.tVar.userInfo).uid: '';
            console.log('session:\n',uid)
            var api_url= zyoAPI.chemist_detail+'&uid='+self.http.query.chemistId+ '&userId='+ uid;
            console.log(api_url)
            request(api_url, function(error, response, body){
                var res= JSON.parse(body)
                self.assign('employeeInfo', JSON.stringify(res.data.employeeInfo))
                self.display('');
            });
        },
        collectAction: function(){
            var self= this, uid;
            (self.view.tVar.userInfo)&& (uid= JSON.parse(self.view.tVar.userInfo).uid);
            console.log('like session:\n',uid);
            if(!uid){
                console.log('redirect')
                self.end('{"code":"7", "msg":"未登录", "data":"unlogin"}')
            }
            else {
                var api_url= zyoAPI.chemist_focus+'&uid='+self.http.query.dataId+'&userId='+uid;
                request(api_url, function(error, response, body){
                    var res= JSON.parse(body)
                    console.log(api_url,'\n')
                    self.end(body)
                })
            }
        },
        uncollectAction: function(){
            var self= this, uid= '';
            (self.view.tVar.userInfo)&& (uid= JSON.parse(self.view.tVar.userInfo).uid);
            if(!uid){
                console.log('redirect')
                self.end('{"code":"7", "msg":"未登录", "data":"unlogin"}')
            }
            else {
                var api_url= zyoAPI.chemist_cancel_focus+'&uid='+self.http.query.dataId+'&userId='+uid;
                console.log(api_url,'\n')
                request(api_url, function(error, response, body){
                    var res= JSON.parse(body)
                    self.end(body)
                })
            }
        },
    };
});


text:
class CuratorLevel < ActiveRecord::Base
  has_many :users

  def self.create_defaults
    if !self.master_curator
      CuratorLevel.create(:label => 'Master Curator')
    end
    if !self.assistant_curator
      CuratorLevel.create(:label => 'Assistant Curator')
    end
    if !self.full_curator
      CuratorLevel.create(:label => 'Full Curator')
    end
  end

  class << self
    def master
      cached_find(:label, 'Master Curator')
    end
    alias :master_curator :master

    def full
      cached_find(:label, 'Full Curator')
    end
    alias :full_curator :full

    def assistant
      cached_find(:label, 'Assistant Curator')
    end
    alias :assistant_curator :assistant
  end

  def translated_label
    I18n.t("curator_level_#{label.gsub(' ', '_').downcase}")
  end

end


text:
Framework '4.0'

properties {
    $birthYear = 2013
    $maintainers = "Patrick Lioi"

    $configuration = 'Release'
    $src = resolve-path '.\src'
    $build = if ($env:build_number -ne $NULL) { $env:build_number } else { '0' }
    $version = [IO.File]::ReadAllText('.\VERSION.txt') + '.' + $build
    $projects = @(gci $src -rec -filter *.csproj)
    $selfTestProjects = "Fixie.Tests","Fixie.Samples"
}

task default -depends Test

task Package -depends Test {
    rd .\package -recurse -force -ErrorAction SilentlyContinue | out-null
    mkdir .\package -ErrorAction SilentlyContinue | out-null
    exec { & $src\.nuget\NuGet.exe pack $src\Fixie\Fixie.csproj -Symbols -Prop Configuration=$configuration -OutputDirectory .\package }

    write-host
    write-host "To publish these packages, issue the following command:"
    write-host "   nuget push .\package\Fixie.$version.nupkg"
}

task Test -depends Compile {
    $fixieRunner = resolve-path ".\build\Fixie.Console.exe"
    exec { & $fixieRunner $src\Fixie.Tests\bin\$configuration\Fixie.Tests.dll $src\Fixie.Samples\bin\$configuration\Fixie.Samples.dll }
}

task Compile -depends SanityCheckOutputPaths, AssemblyInfo, License {
  rd .\build -recurse -force  -ErrorAction SilentlyContinue | out-null
  exec { msbuild /t:clean /v:q /nologo /p:Configuration=$configuration $src\Fixie.sln }
  exec { msbuild /t:build /v:q /nologo /p:Configuration=$configuration $src\Fixie.sln }
}

task SanityCheckOutputPaths {
    $blankLine = ([System.Environment]::NewLine + [System.Environment]::NewLine)
    $expected = "..\..\build\"

    foreach ($project in $projects) {
        $projectName = [System.IO.Path]::GetFileNameWithoutExtension($project)

        $lines = [System.IO.File]::ReadAllLines($project.FullName, [System.Text.Encoding]::UTF8)

        if (!($selfTestProjects -contains $projectName)) {
            foreach($line in $lines) {
                if ($line.Contains("<OutputPath>")) {

                    $outputPath = [regex]::Replace($line, '\s*<OutputPath>(.+)</OutputPath>\s*', '$1')

                    if($outputPath -ne $expected){
                        $summary = "The project '$projectName' has a suspect *.csproj file."
                        $detail = "Expected OutputPath to be $expected for all configurations."

                        Write-Host -ForegroundColor Yellow "$($blankLine)$($summary)  $($detail)$($blankLine)"
                        throw $summary
                    }
                }
            }
        }
    }
}

task AssemblyInfo {
    $copyright = get-copyright

    foreach ($project in $projects) {
        $projectName = [System.IO.Path]::GetFileNameWithoutExtension($project)

        regenerate-file "$($project.DirectoryName)\Properties\AssemblyInfo.cs" @"
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: ComVisible(false)]
[assembly: AssemblyProduct("Fixie")]
[assembly: AssemblyTitle("$projectName")]
[assembly: AssemblyVersion("$version")]
[assembly: AssemblyFileVersion("$version")]
[assembly: AssemblyCopyright("$copyright")]
[assembly: AssemblyCompany("$maintainers")]
[assembly: AssemblyConfiguration("$configuration")]
"@
    }
}

task License {
    $copyright = get-copyright

    regenerate-file "LICENSE.txt" @"
The MIT License (MIT)
$copyright

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"@
}

function get-copyright {
    $date = Get-Date
    $year = $date.Year
    $copyrightSpan = if ($year -eq $birthYear) { $year } else { "$birthYear-$year" }
    return "Copyright © $copyrightSpan $maintainers"
}

function regenerate-file($path, $newContent) {
    $oldContent = [IO.File]::ReadAllText($path)

    if ($newContent -ne $oldContent) {
        $relativePath = Resolve-Path -Relative $path
        write-host "Generating $relativePath"
        [System.IO.File]::WriteAllText($path, $newContent, [System.Text.Encoding]::UTF8)
    }
}


text:
<?php

namespace WebinoDraw\Draw\Helper;

use ArrayObject;
use DOMAttr;
use DOMElement;
use WebinoDraw\VarTranslator\Translation;

/**
 * Generated by PHPUnit_SkeletonGenerator 1.2.1 on 2014-08-03 at 01:23:45.
 */
class AbsolutizeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Absolutize
     */
    protected $object;

    /**
     * @var \Zend\View\Helper\BasePath
     */
    protected $basePath;

    /**
     * @var \Zend\View\Helper\ServerUrl
     */
    protected $serverUrl;

    /**
     * @var
     */
    protected $nodes;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $varTranslator   = $this->getMock('WebinoDraw\VarTranslator\VarTranslator', [], [], '', false);
        $this->serverUrl = $this->getMock('Zend\View\Helper\ServerUrl');
        $this->basePath  = $this->getMock('Zend\View\Helper\BasePath');
        $this->object    = new Absolutize($this->serverUrl, $this->basePath);
        $this->nodes     = $this->getMock('WebinoDraw\Dom\NodeList', [], [], '', false);

        $varTranslator
            ->expects($this->once())
            ->method('createTranslation')
            ->will($this->returnValue(new Translation));

        $this->object->setVarTranslator($varTranslator);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     */
    public function testDrawNodes()
    {
        $basePath      = '/test/base/path';
        $attrValue     = 'test-value';
        $expected      = $basePath . '/' . $attrValue;
        $attr          = new DOMAttr('test-attr', $attrValue);
        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->object->drawNodes($this->nodes, []);
        $this->assertEquals($expected, $attr->nodeValue);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     */
    public function testDrawNodesWithServerUrl()
    {
        $spec          = ['serverUrl' => true];
        $serverUrl     = 'http://example.com';
        $basePath      = '/test/base/path';
        $attrValue     = 'test-value';
        $expected      = $serverUrl . $basePath . '/' . $attrValue;
        $attr          = new DOMAttr('test-attr', $attrValue);
        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->serverUrl
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($serverUrl));

        $this->object->drawNodes($this->nodes, $spec);

        $this->assertEquals($expected, $attr->nodeValue);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     */
    public function testDrawNodesInvalidAttr()
    {
        $this->setExpectedException('WebinoDraw\Exception\RuntimeException');

        // invalid attr
        $attr = new DOMElement('test-element');
        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke');

        $this->object->drawNodes($this->nodes, []);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     */
    public function testDrawNodesCycle()
    {
        $basePath      = '/test/base/path';
        $attrValue     = 'test-value';
        $attrValue2    = 'test-value2';
        $attrValue3    = 'test-value3';
        $attr          = new DOMAttr('test-attr', $attrValue);
        $attr2         = new DOMAttr('test-attr', $attrValue2);
        $attr3         = new DOMAttr('test-attr', $attrValue3);
        $nodesIterator = new ArrayObject([$attr, $attr2, $attr3]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->object->drawNodes($this->nodes, []);

        $this->assertEquals($basePath . '/' . $attrValue, $attr->nodeValue);
        $this->assertEquals($basePath . '/' . $attrValue2, $attr2->nodeValue);
        $this->assertEquals($basePath . '/' . $attrValue3, $attr3->nodeValue);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     * @covers WebinoDraw\Draw\Helper\Absolutize::removeDotSegments
     */
    public function testRemoveDotSegments()
    {
        $basePath      = '/test/base/path';
        $attrValue     = '/test-absolute/./test-relative';
        $expected      = $basePath . '/test-absolute/test-relative';
        $attr          = new DOMAttr('test-attr', $attrValue);
        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->object->drawNodes($this->nodes, []);
        $this->assertEquals($expected, $attr->nodeValue);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     * @covers WebinoDraw\Draw\Helper\Absolutize::removeDotSegments
     */
    public function testRemoveDotSegmentsUp()
    {
        $basePath      = '/test/base/path';
        $attrValue     = '/test-absolute/../test-relative';
        $expected      = $basePath . '/test-relative';
        $attr          = new DOMAttr('test-attr', $attrValue);
        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->object->drawNodes($this->nodes, []);
        $this->assertEquals($expected, $attr->nodeValue);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     * @covers WebinoDraw\Draw\Helper\Absolutize::removeDotSegments
     */
    public function testRemoveDotSegmentsUp2()
    {
        $basePath      = '/test/base/path';
        $attrValue     = '/test-absolute/test/test2/../../../test-relative';
        $expected      = $basePath . '/test-relative';
        $attr          = new DOMAttr('test-attr', $attrValue);
        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->object->drawNodes($this->nodes, []);
        $this->assertEquals($expected, $attr->nodeValue);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     * @covers WebinoDraw\Draw\Helper\Absolutize::removeDotSegments
     */
    public function testRemoveDotSegmentsUpTooMuch()
    {
        $basePath      = '';
        $attrValue     = '/test-absolute/../../test-relative';
        $expected      = $basePath . '/test-relative';
        $attr          = new DOMAttr('test-attr', $attrValue);
        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->object->drawNodes($this->nodes, []);
        $this->assertEquals($expected, $attr->nodeValue);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     * @covers WebinoDraw\Draw\Helper\Absolutize::removeDotSegments
     */
    public function testRemoveDotSegmentsJustDot()
    {
        $basePath      = '/test/base/path';
        $attrValue     = '.';
        $expected      = $basePath . '/';
        $attr          = new DOMAttr('test-attr', $attrValue);
        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->object->drawNodes($this->nodes, []);
        $this->assertEquals($expected, $attr->nodeValue);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     * @covers WebinoDraw\Draw\Helper\Absolutize::removeDotSegments
     */
    public function testRemoveDotSegmentsJustDoubleDot()
    {
        $basePath  = '';
        $attrValue = '..';
        $expected  = '/';
        $attr      = new DOMAttr('test-attr', $attrValue);

        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->object->drawNodes($this->nodes, []);
        $this->assertEquals($expected, $attr->nodeValue);
    }

    /**
     * @covers WebinoDraw\Draw\Helper\Absolutize::drawNodes
     * @covers WebinoDraw\Draw\Helper\Absolutize::removeDotSegments
     */
    public function testRemoveDotSegmentsSomeShit()
    {
        $basePath      = '';
        $attrValue     = './../root/test-absolute/test/../test2/./test3/../.././.././test-relative';
        $expected      = '/root/test-relative';
        $attr          = new DOMAttr('test-attr', $attrValue);
        $nodesIterator = new ArrayObject([$attr]);

        $this->nodes->expects($this->once())
            ->method('getIterator')
            ->will($this->returnValue($nodesIterator));

        $this->basePath
            ->expects($this->once())
            ->method('__invoke')
            ->will($this->returnValue($basePath));

        $this->object->drawNodes($this->nodes, []);
        $this->assertEquals($expected, $attr->nodeValue);
    }
}


text:
#ifndef OPENSSL_HEADER_DES_H
#define OPENSSL_HEADER_DES_H

#include <openssl/base.h>

#if defined(__cplusplus)
extern "C" {
#endif

/* DES. */

typedef struct DES_cblock_st {
  uint8_t bytes[8];
} DES_cblock;

typedef struct DES_ks {
  uint32_t subkeys[16][2];
} DES_key_schedule;

#define DES_KEY_SZ (sizeof(DES_cblock))
#define DES_SCHEDULE_SZ (sizeof(DES_key_schedule))

#define DES_ENCRYPT 1
#define DES_DECRYPT 0

#define DES_CBC_MODE 0
#define DES_PCBC_MODE 1

/* DES_set_key performs a key schedule and initialises |schedule| with |key|. */
OPENSSL_EXPORT void DES_set_key(const DES_cblock *key,
                                DES_key_schedule *schedule);

/* DES_set_odd_parity sets the parity bits (the least-significant bits in each
 * byte) of |key| given the other bits in each byte. */
OPENSSL_EXPORT void DES_set_odd_parity(DES_cblock *key);

/* DES_ecb_encrypt encrypts (or decrypts, if |is_encrypt| is |DES_DECRYPT|) a
 * single DES block (8 bytes) from in to out, using the key configured in
 * |schedule|. */
OPENSSL_EXPORT void DES_ecb_encrypt(const DES_cblock *in, DES_cblock *out,
                                    const DES_key_schedule *schedule,
                                    int is_encrypt);

/* DES_ncbc_encrypt encrypts (or decrypts, if |enc| is |DES_DECRYPT|) |len|
 * bytes from |in| to |out| with DES in CBC mode. */
OPENSSL_EXPORT void DES_ncbc_encrypt(const uint8_t *in, uint8_t *out,
                                     size_t len,
                                     const DES_key_schedule *schedule,
                                     DES_cblock *ivec, int enc);

/* DES_ecb3_encrypt encrypts (or decrypts, if |enc| is |DES_DECRYPT|) a single
 * block (8 bytes) of data from |input| to |output| using 3DES. */
OPENSSL_EXPORT void DES_ecb3_encrypt(const DES_cblock *input,
                                     DES_cblock *output,
                                     const DES_key_schedule *ks1,
                                     const DES_key_schedule *ks2,
                                     const DES_key_schedule *ks3,
                                     int enc);

/* DES_ede3_cbc_encrypt encrypts (or decrypts, if |enc| is |DES_DECRYPT|) |len|
 * bytes from |in| to |out| with 3DES in CBC mode. 3DES uses three keys, thus
 * the function takes three different |DES_key_schedule|s. */
OPENSSL_EXPORT void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out,
                                         size_t len,
                                         const DES_key_schedule *ks1,
                                         const DES_key_schedule *ks2,
                                         const DES_key_schedule *ks3,
                                         DES_cblock *ivec, int enc);

/* DES_ede2_cbc_encrypt encrypts (or decrypts, if |enc| is |DES_DECRYPT|) |len|
 * bytes from |in| to |out| with 3DES in CBC mode. With this keying option, the
 * first and third 3DES keys are identical. Thus, this function takes only two
 * different |DES_key_schedule|s. */
OPENSSL_EXPORT void DES_ede2_cbc_encrypt(const uint8_t *in, uint8_t *out,
                                         size_t len,
                                         const DES_key_schedule *ks1,
                                         const DES_key_schedule *ks2,
                                         DES_cblock *ivec, int enc);

/* Deprecated functions. */

/* DES_set_key_unchecked calls |DES_set_key|. */
OPENSSL_EXPORT void DES_set_key_unchecked(const DES_cblock *key,
                                          DES_key_schedule *schedule);

OPENSSL_EXPORT void DES_ede3_cfb64_encrypt(const uint8_t *in, uint8_t *out,
                                           long length, DES_key_schedule *ks1,
                                           DES_key_schedule *ks2,
                                           DES_key_schedule *ks3,
                                           DES_cblock *ivec, int *num, int enc);

OPENSSL_EXPORT void DES_ede3_cfb_encrypt(const uint8_t *in, uint8_t *out,
                                         int numbits, long length,
                                         DES_key_schedule *ks1,
                                         DES_key_schedule *ks2,
                                         DES_key_schedule *ks3,
                                         DES_cblock *ivec, int enc);

/* Private functions.
 *
 * These functions are only exported for use in |decrepit|. */

OPENSSL_EXPORT void DES_decrypt3(uint32_t *data, const DES_key_schedule *ks1,
                                 const DES_key_schedule *ks2,
                                 const DES_key_schedule *ks3);

OPENSSL_EXPORT void DES_encrypt3(uint32_t *data, const DES_key_schedule *ks1,
                                 const DES_key_schedule *ks2,
                                 const DES_key_schedule *ks3);

#if defined(__cplusplus)
}  /* extern C */
#endif

#endif  /* OPENSSL_HEADER_DES_H */


text:
Following after the [`Github "Scripts to Rule Them All" pattern`](https://github.com/github/scripts-to-rule-them-all), scripts have been wired up.

Why? Good question! - Helps solve the problem of "how do you set things up? How do you do X?" by externalizing it to a scripted source of truth. So, that's nice. (Plus, hey - it's versioned!)

| Script | Description |
| - | - |
| [`_helpers`](./_helpers) | Shared tid bits for consistency throughout the following scripts to handle logging, version checking, etc. |
| [`build`](./build) | Builds the thing, so it can be shipped and run! |
| [`cibuild`](./cibuild) | Composed by the above, this is meant to run through all the necessary checks and balances. |
| [`server`](./server) | Spins up the project for use/testing. |


text:
package org.lucidfox.jpromises.core;

import org.lucidfox.jpromises.Promise;

/**
 * Convenience callback type that works like {@link ResolveCallback}, but returns no value.
 *
 * @param <V> the value type of the promise the callback is being bound to via
 * {@link Promise#thenAccept(VoidResolveCallback,VoidRejectCallback)}
 */
public interface VoidResolveCallback<V> {

	/**
	 * Called when the promise (thenable) is resolved.
	 *
	 * @param value the value with which the promise is resolved
	 * @throws Exception Signals that an error occurred when handling the result of the promise execution.
	 */
	void onResolve(V value) throws Exception;
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Wox.Helper;
using Wox.Plugin;
using Wox.Plugin.System;

namespace Wox.PluginLoader
{
    public class CSharpPluginLoader : BasePluginLoader
    {
        public override List<PluginPair> LoadPlugin()
        {
            List<PluginPair> plugins = new List<PluginPair>();

            List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.CSharp.ToUpper()).ToList();
            foreach (PluginMetadata metadata in metadatas)
            {
                try
                {
                    Assembly asm = Assembly.Load(AssemblyName.GetAssemblyName(metadata.ExecuteFilePath));
                    List<Type> types = asm.GetTypes().Where(o => o.IsClass && !o.IsAbstract && (o.BaseType == typeof(BaseSystemPlugin) || o.GetInterfaces().Contains(typeof(IPlugin)))).ToList();
                    if (types.Count == 0)
                    {
                        Log.Error(string.Format("Cound't load plugin {0}: didn't find the class who implement IPlugin",
                            metadata.Name));
                        continue;
                    }

                    foreach (Type type in types)
                    {
                        PluginPair pair = new PluginPair()
                        {
                            Plugin = Activator.CreateInstance(type) as IPlugin,
                            Metadata = metadata
                        };
                        plugins.Add(pair);
                    }
                }
                catch (Exception e)
                {
                    Log.Error(string.Format("Cound't load plugin {0}: {1}", metadata.Name, e.Message));
#if (DEBUG)
                    {
                        throw;
                    }
#endif
                }

            }

            return plugins;
        }
    }
}


text:
<#
    Suppress this PSSA message because we need to allow credentials to be
    set when running the tests.
#>
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')]
param ()

#region HEADER
$script:dscModuleName = 'ActiveDirectoryCSDsc'
$script:dscResourceName = 'DSC_AdcsEnrollmentPolicyWebService'

try
{
    Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop'
}
catch [System.IO.FileNotFoundException]
{
    throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.'
}

$script:testEnvironment = Initialize-TestEnvironment `
    -DSCModuleName $script:dscModuleName `
    -DSCResourceName $script:dscResourceName `
    -ResourceType 'Mof' `
    -TestType 'Integration'

Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1')

try
{
    <#
        IMPORTANT: To run these tests requires a domain admin account to be
        available on the machine running the tests that can be used to install the
        ADCS component being tested. Please change the following values to the
        credentials that are set up for this purpose.

        These tests can not be run on AppVeyor because it requires a domain joined
        machine.
    #>
    $script:adminUsername = "$($env:USERDNSDOMAIN)\Administrator"
    $script:adminPassword = ConvertTo-SecureString -String 'NotPass12!' -AsPlainText -Force

    # Ensure that the tests can be performed on this computer
    $skipIntegrationTests = $false

    if (-not (Test-WindowsFeature -Name 'ADCS-Enroll-Web-Pol'))
    {
        Write-Warning -Message 'Skipping integration tests for AdcsEnrollmentPolicyWebService because the feature ADCS-Enroll-Web-Pol is not installed.'
        $skipIntegrationTests = $true
    }

    if ([System.String]::IsNullOrEmpty($ENV:USERDNSDOMAIN))
    {
        Write-Warning -Message 'Skipping integration tests for AdcsEnrollmentPolicyWebService because it must be run on a domain joined server.'
        $skipIntegrationTests = $true
    }

    # Integration tests can't be performed on this computer
    if ($skipIntegrationTests)
    {
        return
    }

    # Get the Administrator credential
    $script:adminCredential = New-Object `
        -TypeName System.Management.Automation.PSCredential `
        -ArgumentList ($script:adminUsername, $script:AdminPassword)

    # Create an SSL certificate to be used for the Web Service
    $certificate = New-SelfSignedCertificate `
        -DnsName $ENV:ComputerName `
        -CertStoreLocation Cert:\LocalMachine\My

    Describe "$($script:dscResourceName) integration test" {
        $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).Config.ps1"
        . $configFile

        # These are the test cases to run integration tests for
        $testAdcsEnrollmentPolicyWebServiceTestCases = @(
            @{
                AuthenticationType = 'Certificate'
                KeyBasedRenewal    = $false
            },
            @{
                AuthenticationType = 'Certificate'
                KeyBasedRenewal    = $true
            },
            @{
                AuthenticationType = 'Kerberos'
                KeyBasedRenewal    = $false
            },
            @{
                AuthenticationType = 'UserName'
                KeyBasedRenewal    = $false
            },
            @{
                AuthenticationType = 'UserName'
                KeyBasedRenewal    = $true
            }
        )

        foreach ($testAdcsEnrollmentPolicyWebServiceTestCase in $testAdcsEnrollmentPolicyWebServiceTestCases)
        {
            $authenticationType = $testAdcsEnrollmentPolicyWebServiceTestCase.AuthenticationType
            $keyBasedRenewal = $testAdcsEnrollmentPolicyWebServiceTestCase.KeyBasedRenewal

            Context "Install ADCS Enrollment Policy Web Service for AuthenticationType '$authenticationType' and KeyBasedRenewal '$keyBasedRenewal'" {
                It 'Should compile and apply the MOF without throwing' {
                    {
                        $ConfigData = @{
                            AllNodes = @(
                                @{
                                    NodeName                    = 'localhost'
                                    AuthenticationType          = $authenticationType
                                    SslCertThumbprint           = $certificate.Thumbprint
                                    Credential                  = $script:adminCredential
                                    KeyBasedRenewal             = $keyBasedRenewal
                                    Ensure                      = 'Present'
                                    PsDscAllowPlainTextPassword = $true
                                }
                            )
                        }

                        & "$($script:dscResourceName)_Config" `
                            -OutputPath $TestDrive `
                            -ConfigurationData $ConfigData

                        Start-DscConfiguration `
                            -Path $TestDrive `
                            -ComputerName localhost `
                            -Wait `
                            -Verbose `
                            -Force `
                            -ErrorAction Stop
                    } | Should -Not -Throw
                }

                It 'Should be able to call Get-DscConfiguration without throwing' {
                    { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw
                }

                It 'Should have set the resource and all the parameters should match' {
                    $current = Get-DscConfiguration | Where-Object {
                        $_.ConfigurationName -eq "$($script:dscResourceName)_Config"
                    }
                    $current.Ensure | Should -Be 'Present'
                }
            }

            Context "Uninstall ADCS Enrollment Policy Web Service for AuthenticationType '$authenticationType' and KeyBasedRenewal '$keyBasedRenewal'" {
                It 'Should compile and apply the MOF without throwing' {
                    {
                        $ConfigData = @{
                            AllNodes = @(
                                @{
                                    NodeName                    = 'localhost'
                                    AuthenticationType          = $authenticationType
                                    SslCertThumbprint           = $certificate.Thumbprint
                                    Credential                  = $script:adminCredential
                                    KeyBasedRenewal             = $keyBasedRenewal
                                    Ensure                      = 'Absent'
                                    PsDscAllowPlainTextPassword = $true
                                }
                            )
                        }

                        & "$($script:dscResourceName)_Config" `
                            -OutputPath $TestDrive `
                            -ConfigurationData $ConfigData `
                            -ErrorAction Stop

                        Start-DscConfiguration `
                            -Path $TestDrive `
                            -ComputerName localhost `
                            -Wait `
                            -Verbose `
                            -Force `
                            -ErrorAction Stop
                    } | Should -Not -Throw
                }

                It 'Should be able to call Get-DscConfiguration without throwing' {
                    { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw
                }

                It 'Should have set the resource and all the parameters should match' {
                    $current = Get-DscConfiguration | Where-Object {
                        $_.ConfigurationName -eq "$($script:dscResourceName)_Config"
                    }
                    $current.Ensure | Should -Be 'Absent'
                }
            }
        }
    }
}
finally
{
    # Remove the SSL certificate created for the Web Service
    if ($certificate)
    {
        $null = Remove-Item `
            -Path $certificate.PSPath `
            -Force
    }

    Restore-TestEnvironment -TestEnvironment $script:testEnvironment
}


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * @see BxDolView
 */
class BxDolViewQuery extends BxDolObjectQuery
{
    protected $_iPeriod;

    public function __construct(&$oModule)
    {
        parent::__construct($oModule);

        $this->_sTableTrackFieldAuthor = 'viewer_id';

        $aSystem = $this->_oModule->getSystemInfo();
        $this->_iPeriod = (int)$aSystem['period'];
    }

    public function isPerformed($iObjectId, $iAuthorId)
    {
        $sQuery = $this->prepare("SELECT `date` FROM `{$this->_sTableTrack}` WHERE `object_id` = ? AND `viewer_id` = ? LIMIT 1", $iObjectId, $iAuthorId);
        return (int)$this->getOne($sQuery) > 0;
    }

	public function getPerformedBy($iObjectId)
    {
        $sQuery = $this->prepare("SELECT `viewer_id` AS `id`, COUNT(`viewer_id`) AS `count` FROM `{$this->_sTableTrack}` WHERE `object_id`=? GROUP BY `viewer_id` ORDER BY `date` DESC", $iObjectId);
        return $this->getAll($sQuery);
    }

	public function getView($iObjectId)
    {
        return array('count' => $this->getObjectCount($iObjectId));
    }

    public function doView($iObjectId, $iAuthorId, $sAuthorIp)
    {
        $iAuthorNip = ip2long($sAuthorIp);

        $aBindings = array(
        	'object_id' => $iObjectId
        );
        if($iAuthorId) {
        	$aBindings['viewer_id'] = $iAuthorId;

            $sWhere = " AND `viewer_id` = :viewer_id ";
        }
        else {
        	$aBindings['viewer_nip'] = $iAuthorNip;

            $sWhere = " AND `viewer_id` = '0' AND `viewer_nip` = :viewer_nip ";
        }

        $iDate = (int)$this->getOne("SELECT `date` FROM `{$this->_sTableTrack}` WHERE `object_id` = :object_id " . $sWhere, $aBindings);
        $iDateNow = time();

        if(!$iDate || ($iDateNow - $iDate) > $this->_iPeriod) {
            $sQuery = $this->prepare("INSERT IGNORE INTO `{$this->_sTableTrack}` SET `object_id` = ?, `viewer_id` = ?, `viewer_nip` = ?, `date` = ?", $iObjectId, $iAuthorId, $iAuthorNip, $iDateNow);
            return (int)$this->query($sQuery) > 0;
        }
    }

    public function updateTriggerTable($iObjectId)
    {
        $sQuery = $this->prepare("UPDATE `{$this->_sTriggerTable}` SET `{$this->_sTriggerFieldCount}` = `{$this->_sTriggerFieldCount}` + 1 WHERE `{$this->_sTriggerFieldId}` = ?", $iObjectId);
        return (int)$this->query($sQuery) > 0;
    }
}

/** @} */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using OSky.Core.Data.Entity;
using OSky.Core.Security;

namespace OSky.Consoles.EntityConfigurations
{
    public class FunctionConfiguration : EntityConfigurationBase<Function, Guid>
    {
    }
}


text:
package bfs.c.simple;

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * Used to perform Breadth-First-Search (BFS) using adjacency matrices.
 * For a faster implementation, see @see ../fast/BFS.java (using adjacency Lists)
 */
public class BFS {
    /**
     * Implementation of Breadth-First-Search using adjacency matrix.
     * This returns nothing (yet), it is meant to be a template for whatever you want to do with it,
     * e.g. finding the shortest path in a unweighted graph.
     * This has a runtime of O(|V|^2) (|V| = number of Nodes), for a faster implementation see @see ../fast/BFS.java (using adjacency Lists)
     *
     * @param graph an adjacency-matrix-representation of the graph where (x,y) is true if the the there is an edge between nodes x and y.
     * @param start the node to start from.
     * @return an array containing the shortest distances from the given start node to each other node
     */
    public static int[] bfs(boolean[][] graph, int start) {
        //A Queue to manage the nodes that have yet to be visited
        Queue<Integer> queue = new PriorityQueue<>();
        //Adding the node to start from
        queue.add(start);
        //A boolean array indicating whether we have already visited a node
        boolean[] visited = new boolean[graph.length];
        //(The start node is already visited)
        visited[start] = true;
        // Keeping the distances (might not be necessary depending on your use case)
        int[] distances = new int[graph.length]; // No need to set initial values since every node is visted exactly once
        //While there are nodes left to visit...
        while (!queue.isEmpty()) {
            System.out.println("Visited nodes: " + Arrays.toString(visited));
            System.out.println("Distances: " + Arrays.toString(distances));
            int node = queue.remove();
            System.out.println("Removing node " + node + " from the queue...");
            //...for all neighboring nodes that haven't been visited yet....
            for (int i = 1; i < graph[node].length; i++) {
                if (graph[node][i] && !visited[i]) {
                    // Do whatever you want to do with the node here.
                    // Visit it, set the distance and add it to the queue
                    visited[i] = true;
                    distances[i] = distances[node] + 1;
                    queue.add(i);
                    System.out.println("Visiting node " + i + ", setting its distance to " + distances[i] + " and adding it to the queue");

                }
            }
        }
        System.out.println("No more nodes in the queue. Distances: " + Arrays.toString(distances));
        return distances;
    }
}


text:
// .NAME vtkOSPRayRendererNode - links vtkRenderers to OSPRay
// .SECTION Description
// Translates vtkRenderer state into OSPRay rendering calls

#ifndef vtkOSPRayRendererNode_h
#define vtkOSPRayRendererNode_h

#include "vtkRenderingOSPRayModule.h" // For export macro
#include "vtkRendererNode.h"

#include <vector> // for ivars

class vtkRenderer;
class vtkInformationIntegerKey;
// ospray forward decs so that someone does not need to include ospray.h
namespace osp {
struct Model;
struct Renderer;
struct Light;
}
typedef osp::Model *OSPModel;
typedef osp::Renderer *OSPRenderer;
typedef osp::Light *OSPLight;

class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayRendererNode :
  public vtkRendererNode
{
public:
  static vtkOSPRayRendererNode* New();
  vtkTypeMacro(vtkOSPRayRendererNode, vtkRendererNode);
  void PrintSelf(ostream& os, vtkIndent indent);

  //Description:
  //Builds myself.
  virtual void Build(bool prepass);

  //Description:
  //Traverse graph in ospray's prefered order and render
  virtual void Render(bool prepass);

  //Description:
  //Put my results into the correct place in the provided pixel buffer.
  virtual void WriteLayer(unsigned char *buffer, float *zbuffer,
                          int buffx, int buffy, int layer);

  //state beyond rendering core...

  //Description:
  //When present on renderer, controls the number of primary rays
  //shot per pixel
  //default is 1
  static vtkInformationIntegerKey* SAMPLES_PER_PIXEL();

  //Description:
  //Convenience method to set/get SAMPLES_PER_PIXEL on a vtkRenderer.
  static void SetSamplesPerPixel(int, vtkRenderer *renderer);
  static int GetSamplesPerPixel(vtkRenderer *renderer);

  //Description:
  //When present on renderer, controls the number of ospray render calls
  //for each refresh.
  //default is 1
  static vtkInformationIntegerKey* MAX_FRAMES();
  static void SetMaxFrames(int, vtkRenderer *renderer);
  static int GetMaxFrames(vtkRenderer *renderer);

  //Description:
  //When present on renderer, controls the number of ambient occlusion
  //samples shot per hit.
  //default is 4
  static vtkInformationIntegerKey* AMBIENT_SAMPLES();
  //Description:
  //Convenience method to set/get SAMPLES_PER_PIXEL on a vtkRenderer.
  static void SetAmbientSamples(int, vtkRenderer *renderer);
  static int GetAmbientSamples(vtkRenderer *renderer);

  // Description:
  // Methods for other nodes to access
  OSPModel GetOModel() { return this->OModel; }
  OSPRenderer GetORenderer() { return this->ORenderer; }
  void AddLight(OSPLight light) {
    this->Lights.push_back(light); }

  // Description:
  // Get the last rendered ColorBuffer
  virtual unsigned char *GetBuffer() {
    return this->Buffer; }

  // Description:
  // Get the last rendered ZBuffer
  virtual float *GetZBuffer() {
    return this->ZBuffer; }

  // if you want to traverse your children in a specific order
  // or way override this method
  virtual void Traverse(int operation);

protected:
  vtkOSPRayRendererNode();
  ~vtkOSPRayRendererNode();

  //internal structures
  unsigned char *Buffer;
  float *ZBuffer;

  OSPModel OModel;
  OSPRenderer ORenderer;
  std::vector<OSPLight> Lights;

  int NumActors;
private:
  vtkOSPRayRendererNode(const vtkOSPRayRendererNode&) VTK_DELETE_FUNCTION;
  void operator=(const vtkOSPRayRendererNode&) VTK_DELETE_FUNCTION;
};

#endif


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

<!--

This file is part of the Lug package.

(c) Eric GELOEN <geloen.eric@gmail.com>

For the full copyright and license information, please read the LICENSE
file that was distributed with this source code.

-->

<container xmlns="http://symfony.com/schema/dic/services">
    <services>
        <service
            id="lug.locale.negotiator"
            class="Lug\Component\Locale\Negotiator\LocaleNegotiator"
        />
    </services>
</container>


text:
module GitHub
  module Fetchers
    module User
      def self.get(login)
        attributes = {}
        model = Storage::User.find_by_login(login)
        should_refresh = model ? Config::Options[:strategy].should_refresh?(model) : true
        if should_refresh
          Browser.start do |http|
            request = Net::HTTP::Get.new "/users/#{login}"
            attributes = Fetchers.parse(http.request(request).body)
            model = Storage::User.find_or_create_by_login(login)
            model.update_attributes(Resources::User.valid_attributes(attributes))
          end
        end
        Resources::User.new.tap do |user|
          user.attributes = model.attributes.symbolize_keys!
        end
      end

      def self.association_repositories(user)
        attributes = {}
        models = (um = Storage::User.find_by_name(user.name)) ? um.repositories : []
        should_refresh = models.empty? ? true : Config::Options[:strategy].should_refresh?(models)
        if should_refresh
          models = [] # ensure empty when refreshing
          Browser.start do |http|
            request = Net::HTTP::Get.new "/users/#{user.login}/repos"
            attributes = Fetchers.parse(http.request(request).body)
          end

          ActiveRecord::Base.transaction do
            attributes.each do |repo|
              permalink = repo[:owner][:login] + '/' + repo[:name]
              models << Storage::Repository.find_or_create_by_permalink(permalink)
              models.last.update_attributes(Resources::Repository.valid_attributes(repo))
            end
          end
        end
        collection = []
        models.each do |model|
          collection << Resources::Repository.new.tap do |repo|
            repo.attributes = Resources::Repository.valid_attributes(model.attributes.symbolize_keys!)
          end
        end
        return collection
      end
    end
  end
end


text:
<?php

namespace Drupal\demo\Session;

use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;

class NativeStorage extends NativeSessionStorage
{
    //already started by drupal
    protected $started = true;

}


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

	var Marionette = require('marionette');
	var Element = require('src/model/element.base');
	var InputAttributes = require('./input_attributes');

	/* parent input view, meant to be subclassed for specific input types */

	var InputView = Marionette.ItemView.extend({
		tagName: 'input',
		template: _.template(''),

		constructor: function() {
			Marionette.ItemView.apply(this, arguments);

			// validate model
			if (! (this.model instanceof Element)) throw new Error('InputView requires an Element model.');

			// listen for external changes to the model
			this.listenTo(this.model, 'change:value', this.onModelChangeValue);

			// these steps allow the view to consume an existing dom element
			this.listenTo(this, 'render', this.setAttributes);
			var className = this.model.get('className');
			if (className) this.$el.addClass(className);
		},

		triggers: {
			'change': 'input:change',
		},

		onInputChange: function() {
			var value = this.getInputValue();
			this.model.set('value', value, { from: this });
		},

		getInputValue: function() {
			return this.$el.val();
		},
		setInputValue: function(value) {
			this.$el.val(value);
		},

		onModelChangeValue: function(model, value, options) {
			if (options.from !== this) {
				this.setInputValue(value);
			}
		}
	});

	// apply methods from InputAttributes mixin
	_.extend(InputView.prototype, InputAttributes);

	return InputView;

});


text:
<!doctype html>

    <title>Code coverage report for spec/generic/collection.spec.js</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../prettify.css">
    <link rel="stylesheet" href="../../base.css">

Code coverage report for spec/generic/collection.spec.js

        Statements: 100% (14 / 14)
        Branches: 50% (1 / 2)
        Functions: 100% (4 / 4)
        Lines: 100% (13 / 13)
        Ignored: none

All files » spec/generic/ » collection.spec.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22	1

1
1
1
1

1
1
1

1

1
1
1

1

Eif (typeof(window) === 'undefined') var loki = require('../../src/lokijs.js');

describe('collection', function () {
  it('works', function () {
    function SubclassedCollection() {
      loki.Collection.apply(this, Array.prototype.slice.call(arguments));
    }
    SubclassedCollection.prototype = new loki.Collection;
    SubclassedCollection.prototype.extendedMethod = function () {
      return this.name.toUpperCase();
    }
    var coll = new SubclassedCollection('users', {});

    expect(coll != null).toBe(true);
    expect('users'.toUpperCase()).toEqual(coll.extendedMethod());
    coll.insert({
      name: 'joe'
    });
    expect(coll.data.length).toEqual(1);
  });
});

Generated by istanbul at Thu Jan 07 2016 06:50:52 GMT+0000 (GMT)


text:
<?php

namespace Doctrine\ORM\Id;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMException;

/**
 * Special generator for application-assigned identifiers (doesnt really generate anything).
 *
 * @since   2.0
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class AssignedGenerator extends AbstractIdGenerator
{
    /**
     * Returns the identifier assigned to the given entity.
     *
     * @param object $entity
     * @return mixed
     * @override
     */
    public function generate(EntityManager $em, $entity)
    {
        $class = $em->getClassMetadata(get_class($entity));
        $identifier = array();
        if ($class->isIdentifierComposite) {
            $idFields = $class->getIdentifierFieldNames();
            foreach ($idFields as $idField) {
                $value = $class->getReflectionProperty($idField)->getValue($entity);
                if (isset($value)) {
                    if (is_object($value)) {
                        // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced.
                        $identifier[$idField] = current($em->getUnitOfWork()->getEntityIdentifier($value));
                    } else {
                        $identifier[$idField] = $value;
                    }
                } else {
                    throw ORMException::entityMissingAssignedId($entity);
                }
            }
        } else {
            $idField = $class->identifier[0];
            $value = $class->reflFields[$idField]->getValue($entity);
            if (isset($value)) {
                if (is_object($value)) {
                    // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced.
                    $identifier[$idField] = current($em->getUnitOfWork()->getEntityIdentifier($value));
                } else {
                    $identifier[$idField] = $value;
                }
            } else {
                throw ORMException::entityMissingAssignedId($entity);
            }
        }

        return $identifier;
    }
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Simple.Owin
{
    internal static class OwinFactory
    {
        private static Func<IDictionary<string, object>> _createEnvironment =
            () => new ConcurrentDictionary<string, object>(StringComparer.Ordinal);

        private static Func<IDictionary<string, string[]>> _createHeaders =
            () => new ConcurrentDictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);

        private static Func<IDictionary<string, object>, IDictionary<string, object>> _createScopedEnvironment =
            parent => new ConcurrentDictionary<string, object>(parent, StringComparer.Ordinal);

        public static Func<IDictionary<string, object>> CreateEnvironment {
            get { return _createEnvironment; }
            set {
                if (value == null) {
                    throw new ArgumentNullException("value");
                }
                _createEnvironment = value;
            }
        }

        public static Func<IDictionary<string, string[]>> CreateHeaders {
            get { return _createHeaders; }
            set {
                if (value == null) {
                    throw new ArgumentNullException("value");
                }
                _createHeaders = value;
            }
        }

        public static Func<IDictionary<string, object>, IDictionary<string, object>> CreateScopedEnvironment {
            get { return _createScopedEnvironment; }
            set {
                if (value == null) {
                    throw new ArgumentNullException("value");
                }
                _createScopedEnvironment = value;
            }
        }
    }
}


text:
package org.apache.tools.ant.taskdefs.email;

import java.io.File;
import java.util.Vector;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.util.DateUtils;

/**
 * Base class for the various emailing implementations.
 *
 * @since Ant 1.5
 */
public abstract class Mailer {
    // CheckStyle:VisibilityModifier OFF - bc
    protected String host = null;
    protected int port = -1;
    protected String user = null;
    protected String password = null;
    // CheckStyle:MemberNameCheck OFF - bc
    protected boolean SSL = false;
    // CheckStyle:MemberNameCheck ON
    protected Message message;
    protected EmailAddress from;
    protected Vector<EmailAddress> replyToList = null;
    protected Vector<EmailAddress> toList = null;
    protected Vector<EmailAddress> ccList = null;
    protected Vector<EmailAddress> bccList = null;
    protected Vector<File> files = null;
    protected String subject = null;
    protected Task task;
    protected boolean includeFileNames = false;
    protected Vector headers = null;
    // CheckStyle:VisibilityModifier ON
    private boolean ignoreInvalidRecipients = false;
    private boolean starttls = false;
    private boolean portExplicitlySpecified = false;

    /**
     * Set the mail server.
     *
     * @param host the mail server name.
     */
    public void setHost(String host) {
        this.host = host;
    }

    /**
     * Set the smtp port.
     *
     * @param port the SMTP port.
     */
    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Whether the port has been explicitly specified by the user.
     * @since Ant 1.8.2
     */
    public void setPortExplicitlySpecified(boolean explicit) {
        portExplicitlySpecified = explicit;
    }

    /**
     * Whether the port has been explicitly specified by the user.
     * @since Ant 1.8.2
     */
    protected boolean isPortExplicitlySpecified() {
        return portExplicitlySpecified;
    }

    /**
     * Set the user for smtp auth.
     *
     * @param user the username.
     * @since Ant 1.6
     */
    public void setUser(String user) {
        this.user = user;
    }

    /**
     * Set the password for smtp auth.
     *
     * @param password the authentication password.
     * @since Ant 1.6
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Set whether to send the mail through SSL.
     *
     * @param ssl if true use SSL transport.
     * @since Ant 1.6
     */
    public void setSSL(boolean ssl) {
        this.SSL = ssl;
    }

    /**
     * Set whether to allow authentication to switch to a TLS
     * connection via STARTTLS.
     * @param b boolean; if true STARTTLS will be supported.
     * @since Ant 1.8.0
     */
    public void setEnableStartTLS(boolean b) {
        this.starttls = b;
    }

    protected boolean isStartTLSEnabled() {
        return starttls;
    }

    /**
     * Set the message.
     *
     * @param m the message content.
     */
    public void setMessage(Message m) {
        this.message = m;
    }

    /**
     * Set the address to send from.
     *
     * @param from the sender.
     */
    public void setFrom(EmailAddress from) {
        this.from = from;
    }

    /**
     * Set the replyto addresses.
     *
     * @param list a vector of reployTo addresses.
     * @since Ant 1.6
     */
    public void setReplyToList(Vector<EmailAddress> list) {
        this.replyToList = list;
    }

    /**
     * Set the to addresses.
     *
     * @param list a vector of recipient addresses.
     */
    public void setToList(Vector<EmailAddress> list) {
        this.toList = list;
    }

    /**
     * Set the cc addresses.
     *
     * @param list a vector of cc addresses.
     */
    public void setCcList(Vector<EmailAddress> list) {
        this.ccList = list;
    }

    /**
     * Set the bcc addresses.
     *
     * @param list a vector of the bcc addresses.
     */
    public void setBccList(Vector<EmailAddress> list) {
        this.bccList = list;
    }

    /**
     * Set the files to attach.
     *
     * @param files list of files to attach to the email.
     */
    public void setFiles(Vector<File> files) {
        this.files = files;
    }

    /**
     * Set the subject.
     *
     * @param subject the subject line.
     */
    public void setSubject(String subject) {
        this.subject = subject;
    }

    /**
     * Set the owning task.
     *
     * @param task the owning task instance.
     */
    public void setTask(Task task) {
        this.task = task;
    }

    /**
     * Indicate whether filenames should be listed in the body.
     *
     * @param b if true list attached file names in the body content.
     */
    public void setIncludeFileNames(boolean b) {
        this.includeFileNames = b;
    }

    /**
     * Set the generic headers to add to the email.
     * @param v a Vector presumed to contain Header objects.
     * @since Ant 1.7
     */
    public void setHeaders(Vector v) {
        this.headers = v;
    }

    /**
     * Send the email.
     *
     * @throws BuildException if the email can't be sent.
     */
    public abstract void send()
         throws BuildException;

    /**
     * Whether invalid recipients should be ignored (but a warning
     * will be logged) instead of making the task fail.
     *
     *
Even with this property set to true the task will still fail
     * if the mail couldn't be sent to any recipient at all.

     *
     * @since Ant 1.8.0
     */
    public void setIgnoreInvalidRecipients(boolean b) {
        ignoreInvalidRecipients = b;
    }

    /**
     * Whether invalid recipients should be ignored.
     *
     * @since Ant 1.8.0
     */
    protected boolean shouldIgnoreInvalidRecipients() {
        return ignoreInvalidRecipients;
    }

    /**
     * Return the current Date in a format suitable for a SMTP date
     * header.
     *
     * @return the current date in SMTP suitable format.
     *
     * @since Ant 1.5
     */
    protected final String getDate() {
        return DateUtils.getDateForHeader();
    }
}


text:
package org.apereo.cas.ws.idp.services;

import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.services.RegisteredServiceTestUtils;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.ws.idp.WSFederationClaims;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link WSFederationClaimsReleasePolicyTests}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
public class WSFederationClaimsReleasePolicyTests {
    private static final File JSON_FILE = new File(FileUtils.getTempDirectoryPath(), "WSFederationClaimsReleasePolicyTests.json");
    private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules();

    @Test
    public void verifyAttributeReleaseNone() {
        val service = RegisteredServiceTestUtils.getRegisteredService("verifyAttributeRelease");
        val policy = new WSFederationClaimsReleasePolicy(
            CollectionUtils.wrap("uid", "casuser", "cn", "CAS"));
        val principal = CoreAuthenticationTestUtils.getPrincipal("casuser",
            CollectionUtils.wrap("uid", "casuser", "cn", "CAS", "givenName", "CAS User"));
        val results = policy.getAttributes(principal, CoreAuthenticationTestUtils.getService(), service);
        assertTrue(results.isEmpty());
    }

    @Test
    public void verifyAttributeReleaseInlineGroovy() {
        val service = RegisteredServiceTestUtils.getRegisteredService("verifyAttributeRelease");
        val policy = new WSFederationClaimsReleasePolicy(
            CollectionUtils.wrap(WSFederationClaims.EMAIL_ADDRESS_2005.name(), "groovy { return attributes['cn'][0] + '@example.org' }"));
        val principal = CoreAuthenticationTestUtils.getPrincipal("casuser", CollectionUtils.wrap("cn", "casuser"));
        val results = policy.getAttributes(principal, CoreAuthenticationTestUtils.getService(), service);
        assertFalse(results.isEmpty());
        assertTrue(results.containsKey(WSFederationClaims.EMAIL_ADDRESS_2005.getUri()));
        assertEquals(results.get(WSFederationClaims.EMAIL_ADDRESS_2005.getUri()), List.of("casuser@example.org"));
    }

    @Test
    public void verifyAttributeReleaseScriptGroovy() throws Exception {
        val file = new File(FileUtils.getTempDirectoryPath(), "script.groovy");
        val script = IOUtils.toString(new ClassPathResource("wsfed-attr.groovy").getInputStream(), StandardCharsets.UTF_8);
        FileUtils.write(file, script, StandardCharsets.UTF_8);

        val service = RegisteredServiceTestUtils.getRegisteredService("verifyAttributeRelease");
        val policy = new WSFederationClaimsReleasePolicy(
            CollectionUtils.wrap(WSFederationClaims.EMAIL_ADDRESS_2005.name(), "file:" + file.getCanonicalPath()));
        val principal = CoreAuthenticationTestUtils.getPrincipal("casuser", CollectionUtils.wrap("cn", "casuser"));
        val results = policy.getAttributes(principal, CoreAuthenticationTestUtils.getService(), service);
        assertFalse(results.isEmpty());
        assertTrue(results.containsKey(WSFederationClaims.EMAIL_ADDRESS_2005.getUri()));
        assertEquals(results.get(WSFederationClaims.EMAIL_ADDRESS_2005.getUri()), List.of("casuser@example.org"));
    }

    @Test
    public void verifyAttributeRelease() {
        val service = RegisteredServiceTestUtils.getRegisteredService("verifyAttributeRelease");
        val policy = new WSFederationClaimsReleasePolicy(
            CollectionUtils.wrap(WSFederationClaims.COMMON_NAME.name(), "cn", WSFederationClaims.EMAIL_ADDRESS.name(), "email"));
        val principal = CoreAuthenticationTestUtils.getPrincipal("casuser",
            CollectionUtils.wrap("cn", "casuser", "email", "cas@example.org"));
        val results = policy.getAttributes(principal, CoreAuthenticationTestUtils.getService(), service);
        assertSame(2, results.size());
        assertTrue(results.containsKey(WSFederationClaims.COMMON_NAME.getUri()));
        assertTrue(results.containsKey(WSFederationClaims.EMAIL_ADDRESS.getUri()));
    }

    @Test
    public void verifySerializePolicyToJson() throws IOException {
        val policyWritten = new WSFederationClaimsReleasePolicy(
            CollectionUtils.wrap(WSFederationClaims.COMMON_NAME.name(), "cn", WSFederationClaims.EMAIL_ADDRESS.name(), "email"));
        MAPPER.writeValue(JSON_FILE, policyWritten);
        val policyRead = MAPPER.readValue(JSON_FILE, WSFederationClaimsReleasePolicy.class);
        assertEquals(policyWritten, policyRead);
    }
}


text:
package native

func (dbp *nativeProcess) SupportsBPF() bool {
	return false
}


text:
package com.twitter.elephantbird.mapreduce.io;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.google.protobuf.ByteString;
import com.google.protobuf.Message;
import com.twitter.elephantbird.util.Protobufs;

/**
 * A class to write blocks of serialized objects.
 */
public class BinaryBlockWriter<M> {
  protected static final int DEFAULT_NUM_RECORDS_PER_BLOCK = 100;

  private final OutputStream out_;
  private final int numRecordsPerBlock_;
  protected final Class<M> innerClass_;
  private final BinaryConverter<M> binaryConverter_;
  private int numRecordsWritten_ = 0;
  private List<ByteString> protoBlobs_;

  protected BinaryBlockWriter(OutputStream out, Class<M> protoClass, BinaryConverter<M> binaryConverter, int numRecordsPerBlock) {
    out_ = out;
    numRecordsPerBlock_ = numRecordsPerBlock;
    innerClass_ = protoClass;
    binaryConverter_ = binaryConverter;
    protoBlobs_ = new ArrayList<ByteString>(numRecordsPerBlock_);
  }

  public BinaryBlockWriter(OutputStream out, Class<M> protoClass, BinaryConverter<M> binaryConverter) {
    this(out, protoClass, binaryConverter, DEFAULT_NUM_RECORDS_PER_BLOCK);
  }

  public void write(M message) throws IOException {
    if (message instanceof Message) {
      //a small hack to avoid extra copy, since we need a ByteString anyway.
      protoBlobs_.add(((Message) message).toByteString());
    } else {
      protoBlobs_.add(ByteString.copyFrom(binaryConverter_.toBytes(message)));
    }

    numRecordsWritten_++;

    if (protoBlobs_.size() == numRecordsPerBlock_) {
      serialize();
    }
  }

  public void finish() throws IOException {
    if (protoBlobs_.size() > 0) {
      serialize();
    }
  }

  public void close() throws IOException {
    finish();
    out_.close();
  }

  protected void serialize() throws IOException {
    out_.write(Protobufs.KNOWN_GOOD_POSITION_MARKER);
    Message block = SerializedBlock
        .newInstance(innerClass_.getCanonicalName(),protoBlobs_)
        .getMessage();
    protoBlobs_ = new ArrayList<ByteString>(numRecordsPerBlock_);
    writeRawLittleEndian32(block.getSerializedSize());
    block.writeTo(out_);
  }

  private void writeRawLittleEndian32(int size) throws IOException {
     out_.write((size) & 0xFF);
     out_.write((size >> 8) & 0xFF);
     out_.write((size >> 16) & 0xFF);
     out_.write((size >> 24) & 0xFF);
   }
}


text:
package com.beecavegames.common;

import lombok.NoArgsConstructor;
import java.util.List;

import com.beecavegames.Grantable;
import com.beecavegames.PlayerIdentity;
import com.beecavegames.entities.PlayerGrant.GrantSource;
import com.beecavegames.util.DateUtil;

@NoArgsConstructor
public class MysteryBoxKeyGiverPendingReward extends GrantablePendingReward {

	public PlayerIdentity chestOwner;

	public MysteryBoxKeyGiverPendingReward(List<Grantable> rewards, PlayerIdentity owner) {
		super(DateUtil.now());
		this.rewards = rewards;
		this.source = GrantSource.MYSTERY_BOX;
		this.chestOwner = owner;
	}

}


text:
using System;
using System.Web.UI;

namespace Nucleo.Web.Controls
{
	public class CheckImage
	{
		private bool? _associatedValue = null;
		private string _disabledImageUrl = null;
		private string _imageUrl = null;

		#region " Properties "

		/// <summary>
		/// Gets or sets the associated value for the check image.
		/// </summary>
		public bool? AssociatedValue
		{
			get { return _associatedValue; }
		}

		/// <summary>
		/// Gets or sets the image url when the check image is in a disabled state.
		/// </summary>
		[UrlProperty]
		public string DisabledImageUrl
		{
			get { return _disabledImageUrl; }
			set { _disabledImageUrl = value; }
		}

		/// <summary>
		/// Gets or sets the image url when the check image is in normal state.
		/// </summary>
		[UrlProperty]
		public string ImageUrl
		{
			get { return _imageUrl; }
			set { _imageUrl = value; }
		}

		#endregion

		#region " Constructors "

		public CheckImage(bool? associatedValue)
		{
			_associatedValue = associatedValue;
		}

		public CheckImage(string imageUrl, string disabledImageUrl, bool? associatedValue)
			: this(associatedValue)
		{
			_imageUrl = imageUrl;
			_disabledImageUrl = disabledImageUrl;
		}

		#endregion

		#region " Methods "

		public void CopyFrom(CheckImage image)
		{
			_imageUrl = image.ImageUrl;
			_disabledImageUrl = image.DisabledImageUrl;
			_associatedValue = image.AssociatedValue;

		}

		#endregion
	}
}


text:
package optimize

import (
	"math"
)

// localOptimizer is a helper type for running an optimization using a LocalMethod.
type localOptimizer struct{}

// run controls the optimization run for a localMethod. The calling method
// must close the operation channel at the conclusion of the optimization. This
// provides a happens before relationship between the return of status and the
// closure of operation, and thus a call to method.Status (if necessary).
func (l localOptimizer) run(method localMethod, operation chan<- Task, result <-chan Task, tasks []Task) (Status, error) {
	// Local methods start with a fully-specified initial location.
	task := tasks[0]
	task = l.initialLocation(operation, result, task, method)
	if task.Op == PostIteration {
		l.finish(operation, result)
		return NotTerminated, nil
	}
	status, err := l.checkStartingLocation(task)
	if err != nil {
		l.finishMethodDone(operation, result, task)
		return status, err
	}

	// Send a major iteration with the starting location.
	task.Op = MajorIteration
	operation <- task
	task = <-result
	if task.Op == PostIteration {
		l.finish(operation, result)
		return NotTerminated, nil
	}

	op, err := method.initLocal(task.Location)
	if err != nil {
		l.finishMethodDone(operation, result, task)
		return Failure, err
	}
	task.Op = op
	operation <- task
Loop:
	for {
		r := <-result
		switch r.Op {
		case PostIteration:
			break Loop
		default:
			op, err := method.iterateLocal(r.Location)
			if err != nil {
				l.finishMethodDone(operation, result, r)
				return Failure, err
			}
			r.Op = op
			operation <- r
		}
	}
	l.finish(operation, result)
	return NotTerminated, nil
}

// initialOperation returns the Operation needed to fill the initial location
// based on the needs of the method and the values already supplied.
func (localOptimizer) initialOperation(task Task, needser Needser) Operation {
	var newOp Operation
	op := task.Op
	if op&FuncEvaluation == 0 {
		newOp |= FuncEvaluation
	}
	needs := needser.Needs()
	if needs.Gradient && op&GradEvaluation == 0 {
		newOp |= GradEvaluation
	}
	if needs.Hessian && op&HessEvaluation == 0 {
		newOp |= HessEvaluation
	}
	return newOp
}

// initialLocation fills the initial location based on the needs of the method.
// The task passed to initialLocation should be the first task sent in RunGlobal.
func (l localOptimizer) initialLocation(operation chan<- Task, result <-chan Task, task Task, needser Needser) Task {
	task.Op = l.initialOperation(task, needser)
	operation <- task
	return <-result
}

func (localOptimizer) checkStartingLocation(task Task) (Status, error) {
	if math.IsInf(task.F, 1) || math.IsNaN(task.F) {
		return Failure, ErrFunc(task.F)
	}
	for i, v := range task.Gradient {
		if math.IsInf(v, 0) || math.IsNaN(v) {
			return Failure, ErrGrad{Grad: v, Index: i}
		}
	}
	return NotTerminated, nil
}

// finish completes the channel operations to finish an optimization.
func (localOptimizer) finish(operation chan<- Task, result <-chan Task) {
	// Guarantee that result is closed before operation is closed.
	for range result {
	}
}

// finishMethodDone sends a MethodDone signal on operation, reads the result,
// and completes the channel operations to finish an optimization.
func (l localOptimizer) finishMethodDone(operation chan<- Task, result <-chan Task, task Task) {
	task.Op = MethodDone
	operation <- task
	task = <-result
	if task.Op != PostIteration {
		panic("optimize: task should have returned post iteration")
	}
	l.finish(operation, result)
}


text:
/*
 * Testcase: Check that drop/setMaster correctly transfer master state
 *
 * Test approach is only checking auth state (which is part of master state) by
 * trying to authenticate a client against the wrong master.
 */

#define _GNU_SOURCE
#include "igt.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef __linux__
# include <sys/syscall.h>
#else
# include <pthread.h>
#endif

IGT_TEST_DESCRIPTION("Check that drop/setMaster correctly transfer master "
		     "state");

igt_simple_main
{
	int master1, master2, client;
	drm_magic_t magic;

	master1 = drm_open_driver(DRIVER_ANY);
	do_or_die(drmSetMaster(master1));

	/* Get an authentication magic from the first master */
	client = drm_open_driver(DRIVER_ANY);
	do_or_die(drmGetMagic(client, &magic));

	/* Open an fd an make it master */
	master2 = drm_open_driver(DRIVER_ANY);
	do_or_die(drmDropMaster(master1));
	do_or_die(drmSetMaster(master2));

	/* Auth shouldn't work since we're authenticating with a different
	 * master than the one we got the magic from. */
	igt_assert_neq(drmAuthMagic(master2, magic), 0);
	igt_assert_eq(errno, EINVAL);

	close(client);
	close(master2);
	close(master1);
}