text:
(function(root, undefined) {

  var app = root.Spinoza;

  app.module("Views.Documents", function(mod, app, BB, BM, $, _) {

    var OutlineEmpty = BM.ItemView.extend({
      tagName   : 'li',
      className : 'fg-empty',
      template  : function() { return ''; }
    });

    var OutlineItem = BM.ItemView.extend({
      tagName  : 'li',
      template : 'jst:collection_date_item',
      serializeData: function() {
        var json = this.model.toJSON(),
          links = json.links,
          dateLinks = links ? links['has-locus'] : {},
          dateLink = _.values(dateLinks)[0],
          date = dateLink ? dateLink.time_range : '';
        return {
          link  : json.link,
          title : json.title,
          date  : date
        };
      }
    });

    mod.DatesOutline = BM.CollectionView.extend({
      tagName   : 'ul',
      className : 'fg-undecorated',
      itemView  : OutlineItem,
      emptyView : OutlineEmpty
    });

  });

}).call({}, window);


text:
#ifndef NATUS_INTERNAL_H_
#define NATUS_INTERNAL_H_
#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE
#include <natus-engine.h>

#define NATUS_PRIV_CLASS     "natus::Class"
#define NATUS_PRIV_FUNCTION  "natus::Function"
#define NATUS_PRIV_GLOBAL    "natus::Global"

#define callandmkval(n, t, c, f, ...) \
  natusEngValFlags _flags = natusEngValFlagUnlock | natusEngValFlagFree; \
  natusEngVal _val = c->ctx->spec->f(__VA_ARGS__, &_flags); \
  n = mkval(c, _val, _flags, t);

#define callandreturn(t, c, f, ...) \
  callandmkval(natusValue *_value, t, c, f, __VA_ARGS__); \
  return _value

typedef struct evalHook evalHook;

typedef struct natusContext natusContext;
struct natusContext {
  natusEngCtx      ctx;
  natusEngineSpec *spec;
  evalHook        *evalhooks;
};

struct natusValue {
  natusContext    *ctx;
  natusEngVal      val;
  natusEngValFlags flag;
  natusValueType   type;
};

natusValue *
mkval(const natusValue *ctx, natusEngVal val, natusEngValFlags flags, natusValueType type);

void *
private_get(const natusPrivate *self, const char *name);

bool
private_set(natusPrivate *self, const char *name, void *priv, natusFreeFunction free);

#endif /* NATUS_INTERNAL_H_ */

redpajama_set_name: RedPajamaGithub


text:
from django.db import models
#from django.forms.extras.widgets import SelectDateWidget
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.log import getLogger
from TeaScrum.product.models import Product
from TeaScrum.sprint.models import Sprint
#from TeaScrum.backlog.models import Backlog
#from TeaScrum import BACKLOG_STATUS_CHOICES
#from managers import TaskManager

logger = getLogger('TeaScrum')

class Daily(models.Model):
    """ Collection of daily scrum.
        This table can be used to let team members write a diary before daily scrum about the summary
        of what has been done yesterday, and what to do today, and what problem there is and how serious.
    """
    product = models.ForeignKey(Product, verbose_name=_('Product ID'))
    member = models.ForeignKey(User, verbose_name=_('Team member'))
    sprint = models.ForeignKey(Sprint, verbose_name=_('Sprint ID'))
    scrumdate = models.DateTimeField(_('Todays date'), auto_now_add=True, help_text=_('Auto added date'))
    yesterday = models.TextField(_('Done yesterday'), blank=True, help_text=_('What has been done yesterday?'))
    today = models.TextField(_('Will do today'), blank=True, help_text=_('What to do today?'))
    problem = models.TextField(_('Problem'), blank=True, help_text=('Any difficulties?'))
    serious = models.IntegerField(_('Severity'), default=3, help_text=_('How serious the problem is? 1-5'))

    class Meta:
        db_table = 'scrum_daily'
        verbose_name = _('Daily Scrum')
        verbose_name_plural = _('Daily Scrums')
        ordering = ('-scrumdate',)

    def __unicode__(self):
        return 'DailyScrum %s' % (self.scrumdate)

class ScrumEvent(models.Model):
    """ General events as notifications about task assignment etc.
    """
    user = models.ForeignKey(User, verbose_name=_('User ID'), help_text=_('Who posted this event'))
    etype = models.CharField(_('EventType'), max_length=10, default='PICK', help_text=_('Type of event or action'))
    tstamp = models.DateTimeField(_('Timestamp'), auto_now_add=True, help_text=_('Exact time of event'))
    object = models.CharField(_('Object'), max_length=16, blank=True, help_text=_('Object like task_id'))

    class Meta:
        ordering = ('-tstamp',)


text:
import fetch from 'isomorphic-fetch';
import CSV from 'comma-separated-values';
import async from 'async';
const CROS_URL = 'http://crossorigin.me/';
const API_HISTORY_URL = 'http://www.twse.com.tw/ch/trading/exchange/STOCK_DAY/STOCK_DAY_print.php?genpage=genpage/';
const API_CURRENT_URL = 'http://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=';
const FIELDS = ['date', 'trading_volume', 'turnover', 'open', 'high', 'low', 'close', 'price_limit', 'transaction_number'];

export const STOCK_REQUEST = 'STOCK_REQUEST';
export const STOCK_SUCCESS = 'STOCK_SUCCESS';
export const STOCK_FAILURE = 'STOCK_FAILURE';

function getStockRequest(stockNo) {
  return {
    type: STOCK_REQUEST,
    payload: {
      stockNo: stockNo
    }
  };
}

function getStockSuccess(stockNo, stockData) {
  return {
    type: STOCK_SUCCESS,
    payload: {
      stockNo: stockNo,
      stockData: stockData
    }
  };
}

function getStockFailure(stockNo) {
  return {
    type: STOCK_FAILURE,
    payload: {
      stockNo: stockNo
    }
  };
}

export function fetchStock(stockNo) {
  return dispatch => {
    const apiHistoryUrl = API_HISTORY_URL + `Report201510/201510_F3_1_8_${stockNo}.php&type=csv`;
    const apiCurrentUrl = API_CURRENT_URL + `tse_${stockNo}.tw`;

    dispatch(getStockRequest(stockNo));

    return async.parallel({
      current: function(callback) {
        fetch(apiCurrentUrl)
          .then(response => response.json())
          .then(json => callback(null, json));
      },
      history: function(callback) {
        fetch(apiHistoryUrl)
          .then(response => response.text())
          .then(text => callback(null, text));
      }
    }, function(err, results) {

      var text = results.history;
      var current = results.currnet;

      if (text === '') dispatch(getStockFailure(stockNo));

      let lines = text.split('\n');
      // 去除開頭兩行標題與欄位行
      lines.splice(0, 2);

      lines = lines.join('\r\n');

      const datas = new CSV(lines, {
        header: FIELDS
      }).parse();

      const stockData = {
        name: current.nf,
        datas: datas
      };

      dispatch(getStockSuccess(stockNo, stockData));
    });

    return fetch(apiHistoryUrl)
      .then(response => response.text())
      .then(text => {
        if (text === '') dispatch(getStockFailure(stockNo));

        let lines = text.split('\n');
        // 去除開頭兩行標題與欄位行
        lines.splice(0, 2);

        lines = lines.join('\r\n');

        const datas = new CSV(lines, {
          header: FIELDS
        }).parse();

        const stockData = {
          datas: datas
        };

        dispatch(getStockSuccess(stockNo, stockData));
      });
  };
}


text:
using Appium.Net.Integration.Tests.helpers;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium.iOS;

namespace Appium.Net.Integration.Tests.IOS
{
    internal class LockDeviceTest
    {
        private IOSDriver<IWebElement> _driver;

        [SetUp]
        public void TestSetup()
        {
            var capabilities = Caps.GetIosCaps(Apps.Get("iosWebviewApp"));
            var serverUri = Env.ServerIsRemote() ? AppiumServers.RemoteServerUri : AppiumServers.LocalServiceUri;
            _driver = new IOSDriver<IWebElement>(serverUri, capabilities, Env.InitTimeoutSec);
            _driver.Manage().Timeouts().ImplicitWait = Env.ImplicitTimeoutSec;
        }

        [TearDown]
        public void Cleanup()
        {
            if (_driver.IsLocked())
                _driver.Unlock();
            _driver?.Quit();
            if (!Env.ServerIsRemote())
            {
                AppiumServers.StopLocalService();
            }
        }

        [Test]
        public void IsLockedTest()
        {
            Assert.AreEqual(_driver.IsLocked(), false);
        }

        [Test]
        public void LockTest()
        {
            Assert.AreEqual(_driver.IsLocked(), false);
            _driver.Lock();
            Assert.AreEqual(_driver.IsLocked(), true);
        }

        [Test]
        public void LockTestWithSeconds()
        {
            Assert.AreEqual(_driver.IsLocked(), false);
            _driver.Lock(5);
            Assert.AreEqual(_driver.IsLocked(), false);
        }

        [Test]
        public void UnlockTest()
        {
            Assert.AreEqual(_driver.IsLocked(), false);
            _driver.Lock();
            Assert.AreEqual(_driver.IsLocked(), true);
            _driver.Unlock();
            Assert.AreEqual(_driver.IsLocked(), false);
        }
    }
}


text:
 /* jssor slider bullet navigator skin 21 css */

.jssorb21 {
position: absolute;
}
.jssorb21 div, .jssorb21 div:hover, .jssorb21 .av {
position: absolute;
/* size of bullet elment */
width: 19px;
height: 19px;
text-align: center;
line-height: 19px;
color: white;
font-size: 12px;
background: url(../../img/homepageslider/b21.png) no-repeat;
overflow: hidden;
cursor: pointer;
}
.jssorb21 div { background-position: -5px -5px; }
.jssorb21 div:hover, .jssorb21 .av:hover { background-position: -35px -5px; }
.jssorb21 .av { background-position: -65px -5px; }
.jssorb21 .dn, .jssorb21 .dn:hover { background-position: -95px -5px; }

/* jssor slider arrow navigator skin 21 css */

.jssora21l, .jssora21r {
display: block;
position: absolute;
/* size of arrow element */
width: 55px;
height: 55px;
cursor: pointer;
background: url(../../img/homepageslider/a21.png) center center no-repeat;
overflow: hidden;
}
.jssora21l { background-position: -3px -33px; }
.jssora21r { background-position: -63px -33px; }
.jssora21l:hover { background-position: -123px -33px; }
.jssora21r:hover { background-position: -183px -33px; }
.jssora21l.jssora21ldn { background-position: -243px -33px; }
.jssora21r.jssora21rdn { background-position: -303px -33px; }


text:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <stroke android:width="8dp"
        android:color="#B45F04" />

    <padding android:left="9dp"
        android:top="9dp"
        android:right="9dp"
        android:bottom="9dp"/>
    <corners android:radius="15dp" />
</shape><!-- From: file:/C:/Users/luiz/AndroidStudioProjects/TabsFragments2/app/src/main/res/drawable/normal.xml -->


text:
	<title>Rosalind Miles's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Rosalind Miles's panel show appearances

Rosalind Miles (born 1943-01-06[ref]) has appeared in 2 episodes between 1990-1991.  Rosalind Miles on Wikipedia.

1990

1991

1991-05-30 / Question Time

1990-04-05 / Question Time


text:
title: "Found standing in his cot"
type: first
---

Found standing in his cot for the first time.

Emergency cot adjustments were carried out in short order.

![Standing in cot](img/photos/2014-08-12-cot.jpg)


text:
require 'test_helper'

class RoleRequestTest < ActiveSupport::TestCase
  fixtures :users, :courses, :roles, :role_requests

  before do
    @request = RoleRequest.new user: users(:inactive), name: 'staff',
                               course: courses(:main)
  end

  it 'validates the setup request' do
    assert @request.valid?
  end

  it 'requires a user' do
    @request.user = nil
    assert_equal false, @request.valid?
  end

  it 'requires a name' do
    @request.name = nil
    assert_equal false, @request.valid?
  end

  it 'rejects invalid names' do
    @request.name = 'invalid'
    assert_equal false, @request.valid?
  end

  it 'requires a course on course-specific role' do
    @request.name = 'staff'
    @request.course = nil
    assert_equal false, @request.valid?
  end

  it 'rejects a course on site-wide role' do
    @request.name = 'admin'
    @request.course = courses(:main)
    assert_equal false, @request.valid?
  end

  it 'validates for a course-specific role' do
    @request.name = 'staff'
    @request.course = courses(:main)
    assert @request.valid?
  end

  it 'validates for a site-wide role' do
    @request.name = 'admin'
    @request.course = nil
    assert @request.valid?
  end

  it 'rejects site-wide duplicates' do
    @request.user = users(:solo)
    @request.name = 'admin'
    @request.course = nil
    assert_equal false, @request.valid?
  end

  it 'rejects course-specific duplicates' do
    @request.user = users(:dexter)
    @request.name = 'grader'
    @request.course = courses(:main)
    assert_equal false, @request.valid?
  end

  describe '#approve' do
    describe 'for site-wide roles' do
      it 'creates a Role when necessary' do
        assert_equal false, Role.has_entry?(users(:solo), 'admin')
        role_requests(:solo_wants_to_admin).approve
        assert_equal true, Role.has_entry?(users(:solo), 'admin')
      end

      it "doesn't crash if the Role exists" do
        assert_equal false, Role.has_entry?(users(:solo), 'admin')
        role_requests(:solo_wants_to_admin).approve
        assert_equal true, Role.has_entry?(users(:solo), 'admin')
        role_requests(:solo_wants_to_admin).approve
        assert_equal true, Role.has_entry?(users(:solo), 'admin')
      end
    end

    describe 'for course-specific roles' do
      it 'creates a Role when necessary' do
        assert_equal false, Role.has_entry?(users(:dexter), 'grader',
                                            courses(:main))
        role_requests(:dexter_wants_to_grade).approve
        assert_equal true, Role.has_entry?(users(:dexter), 'grader',
                                           courses(:main))
      end

      it "doesn't crash if the Role exists" do
        assert_equal false, Role.has_entry?(users(:dexter), 'grader',
                                            courses(:main))
        role_requests(:dexter_wants_to_grade).approve
        assert_equal true, Role.has_entry?(users(:dexter), 'grader',
                                           courses(:main))
        role_requests(:dexter_wants_to_grade).approve
        assert_equal true, Role.has_entry?(users(:dexter), 'grader',
                                           courses(:main))
      end
    end
  end
end


text:
class Staff::CharacterInventoriesController < ApplicationController
  before_action :authenticate_staff_editor!

  def update
    @character = Character.find_by(slug: params[:id])
    if duplicate_ingredient_ids?(params)
      flash.now[:alert] = "There was a problem updating your component inventory."
      @components = Ingredient.all - @character.ingredients
      @inventories = Inventory.order_by_ingredient_name.where(character: @character)
      render 'staff/inventories/index'
    elsif @character.update(inventory_params)
      flash[:success] = "Component inventory updated successfully."
      redirect_to staff_user_character_path(@character.user, @character)
    else
      flash.now[:alert] = "There was a problem updating your component inventory."
      @components = Ingredient.all - @character.ingredients
      @inventories = Inventory.order_by_ingredient_name.where(character: @character)
      render 'staff/inventories/index'
    end
  end

  protected

  def inventory_params
    params.require(:character).permit(inventories_attributes: [:id, :quantity, :ingredient_id, :unlocked_calcination, :unlocked_concentration, :unlocked_dissolution, :unlocked_extraction, :unlocked_crafting, :unlocked_ritual])
  end

  def duplicate_ingredient_ids?(params)
    ingredient_ids = Array.new
    params[:character][:inventories_attributes].values.each { |inventory| ingredient_ids << inventory[:ingredient_id] unless inventory[:ingredient_id].nil?}
    if ingredient_ids.uniq != ingredient_ids
      true
    else
      false
    end
  end
end


text:
package net.sf.mmm.ui.toolkit.base.view;

import net.sf.mmm.client.ui.api.attribute.AttributeWriteEnabled;
import net.sf.mmm.client.ui.api.attribute.AttributeWriteHtmlId;
import net.sf.mmm.client.ui.api.attribute.AttributeWriteStylesAdvanced;
import net.sf.mmm.client.ui.api.attribute.AttributeWriteVisible;
import net.sf.mmm.ui.toolkit.api.view.UiNode;
import net.sf.mmm.util.lang.api.attribute.AttributeWriteDisposed;

/**
 * This is the interface that adapts to the native UI object of the underlying toolkit implementation for a
 * {@link net.sf.mmm.ui.toolkit.api.view.UiNode}.

 * It is a design trade-off as java does not have multi-inheritance (we would need scala traits here). This
 * way it is possible to implement an abstract base-implementation for the types of the
 * {@link net.sf.mmm.ui.toolkit.api.view.UiNode}-hierarchy and inherit different implementations (Swing, SWT,
 * GWT, etc.) from that without creating redundant code.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @param <DELEGATE> is the generic type of the {@link #getDelegate() delegate}.
 * @since 1.0.0
 */
public interface UiNodeAdapter<DELEGATE> extends AttributeWriteHtmlId, AttributeWriteStylesAdvanced, AttributeWriteVisible,
    AttributeWriteEnabled, AttributeWriteDisposed {

  /**
   * This method gets the native UI object.
   *
   * @return the native UI object.
   */
  DELEGATE getDelegate();

  /**
   * This method gets the top-level UI object of this node. This is typically the same as the
   * {@link #getDelegate() delegate}. However more complex widgets may be composed out of multiple native UI
   * objects. In such case this method can be overridden to return the top-level delegate used for composition
   * e.g. via
   * {@link net.sf.mmm.ui.toolkit.api.view.composite.UiExtendableComposite#addChild(net.sf.mmm.ui.toolkit.api.view.UiElement)}
   * as well as to update {@link AttributeWriteVisible#setVisible(boolean) visibility}. However
   * {@link #getDelegate() delegate} still returns the active part of the composed widget used to update
   * {@link AttributeWriteEnabled#setEnabled(boolean) activity}, etc.
   *
   * @return the top-level UI object.
   */
  Object getToplevelDelegate();

  /**
   * This method is invoked by {@link AbstractUiNode#setParent(UiNode)}.
   *
   * @param newParent is the new parent node. May be null to remove this object from the UI tree.
   */
  void setParent(UiNode newParent);

}


text:
package org.mashti.jetson.exception;

public class ServerRuntimeException extends ServerException {

    private static final long serialVersionUID = -869413349986223849L;

    public ServerRuntimeException(final RuntimeException cause) {

        super(cause);
    }
}


text:
@interface DemoURLFilter : NSObject <RBEURLAdapterProtocol>

@end

@implementation DemoURLFilter

- (NSString *)adaptedURL:(NSString *)originURL {
    if ([originURL hasPrefix:@"demo"]) {
        return [originURL stringByAppendingString:@"/v1"];
    } else {
        return originURL;
    }
}

@end

@interface DemoParametersFilter : NSObject <RBEParametersAdapterProtocol>

@end

@implementation DemoParametersFilter

- (id)adaptedParametersWithOriginalParameters:(id)parameters {
    if (parameters) {
        NSMutableDictionary *paraDic = parameters;
        [paraDic setObject:@(1) forKey:@"type"];
        parameters = paraDic;
    }else {
        parameters = [[NSMutableDictionary alloc] init];
        [parameters setObject:@(1) forKey:@"type"];
    }

    return parameters;
}

@end

@implementation DemoNetworkUtil

+ (void)configureNetworkAdpater {
    RBEFireworkAdapter *adapter = [RBEFireworkAdapter sharedInstance];
    adapter.baseURL = @"DemoProjectBaseURL";
    adapter.CDNURL = @"DemoProjectCDNURL";
    adapter.allowInvalidCertificates = YES;

    NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

    //For Freshness Cache
    NSString *freshnessCacheDir = [cacheDirectory stringByAppendingPathComponent:@"FreshnessCache"];
    [adapter enableCacheWithFreshnessCachePatternDirectory:freshnessCacheDir freshnessMemoryCount:20 freshnessDiskCapacity:10 * 1024 * 1024];

    //For HTTP Cache
    NSString *HTTPCacheDir = [cacheDirectory stringByAppendingPathComponent:@"HTTPCache"];
    [adapter enableCacheWithHTTPCachePatternDirectory:HTTPCacheDir HTTPMemoryCapacity:2 * 1024 * 1024 HTTPDiskCapacity:10 * 1024 * 1024];

    //clear memory cache
    [adapter purgeInMemoryCache];
    //clear memory cache and disk cache
    [adapter purgeAllCache];

    //Adapte global Parameters
    DemoParametersFilter *paramFilter = [[DemoParametersFilter alloc] init];
    [adapter addParamterAdapters:paramFilter];

    //Adapte URL
    DemoURLFilter *URLFilter = [[DemoURLFilter alloc] init];
    [adapter addURLAdapters:URLFilter];

    //Global response call back
    adapter.validateBlock = ^(RBEFirework *responseFirework) {
        RBEFireworkResponseType responseType = RBEFireworkResponseTypeSuccess;

        NSDictionary *responseDic = responseFirework.responseObject;
        if (responseDic) {
            NSNumber *code = responseDic[@"code"];

            if ([code isEqualToNumber:@0]) {
                //success
            } else if ([code isEqualToNumber:@1]) {
                responseType = RBEFireworkResponseTypeFailure;
            } else {
                responseType = RBEFireworkResponseTypeIgnore;
            }
        }
        return responseType;
    };

    //AFNetworking Configuration
    adapter.requestSerializerType = RBEFireworkRequestSerializerTypeHTTP;
    adapter.responseSerializerType = RBEFireworkResponseSerializerTypeJSON;
    adapter.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];

    [adapter setCookieWithCookieDomain:@".demo.com"
                       cookieOriginUrl:nil
                            cookieName:@"demo"
                           cookieValue:@"demo_value"
                            cookiePath:@"/"
                         cookieVersion:nil
                         cookieExpires:nil];
    NSHTTPCookie *cookie = [adapter cookieWithcookieName:@"demo"];
    if (cookie) {
        //cookie to do...
    }

    //cancel all request, see more from NSURLSession finishTasksAndInvalidate API invalidateAndCancel API
    [adapter cancelAllRBEFireworkInConfigurationTpye:RBESessionConfigurationTypeDefault allowOutstandingTaskFinish:YES];
}

@end


text:
using jarwin.DAL;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Database;
using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace jarwin.Utility
{
    public class Utility
    {
        public string GetAppSetting(string key)
        {
            try
            {
                return ConfigurationManager.AppSettings[key];
            }
            catch
            {
                return String.Empty;
            }
        }

        public static LoggingConfiguration BuildProgrammaticConfig()
        {
            // Formatter
            TextFormatter briefFormatter = new TextFormatter("Timestamp: {timestamp(local)}{newline}Message: {message}{newline}");

            // Trace Listener
            var flatFileTraceListener = new FlatFileTraceListener(
                @"C:\Temp\jarwin.log",
                "----------------------------------------",
                "----------------------------------------",
                briefFormatter);

            // Build Configuration
            var config = new LoggingConfiguration();

            config.AddLogSource("jarwin", SourceLevels.All, true)
                .AddTraceListener(flatFileTraceListener);

            config.IsLoggingEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["loggingEnabled"]);

            return config;
        }
    }
}


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

class_alias(\ReturnTypes\Foo::class, \ReturnTypes\FooAlias::class, true);
class_alias(\TestAccessProperties\FooAccessProperties::class, \TestAccessProperties\FooAccessPropertiesAlias::class, true);


text:
You can either watch [this screencast](https://www.youtube.com/watch?v=UlXJoYn_dek) or try it in [this JS Bin](http://jsbin.com/zobaqa/3/).

## Example

```html
<html>
  <head>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="bootstrap_modal" class="modal hide fade"></div>

    <div id="competitive_list_for_items">
      <ul class="competitive_list" data-update-all-positions-path="/items/update_all">
        <li id="competitor_1" data-id="1" data-position="1">
          <span class="competitor_position">1</span>
          P1
          <span class="competitor_name hide">
            P1
          </span>
        </li>
        <li id="competitor_2" data-id="2" data-position="2">
          <span class="competitor_position">2</span>
          P2
          <span class="competitor_name hide">
            P2
          </span>
        </li>
        <li id="competitor_3" data-id="3" data-position="3">
          <span class="competitor_position">3</span>
          P3
          <span class="competitor_name hide">
            P3
          </span>
        </li>
      </ul>

      <p>
        <button type="button" class="btn competitive_list_start_link">Sort by round-robin tournament</button>
        <button type="button" class="btn hide save_match_results_link">
          <span class='icon-warning-sign'></span> Save match results
        </button>
      </p>
    </div>

    <script src="//code.jquery.com/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
    <script src="https://raw.githubusercontent.com/gawlista/competitive_list.js/master/competitive_list.min.js"></script>
    <script>
    //<![CDATA[

      $( document ).ready(function() {
        $('#competitive_list_for_items').competitiveList();
        $('#competitive_list_for_items').data('competitiveList').matches = []
      });

    //]]>
    </script>
  </body>
</html>
```

## Auto Winner

A winner of a match will be appointed automatically sometimes, what reduces the matches to vote dramatically.
So the winner of the match automatically beats the competitors which have been defeated by the loser of the match and furthermore the defeaters of the match winner also beat the match loser automatically.

## competitor_name_proc

You can pass the constructor of CompetitiveList a proc of which the result will be rendered in the match modal at the place of the competitor.
data-proc-argument of .competitor_name will be passed to this proc.

```html
<div id="competitive_list_for_items">
  <ul class="competitive_list" data-update-all-positions-path="/items/update_all">
    <li id="competitor_1" data-id="1" data-position="1">
      <span class="competitor_position">1</span>
      P1
      <span class="competitor_name hide" data-proc-argument="value">
        P1
      </span>
    </li>

    ...

  </ul>
</div>

<script>
//<![CDATA[

  $( document ).ready(function() {
    $('#competitive_list_for_items').competitiveList({
      competitor_name_proc: function(value) {
        return value;
      }
    });
  });

//]]>
</script>
```

## @moveCompetitorToPosition(competitorId, position, after_update_request_proc = null)

You can move a competitor to a position without rating all matches which is good for drag & drop.
In that case the competitor loses against all opponents with position <= position - 1 unless position is 1.
Furthermore the competitor wins against all opponents with position >= position if competitor is not yet on this position else the competitor wins against all opponents with position >= position + 1.

## Contribution

Pleae follow this screencast http://railscasts.com/episodes/300-contributing-to-open-source

To change the code of the plugin you should only change the file under app/assets/javascripts/competitive_list.js.coffee
The tests can be run after you started the Rails server and go to http://localhost:3000/specs
Alternatively the tests can be run by this command:

```bash
RAILS_ENV=test bundle exec rake spec:javascript
```

When you're done with that you can release the code as:

* uncompressed vanilla JavaScript: copy & paste http://localhost:3000/assets/competitive_list.js?body=1 to /competitive_list.js in the repository
* minified JavaScript: run RAILS_ENV=production bundle exec rake assets:precompile, copy /public/assets/competitive_list-#{token}.js to /competitive_list.min.js in the repository and run rm -rf public/assets/


text:
                About Codeville
                Our Team
            	Facebook
                Contact Us

Copyright © {{ site.title }} {{ site.time | date: '%Y' }}


text:
package templates

import (
	"bytes"
	"container/list"
	"encoding/json"
	"fmt"
	"html/template"
	"mime"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"github.com/microcosm-cc/bluemonday"
	"golang.org/x/net/html/charset"
	"golang.org/x/text/transform"
	"gopkg.in/editorconfig/editorconfig-core-go.v1"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/base"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/markup"
	"code.gitea.io/gitea/modules/setting"
)

// NewFuncMap returns functions for injecting to templates
func NewFuncMap() []template.FuncMap {
	return []template.FuncMap{map[string]interface{}{
		"GoVer": func() string {
			return strings.Title(runtime.Version())
		},
		"UseHTTPS": func() bool {
			return strings.HasPrefix(setting.AppURL, "https")
		},
		"AppName": func() string {
			return setting.AppName
		},
		"AppSubUrl": func() string {
			return setting.AppSubURL
		},
		"AppUrl": func() string {
			return setting.AppURL
		},
		"AppVer": func() string {
			return setting.AppVer
		},
		"AppBuiltWith": func() string {
			return setting.AppBuiltWith
		},
		"AppDomain": func() string {
			return setting.Domain
		},
		"DisableGravatar": func() bool {
			return setting.DisableGravatar
		},
		"ShowFooterTemplateLoadTime": func() bool {
			return setting.ShowFooterTemplateLoadTime
		},
		"LoadTimes": func(startTime time.Time) string {
			return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
		},
		"AvatarLink":   base.AvatarLink,
		"Safe":         Safe,
		"SafeJS":       SafeJS,
		"Sanitize":     bluemonday.UGCPolicy().Sanitize,
		"Str2html":     Str2html,
		"TimeSince":    base.TimeSince,
		"RawTimeSince": base.RawTimeSince,
		"FileSize":     base.FileSize,
		"Subtract":     base.Subtract,
		"Add": func(a, b int) int {
			return a + b
		},
		"ActionIcon": ActionIcon,
		"DateFmtLong": func(t time.Time) string {
			return t.Format(time.RFC1123Z)
		},
		"DateFmtShort": func(t time.Time) string {
			return t.Format("Jan 02, 2006")
		},
		"SizeFmt": func(s int64) string {
			return base.FileSize(s)
		},
		"List": List,
		"SubStr": func(str string, start, length int) string {
			if len(str) == 0 {
				return ""
			}
			end := start + length
			if length == -1 {
				end = len(str)
			}
			if len(str) < end {
				return str
			}
			return str[start:end]
		},
		"EllipsisString":    base.EllipsisString,
		"DiffTypeToStr":     DiffTypeToStr,
		"DiffLineTypeToStr": DiffLineTypeToStr,
		"Sha1":              Sha1,
		"ShortSha":          base.ShortSha,
		"MD5":               base.EncodeMD5,
		"ActionContent2Commits": ActionContent2Commits,
		"EscapePound": func(str string) string {
			return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
		},
		"RenderCommitMessage": RenderCommitMessage,
		"ThemeColorMetaTag": func() string {
			return setting.UI.ThemeColorMetaTag
		},
		"MetaAuthor": func() string {
			return setting.UI.Meta.Author
		},
		"MetaDescription": func() string {
			return setting.UI.Meta.Description
		},
		"MetaKeywords": func() string {
			return setting.UI.Meta.Keywords
		},
		"FilenameIsImage": func(filename string) bool {
			mimeType := mime.TypeByExtension(filepath.Ext(filename))
			return strings.HasPrefix(mimeType, "image/")
		},
		"TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
			if ec != nil {
				def := ec.GetDefinitionForFilename(filename)
				if def.TabWidth > 0 {
					return fmt.Sprintf("tab-size-%d", def.TabWidth)
				}
			}
			return "tab-size-8"
		},
		"SubJumpablePath": func(str string) []string {
			var path []string
			index := strings.LastIndex(str, "/")
			if index != -1 && index != len(str) {
				path = append(path, str[0:index+1])
				path = append(path, str[index+1:])
			} else {
				path = append(path, str)
			}
			return path
		},
		"JsonPrettyPrint": func(in string) string {
			var out bytes.Buffer
			err := json.Indent(&out, []byte(in), "", "  ")
			if err != nil {
				return ""
			}
			return out.String()
		},
		"DisableGitHooks": func() bool {
			return setting.DisableGitHooks
		},
	}}
}

// Safe render raw as HTML
func Safe(raw string) template.HTML {
	return template.HTML(raw)
}

// SafeJS renders raw as JS
func SafeJS(raw string) template.JS {
	return template.JS(raw)
}

// Str2html render Markdown text to HTML
func Str2html(raw string) template.HTML {
	return template.HTML(markup.Sanitize(raw))
}

// List traversings the list
func List(l *list.List) chan interface{} {
	e := l.Front()
	c := make(chan interface{})
	go func() {
		for e != nil {
			c <- e.Value
			e = e.Next()
		}
		close(c)
	}()
	return c
}

// Sha1 returns sha1 sum of string
func Sha1(str string) string {
	return base.EncodeSha1(str)
}

// ToUTF8WithErr converts content to UTF8 encoding
func ToUTF8WithErr(content []byte) (string, error) {
	charsetLabel, err := base.DetectEncoding(content)
	if err != nil {
		return "", err
	} else if charsetLabel == "UTF-8" {
		return string(content), nil
	}

	encoding, _ := charset.Lookup(charsetLabel)
	if encoding == nil {
		return string(content), fmt.Errorf("Unknown encoding: %s", charsetLabel)
	}

	// If there is an error, we concatenate the nicely decoded part and the
	// original left over. This way we won't loose data.
	result, n, err := transform.String(encoding.NewDecoder(), string(content))
	if err != nil {
		result = result + string(content[n:])
	}

	return result, err
}

// ToUTF8 converts content to UTF8 encoding and ignore error
func ToUTF8(content string) string {
	res, _ := ToUTF8WithErr([]byte(content))
	return res
}

// ReplaceLeft replaces all prefixes 'old' in 's' with 'new'.
func ReplaceLeft(s, old, new string) string {
	oldLen, newLen, i, n := len(old), len(new), 0, 0
	for ; i < len(s) && strings.HasPrefix(s[i:], old); n++ {
		i += oldLen
	}

	// simple optimization
	if n == 0 {
		return s
	}

	// allocating space for the new string
	curLen := n*newLen + len(s[i:])
	replacement := make([]byte, curLen, curLen)

	j := 0
	for ; j < n*newLen; j += newLen {
		copy(replacement[j:j+newLen], new)
	}

	copy(replacement[j:], s[i:])
	return string(replacement)
}

// RenderCommitMessage renders commit message with XSS-safe and special links.
func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) template.HTML {
	cleanMsg := template.HTMLEscapeString(msg)
	fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
	msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
	numLines := len(msgLines)
	if numLines == 0 {
		return template.HTML("")
	} else if !full {
		return template.HTML(msgLines[0])
	} else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
		// First line is a header, standalone or followed by empty line
		header := fmt.Sprintf("
%s
", msgLines[0])
		if numLines >= 2 {
			fullMessage = header + fmt.Sprintf("\n
%s
", strings.Join(msgLines[2:], "\n"))
		} else {
			fullMessage = header
		}
	} else {
		// Non-standard git message, there is no header line
		fullMessage = fmt.Sprintf("
%s
", strings.Join(msgLines, "
"))
	}
	return template.HTML(fullMessage)
}

// Actioner describes an action
type Actioner interface {
	GetOpType() int
	GetActUserName() string
	GetRepoUserName() string
	GetRepoName() string
	GetRepoPath() string
	GetRepoLink() string
	GetBranch() string
	GetContent() string
	GetCreate() time.Time
	GetIssueInfos() []string
}

// ActionIcon accepts a int that represents action operation type
// and returns a icon class name.
func ActionIcon(opType int) string {
	switch opType {
	case 1, 8: // Create and transfer repository
		return "repo"
	case 5, 9: // Commit repository
		return "git-commit"
	case 6: // Create issue
		return "issue-opened"
	case 7: // New pull request
		return "git-pull-request"
	case 10: // Comment issue
		return "comment-discussion"
	case 11: // Merge pull request
		return "git-merge"
	case 12, 14: // Close issue or pull request
		return "issue-closed"
	case 13, 15: // Reopen issue or pull request
		return "issue-reopened"
	default:
		return "invalid type"
	}
}

// ActionContent2Commits converts action content to push commits
func ActionContent2Commits(act Actioner) *models.PushCommits {
	push := models.NewPushCommits()
	if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
		log.Error(4, "json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
	}
	return push
}

// DiffTypeToStr returns diff type name
func DiffTypeToStr(diffType int) string {
	diffTypes := map[int]string{
		1: "add", 2: "modify", 3: "del", 4: "rename",
	}
	return diffTypes[diffType]
}

// DiffLineTypeToStr returns diff line type name
func DiffLineTypeToStr(diffType int) string {
	switch diffType {
	case 2:
		return "add"
	case 3:
		return "del"
	case 4:
		return "tag"
	}
	return "same"
}


text:
<?php

	namespace Uneak\AssetsBundle\Exception;

	class PackageNotFoundException extends NotFoundException {
	}


text:
#include "CCDefines.h"
#include "CCObjects.h"
#include "CCTextureFontPage.h"

CCTile3D::CCTile3D()
{
    movementController = NULL;
}

// CCRenderable
void CCTile3D::dirtyModelMatrix()
{
    super::dirtyModelMatrix();
    for( int i=0; i<attachments.length; ++i )
    {
        CCSceneObject *attachment = attachments.list[i];
        attachment->dirtyModelMatrix();
    }
}

void CCTile3D::setPositionXYZ(const float x, const float y, const float z)
{
    if( position.x != x || position.y != y || position.z != z )
    {
        CCVector3 distance = position;
        super::setPositionXYZ( x, y, z );
        distance.sub( position );

        for( int i=0; i<attachments.length; ++i )
        {
            CCSceneObject *attachment = attachments.list[i];
            attachment->translate( -distance.x, -distance.y, -distance.z );
        }

        CCOctreeRefreshObject( this );
    }
}

void CCTile3D::translate(const float x, const float y, const float z)
{
    super::translate( x, y, z );

    for( int i=0; i<attachments.length; ++i )
    {
        CCSceneObject *attachment = attachments.list[i];
        attachment->translate( x, y, z );
    }

    CCOctreeRefreshObject( this );
}

// Positioning Tiles
void CCTile3D::positionTileY(float &y)
{
    y -= collisionBounds.y;
    translate( 0.0f, y, 0.0f );
    y -= collisionBounds.y;
}

void CCTile3D::positionTileBelow(CCTile3D *fromTile)
{
    setPosition( fromTile->getPosition() );
    translate( 0.0f, -( fromTile->collisionBounds.y + collisionBounds.y ), 0.0f );
}

void CCTile3D::positionTileAbove(CCTile3D *fromTile)
{
    setPosition( fromTile->getPosition() );
    translate( 0.0f, fromTile->collisionBounds.y + collisionBounds.y, 0.0f );
}

void CCTile3D::positionTileRight(CCTile3D *fromTile)
{
    setPosition( fromTile->getPosition() );
    translate( fromTile->collisionBounds.x + collisionBounds.x, 0.0f, 0.0f );
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="org.sms.tetris3d">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        tools:replace="android:icon"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ScrollingActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainGameActivity"
            android:hardwareAccelerated="true"
            android:label="tet game"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".GameLogViewActivity"
            android:label="Game Log"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
**THIS TOOL IS WORK IN PROGRESS - USE IT CAREFULLY!**

## Description

This is an automation tool to organize deploys.
Currently, it uses AWS OpsWorks.

Also currently, it provides two ways to operate it:

* Operations engineer: Allows to run things.
* Infrastructure developer mode: Enabling to do cookbook testing.

### Set up

A repository containing all the chef opsworks-enabled recipes is required, and
must be cloned into the development workstation.
This repository can be created by running the following:

    git init cookbooks

Then, add the following line to the Gemfile within this repository, creating
it if you don't have one:

    echo "gem 'skyed'" > cookbooks/Gemfile

And then, run:

    cd cookbooks
    bundle install

Now, commit both the Gemfile and the Gemfile.lock:

    git add Gemfile*
    git commit -m "Initial commit"

Once the gem is installed, run:

    skyed init

It will guide through the setup process asking about the repository's local
location where the coobooks are stored, trying to check if the current
directory is, or asking about the location. It also will try to get the AWS
credentials from the environment variables, or ask for them. This process
will create '~/.skyed', unless that file already exists, in which case it
will fail before any other question.

Alternatively, if the only need is to run skyed but without having to
initialize it at all, then set the PKEY environment variable to point the
file containing the SSH key with access to the cookbooks remote repository:

    export PKEY=~/.ssh/id_dsa
    skyed run -s Stack -l Layer snmp

## Run

This tool allows to execute recipes on specific layers by using the run
command with the -s and -l options:

    skyed run -s Stack_name -l Layer name snmp

Stack and layer ids can be used, instead of the names.

## List

The list command, with the --rds switch, lists all snapshots in AWS RDS:

    skyed list --rds

## Create

To create RDS for PostgreSQL instances, from snapshot, with the same
parameters of the original, except for the `--db-parameters-group`
and `--db-security-group` parameters:

    skyed create --rds new_instance_name rds:snapshot

Or from scratch, specifying parameters (check this list using `create --help`):

    skyed create --rds new_instance_name --size 150 --type m1.xlarge --user owner

It returns the endpoint for the new instance.

## Destroy

AWS RDS instances can be also destroyed, optionally saving a final snapshot:

    skyed destroy --rds instance_name_to_remove

## Deploy

With that command, current cookbook repository is used to deploy a local
vagrant machine.
This feature requires `.skyed` to exist with valid parameters.


text:
<?php
  declare( strict_types = 1 );
  // backward compatibility
  if (!class_exists('\PHPUnit\Framework\TestCase')) {
    class_alias('\PHPUnit_Framework_TestCase', '\PHPUnit\Framework\TestCase');
  }
  use PHPUnit\Framework\TestCase;

  final class HtmlTest extends TestCase {
    public function testNoTemplateSet() {
      $this->expectException(JException::class);
      $app = new JConfig("tests/jate/modules/Html/file/app.json");
      $html = new TestHtml();
      $html->init();
      $html->setParameters(["app" => $app, "page" => []]);
      $html->draw();
    }
    public function testCorrectTemplateSet() {
      $app = new JConfig("tests/jate/modules/Html/file/app.json");
      $html = new TestHtml();
      $html->init();
      $html->setParameters(["app" => $app, "page" => []]);
      $html->setTemplate();
      $this->assertEquals("aaa", trim($html->draw()));
    }
  }
  class TestHtml extends Html {
    public function init() {
      setServerVar();
    }
    public function setTemplate() {
      $this->template = "tests/jate/modules/Html/file/template.html";
    }
  }
?>


text:
require File.expand_path(File.dirname(__FILE__) + "/../spec_helper")

describe "reloads" do
  before do
    @session = Webrat::TestSession.new
    @session.response_body = "Hello world"
  end

  it "should reload the page with http referer" do
    @session.should_receive(:get).with("/", {})
    @session.should_receive(:get).with("/", {}, {"HTTP_REFERER"=>"/"})
    @session.visits("/")
    @session.reloads
  end
end


text:
package execution

import (
	"sync"

	"github.com/containerd/containerd"
	api "github.com/containerd/containerd/api/services/execution"
	"github.com/containerd/containerd/api/types/container"
	"github.com/containerd/containerd/log"
	"github.com/containerd/containerd/plugin"
	google_protobuf "github.com/golang/protobuf/ptypes/empty"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

var (
	_     = (api.ContainerServiceServer)(&Service{})
	empty = &google_protobuf.Empty{}
)

func init() {
	plugin.Register("runtime-grpc", &plugin.Registration{
		Type: plugin.GRPCPlugin,
		Init: New,
	})
}

func New(ic *plugin.InitContext) (interface{}, error) {
	c, err := newCollector(ic.Context, ic.Runtimes)
	if err != nil {
		return nil, err
	}
	return &Service{
		runtimes:   ic.Runtimes,
		containers: make(map[string]containerd.Container),
		collector:  c,
	}, nil
}

type Service struct {
	mu sync.Mutex

	runtimes   map[string]containerd.Runtime
	containers map[string]containerd.Container
	collector  *collector
}

func (s *Service) Register(server *grpc.Server) error {
	api.RegisterContainerServiceServer(server, s)
	// load all containers
	for _, r := range s.runtimes {
		containers, err := r.Containers(context.Background())
		if err != nil {
			return err
		}
		for _, c := range containers {
			s.containers[c.Info().ID] = c
		}
	}
	return nil
}

func (s *Service) Create(ctx context.Context, r *api.CreateRequest) (*api.CreateResponse, error) {
	opts := containerd.CreateOpts{
		Spec: r.Spec.Value,
		IO: containerd.IO{
			Stdin:    r.Stdin,
			Stdout:   r.Stdout,
			Stderr:   r.Stderr,
			Terminal: r.Terminal,
		},
	}
	for _, m := range r.Rootfs {
		opts.Rootfs = append(opts.Rootfs, containerd.Mount{
			Type:    m.Type,
			Source:  m.Source,
			Options: m.Options,
		})
	}
	runtime, err := s.getRuntime(r.Runtime)
	if err != nil {
		return nil, err
	}
	s.mu.Lock()
	if _, ok := s.containers[r.ID]; ok {
		s.mu.Unlock()
		return nil, containerd.ErrContainerExists
	}
	c, err := runtime.Create(ctx, r.ID, opts)
	if err != nil {
		s.mu.Unlock()
		return nil, err
	}
	s.containers[r.ID] = c
	s.mu.Unlock()
	state, err := c.State(ctx)
	if err != nil {
		s.mu.Lock()
		delete(s.containers, r.ID)
		runtime.Delete(ctx, c)
		s.mu.Unlock()
		return nil, err
	}
	return &api.CreateResponse{
		ID:  r.ID,
		Pid: state.Pid(),
	}, nil
}

func (s *Service) Start(ctx context.Context, r *api.StartRequest) (*google_protobuf.Empty, error) {
	c, err := s.getContainer(r.ID)
	if err != nil {
		return nil, err
	}
	if err := c.Start(ctx); err != nil {
		return nil, err
	}
	return empty, nil
}

func (s *Service) Delete(ctx context.Context, r *api.DeleteRequest) (*api.DeleteResponse, error) {
	c, err := s.getContainer(r.ID)
	if err != nil {
		return nil, err
	}
	runtime, err := s.getRuntime(c.Info().Runtime)
	if err != nil {
		return nil, err
	}
	exit, err := runtime.Delete(ctx, c)
	if err != nil {
		return nil, err
	}

	delete(s.containers, r.ID)

	return &api.DeleteResponse{
		ExitStatus: exit.Status,
		ExitedAt:   exit.Timestamp,
	}, nil
}

func containerFromContainerd(ctx context.Context, c containerd.Container) (*container.Container, error) {
	state, err := c.State(ctx)
	if err != nil {
		return nil, err
	}

	var status container.Status
	switch state.Status() {
	case containerd.CreatedStatus:
		status = container.Status_CREATED
	case containerd.RunningStatus:
		status = container.Status_RUNNING
	case containerd.StoppedStatus:
		status = container.Status_STOPPED
	case containerd.PausedStatus:
		status = container.Status_PAUSED
	default:
		log.G(ctx).WithField("status", state.Status()).Warn("unknown status")
	}
	return &container.Container{
		ID:     c.Info().ID,
		Pid:    state.Pid(),
		Status: status,
	}, nil
}

func (s *Service) Info(ctx context.Context, r *api.InfoRequest) (*container.Container, error) {
	c, err := s.getContainer(r.ID)
	if err != nil {
		return nil, err
	}
	return containerFromContainerd(ctx, c)
}

func (s *Service) List(ctx context.Context, r *api.ListRequest) (*api.ListResponse, error) {
	resp := &api.ListResponse{}
	s.mu.Lock()
	defer s.mu.Unlock()
	for _, cd := range s.containers {
		c, err := containerFromContainerd(ctx, cd)
		if err != nil {
			return nil, err
		}
		resp.Containers = append(resp.Containers, c)
	}
	return resp, nil
}

func (s *Service) Kill(ctx context.Context, r *api.KillRequest) (*google_protobuf.Empty, error) {
	c, err := s.getContainer(r.ID)
	if err != nil {
		return nil, err
	}
	if err := c.Kill(ctx, r.Signal, r.All); err != nil {
		return nil, err
	}
	return empty, nil
}

func (s *Service) Events(r *api.EventsRequest, server api.ContainerService_EventsServer) error {
	w := &grpcEventWriter{
		server: server,
	}
	return s.collector.forward(w)
}

func (s *Service) Exec(ctx context.Context, r *api.ExecRequest) (*api.ExecResponse, error) {
	c, err := s.getContainer(r.ID)
	if err != nil {
		return nil, err
	}
	process, err := c.Exec(ctx, containerd.ExecOpts{
		Spec: r.Spec.Value,
		IO: containerd.IO{
			Stdin:    r.Stdin,
			Stdout:   r.Stdout,
			Stderr:   r.Stderr,
			Terminal: r.Terminal,
		},
	})
	if err != nil {
		return nil, err
	}
	state, err := process.State(ctx)
	if err != nil {
		return nil, err
	}
	return &api.ExecResponse{
		Pid: state.Pid(),
	}, nil
}

func (s *Service) Pty(ctx context.Context, r *api.PtyRequest) (*google_protobuf.Empty, error) {
	c, err := s.getContainer(r.ID)
	if err != nil {
		return nil, err
	}
	if err := c.Pty(ctx, r.Pid, containerd.ConsoleSize{
		Width:  r.Width,
		Height: r.Height,
	}); err != nil {
		return nil, err
	}
	return empty, nil
}

func (s *Service) CloseStdin(ctx context.Context, r *api.CloseStdinRequest) (*google_protobuf.Empty, error) {
	c, err := s.getContainer(r.ID)
	if err != nil {
		return nil, err
	}
	if err := c.CloseStdin(ctx, r.Pid); err != nil {
		return nil, err
	}
	return empty, nil
}

func (s *Service) getContainer(id string) (containerd.Container, error) {
	s.mu.Lock()
	c, ok := s.containers[id]
	s.mu.Unlock()
	if !ok {
		return nil, containerd.ErrContainerNotExist
	}
	return c, nil
}

func (s *Service) getRuntime(name string) (containerd.Runtime, error) {
	runtime, ok := s.runtimes[name]
	if !ok {
		return nil, containerd.ErrUnknownRuntime
	}
	return runtime, nil
}

type grpcEventWriter struct {
	server api.ContainerService_EventsServer
}

func (g *grpcEventWriter) Write(e *containerd.Event) error {
	var t container.Event_EventType
	switch e.Type {
	case containerd.ExitEvent:
		t = container.Event_EXIT
	case containerd.ExecAddEvent:
		t = container.Event_EXEC_ADDED
	case containerd.PausedEvent:
		t = container.Event_PAUSED
	case containerd.CreateEvent:
		t = container.Event_CREATE
	case containerd.StartEvent:
		t = container.Event_START
	case containerd.OOMEvent:
		t = container.Event_OOM
	}
	return g.server.Send(&container.Event{
		Type:       t,
		ID:         e.ID,
		Pid:        e.Pid,
		ExitStatus: e.ExitStatus,
	})
}


text:
namespace Slash.Collections.Grid
{
    using System;
    using System.Collections;
    using System.Linq;
    using System.Text;

    public class Grid<T> : IEnumerable
    {
        #region Fields

        private T[,] grid;

        #endregion

        #region Constructors and Destructors

        public Grid(int width, int height)
        {
            this.grid = new T[width,height];
        }

        public Grid(T[,] grid)
        {
            this.grid = grid;
        }

        public Grid(Grid<T> grid)
        {
            this.grid = new T[grid.Width,grid.Height];

            for (int i = 0; i < grid.Width; i++)
            {
                for (int j = 0; j < grid.Height; j++)
                {
                    this.grid[i, j] = grid[i, j];
                }
            }
        }

        #endregion

        #region Public Properties

        public int Height
        {
            get
            {
                return this.grid.GetUpperBound(1) + 1;
            }
        }

        public int Width
        {
            get
            {
                return this.grid.GetUpperBound(0) + 1;
            }
        }

        #endregion

        #region Public Indexers

        public T this[int x, int y]
        {
            get
            {
                return this.GetObjectAt(x, y);
            }
            set
            {
                this.SetObjectAt(value, x, y);
            }
        }

        #endregion

        #region Public Methods and Operators

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }
            if (ReferenceEquals(this, obj))
            {
                return true;
            }
            if (obj.GetType() != this.GetType())
            {
                return false;
            }
            return this.Equals((Grid<T>)obj);
        }

        public IEnumerator GetEnumerator()
        {
            return this.grid.GetEnumerator();
        }

        public override int GetHashCode()
        {
            return (this.grid != null ? this.grid.GetHashCode() : 0);
        }

        public T GetObjectAt(int x, int y)
        {
            if (x < 0 || x >= this.grid.GetLength(0))
            {
                throw new ArgumentOutOfRangeException(
                    "x",
                    x,
                    string.Format("Value has to be between 0 and {0}, but was {1}.", this.grid.GetLength(0) - 1, x));
            }
            if (y < 0 || y >= this.grid.GetLength(1))
            {
                throw new ArgumentOutOfRangeException(
                    "y",
                    y,
                    string.Format("Value has to be between 0 and {0}, but was {1}.", this.grid.GetLength(1) - 1, y));
            }

            return this.grid[x, y];
        }

        public void Resize(int newWidth, int newHeight)
        {
            T[,] newGrid = new T[newWidth,newHeight];
            for (int x = 0; x < newWidth && x < this.Width; x++)
            {
                for (int y = 0; y < newHeight && y < this.Height; y++)
                {
                    newGrid[x, y] = this.grid[x, y];
                }
            }
            this.grid = newGrid;
        }

        public void SetObjectAt(T gridObject, int x, int y)
        {
            if (x < 0 || x >= this.grid.GetLength(0))
            {
                throw new ArgumentOutOfRangeException(
                    "x",
                    x,
                    string.Format("Value has to be between 0 and {0}, but was {1}.", this.grid.GetLength(0) - 1, x));
            }
            if (y < 0 || y >= this.grid.GetLength(1))
            {
                throw new ArgumentOutOfRangeException(
                    "y",
                    y,
                    string.Format("Value has to be between 0 and {0}, but was {1}.", this.grid.GetLength(1) - 1, y));
            }

            this.grid[x, y] = gridObject;
        }

        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < this.grid.GetLength(0); i++)
            {
                stringBuilder.Append("[ ");

                for (int j = 0; j < this.grid.GetLength(1); j++)
                {
                    stringBuilder.AppendFormat("{0}, ", this.grid[i, j]);
                }

                stringBuilder.Length = stringBuilder.Length - 2;
                stringBuilder.AppendLine("]");
            }

            return stringBuilder.ToString();
        }

        public bool TryGetObject(int x, int y, out T gridObject)
        {
            if (x < 0 || x >= this.grid.GetLength(0) || y < 0 || y >= this.grid.GetLength(1))
            {
                gridObject = default(T);
                return false;
            }

            gridObject = this.grid[x, y];
            return true;
        }

        #endregion

        #region Methods

        protected bool Equals(Grid<T> other)
        {
            bool equal = this.grid.Rank == other.grid.Rank
                         && Enumerable.Range(0, this.grid.Rank)
                                      .All(
                                          dimension => this.grid.GetLength(dimension) == other.grid.GetLength(dimension))
                         && this.grid.Cast<T>().SequenceEqual(other.grid.Cast<T>());

            return equal;
        }

        #endregion
    }
}


text:
node.set['postgresql']['pg_hba'] = Array(node['postgresql']['pg_hba']).
  reject { |hba| hba['docker_appliance'] }
node.set['postgresql']['pg_hba'] << {
  type: 'host',
  db: 'all',
  user: 'all',
  addr: node['docker']['bridge_network'],
  method: 'md5',
  docker_appliance: true
}

node.set['postgresql']['config']['listen_addresses'] = ( node['postgresql']['config']['listen_addresses'].split(',') | [ node['docker']['bridge_ip'] ] ).join(',')

include_recipe 'database::postgresql'
include_recipe 'postgresql::server'


text: export * from '../../shared/async'


text:
<?php

    if (!class_exists('DOPBSPWooCommerceProduct')){
        class DOPBSPWooCommerceProduct{
            /*
             * Constructor.
             */
            function __construct(){
                global $product;
                /*
                 * Add calendar in product summary.
                 */
                add_filter('woocommerce_single_product_summary', array(&$this, 'summary'), 25);

                /*
                 * Add calendar in product tab.
                 */
                add_filter('woocommerce_product_tabs', array(&$this, 'tab'));

                /*
                 * Display minimum price from calendar.
                 */
                // add_filter('woocommerce_get_price_html', array(&$this, 'price'), $product, 2);
            }

            /*
             * Add booking calendar in product summary section.
             *
             * @return sidebar HTML or calendar shortcode
             */
            function summary(){
                global $post;

                $dopbsp_woocommerce_options = array('calendar' => get_post_meta($post->ID, 'dopbsp_woocommerce_calendar', true),
                                                    'language' => get_post_meta($post->ID, 'dopbsp_woocommerce_language', true) == '' ? 'en':get_post_meta($post->ID, 'dopbsp_woocommerce_language', true),
                                                    'position' => get_post_meta($post->ID, 'dopbsp_woocommerce_position', true) == '' ? 'summary':get_post_meta($post->ID, 'dopbsp_woocommerce_position', true),
                                                    'add_to_cart' => get_post_meta($post->ID, 'dopbsp_woocommerce_add_to_cart', true) == '' ? 'false':get_post_meta($post->ID, 'dopbsp_woocommerce_add_to_cart', true));

                if ($dopbsp_woocommerce_options['calendar'] != ''
                        && $dopbsp_woocommerce_options['calendar'] != '0'){
                    /*
                     * Add all calendar.
                     */
                    if ($dopbsp_woocommerce_options['position'] == 'summary'){
                        echo do_shortcode('[dopbsp id='.$dopbsp_woocommerce_options['calendar'].' lang='.$dopbsp_woocommerce_options['language'].' woocommerce=true woocommerce_product_id='.$post->ID.' woocommerce_position='.$dopbsp_woocommerce_options['position'].' woocommerce_add_to_cart='.$dopbsp_woocommerce_options['add_to_cart'].']');
                    }

                    /*
                     * Add only sidebar.
                     */
                    if ($dopbsp_woocommerce_options['position'] == 'summary-tabs'){
                        echo '

';
                    }
                }
            }

            /*
             * Add booking calendar in product tab section.
             *
             * @return tab object
             */
            function tab(){
		global $post;
                global $DOPBSP;

		$tab = array();

                $dopbsp_woocommerce_options = array('calendar' => get_post_meta($post->ID, 'dopbsp_woocommerce_calendar', true),
                                                    'language' => get_post_meta($post->ID, 'dopbsp_woocommerce_language', true) == '' ? 'en':get_post_meta($post->ID, 'dopbsp_woocommerce_language', true),
                                                    'position' => get_post_meta($post->ID, 'dopbsp_woocommerce_position', true) == '' ? 'summary':get_post_meta($post->ID, 'dopbsp_woocommerce_position', true),
                                                    'add_to_cart' => get_post_meta($post->ID, 'dopbsp_woocommerce_add_to_cart', true) == '' ? 'false':get_post_meta($post->ID, 'dopbsp_woocommerce_add_to_cart', true));

                if ($dopbsp_woocommerce_options['calendar'] != ''
                        && $dopbsp_woocommerce_options['calendar'] != '0'
                        && ($dopbsp_woocommerce_options['position'] == 'tabs'
                                || $dopbsp_woocommerce_options['position'] == 'summary-tabs')){
                    $DOPBSP->classes->translation->set($dopbsp_woocommerce_options['language'],
                                                       false);

                    $tab['booking-system'] = array('title' => $DOPBSP->text('WOOCOMMERCE_TABS'),
                                                   'priority' => 1,
                                                   'callback' => array($this, 'tabContent'));
                    return $tab;
                }
            }

            /*
             * Add booking calendar in product tab section.
             *
             * @return calendar shortcode
             */
            function tabContent(){
                global $post;

                $dopbsp_woocommerce_options = array('calendar' => get_post_meta($post->ID, 'dopbsp_woocommerce_calendar', true),
                                                    'language' => get_post_meta($post->ID, 'dopbsp_woocommerce_language', true) == '' ? 'en':get_post_meta($post->ID, 'dopbsp_woocommerce_language', true),
                                                    'position' => get_post_meta($post->ID, 'dopbsp_woocommerce_position', true) == '' ? 'summary':get_post_meta($post->ID, 'dopbsp_woocommerce_position', true),
                                                    'add_to_cart' => get_post_meta($post->ID, 'dopbsp_woocommerce_add_to_cart', true) == '' ? 'false':get_post_meta($post->ID, 'dopbsp_woocommerce_add_to_cart', true));

                echo do_shortcode('[dopbsp id='.$dopbsp_woocommerce_options['calendar'].' lang='.$dopbsp_woocommerce_options['language'].' woocommerce=true woocommerce_product_id='.$post->ID.' woocommerce_position='.$dopbsp_woocommerce_options['position'].' woocommerce_add_to_cart='.$dopbsp_woocommerce_options['add_to_cart'].']');
            }

            /*
             * Display minimum price from calendar on product page.
             *
             * @param price (string): current price html
             * @param product (object): product data
             *
             * @return price html
             */
            function price($price,
                           $product){
                global $wpdb;
                global $DOPBSP;

                $dopbsp_woocommerce_options = array('calendar' => get_post_meta($product->id, 'dopbsp_woocommerce_calendar', true));

                if ($dopbsp_woocommerce_options['calendar'] != ''
                        && $dopbsp_woocommerce_options['calendar'] != '0'){
                    $calendar = $wpdb->get_row($wpdb->prepare('SELECT * FROM '.$DOPBSP->tables->calendars.' WHERE id=%d',
                                                              $dopbsp_woocommerce_options['calendar']));

                    $settings_calendar = $DOPBSP->classes->backend_settings->values($calendar->id,
                                                                                'calendar');
                    $price_value = $DOPBSP->classes->price->set($calendar->price_min,
                                                                $DOPBSP->classes->currencies->get($settings_calendar->currency),
                                                                $settings_calendar->currency_position);
                    $price = ''.$DOPBSP->text('WOOCOMMERCE_STARTING_FROM').': '.$price_value.'';
                }

                return $price;
            }
        }
    }


text:
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "BuildingSpaceGameModeBase.generated.h"

/**
 *
 */
UCLASS()
class BUILDINGSPACE_API ABuildingSpaceGameModeBase : public AGameModeBase
{
	GENERATED_BODY()

};


text:
import { get, merge } from 'lodash';

/* eslint-disable no-param-reassign */
export default function() {
  return (hook) => {
    const provider = get(hook, 'params.oauth.provider');

    // TODO: Work out account merging strategy
    if (provider === 'google-token') {
      hook.data.google = merge(hook.data.google, hook.data['google-token']);
    }

    if (hook.data.google) {
      const {
        gender,
        name: { familyName, givenName },
        // emails: [{ value: email }],
      } = hook.data.google.profile;

      hook.data.gender = hook.data.gender || gender;
      hook.data.firstName = hook.data.firstName || givenName;
      hook.data.lastName = hook.data.lastName || familyName;
      // hook.data.email = hook.data.email || email;
    }

    return Promise.resolve(hook);
  }
}


text:
ML Engineer Exercise
=========

Overview
--------

This exercise requires the engineer to perform a range of tasks using the deals.txt file located in the data directory. The deals.txt file should remain unchanged, and any mutations on the data should happen as part of your submission.

Each task has an individual python file in the mywork package directory, please confine your solution for each task within those files. In addition, there is a test directory in the project root, with an associated test_* python file, where your unit tests will go.

Requirements
------------

Your code should meet the following requirements:

* Be [PEP8] compliant
* Implement a unit test for each material function, capable of being tested using [pytest] or [nosetest]
* Contain sufficient docstrings and comments to make it easy to reason about

Things to keep in mind
----------------------
- Each task is designed to explore a specific domain approach and technical method. Read the header carefully as the problem and the approach to solving it are carefully described therein
- There is definitely not one solution for each task, so if you feel there are multiple, valid approaches, please implement them, we can use these for follow-up discussions

[PEP8]:http://legacy.python.org/dev/peps/pep-0008/
[pytest]:http://pytest.org/latest/
[nosetest]:https://nose.readthedocs.org/en/latest/


text:
"""Distribution Strategy-related dataset transformations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.util import nest
from tensorflow.python.data.util import structure
from tensorflow.python.framework import errors
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops

class _AutoShardDataset(dataset_ops.UnaryDataset):
  """A `Dataset` that shards the `Dataset` automatically.

  This dataset takes in an existing dataset and tries to automatically figure
  out how to shard the dataset in a multi-worker scenario. Currently, it uses
  Grappler to walk up the dataset graph until it finds a reader dataset (e.g.
  CSVDataset, TFRecordDataset), then inserts a ShardDataset op before that node
  so that each worker only sees some files.

  Args:
    num_workers: Total number of workers to shard this dataset across.
    index: The current worker index (out of the total number of workers) this
      dataset is for.

  Raises:
    NotFoundError: If we cannot find a suitable reader dataset to begin
      automatically sharding the dataset.
  """

  def __init__(self, input_dataset, num_workers, index):
    self._input_dataset = input_dataset

    self._structure = input_dataset._element_structure  # pylint: disable=protected-access
    variant_tensor = ged_ops.experimental_auto_shard_dataset(
        self._input_dataset._variant_tensor,  # pylint: disable=protected-access
        num_workers=num_workers,
        index=index,
        **dataset_ops.flat_structure(self))
    super(_AutoShardDataset, self).__init__(input_dataset, variant_tensor)

  @property
  def _element_structure(self):
    return self._structure

def _AutoShardDatasetV1(input_dataset, num_workers, index):
  return dataset_ops.DatasetV1Adapter(
      _AutoShardDataset(input_dataset, num_workers, index))

class _RebatchDataset(dataset_ops.UnaryDataset):
  """A `Dataset` that divides the batch size by `num_workers`."""

  def __init__(self, input_dataset, num_workers):
    self._input_dataset = input_dataset

    def recalculate_output_shapes(output_shapes):
      """Recalculates the output_shapes after dividing it by num_workers."""
      if len(output_shapes) < 1:
        raise ValueError(
            "Input shape should have at least one dimension. "
            "Perhaps your input dataset is not batched?")
      if (tensor_shape.dimension_value(output_shapes[0]) and
          tensor_shape.dimension_value(output_shapes[0]) % num_workers != 0):
        raise errors.InvalidArgumentError(
            None, None,
            "First dim of input shape: %d is not divisible by num_workers: %d" %
            (output_shapes[0], num_workers))
      output_dims = [d for d in output_shapes.dims]
      output_dims[0] = output_dims[0] // num_workers
      return tensor_shape.TensorShape(output_dims)

    input_types = dataset_ops.get_legacy_output_types(self._input_dataset)
    input_shapes = dataset_ops.get_legacy_output_shapes(self._input_dataset)
    input_classes = dataset_ops.get_legacy_output_classes(self._input_dataset)
    output_shapes = nest.map_structure(recalculate_output_shapes, input_shapes)

    self._structure = structure.convert_legacy_structure(
        input_types, output_shapes, input_classes)
    variant_tensor = ged_ops.experimental_rebatch_dataset(
        self._input_dataset._variant_tensor,  # pylint: disable=protected-access
        num_workers=num_workers,
        **dataset_ops.flat_structure(self))
    super(_RebatchDataset, self).__init__(input_dataset, variant_tensor)

  @property
  def _element_structure(self):
    return self._structure

_AutoShardDatasetV1.__doc__ = _AutoShardDataset.__doc__


text:
// Copyright 2014 Samsung Electronics. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "utc_blink_ewk_base.h"

class utc_blink_ewk_view_javascript_confirm_reply : public utc_blink_ewk_base
{
 protected:

  void LoadFinished(Evas_Object* webview)
  {
    EventLoopStop(utc_blink_ewk_base::Success);
  }

  /* Callback for script confirm */
  static Eina_Bool confirmCallback(Evas_Object* webview, const char* message, void* data)
  {
    Eina_Bool result = EINA_TRUE;
    ewk_view_javascript_confirm_reply(webview, result);
  }
};

/**
 * @brief Positive  test case of ewk_view_javascript_confirm_reply()
 * ewk_view_javascript_confirm_reply() should be performed without any problem.
 */
TEST_F(utc_blink_ewk_view_javascript_confirm_reply, POS_TEST)
{
  ewk_view_javascript_confirm_callback_set(GetEwkWebView(), confirmCallback, this);

  ASSERT_EQ(EINA_TRUE, ewk_view_url_set(GetEwkWebView(), GetResourceUrl("ewk_view/confirm_test.html").c_str()));
  ASSERT_EQ(Success, EventLoopStart());

  const char* title = ewk_view_title_get(GetEwkWebView());
  const char* expected = "You pressed OK!";

  EXPECT_STREQ(expected, title);
}

/**
* @brief Checking whether function works properly in case of NULL of a webview.
*/
TEST_F(utc_blink_ewk_view_javascript_confirm_reply, NEG_TEST)
{
  ewk_view_javascript_confirm_reply(NULL, EINA_FALSE);
}


text:
namespace salamandre
{
    const std::string RegistryRecord::fileName = "FEC";

    RegistryRecord::RegistryRecord(const std::string path)
    {
        this->setFilePath(path);
    }

    RegistryRecord::~RegistryRecord()
    {

    }

    std::string RegistryRecord::serialize(std::string key)
    {
        std::ostringstream os;
        os << *this;
        std::string s = os.str();
        std::string strEncrypt = this->strEncrypt(key, s);

        return Record::strCompress(strEncrypt);
    }

    bool RegistryRecord::unSerialize(std::string key, std::string string)
    {
        std::istringstream is;
        std::string decompressString = Record::strDecompress(string);
        std::string decryptString = this->strDecrypt(key, decompressString);

        if(decryptString != std::string()){
            is.str(decryptString);
            is >> *this;
            return true;
        }

        return false;
    }

    void RegistryRecord::setFirstName(std::string firstName)
    {
        this->firstName = firstName;
    }

    std::string RegistryRecord::getFirstName()
    {
        return this->firstName;
    }

    void RegistryRecord::setLastName(std::string lastName)
    {
        this->lastName = lastName;
    }

    std::string RegistryRecord::getLastName()
    {
        return this->lastName;
    }

    void RegistryRecord::setBirthDate(std::string birthDate)
    {
        this->birthDate = birthDate;
    }

    std::string RegistryRecord::getBirthDate()
    {
        return this->birthDate;
    }

    void RegistryRecord::setSex(std::string sex)
    {
        this->sex = sex;
    }

    std::string RegistryRecord::getSex()
    {
        return this->sex;
    }

    void RegistryRecord::setAdress(std::string adress)
    {
        this->adress = adress;
    }

    std::string RegistryRecord::getAdress()
    {
        return this->adress;
    }
}


text:
namespace Nancy
{
    using System;

    /// <summary>
    /// Default implementation of <see cref="IRootPathProvider"/>.
    /// </summary>
    public class DefaultRootPathProvider : IRootPathProvider
    {
        /// <summary>
        /// Returns the root folder path of the current Nancy application.
        /// </summary>
        /// <returns>A <see cref="string"/> containing the path of the root folder.</returns>
        public string GetRootPath()
        {
#if CORE
            return Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath;
#else
            return AppDomain.CurrentDomain.BaseDirectory;
#endif
        }
    }
}


text:
import user from './user';
import admin from './admin';
import admin_users from './admin_users';
import admin_user from './admin_user';
import admin_dashboard from './admin_dashboard';
import admin_permission from './admin_permission';
import admin_roles from './admin_roles';
import admin_role from './admin_role';
import speakers from './speakers';

export default {
	user: user,
	admin: admin,
	admin_users: admin_users,
	admin_user: admin_user,
	admin_dashboard: admin_dashboard,
	admin_permission: admin_permission,
	admin_roles: admin_roles,
	admin_role: admin_role,
	speakers: speakers,
	hackathon_map: require('./hackathon_map'),
	room: require('./room'),
	event: require('./event'),
	Events: require('./Events'),
	ticket: require('./Ticket'),
	tickets: require('./Tickets'),
	EventRegistration: require('./EventRegistration'),
	EventRegister: require('./EventRegister')
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.github.muellerc.techforum-2016-from-fuse-transform-to-jboss</groupId>
        <artifactId>book-search-fuse</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <groupId>com.github.muellerc.techforum-2016-from-fuse-transform-to-jboss.book-search-fuse</groupId>
    <artifactId>interfaces</artifactId>
    <name>.... interfaces</name>
    <packaging>pom</packaging>

    <modules>
        <module>pricing-service</module>
    </modules>
</project>


text:
import json
import logging
from smtplib import SMTPException

from .rabbit import RabbitWorker
from .models import Collection, Harvest, default_uuid
from .utils import collection_path, get_email_addresses_for_collection_set

from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.urls import reverse
from django.contrib.sites.models import Site
from django.core.mail import send_mail
from django.conf import settings

log = logging.getLogger(__name__)

def collection_harvest(collection_pk):
    with transaction.atomic():
        message = {
            "collection_set": {},
            "collection": {}
        }

        # Retrieve collection
        try:
            collection = Collection.objects.get(id=collection_pk)
        except ObjectDoesNotExist:
            log.error("Harvesting collection %s failed because collection does not exist", collection_pk)
            return

        if not collection.is_on:
            log.debug("Ignoring Harvest for collection as collection %s is off", collection_pk)
            return

        historical_collection = collection.history.all()[0]
        historical_credential = historical_collection.credential.history.all()[0]
        historical_seeds = []
        for seed in collection.seeds.all():
            if seed.is_active:
                historical_seeds.append(seed.history.all()[0])
            else:
                log.debug("Seed %s is ignored from the harvest as it is inactive", seed)

        # Make sure that have the correct number of seeds.
        required_seed_count = collection.required_seed_count()
        if (required_seed_count is None and len(historical_seeds) == 0) or (
                required_seed_count is not None and required_seed_count != len(historical_seeds)):
            log.warning("Collection %s has wrong number of active seeds.", collection_pk)
            return

        # Id
        harvest_id = default_uuid()
        message["id"] = harvest_id

        # Collection set
        collection_set = historical_collection.collection_set
        message["collection_set"]["id"] = collection_set.collection_set_id

        # Collection
        message["collection"]["id"] = historical_collection.collection_id

        # Path
        message["path"] = collection_path(collection)

        # Credential
        message["credentials"] = json.loads(str(historical_credential.token))

        # Type
        harvest_type = historical_collection.harvest_type
        message["type"] = harvest_type

        # Options
        message["options"] = json.loads(historical_collection.harvest_options or "{}")

        # Seeds
        if historical_seeds:
            message["seeds"] = []
            for historical_seed in historical_seeds:
                if historical_seed.is_active:
                    seed_map = dict()
                    seed_map["id"] = historical_seed.seed_id
                    if historical_seed.token:
                        # This may be json
                        try:
                            seed_map["token"] = json.loads(historical_seed.token)
                        except ValueError:
                            seed_map["token"] = historical_seed.token
                    if historical_seed.uid:
                        seed_map["uid"] = historical_seed.uid
                    message["seeds"].append(seed_map)

        routing_key = "harvest.start.{}.{}".format(historical_credential.platform,
                                                   harvest_type)
        # Determine if .priority should be appended
        if collection.harvest_type in settings.PRIORITY_HARVEST_TYPES \
                and collection.schedule_minutes \
                and collection.schedule_minutes <= settings.PRIORITY_SCHEDULE_MINUTES:
            routing_key += ".priority"

        # Skip this harvest if last harvest not completed or voided
        last_harvest = collection.last_harvest()
        if not last_harvest or last_harvest.status in (Harvest.SUCCESS, Harvest.FAILURE, Harvest.VOIDED):
            # Record harvest model instance
            harvest = Harvest.objects.create(harvest_type=harvest_type,
                                             harvest_id=harvest_id,
                                             collection=collection,
                                             historical_collection=historical_collection,
                                             historical_credential=historical_credential)
            harvest.historical_seeds.add(*historical_seeds)
        else:
            log.warning("Skipping harvest with id %s", harvest_id)

            # Set message to None to indicate that should not be sent
            message = None

            # Record harvest model instance
            harvest = Harvest.objects.create(harvest_type=harvest_type,
                                             harvest_id=harvest_id,
                                             collection=collection,
                                             historical_collection=historical_collection,
                                             historical_credential=historical_credential,
                                             status=Harvest.SKIPPED)
            harvest.historical_seeds.add(*historical_seeds)

            # Send notifications
            if settings.PERFORM_EMAILS:
                receiver_emails = get_email_addresses_for_collection_set(harvest.collection.collection_set,
                                                                         use_harvest_notification_preference=True,
                                                                         include_admins=True)
                harvest_url = 'http://{}{}'.format(Site.objects.get_current().domain,
                                                   reverse('harvest_detail', args=(harvest.id,)))
                mail_subject = u"SFM Harvest for {} was skipped".format(
                    harvest.collection.name)
                mail_message = u"The harvest for {} ({}) was skipped. This may be because it is scheduled too " \
                               u"frequently and the last harvest has not had time to complete. It " \
                               u"may also indicate a problem with SFM. The SFM administrator has been notified.".format(
                                harvest.collection.name, harvest_url)

                if receiver_emails:
                    try:
                        log.debug("Sending email to %s: %s", receiver_emails, mail_subject)
                        send_mail(mail_subject, mail_message, settings.EMAIL_FROM,
                                  receiver_emails, fail_silently=False)
                    except SMTPException as ex:
                        log.error("Error sending email: %s", ex)
                    except IOError as ex:
                        log.error("Error sending email: %s", ex)

    # Send message outside the transaction
    if message:
        log.info("Sending %s message to %s with id %s for collection %s", harvest_type,
                 routing_key, harvest_id, collection_pk)

        # Publish message to queue via rabbit worker
        RabbitWorker().send_message(message, routing_key)

@transaction.atomic
def collection_stop(collection_id):
    # Retrieve collection
    try:
        collection = Collection.objects.get(id=collection_id)
    except ObjectDoesNotExist:
        log.error("Stopping harvest of %s failed because collection does not exist", collection_id)
        return
    harvest = collection.last_harvest()
    assert collection.is_streaming()
    if harvest is None or harvest.status not in (Harvest.REQUESTED, Harvest.RUNNING, Harvest.FAILURE):
        log.debug("Ignoring stop harvest of collection since %s does not have a running harvest.")
        return

    message = {
        "id": harvest.harvest_id
    }

    routing_key = "harvest.stop.{}.{}".format(harvest.historical_credential.platform, harvest.harvest_type)

    log.info("Sending %s stop message to %s with id %s for collection %s", harvest.harvest_type, routing_key,
             harvest.harvest_id, collection_id)

    # Publish message to queue via rabbit worker
    RabbitWorker().send_message(message, routing_key)

    # Update harvest model instance
    if harvest.status in (Harvest.REQUESTED, Harvest.RUNNING):
        harvest.status = Harvest.STOP_REQUESTED
        harvest.save()


text:
<?php

namespace CalendArt\Adapter;

use CalendArt\AbstractCalendar;

/**
 * Handle the dialog with an Adapter
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
interface AdapterInterface
{
    /**
     * Get the Calendar API to use for this adapter
     *
     * @return CalendarApiInterface
     */
    public function getCalendarApi();

    /**
     * Get the Event API to use for this adapter
     *
     * @return EventApiInterface
     */
    public function getEventApi();
}


text:
class TModelObject;
class TrainDatasetObject;
class QJsonArray;

class T_MODEL_EXPORT TrainDataset : public TAbstractModel
{
public:
    TrainDataset();
    TrainDataset(const TrainDataset &other);
    TrainDataset(const TrainDatasetObject &object);
    ~TrainDataset();

    int id() const;
    QString dbPath() const;
    void setDbPath(const QString &dbPath);
    QString dbType() const;
    void setDbType(const QString &dbType);
    QString meanPath() const;
    void setMeanPath(const QString &meanPath);
    QDateTime updatedAt() const;
    int lockRevision() const;
    TrainDataset &operator=(const TrainDataset &other);

    bool create() { return TAbstractModel::create(); }
    bool update() { return TAbstractModel::update(); }
    bool save()   { return TAbstractModel::save(); }
    bool remove() { return TAbstractModel::remove(); }

    static TrainDataset create(const QString &dbPath, const QString &dbType, const QString &meanPath);
    static TrainDataset create(const QVariantMap &values);
    static TrainDataset get(int id);
    static TrainDataset get(int id, int lockRevision);
    static int count();
    static QList<TrainDataset> getAll();
    static QJsonArray getAllJson();

private:
    QSharedDataPointer<TrainDatasetObject> d;

    TModelObject *modelData();
    const TModelObject *modelData() const;
};

Q_DECLARE_METATYPE(TrainDataset)
Q_DECLARE_METATYPE(QList<TrainDataset>)

#endif // TRAINDATASET_H


text:
#include "gm.h"
#include "SkRandom.h"
#include "SkRRect.h"

namespace skiagm {

/*
 * This is the base class for two GMs that cover various corner cases with primitive Skia shapes
 * (zero radius, near-zero radius, inner shape overlap, etc.) It uses an xfermode of darken to help
 * double-blended and/or dropped pixels stand out.
 */
class ShapesGM : public GM {
protected:
    ShapesGM(const char* name, bool antialias) : fName(name), fAntialias(antialias) {
        if (!antialias) {
            fName.append("_bw");
        }
    }

    SkString onShortName() override final { return fName; }
    SkISize onISize() override { return SkISize::Make(500, 500); }

    void onOnceBeforeDraw() override {
        fShapes.push_back().setOval(SkRect::MakeXYWH(-5, 25, 200, 100));
        fRotations.push_back(21);

        fShapes.push_back().setRect(SkRect::MakeXYWH(95, 75, 125, 100));
        fRotations.push_back(94);

        fShapes.push_back().setRectXY(SkRect::MakeXYWH(0, 75, 150, 100), 1e-5f, 1e-5f);
        fRotations.push_back(132);

        fShapes.push_back().setRectXY(SkRect::MakeXYWH(15, -20, 100, 100), 20, 15);
        fRotations.push_back(282);

        fSimpleShapeCount = fShapes.count();

        fShapes.push_back().setNinePatch(SkRect::MakeXYWH(140, -50, 90, 110), 10, 5, 25, 35);
        fRotations.push_back(0);

        fShapes.push_back().setNinePatch(SkRect::MakeXYWH(160, -60, 60, 90), 10, 60, 50, 30);
        fRotations.push_back(-35);

        fShapes.push_back().setNinePatch(SkRect::MakeXYWH(220, -120, 60, 90), 1, 89, 59, 1);
        fRotations.push_back(65);

        SkVector radii[4] = {{4, 6}, {12, 8}, {24, 16}, {32, 48}};
        fShapes.push_back().setRectRadii(SkRect::MakeXYWH(150, -129, 80, 160), radii);
        fRotations.push_back(265);

        SkVector radii2[4] = {{0, 0}, {80, 60}, {0, 0}, {80, 60}};
        fShapes.push_back().setRectRadii(SkRect::MakeXYWH(180, -30, 80, 60), radii2);
        fRotations.push_back(295);

        fPaint.setAntiAlias(fAntialias);
    }

    void onDraw(SkCanvas* canvas) override {
        canvas->clear(SK_ColorWHITE);

        canvas->save();
        canvas->translate(canvas->imageInfo().width() / 2.f, canvas->imageInfo().height() / 2.f);
        this->drawShapes(canvas);
        canvas->restore();
    }

    virtual void drawShapes(SkCanvas* canvas) const = 0;

protected:
    SkString             fName;
    bool                 fAntialias;
    SkPaint              fPaint;
    SkTArray<SkRRect>    fShapes;
    SkTArray<SkScalar>   fRotations;
    int                  fSimpleShapeCount;

private:
    typedef GM INHERITED;
};

class SimpleShapesGM : public ShapesGM {
public:
    SimpleShapesGM(bool antialias) : INHERITED("simpleshapes", antialias) {}

private:
    void drawShapes(SkCanvas* canvas) const override {
        SkRandom rand(2);
        for (int i = 0; i < fShapes.count(); i++) {
            SkPaint paint(fPaint);
            paint.setColor(rand.nextU() & ~0x808080);
            paint.setAlphaf(0.5f);  // Use alpha to detect double blends.
            const SkRRect& shape = fShapes[i];
            canvas->save();
            canvas->rotate(fRotations[i]);
            switch (shape.getType()) {
                case SkRRect::kRect_Type:
                    canvas->drawRect(shape.rect(), paint);
                    break;
                case SkRRect::kOval_Type:
                    canvas->drawOval(shape.rect(), paint);
                    break;
                default:
                    canvas->drawRRect(shape, paint);
                    break;
            }
            canvas->restore();
        }
    }

    typedef ShapesGM INHERITED;
};

class InnerShapesGM : public ShapesGM {
public:
    InnerShapesGM(bool antialias) : INHERITED("innershapes", antialias) {}

private:
    void drawShapes(SkCanvas* canvas) const override {
        SkRandom rand;
        for (int i = 0; i < fShapes.count(); i++) {
            const SkRRect& outer = fShapes[i];
            const SkRRect& inner = fShapes[(i * 7 + 11) % fSimpleShapeCount];
            float s = 0.95f * SkTMin(outer.rect().width() / inner.rect().width(),
                                     outer.rect().height() / inner.rect().height());
            SkMatrix innerXform;
            float dx = (rand.nextF() - 0.5f) * (outer.rect().width() - s * inner.rect().width());
            float dy = (rand.nextF() - 0.5f) * (outer.rect().height() - s * inner.rect().height());
            innerXform.setTranslate(outer.rect().centerX() + dx, outer.rect().centerY() + dy);
            if (s < 1) {
                innerXform.preScale(s, s);
            }
            innerXform.preTranslate(-inner.rect().centerX(), -inner.rect().centerY());
            SkRRect xformedInner;
            inner.transform(innerXform, &xformedInner);
            SkPaint paint(fPaint);
            paint.setColor(rand.nextU() & ~0x808080);
            paint.setAlphaf(0.5f);  // Use alpha to detect double blends.
            canvas->save();
            canvas->rotate(fRotations[i]);
            canvas->drawDRRect(outer, xformedInner, paint);
            canvas->restore();
        }
    }

    typedef ShapesGM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

DEF_GM( return new SimpleShapesGM(true); )
DEF_GM( return new SimpleShapesGM(false); )
DEF_GM( return new InnerShapesGM(true); )
DEF_GM( return new InnerShapesGM(false); )

}