text:
> **Challenge 1: Retrieve Product Information**
Adventure Works sells many products that are variants of the same product model. You must write
queries that retrieve information about these products

####1. Retrieve product model descriptions
Retrieve the product ID, product name, product model name, and product model summary for each
product from the SalesLT.Product table and the SalesLT.vProductModelCatalogDescription view.
```sql
SELECT	p.ProductID
		,p.Name AS ProductName
		,vPMCD.Name AS ProductModel
		,vPMCD.Summary AS Description
FROM SalesLT.Product AS p
JOIN SalesLT.vProductModelCatalogDescription AS vPMCD
	ON p.ProductModelID = vPMCD.ProductModelID
ORDER BY p.ProductID
```
####2. Create a table of distinct colors
```
Tip: Review the documentation for Variables in Transact-SQL Language Reference.
```
Create a table variable and populate it with a list of distinct colors from the SalesLT.Product table. Then
use the table variable to filter a query that returns the product ID, name, and color from the
SalesLT.Product table so that only products with a color listed in the table variable are returned.
```sql
DECLARE @Kolor AS TABLE
(Color nvarchar(15))

INSERT INTO @Kolor(Color)
	SELECT DISTINCT Color
	FROM SalesLT.Product

SELECT	ProductID
		,Name
		,Color
FROM SalesLT.Product
WHERE Color IN (SELECT Color FROM @Kolor)
```
####3. Retrieve product parent categories
The AdventureWorksLT database includes a table-valued function named dbo.ufnGetAllCategories,
which returns a table of product categories (for example 'Road Bikes') and parent categories (for
example 'Bikes'). Write a query that uses this function to return a list of all products including their
parent category and category.
```sql
SELECT	p.Name AS ProductName
		,func.ProductCategoryName AS ProductCategory
		,func.ParentProductCategoryName AS ParentProductCategory
FROM SalesLT.Product AS p
JOIN dbo.ufnGetAllCategories() AS func
	ON p.ProductCategoryID = func.ProductCategoryID
ORDER BY ParentProductCategory, ProductCategory, ProductName
```


text:
'use strict'

const seneca = require('seneca')();
const config = require('./config');
const logger = require('./lib/logger');
const mailer = require('./lib/mailer');
const RabbitMQTransport = require('seneca-rabbitmq-transport');
//const act = Promise.promisify(seneca.act);

logger.debug('loading actions');
const MailingPlugin = require("./actions/mailing");

logger.debug('registering plugins');
seneca
    .use('mesh', {
        bash: true
    })
    .use(RabbitMQTransport)
    .use(MailingPlugin, {
        mailer: mailer.create({
            apiKey: config.apiKey,
            domain: config.domain
        })
    });

seneca.ready(err => {
    if (err) {
        logger.log('error', 'Seneca failed to get ready!');
        return;
    }

    logger.log('info', 'Seneca listening on port: %s', config.port);
    seneca.listen({
        port: config.port
    })
});

redpajama_set_name: RedPajamaGithub


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

    <include layout="@layout/layout_header_action_bar"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/main_good"
        android:orientation="vertical" >

       <!--  <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <ImageButton
                android:id="@+id/about_us_back"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:background="@null"
                android:clickable="true"
                android:src="@drawable/ic_ab_back" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:gravity="center"
                android:text="@string/main_popwindow_about_us"
                android:textColor="@color/white"
                android:textSize="16sp" />
        </LinearLayout> -->

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <ImageView
                android:id="@+id/imageLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:scaleType="fitCenter"
                android:src="@drawable/ic_onetouch" />

            <TextView android:id="@+id/textVersionname"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_below="@+id/imageLogo"
                android:layout_marginTop="20dp"
                android:textColor="@color/white"
                android:textSize="16sp"
                   ></TextView>
        </RelativeLayout>
    </LinearLayout>

   <!--  <RelativeLayout android:id="@+id/layout_checkupdate"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:onClick="onClick" >
         <TextView
	        android:id="@+id/textView1"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_centerVertical="true"
	        android:layout_marginLeft="25dp"
	        android:layout_marginStart="25dp"
	        android:textSize="17sp"
	        android:singleLine="true"
	        android:textColor="@color/fragment_list_item_text1_color"
	        android:text="@string/about_checkupate_text" />

         <ImageView
             android:layout_width="wrap_content"
	       	 android:layout_height="wrap_content"
	       	 android:layout_centerVertical="true"
	       	 android:layout_alignParentRight="true"
	       	 android:layout_alignParentEnd="true"
	        android:layout_marginRight="25dp"
	        android:layout_marginEnd="25dp"
	        android:src="@drawable/ic_go" />

    </RelativeLayout> -->
        <!-- <View android:layout_width="match_parent"
        android:layout_height="0.3dp"
        android:background="@color/dialog_textcolor_msg" /> -->

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>


text:
require 'test_helper'

class Exporter::JekyllTest < ActiveSupport::TestCase
  def setup
    @space = create :space
    2.times { create :article, :space => @space }

    @exporter = Exporter::Jekyll.new(@space)
  end

  test "should export" do
    @exporter.export
    assert File.exists?("#{@exporter.output_path}/jekyll.zip")
  end
end


text:
unset PYTHONPATH
python3 -m venv build/venv
. build/venv/bin/activate

pip install --upgrade build twine
python -m build
twine check dist/*

echo 'When ready, upload to PyPI using: build/venv/bin/twine upload dist/*'


text:
var map = require('../..');

module.exports = function (arr) {
  return map(arr, function (ele) {
    return ele + ele;
  });
};


text:
@interface XXColumnChartView : UIView

- (instancetype)initWithValues:(NSArray *)values xTittles:(NSArray *)xTittles yTittleCount:(NSInteger)yTittleCount;
+ (instancetype)chartViewWithValues:(NSArray *)values xTittles:(NSArray *)xTittles yTittleCount:(NSInteger)yTittleCount;

@property (nonatomic, assign) NSInteger yTittleCount;
@property (nonatomic, strong) NSArray *xTittles;
@property (nonatomic, strong) NSArray *values;
@property (nonatomic, strong) UIColor *tintColor;
@property (nonatomic, strong) UIColor *axisTitleColor;

@property (nonatomic, strong) UIColor *axisColor;
@property (nonatomic, strong) UIColor *backLineColor;
@property (nonatomic, strong) UIColor *circleColor;
@property (nonatomic, strong) UIColor *lineColor;
@property (nonatomic, strong) UIColor *downColor;

@end


text:
<?php

/**
 * Program form base class.
 *
 * @method Program getObject() Returns the current form's model object
 *
 * @package    alumni
 * @subpackage form
 * @author     E.R. Nurwijayadi <epsi.rns@gmail.com>
 * @version    SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $
 */
abstract class BaseProgramForm extends BaseFormDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'program_id' => new sfWidgetFormInputHidden(),
    ));

    $this->setValidators(array(
      'program_id' => new sfValidatorChoice(array('choices' => array($this->getObject()->get('program_id')), 'empty_value' => $this->getObject()->get('program_id'), 'required' => false)),
    ));

    $this->widgetSchema->setNameFormat('program[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'Program';
  }

}


text:
package gettingStarted

import org.specs2.mutable.Specification
import play.api._

package consoleapp {
  class MyPlayConsole {
    def createApplication() = {
      //#consoleapp
      import play.api._
      val env     = Environment(new java.io.File("."), this.getClass.getClassLoader, Mode.Dev)
      val context = ApplicationLoader.Context.create(env)
      val loader  = ApplicationLoader(context)
      val app     = loader.load(context)
      Play.start(app)
      //#consoleapp
      app
    }
  }
}

class PlayConsole extends Specification {
  "Play console" should {
    "support creating an instance of the Play application" in {
      val app = new gettingStarted.consoleapp.MyPlayConsole().createApplication()
      app must beAnInstanceOf[Application]
    }
  }
}


text:
layout: newsstory
title: TOO WET
match: Cinderford P Yeltz P
---

The recent wet weather caused the game down in Cinderford to be called off. However it wasn't too bad a day with several other results going our way somewhat.

Despite Redditch only drawing and Gloucester losing again, we're down to  5th in the table  with Cirencester looking the main hope to catch Redditch at the moment. They lost their first 4 games, so it's been an amazing run of 12 wins and 2 draws since.

We start a run of 4 home games on Tuesday against lowly Rushall Olympic in the B'ham Senior Cup before Swindon Supermarine visit The Grove on Saturday.


text:
<?php
namespace Cron\Controller;

use Application\Controller\BaseController;
use Cron\Service\CronServiceInterface;
use Cron\Form\CronForm;
use Zend\View\Model\ViewModel;

class UpdateController extends BaseController
{
    /**
    *
    * @var CronServiceInterface
    */
    protected $cronService;

    /**
     *
     * @var CronForm
     */
    protected $form;

    /**
     *
     * @param CronServiceInterface $cronService
     * @param CronForm $form
     */
    public function __construct(CronServiceInterface $cronService, CronForm $form)
    {
        $this->cronService = $cronService;

        $this->form = $form;
    }

    /**
     *
     * {@inheritDoc}
     * @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        $request = $this->getRequest();

        $cronId = $this->params('cronId');

        $cronEntity = $this->cronService->get($cronId);

        if(! $cronEntity) {
            $this->flashMessenger()->addErrorMessage('Cron not found');

            return $this->redirect()->toRoute('cron-index');
        }

        // if we have a post
        if ($request->isPost()) {

            $postData = $request->getPost();

            $this->form->setData($postData);

            // if the form is valid
            if ($this->form->isValid()) {
                $entity = $this->form->getData();

                $cronEntity = $this->cronService->save($entity);

                // trigger event
                $this->getEventManager()->trigger('cronCreate', $this, array(
                    'cronEntity' => $cronEntity,
                    'authId' => $this->identity()->getAuthId(),
                    'historyUrl' => $this->getRequest()->getUri()
                ));

                $this->flashMessenger()->addSuccessMessage('Cron was saved');

                return $this->redirect()->toRoute('cron-index');
            }
        }

        $this->form->bind($cronEntity);

        return new ViewModel(array(
            'form' => $this->form
        ));
    }
}

?>


text:
package de.esri.geotrigger.core;

import org.apache.http.Header;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicHeader;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.json.JSONObject;

public class GeotriggerApiClient {
	private static Logger log = LogManager.getLogger(GeotriggerApiClient.class.getName());
	private static final String GEOTRIGGER_BASE_URL = "https://geotrigger.arcgis.com";

    private GeotriggerApiClient()
    {
    }

    /**
     * Run a request to the geotrigger service.
     * @param route The route of the geotrigger endpoint (like "trigger/create").
     * @param listener The GeotriggerApiListener.
     */
    public static void runRequest(String route, GeotriggerApiListener listener){
        runRequest(route, null, listener);
    }

    /**
     * Run a request to the geotrigger service.
     * @param route The route of the geotrigger endpoint (like "trigger/create").
     * @param params The parameter JSON object.
     * @param listener The GeotriggerApiListener.
     */
    public static void runRequest(String route, JSONObject params, final GeotriggerApiListener listener){
    	String url = new StringBuilder().append(GEOTRIGGER_BASE_URL).append("/").append(route).toString();
    	Header headers[] = {
    			new BasicHeader("Authorization", String.format("Bearer %s", Params.get().getAccessToken()))
    	};
    	log.debug("Sending request to geotrigger service: " + url);
    	for (Header header : headers) {
    		log.debug("Header: " + header.getName() + " " + header.getValue());
		}
    	log.debug("Request: " + params.toString());
    	HttpUtil.postJsonRequest(url, headers, params, new JsonRequestListener() {
			@Override
			public void onSuccess(JSONObject jsonObject) {
				JSONObject errorObject = jsonObject.optJSONObject("error");
				if(errorObject == null){
					log.debug("Response: " + jsonObject.toString());
					listener.onSuccess(jsonObject);
				}else{
					int errorCode = errorObject.optInt("code", 400);
					log.error("Error executing geotrigger request. Code: " + errorCode);
					if(errorCode == 498){
						// handle refresh token
					}else{
						String response = jsonObject.toString();
						log.error("Error response: " + response);
                        String message = "";
                        for(int i = response.indexOf("\"message\":"); i > 0; i = response.indexOf("\"message\":", i + 11)){
                            message = (new StringBuilder()).append(message).append(response.substring(i + 10, response.indexOf("\"", i + 11)).replaceAll("\"", "")).append("; ").toString();
                        }
                        listener.onFailure(new Exception(message));
					}
				}
			}

			@Override
			public void onError(JSONObject jsonObject, StatusLine statusLine) {
				listener.onFailure(new Exception(statusLine.getReasonPhrase()));
			}

			@Override
			public void onFailure(Throwable error) {
				listener.onFailure(new Exception(error));
			}
		});
    }
}


text:
<?php

namespace Forum\Model;

class User{
    public $user_id;
    public $username;
    public $password;        // maybe a bad idea to have these public?
    public $level;
    //public user_date;

    public function exchangeArray($data)
    {
        $this->user_id  = (!empty($data['user_id'])) ? $data['user_id'] : null;
        $this->username = (!empty($data['username'])) ? $data['username'] : null;
        $this->password = (!empty($data['password'])) ? $data['password'] : null;
        $this->level = (!empty($data['level'])) ? $data['level'] : null;

        // $this->replies  = (!empty($data['replies'])) ? $data['replies'] : null;
        // $this->lastpost = (!empty($data['lastpost'])) ? $lastpost['lastpost'} : null;
    }

}


text:
require File.expand_path '../../test_helper', __dir__

# Test class for List Public Ips Request
class TestListPublicIps < Minitest::Test
  def setup
    @service = Fog::Network::AzureRM.new(credentials)
    @network_client = @service.instance_variable_get(:@network_client)
    @public_ips = @network_client.public_ipaddresses
  end

  def test_list_public_ips_success
    mocked_response = ApiStub::Requests::Network::PublicIp.list_public_ips_response(@network_client)
    @public_ips.stub :list_as_lazy, mocked_response do
      assert_equal @service.list_public_ips('fog-test-rg'), mocked_response.value
    end
  end

  def test_list_public_ips_failure
    response = proc { raise MsRestAzure::AzureOperationError.new(nil, nil, 'error' => { 'message' => 'mocked exception' }) }
    @public_ips.stub :list_as_lazy, response do
      assert_raises(MsRestAzure::AzureOperationError) { @service.list_public_ips('fog-test-rg') }
    end
  end
end


text:
package org.optaplanner.core.impl.heuristic.selector.value.decorator;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.optaplanner.core.impl.testdata.util.PlannerAssert.assertAllCodesOfValueSelectorForEntity;
import static org.optaplanner.core.impl.testdata.util.PlannerAssert.verifyPhaseLifecycle;

import java.util.Arrays;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.optaplanner.core.impl.heuristic.selector.SelectorTestUtils;
import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import org.optaplanner.core.impl.heuristic.selector.value.ValueSelector;
import org.optaplanner.core.impl.phase.scope.AbstractPhaseScope;
import org.optaplanner.core.impl.phase.scope.AbstractStepScope;
import org.optaplanner.core.impl.solver.scope.SolverScope;
import org.optaplanner.core.impl.testdata.domain.TestdataEntity;
import org.optaplanner.core.impl.testdata.domain.TestdataSolution;
import org.optaplanner.core.impl.testdata.domain.TestdataValue;

class FilteringValueSelectorTest {

    @Test
    void filterEntityDependent() {
        TestdataEntity entity = new TestdataEntity("e1");
        ValueSelector childValueSelector = SelectorTestUtils.mockValueSelector(
                TestdataEntity.class, "value",
                new TestdataValue("v1"), new TestdataValue("v2"), new TestdataValue("v3"), new TestdataValue("v4"));

        SelectionFilter<TestdataSolution, TestdataValue> filter = (scoreDirector, value) -> !value.getCode().equals("v3");
        List<SelectionFilter> filterList = Arrays.asList(filter);
        ValueSelector valueSelector = new FilteringValueSelector(childValueSelector, filterList);

        SolverScope solverScope = mock(SolverScope.class);
        valueSelector.solvingStarted(solverScope);

        AbstractPhaseScope phaseScopeA = mock(AbstractPhaseScope.class);
        when(phaseScopeA.getSolverScope()).thenReturn(solverScope);
        valueSelector.phaseStarted(phaseScopeA);

        AbstractStepScope stepScopeA1 = mock(AbstractStepScope.class);
        when(stepScopeA1.getPhaseScope()).thenReturn(phaseScopeA);
        valueSelector.stepStarted(stepScopeA1);
        assertAllCodesOfValueSelectorForEntity(valueSelector, entity, 4L, "v1", "v2", "v4");
        valueSelector.stepEnded(stepScopeA1);

        AbstractStepScope stepScopeA2 = mock(AbstractStepScope.class);
        when(stepScopeA2.getPhaseScope()).thenReturn(phaseScopeA);
        valueSelector.stepStarted(stepScopeA2);
        assertAllCodesOfValueSelectorForEntity(valueSelector, entity, 4L, "v1", "v2", "v4");
        valueSelector.stepEnded(stepScopeA2);

        valueSelector.phaseEnded(phaseScopeA);

        AbstractPhaseScope phaseScopeB = mock(AbstractPhaseScope.class);
        when(phaseScopeB.getSolverScope()).thenReturn(solverScope);
        valueSelector.phaseStarted(phaseScopeB);

        AbstractStepScope stepScopeB1 = mock(AbstractStepScope.class);
        when(stepScopeB1.getPhaseScope()).thenReturn(phaseScopeB);
        valueSelector.stepStarted(stepScopeB1);
        assertAllCodesOfValueSelectorForEntity(valueSelector, entity, 4L, "v1", "v2", "v4");
        valueSelector.stepEnded(stepScopeB1);

        AbstractStepScope stepScopeB2 = mock(AbstractStepScope.class);
        when(stepScopeB2.getPhaseScope()).thenReturn(phaseScopeB);
        valueSelector.stepStarted(stepScopeB2);
        assertAllCodesOfValueSelectorForEntity(valueSelector, entity, 4L, "v1", "v2", "v4");
        valueSelector.stepEnded(stepScopeB2);

        AbstractStepScope stepScopeB3 = mock(AbstractStepScope.class);
        when(stepScopeB3.getPhaseScope()).thenReturn(phaseScopeB);
        valueSelector.stepStarted(stepScopeB3);
        assertAllCodesOfValueSelectorForEntity(valueSelector, entity, 4L, "v1", "v2", "v4");
        valueSelector.stepEnded(stepScopeB3);

        valueSelector.phaseEnded(phaseScopeB);

        valueSelector.solvingEnded(solverScope);

        verifyPhaseLifecycle(childValueSelector, 1, 2, 5);
        verify(childValueSelector, times(5)).iterator(entity);
        verify(childValueSelector, times(5)).getSize(entity);
    }

}


text:
@interface LocationDetailBodyCell : UITableViewCell

@property (nonatomic, weak) IBOutlet UITextView *textView;

@end


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

  angular.module('frontend.services', [
    'angular.chips',
    'ngFileUpload'
  ]);

  // Module configuration
  angular.module('frontend.services')
    .config([
      '$stateProvider',
      function config($stateProvider) {
        $stateProvider
          .state('services', {
            parent: 'frontend',
            url: '/services',
            data: {
              activeNode: true,
              pageName: "Services",
              pageDescription: "Service entities, as the name implies, are abstractions of each of your own upstream services. Examples of Services would be a data transformation microservice, a billing API, etc.",
              //displayName : "services",
              prefix: 'cloud_queue'
            },
            views: {
              'content@': {
                templateUrl: 'js/app/services/views/services.html',
                controller: 'ServicesController',
              }
            }
          })
          .state('services.read', {
            url: '/:service_id/read',
            data: {
              pageName: "Show Service",
              pageDescription: "",
              displayName: "show",
              prefix: ''
            },
            views: {
              'content@': {
                templateUrl: 'js/app/services/views/edit-service.html',
                controller: 'ServiceController',
                resolve: {
                  _service: [
                    'ServiceService', '$stateParams',
                    function resolve(ServiceService, $stateParams) {
                      return ServiceService.findById($stateParams.service_id);
                    }
                  ],
                  _gateway: [
                    'InfoService',
                    '$rootScope',
                    function (InfoService, $rootScope) {
                      return new Promise((resolve, reject) => {
                        var watcher = $rootScope.$watch('Gateway', function (newValue, oldValue) {
                          if (newValue) {
                            watcher(); // clear watcher
                            resolve(newValue)
                          }
                        })
                      })
                    }
                  ],
                  _activeNode: [
                    'NodesService',
                    function resolve(NodesService) {
                      return NodesService.isActiveNodeSet();
                    }
                  ],
                }

              },
              'details@services.read': {
                templateUrl: 'js/app/services/views/service-details.html',
                controller: 'ServiceDetailsController',
              },
              'routes@services.read': {
                templateUrl: 'js/app/services/views/service-routes.html',
                controller: 'ServiceRoutesController'
              },
              'consumers@services.read': {
                templateUrl: 'js/app/services/views/service-consumers.html',
                controller: 'ServiceConsumersController'
              },
              'plugins@services.read': {
                templateUrl: 'js/app/services/views/service-plugins.html',
                controller: 'ServicePluginsController',
                // resolve: {
                //   _plugins: [
                //     'PluginsService', '$stateParams',
                //     function (PluginsService, $stateParams) {
                //       return PluginsService.load({service_id: $stateParams.service_id})
                //     }
                //   ]
                // }
              },
              'healthchecks@services.read': {
                templateUrl: 'js/app/services/views/service-health-checks.html',
                controller: 'ServiceHealthChecksController',
              }
            }
          })
          .state('services.plugins', {
            url: '/:service_id/plugins',
            params: {
              service: {}
            },
            data: {
              pageName: "Service Plugins",
              displayName: "Service plugins"
            },
            views: {
              'content@': {
                templateUrl: 'js/app/services/views/service-plugins.html',
                controller: 'ServicePluginsController',
                resolve: {
                  _service: [
                    'ServiceService', '$stateParams',
                    function (ServiceService, $stateParams) {
                      return ServiceService.findById($stateParams.service_id)
                    }
                  ],
                  _plugins: [
                    'PluginsService', '$stateParams',
                    function (PluginsService, $stateParams) {
                      return PluginsService.load({
                        service_id: $stateParams.service_id
                      })
                    }
                  ],
                  _activeNode: [
                    'NodesService',
                    function resolve(NodesService) {

                      return NodesService.isActiveNodeSet()
                    }
                  ],
                }
              }
            },
          })
          .state('services.plugins.manage', {
            url: '/manage',
            data: {
              pageName: "Manage Service Plugins",
              displayName: "manage"
            },
            views: {
              'content@': {
                templateUrl: 'js/app/services/views/plugins/manage/manage-service-plugins.html',
                controller: 'ManageServicePluginsController',
                resolve: {
                  _service: [
                    '$stateParams',
                    'ServiceService',
                    '$log',
                    function resolve(
                      $stateParams,
                      ServiceService,
                      $log
                    ) {
                      return ServiceService.findById($stateParams.service_id)
                    }
                  ],
                  _plugins: [
                    '$stateParams',
                    'ServiceService',
                    '$log',
                    function resolve(
                      $stateParams,
                      ServiceService,
                      $log
                    ) {
                      return ServiceService.plugins($stateParams.service_id)
                    }
                  ],
                  _info: [
                    '$stateParams',
                    'InfoService',
                    '$log',
                    function resolve(
                      $stateParams,
                      InfoService,
                      $log
                    ) {
                      return InfoService.getInfo()
                    }
                  ],
                  _activeNode: [
                    'NodesService',
                    function resolve(NodesService) {

                      return NodesService.isActiveNodeSet()
                    }
                  ],
                }
              }
            },
          })
      }
    ])
  ;
}());


text:
package org.apache.fineract.portfolio.charge.exception;

import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException;

public class LoanChargeCannotBePayedException extends AbstractPlatformDomainRuleException {

    /*** enum of reasons of why Loan Charge cannot be waived **/
    public static enum LOAN_CHARGE_CANNOT_BE_PAYED_REASON {
        ALREADY_PAID, ALREADY_WAIVED, LOAN_INACTIVE, CHARGE_NOT_ACCOUNT_TRANSFER, CHARGE_NOT_PAYABLE;

        public String errorMessage() {
            if (name().toString().equalsIgnoreCase("ALREADY_PAID")) {
                return "This loan charge has been completely paid";
            } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) {
                return "This loan charge has already been waived";
            } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) {
                return "This loan charge can be payed as the loan associated with it is currently inactive";
            } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) {
                return "This loan charge can be payed as the charge payment mode is not account transfer";
            } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { return "This loan charge is not Payable through account transfer"; }

            return name().toString();
        }

        public String errorCode() {
            if (name().toString().equalsIgnoreCase("ALREADY_PAID")) {
                return "error.msg.loan.charge.already.paid";
            } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) {
                return "error.msg.loan.charge.already.waived";
            } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) {
                return "error.msg.loan.charge.associated.loan.inactive";
            } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) {
                return "error.msg.loan.charge.payment.mode.not.account.transfer";
            } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_PAYABLE")) { return "error.msg.loan.charge.payment.not.allowed.account.transfer"; }
            return name().toString();
        }
    }

    public LoanChargeCannotBePayedException(final LOAN_CHARGE_CANNOT_BE_PAYED_REASON reason, final Long loanChargeId) {
        super(reason.errorCode(), reason.errorMessage(), loanChargeId);
    }
}


text:
#ifndef _ARKDENSE_H
#define _ARKDENSE_H

#include <arkode/arkode_direct.h>
#include <sundials/sundials_dense.h>

#ifdef __cplusplus  /* wrapper to enable C++ usage */
extern "C" {
#endif

/*---------------------------------------------------------------
 Function: ARKDense
-----------------------------------------------------------------
 A call to the ARKDense function links the main integrator with
 the ARKDENSE linear solver.

 arkode_mem is the pointer to the integrator memory returned by
            ARKodeCreate.

 N is the size of the ODE system.

 The return value of ARKDense is one of:
    ARKDLS_SUCCESS   if successful
    ARKDLS_MEM_NULL  if the arkode memory was NULL
    ARKDLS_MEM_FAIL  if there was a memory allocation failure
    ARKDLS_ILL_INPUT if a required vector operation is missing
---------------------------------------------------------------*/
SUNDIALS_EXPORT int ARKDense(void *arkode_mem, long int N);

/*---------------------------------------------------------------
 Function: ARKMassDense
-----------------------------------------------------------------
 A call to the ARKMassDense function links the mass matrix solve
 with the ARKDENSE linear solver.

 arkode_mem is the pointer to the integrator memory returned by
            ARKodeCreate.

 N is the size of the ODE system.

 dmass is the user-supplied dense mass matrix setup function.

 The return value of ARKMassDense is one of:
    ARKDLS_SUCCESS   if successful
    ARKDLS_MEM_NULL  if the arkode memory was NULL
    ARKDLS_MEM_FAIL  if there was a memory allocation failure
    ARKDLS_ILL_INPUT if a required vector operation is missing
---------------------------------------------------------------*/
SUNDIALS_EXPORT int ARKMassDense(void *arkode_mem, long int N,
				 ARKDlsDenseMassFn dmass);

#ifdef __cplusplus
}
#endif

#endif


text:
function a = asmatrix(varargin)
numpy = pyimport('numpy');
a = numpy.asmatrix(varargin{:});

% Copyright (c) 2009 Ken Watford (kwatford@cise.ufl.edu)
% For full license details, see the LICENSE file.


text:
using namespace legion;

#define OPTIX_CATCH_RETHROW                                                    \
    catch ( optix::Exception& e )                                              \
    {                                                                          \
        throw legion::Exception( std::string("OPTIX_EXCEPTION: ")+e.what() );  \
    }                                                                          \
    catch ( std::exception& e )                                                \
    {                                                                          \
        throw legion::Exception( std::string("OPTIX_EXCEPTION: ")+e.what() );  \
    }                                                                          \
    catch (...)                                                                \
    {                                                                          \
        throw legion::Exception( std::string("OPTIX_EXCEPTION: unknown") );    \
    }

#define OPTIX_CATCH_WARN                                                       \
    catch ( optix::Exception& e )                                              \
    {                                                                          \
        LLOG_WARN << "OPTIX_EXCEPTION: " << e.what();                          \
    }                                                                          \
    catch ( std::exception& e )                                                \
    {                                                                          \
        LLOG_WARN << "OPTIX_EXCEPTION: " << e.what();                          \
    }                                                                          \
    catch (...)                                                                \
    {                                                                          \
        LLOG_WARN << "OPTIX_EXCEPTION: Unknown";                               \
    }

OptiXScene::OptiXScene()
    : m_optix_context( optix::Context::create() ),
      m_program_mgr( m_optix_context ),
      m_renderer( 0u ),
      m_camera( 0u ),
      m_accel_cache_loaded( false )
{
    m_program_mgr.addPath( PTX_DIR );
    initializeOptixContext();

    m_light_sample_buffer = m_optix_context->createBuffer(
        RT_BUFFER_INPUT,
        RT_FORMAT_PROGRAM_ID,
        0 // initially empty
        );
    m_optix_context[ "legionLightSampleFuncs" ]->set( m_light_sample_buffer );

    m_light_eval_buffer = m_optix_context->createBuffer(
        RT_BUFFER_INPUT,
        RT_FORMAT_PROGRAM_ID,
        0 // initially empty
        );
    m_optix_context[ "legionLightEvaluateFuncs" ]->set( m_light_eval_buffer );
}

OptiXScene::~OptiXScene()
{
    m_optix_context->destroy();
}

void OptiXScene::setRenderer( IRenderer* renderer )
{
    m_raygen_program =
            m_program_mgr.get( std::string( renderer->name() ) + ".ptx",
                               renderer->rayGenProgramName() );

    m_optix_context->setRayGenerationProgram( 0, m_raygen_program );

    m_renderer = renderer;
}

void OptiXScene::setCamera( ICamera* camera )
{
    m_camera = camera;
    try
    {
        m_create_ray_program =
            m_program_mgr.get( std::string( camera->name() ) + ".ptx",
                               camera->createRayFunctionName() );
        m_create_ray_program->getId();

        m_optix_context[ "legionCameraCreateRay" ]->set( m_create_ray_program );
    }
    OPTIX_CATCH_RETHROW;
}

void OptiXScene::setEnvironment( IEnvironment* environment )
{
    m_environment = environment;

    try
    {
        // If we have not created a miss program, create now
        if( !m_environment_program )
        {
            m_environment_program =
                m_program_mgr.get( "Environment.ptx", "legionEnvironment" );
            m_optix_context->setMissProgram( RADIANCE_TYPE, m_environment_program );
        }

        // Get environment programs
        m_environment_miss_evaluate =
            m_program_mgr.get( std::string( environment->name() ) + ".ptx",
                               environment->missEvaluateFunctionName() );
        m_environment_miss_evaluate->getId();

        m_environment_light_evaluate =
            m_program_mgr.get( std::string( environment->name() ) + ".ptx",
                               environment->lightEvaluateFunctionName() );
        m_environment_light_evaluate->getId();

        m_environment_sample =
            m_program_mgr.get( std::string( environment->name() ) + ".ptx",
                    environment->sampleFunctionName() );
        m_environment_sample->getId();

        // Set miss program evaluator
        m_optix_context[ "legionEnvironmentMissEvaluate" ]->set(
                m_environment_miss_evaluate
                );

        // Add light
        m_light_sample_ids.push_back( m_environment_sample->getId() );
        m_light_eval_ids.push_back( m_environment_light_evaluate->getId() );
    }
    OPTIX_CATCH_RETHROW;
}

void OptiXScene::addLight( ILight* light )
{
    LLOG_INFO << "Light: " << light;
    LEGION_TODO();
}

void OptiXScene::addGeometry( IGeometry* geometry )
{
    // TODO: break this into separate creation functions, eg, createMaterial,
    //       createGeometry, createLight
    try
    {
        // Load the geometry programs
        optix::Program intersect =
            m_program_mgr.get( std::string( geometry->name() ) + ".ptx",
                               geometry->intersectionFunctionName() );

        optix::Program bbox =
            m_program_mgr.get( std::string( geometry->name() ) + ".ptx",
                               geometry->boundingBoxFunctionName() );

        //
        // Create optix Geometry
        //
        optix::Geometry optix_geometry = m_optix_context->createGeometry();
        optix_geometry->setPrimitiveCount( geometry->numPrimitives() );
        optix_geometry->setIntersectionProgram( intersect );
        optix_geometry->setBoundingBoxProgram( bbox );

        //
        // Create optix GeometryInstance
        //
        optix::GeometryInstance optix_geometry_instance =
            m_optix_context->createGeometryInstance();
        optix_geometry_instance->setGeometry( optix_geometry );
        optix_geometry_instance->setMaterialCount( 1u );
        optix_geometry_instance->setGeometry( optix_geometry );

        //
        // Create optix Material
        //
        optix::Material material = m_optix_context->createMaterial();
        optix_geometry_instance->setMaterial( 0, material );
        material->setClosestHitProgram( RADIANCE_TYPE, m_closest_hit_program );
        material->setAnyHitProgram( SHADOW_TYPE, m_any_hit_program );

        ISurface* surface = geometry->getSurface();
        const std::string surface_name( surface->name() );
        const std::string surface_ptx( surface_name + ".ptx" );

        optix::Program evaluate_bsdf =
            m_program_mgr.get( surface_ptx,
                               surface->evaluateBSDFFunctionName(),
                               false );
        material[ "legionSurfaceEvaluateBSDF" ]->set( evaluate_bsdf );
        evaluate_bsdf->getId();

        optix::Program sample_bsdf =
            m_program_mgr.get( surface_ptx,
                               surface->sampleBSDFFunctionName(),
                               false );
        material[ "legionSurfaceSampleBSDF" ]->set( sample_bsdf );
        sample_bsdf->getId();

        optix::Program pdf =
            m_program_mgr.get( surface_ptx,
                               surface->pdfFunctionName(),
                               false );
        material[ "legionSurfacePDF" ]->set( pdf );
        pdf->getId();

        const std::string emission_func_name = surface->emissionFunctionName();
        optix::Program emission =
            m_program_mgr.get(
                    surface_ptx,
                    emission_func_name,
                    false
                    );
        material[ "legionSurfaceEmission" ]->set( emission );
        emission->getId();

        optix::Program light_pdf =
          m_program_mgr.get( std::string( geometry->name() ) + ".ptx",
                             geometry->pdfFunctionName() );
        optix_geometry_instance[ "legionLightPDF" ]->set( light_pdf );
        light_pdf->getId();

        //
        // Add Light
        //
        if( emission_func_name != "nullSurfaceEmission" )
        {
            optix::Program sample =
                m_program_mgr.get( std::string( geometry->name() ) + ".ptx",
                                   geometry->sampleFunctionName(),
                                   false );

            m_light_sample_ids.push_back( sample->getId() );
            m_light_eval_ids.push_back( emission->getId() );

            // TODO: move to sync
            VariableContainer vc0( sample.get() );
            geometry->setVariables( vc0 );

            VariableContainer vc1( emission.get() );
            surface->setVariables( vc1 );
        }

        m_top_group->setChildCount( m_top_group->getChildCount()+1u );
        m_top_group->setChild(
                m_top_group->getChildCount()-1,
                optix_geometry_instance
                );

        m_geometry.insert(std::make_pair( geometry, optix_geometry_instance ) );
    }
    OPTIX_CATCH_RETHROW;
}

void OptiXScene::addAssetPath( const std::string& path )
{
    m_program_mgr.addPath( path );
}

void OptiXScene::sync()
{
    // TODO: have defaults objects for all of these
    LEGION_ASSERT( m_renderer );
    LEGION_ASSERT( m_camera );

    //
    // Update optix variables for all objects
    //
    {
        VariableContainer vc( m_optix_context.get() );
        m_renderer->setVariables( vc );
    }

    {
        VariableContainer vc( m_create_ray_program.get() );
        m_camera->setVariables( vc );
    }

    if( m_environment_sample )
    {
        VariableContainer vc( m_environment_sample.get() );
        m_environment->setVariables( vc );
    }

    if( m_environment_miss_evaluate )
    {
        VariableContainer vc( m_environment_miss_evaluate.get() );
        m_environment->setVariables( vc );
    }

    if( m_environment_light_evaluate )
    {
        VariableContainer vc( m_environment_light_evaluate.get() );
        m_environment->setVariables( vc );
    }

    for( GeometryMap::iterator geom_it = m_geometry.begin();
         geom_it != m_geometry.end();
         ++geom_it )
    {
        IGeometry*              geometry          = geom_it->first;
        ISurface*               surface           = geometry->getSurface();
        optix::GeometryInstance geometry_instance = geom_it->second;

        //optix::Geometry optix_geometry = geometry_instance->getGeometry();
        VariableContainer geom_vc( geometry_instance.get() );
        geometry->setVariables( geom_vc );

        optix::Material optix_material = geometry_instance->getMaterial( 0u );

        optix::Program eval_bsdf =
          optix_material[ "legionSurfaceEvaluateBSDF" ]->getProgram();
        optix::Program sample_bsdf =
          optix_material[ "legionSurfaceSampleBSDF"   ]->getProgram();
        optix::Program pdf =
          optix_material[ "legionSurfacePDF"          ]->getProgram();
        //setSurfaceVariables( optix_material,   surface );
        setSurfaceVariables( eval_bsdf,   surface );
        setSurfaceVariables( sample_bsdf, surface );
        setSurfaceVariables( pdf,         surface );
    }

    // Sync lights
    LEGION_ASSERT( m_light_sample_ids.size() == m_light_eval_ids.size() );
    const RTsize num_lights = m_light_sample_ids.size();

    m_light_sample_buffer->setSize( num_lights );
    m_light_eval_buffer->setSize( num_lights );

    int* sample_ids = static_cast<int*>( m_light_sample_buffer->map() );
    int* eval_ids   = static_cast<int*>( m_light_eval_buffer->map() );
    for( size_t i = 0; i < num_lights; ++i )
    {
        sample_ids[i] = m_light_sample_ids[i];
        eval_ids[i]   = m_light_eval_ids[i];
    }
    m_light_sample_buffer->unmap();
    m_light_eval_buffer->unmap();
}

void OptiXScene::initializeOptixContext()
{
    try
    {
        m_optix_context->setEntryPointCount( 1u ); // Single raygen
        m_optix_context->setRayTypeCount   ( 2u ); // Radiance, shadow query

        m_optix_context[ "legion_radiance_ray_type" ]->setUint( RADIANCE_TYPE );
        m_optix_context[ "legion_shadow_ray_type"   ]->setUint( SHADOW_TYPE );

        // Create the top level scene group
        m_top_group = m_optix_context->createGeometryGroup();
        m_top_group->setAcceleration(
                m_optix_context->createAcceleration( "Sbvh", "Bvh" ) );
        m_optix_context[ "legion_top_group" ]->set( m_top_group );

        m_closest_hit_program =
            m_program_mgr.get(
                    "Surface.ptx",
                    "legionClosestHit"
                    );

        m_any_hit_program =
                m_program_mgr.get(
                    "Surface.ptx",
                    "legionAnyHit"
                    );

        m_default_texture_proc1 =
                m_program_mgr.get(
                    "Texture.ptx",
                    "legionDefaultTextureProc1"
                    );
        m_default_texture_proc1->getId();

        m_default_texture_proc2 =
                m_program_mgr.get(
                    "Texture.ptx",
                    "legionDefaultTextureProc2"
                    );
        m_default_texture_proc2->getId();

        m_default_texture_proc4 =
                m_program_mgr.get(
                    "Texture.ptx",
                    "legionDefaultTextureProc4"
                    );
        m_default_texture_proc4->getId();

    }
    OPTIX_CATCH_RETHROW;
}

template <typename OptiXNode>
void OptiXScene::setSurfaceVariables(
    OptiXNode       node,
    const ISurface* surface
    )
{
    VariableContainer vc( node.get() );
    surface->setVariables( vc );

    const VariableContainer::Textures& textures = vc.getTextures();
    for( VariableContainer::Textures::const_iterator it = textures.begin();
            it != textures.end();
            ++it )
    {
        setTextureVariables( node, it->first, it->second );
    }

    const VariableContainer::Surfaces& surfaces = vc.getSurfaces();
    for( VariableContainer::Surfaces::const_iterator it = surfaces.begin();
            it != surfaces.end();
            ++it )
    {
        setNestedSurfaceVariables( node, it->first, it->second );
    }
}

template <typename OptiXNode>
void OptiXScene::setNestedSurfaceVariables( OptiXNode          node,
                                            const std::string& name,
                                            const ISurface*    surf )
{
    // TODO: be smarter about nested program assignments -- only assign PDF
    //       callableFunction to parent PDF function

    {
        optix::Program proc =
            m_program_mgr.get( std::string( surf->name() ) + ".ptx",
                    surf->sampleBSDFFunctionName(),
                    false
                    );
        proc->getId();

        VariableContainer vc( proc.get() );
        surf->setVariables( vc );
        const VariableContainer::Textures& textures = vc.getTextures();
        for( VariableContainer::Textures::const_iterator it = textures.begin();
             it != textures.end();
             ++it )
        {
            setTextureVariables( proc, it->first, it->second );
        }

        const std::string sample_bsdf_name = name + "_sampleBSDF__";
        node[ sample_bsdf_name ]->set( proc );
    }

    {
        optix::Program proc =
            m_program_mgr.get( std::string( surf->name() ) + ".ptx",
                    surf->evaluateBSDFFunctionName(),
                    false
                    );
        proc->getId();

        VariableContainer vc( proc.get() );
        surf->setVariables( vc );
        const VariableContainer::Textures& textures = vc.getTextures();
        for( VariableContainer::Textures::const_iterator it = textures.begin();
             it != textures.end();
             ++it )
        {
            setTextureVariables( proc, it->first, it->second );
        }

        const std::string eval_bsdf_name = name + "_evaluateBSDF__";
        node[ eval_bsdf_name ]->set( proc );
    }

    {
        optix::Program proc =
            m_program_mgr.get( std::string( surf->name() ) + ".ptx",
                    surf->pdfFunctionName(),
                    false
                    );
        proc->getId();

        VariableContainer vc( proc.get() );
        surf->setVariables( vc );
        const VariableContainer::Textures& textures = vc.getTextures();
        for( VariableContainer::Textures::const_iterator it = textures.begin();
             it != textures.end();
             ++it )
        {
            setTextureVariables( proc, it->first, it->second );
        }

        const std::string pdf_name = name + "_PDF__";
        node[ pdf_name ]->set( proc );
    }

    {
        optix::Program proc =
            m_program_mgr.get( std::string( surf->name() ) + ".ptx",
                    surf->emissionFunctionName(),
                    false
                    );
        proc->getId();

        VariableContainer vc( proc.get() );
        surf->setVariables( vc );
        const VariableContainer::Textures& textures = vc.getTextures();
        for( VariableContainer::Textures::const_iterator it = textures.begin();
             it != textures.end();
             ++it )
        {
            setTextureVariables( proc, it->first, it->second );
        }

        const std::string emission_name = name + "_emission__";
        node[ emission_name ]->set( proc );
    }
}

template <typename OptiXNode>
void OptiXScene::setTextureVariables( OptiXNode          node,
                                      const std::string& name,
                                      const ITexture*    tex )
{
    const ITexture::Type type = tex->getType();
    const unsigned val_dim = tex->getValueDim();

    node[ name + "_type__" ]->setUint( tex->getType() );

    const std::string cname = name + "_const__";
    const std::string tname = name + "_texid__";
    const std::string pname = name + "_proc__";

    // TODO: combine some of this logic
    if( type == ITexture::TYPE_CONSTANT )
    {
        float    v[4];
        tex->getConstValue( v );
        switch( val_dim )
        {
            case 1:
                {
                    node[ cname ]->set1fv( v );
                    node[ pname ]->set( m_default_texture_proc1 );
                    node[ tname ]->setInt( -1 );
                    break;
                }
            case 2:
                {
                    node[ cname ]->set2fv( v );
                    node[ pname ]->set( m_default_texture_proc2 );
                    node[ tname ]->setInt( -1 );
                    break;
                }
            case 4:
                {
                    node[ cname ]->set4fv( v );
                    node[ pname ]->set( m_default_texture_proc4 );
                    node[ tname ]->setInt( -1 );
                    break;
                }
            default:
                throw Exception( "Invalid texture result dim: " + name );
        };
    }
    else if( type == ITexture::TYPE_IMAGE )
    {
        switch( val_dim )
        {
            case 1:
                {
                    node[ cname ]->setFloat( 0.0f );
                    node[ pname ]->set( m_default_texture_proc1 );
                    node[ tname ]->setInt( tex->getTexID() );
                    break;
                }
            case 2:
                {
                    node[ cname ]->setFloat( 0.0f, 0.0f );
                    node[ pname ]->set( m_default_texture_proc2 );
                    node[ tname ]->setInt( tex->getTexID() );
                    break;
                }
            case 4:
                {
                    node[ cname ]->setFloat( 0.0f, 0.0f, 0.0f, 0.0f );
                    node[ pname ]->set( m_default_texture_proc4 );
                    node[ tname ]->setInt( tex->getTexID() );
                    break;
                }
            default:
                throw Exception( "Invalid texture result dim: " + name );
        };
    }
    else // ( type == ITexture::TYPE_PROCEDURAL )
    {
        optix::Program proc =
            m_program_mgr.get( std::string( tex->name() ) + ".ptx",
                    tex->proceduralFunctionName(),
                    false
                    );
        proc->getId();

        VariableContainer vc( proc.get() );
        tex->setVariables( vc );

        switch( val_dim )
        {
            case 1:
                {
                    node[ cname ]->setFloat( 0.0f );
                    node[ pname ]->set( proc );
                    node[ tname ]->setInt( -1 );
                    break;
                }
            case 2:
                {
                    node[ cname ]->setFloat( 0.0f, 0.0f );
                    node[ pname ]->set( proc );
                    node[ tname ]->setInt( -1 );
                    break;
                }
            case 4:
                {
                    node[ cname ]->setFloat( 0.0f, 0.0f, 0.0f, 0.0f );
                    node[ pname ]->set( proc );
                    node[ tname ]->setInt( -1 );
                    break;
                }
            default:
                throw Exception( "Invalid texture result dim: " + name );
        };
    }
}

void
OptiXScene::loadAccelCache(const std::string& cache_file)
{
    std::ifstream in( cache_file.c_str(), std::ifstream::in | std::ifstream::binary );
    if ( in ) {
        unsigned long long int size = 0ull;

#ifdef WIN32
        // This is to work around a bug in Visual Studio where a pos_type is cast to an
        // int before being cast to the requested type, thus wrapping file sizes at 2
        // GB. To be fixed in VS2011.
        FILE *fp = fopen(cache_file.c_str(), "rb");

        _fseeki64(fp, 0L, SEEK_END);
        size = _ftelli64(fp);
        fclose(fp);
#else
        // Read data from file
        in.seekg (0, std::ios::end);
        std::ifstream::pos_type szp = in.tellg();
        in.seekg (0, std::ios::beg);
        size = static_cast<unsigned long long int>(szp);
#endif

        std::cerr << "acceleration cache file found: '" << cache_file << "' (" << size << " bytes)\n";

        if(sizeof(size_t) <= 4 && size >= 0x80000000ULL) {
            std::cerr << "[WARNING] acceleration cache file too large for 32-bit application.\n";
            m_accel_cache_loaded = false;
            return;
        }

        std::vector<char> d(static_cast<size_t>(size));
        char* data = &d[0];
        in.read( data, static_cast<std::streamsize>(size) );

        // Load data into accel
        optix::Acceleration accel = m_top_group->getAcceleration();
        try {
            accel->setData( data, static_cast<RTsize>(size) );
            m_accel_cache_loaded = true;

        } catch( optix::Exception& e ) {
            // Setting the acceleration cache failed, but that's not a problem. Since the
            // acceleration is marked dirty and builder and traverser are both set
            // already, it will simply build as usual, without using the cache. So we just
            // warn the user here, but don't do anything else.
            std::cerr << "[WARNING] could not use acceleration cache, reason: " << e.getErrorString() << std::endl;
            m_accel_cache_loaded = false;
        }

    } else {
        m_accel_cache_loaded = false;
        std::cerr << "no acceleration cache file found\n";
    }
}

void
OptiXScene::saveAccelCache(const std::string& cache_file)
{
    // If accel caching on, marshallize the accel
    if( !m_accel_cache_loaded ) {

        // Get data from accel
        optix::Acceleration accel = m_top_group->getAcceleration();
        RTsize size = accel->getDataSize();
        std::vector<char> d(size);
        char* data = &d[0];
        accel->getData( data );

        // Write to file
        std::ofstream out( cache_file.c_str(), std::ofstream::out | std::ofstream::binary );
        if( !out ) {
            std::cerr << "could not open acceleration cache file '" << cache_file << "'" << std::endl;
            return;
        }
        out.write( data, size );
        std::cerr << "acceleration cache written: '" << cache_file << "'" << std::endl;
    }
}


text:
package io.github.dawncraft.command;

import java.util.List;

import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;

public class CommandTalent extends CommandBase
{
    @Override
    public String getName()
    {
        return "talent";
    }

    @Override
    public int getRequiredPermissionLevel()
    {
        return 2;
    }

    @Override
    public String getUsage(ICommandSender sender)
    {
        return "commands.talent.usage";
    }

    @Override
    public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
    {
        throw new WrongUsageException("commands.talent.usage");
    }

    @Override
    public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos)
    {
        return args.length == 1 ? getListOfStringsMatchingLastWord(args, server.getOnlinePlayerNames()) : null;
    }
}


text:
.dropdown-hidden {
    display: none;
}


text:
package com.tascape.qa.th.ios.model;

/**
 *
 * @author linsong wang
 */
public class UIASegmentedControl extends UIAElement {

}


text:
<?php

namespace AcmeGroup\LaboBundle\Entity;

// use AcmeGroup\LaboBundle\Entity\baseRepository;
use labo\Bundle\TestmanuBundle\Entity\visiteRepository as visiteBaseRepo;

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

}


text:
RESTIC_VERSION=$1
[ -z "$RESTIC_VERSION" ] && RESTIC_VERSION="0.8.1"

exit1() {
    local msg=$1
    echo $1 >&2
    exit 1
}

ensure_commands_exist() {
    while [ -n "$1" ]; do
        command -v $1 >/dev/null 2>/dev/null || exit1 "$1: command not found"
        shift
    done
}

ensure_commands_exist "getgid" "groupadd" "id" "chmod" "chown" "setcap" "install" "jq" "wget" "wget" "openssl" "curl"

getgid restic >/dev/null 2>/dev/null || groupadd restic || exit 1
id -u restic >/dev/null 2>/dev/null || useradd restic -m -d /home/services/restic -g restic || exit 1
mkdir -p ~restic/bin || exit 1

RESTIC_BIN=~restic/bin/restic
if [ ! -f $RESTIC_BIN ]; then
    echo "* installing restic"
    arch="386"
    if [ "$(uname)" == "x86_64" ]; then
        arch="amd64"
    fi
    url="https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_linux_${arch}.bz2"
    rm -f ~restic/bin/*.bz2
    wget -q $url -O ~restic/bin/restic.bz2 && bunzip2 -c ~restic/bin/restic.bz2 > $RESTIC_BIN || exit 1
    rm -f ~restic/bin/*.bz2
fi

if [ -f $RESTIC_BIN ]; then
    echo "* setting $RESTIC_BIN permissions"
    chmod 750 $RESTIC_BIN || exit 1
    chown root:restic ~restic/bin/restic ||  exit 1
    setcap cap_dac_read_search=+ep ~restic/bin/restic || exit 1
fi
echo "* installing scripts"
install -m 750 -g restic -o root restic.sh restic-backup.sh ~restic/bin/ || exit 1

[ -f ~restic/jobs.json ] || install -o restic -g restic -m 600 jobs.json ~restic
[ -f ~restic/.restic.env ] || install -o restic -g restic -m 600 restic.env ~restic/.restic.env

if [ ! -f /etc/cron.d/restic-backup ]; then
    echo "* installing crontab"
    install -m 640 crontab /etc/cron.d/restic-backup
fi

RESTIC_PASSWORD_FILE=~restic/.restic.key
if [ ! -f $RESTIC_PASSWORD_FILE ]; then
    echo "* generating repo key $RESTIC_PASSWORD_FILE"
    openssl rand -base64 24 > $RESTIC_PASSWORD_FILE
    chown root:restic $RESTIC_PASSWORD_FILE
    chmod 640 $RESTIC_PASSWORD_FILE
fi

echo "* installation complete"


text:
(function () {  //use //IIFE
    "use strict";
    var app = angular.module("drillTimeNgOnly",
        ['ui.router', "common.services"]);  //having the second parameter of an array means we are 'setting' the module, without the secound param, its a 'getter'

    app.config(
        [
            "$stateProvider",
            "$urlRouterProvider",
            function ($stateProvider, $urlRouterProvider) {
                $urlRouterProvider.otherwise("/");
                $stateProvider

                    .state("home",
                    {
                        url: "/",
                        templateUrl: "app/welcomeView.html"
                    })

                    .state("drillList",
                    {
                        url: "/drills",
                        templateUrl: "app/drills/drillListView.html",
                        controller: "DrillListCtrl as vm"
                    })

                    .state("drillDetail",
                    {
                        url: "/drills/:drillId",
                        templateUrl: "app/drills/drillDetailView.html",
                        controller: "DrillDetailCtrl as vm",
                        resolve: {
                            drillResource: "drillResource",
                            drill: function (drillResource, $stateParams) {
                                var drillId = $stateParams.drillId;
                                return drillResource.get({ drillId: drillId }).$promise;

                            }
                        }
                    })

                    .state("drillEdit",
                    {
                        abstract: true,
                        url: "/drills/edit/:drillId",
                        templateUrl: "app/drills/drillEditView.html",
                        controller: "DrillEditCtrl as vm",
                        resolve: {
                        drillResource: "drillResource",
                                drill: function (drillResource, $stateParams) {
                                var drillId = $stateParams.drillId;
                                return drillResource.get({
                                    drillId: drillId
                                }).$promise;

                                }
                        }
                    })

                        .state("drillEdit.info",
                        {
                            url: "/info",
                            templateUrl: "app/drills/drillEditInfoView.html"
                        })
                        .state("drillEdit.image",
                        {
                            url: "/image",
                            templateUrl: "app/drills/drillEditImageView.html"
                        })
                        .state("drillEdit.tags",
                        {
                            url: "/tags",
                            templateUrl: "app/drills/drillEditTagsView.html"
                        });
            }
        ]
    );
}());


text:
layout: post-index
permalink: /marcacoes/
title: Arquivo de marcações
modified: 2014-11-07 00:00:02 -0000
lang: "pt"
description: "Um arquivo das postagens oredenadas por marcaçãos."
---

{% capture site_tags %}{% for tag in site.tags %}{{ tag | first }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}
{% assign tags_list = site_tags | split:',' | sort %}

  {% for item in (0..site.tags.size) %}{% unless forloop.last %}
    {% capture this_word %}{{ tags_list[item] | strip_newlines }}{% endcapture %}
    {% assign posts_by_lang = site.tags[this_word] | group_by: "lang" %}
    {% for posts_lang in posts_by_lang %}
    {% if posts_lang.name == page.lang and posts_lang.items.size > -1 %}

{{ this_word }} {{ posts_lang.items.size }}

    {% endif %}{% endfor %}
  {% endunless %}{% endfor %}

{% for item in (0..site.tags.size) %}{% unless forloop.last %}
  {% capture this_word %}{{ tags_list[item] | strip_newlines }}{% endcapture %}
  {% assign posts_by_lang = site.tags[this_word] | group_by: "lang" %}
  {% for posts_lang in posts_by_lang %}
  {% if posts_lang.name == page.lang and posts_lang.items.size > -1 %}

{{ this_word }}

    {% for post in posts_lang.items %}{% if post.title != null %}

{{ post.title }}

    {% endif %}{% endfor %}

  {% endif %}{% endfor %}
{% endunless %}{% endfor %}


text:
"""
Importer print test
"""
import os
import django
import dota.factory
import dota2api

os.environ['DJANGO_SETTINGS_MODULE'] = 'dota.settings'
django.setup()

API_KEY = 'YOURAPIKEY'
DOTA_API = dota2api.Initialise(API_KEY)

def populate_matches(pid):
    """ Print all matches for given player ID """
    hist = DOTA_API.get_match_history(account_id=pid)
    for match in hist['matches']:
        str_match = match['match_id']
        obj_player = dota.factory.player_get_byid(pid)
        print 'p = ' + str(obj_player) + ', m = ' + str(str_match)
    print '--- Finished match import for ' + str(obj_player)

def populate_detail(mid, pid):
    """ Print all details for given match ID """
    details = DOTA_API.get_match_details(match_id=mid)
    for detail in details['players']:
        player_id = detail['account_id']
        if player_id == pid:
            print detail['hero_name']
            print detail['level']
            print detail['kills']
            print detail['deaths']
            print detail['assists']
            print detail['last_hits']
            print detail['denies']
            print detail['hero_damage']
            print detail['tower_damage']
            if 'item_0_name' in detail:
                print detail['item_0_name']
            if 'item_1_name' in detail:
                print detail['item_1_name']
            if 'item_2_name' in detail:
                print detail['item_2_name']
            if 'item_3_name' in detail:
                print detail['item_3_name']
            if 'item_4_name' in detail:
                print detail['item_4_name']
            if 'item_5_name' in detail:
                print detail['item_5_name']
            print details['game_mode_name']
    print '--- Finished detail import for match ' + str(mid)

PLAYERS = dota.factory.player_get_allid()
for player in PLAYERS:
    populate_matches(player)
    p = dota.factory.player_get_byid(player)
    for m in dota.factory.match_get_byplayer(p):
        populate_detail(m.match_id, player)


text:
package io.github.josehsantos.hack.lang.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface HackQueryContinuation extends HackPsiElement {

  @NotNull
  HackQueryBody getQueryBody();

  @NotNull
  HackVariableIdentifier getVariableIdentifier();

}


text:
INTRA_PUSH_DISABLE_REDUNDANT_WARNINGS

namespace Intra { namespace IO {

class BasicFileMapping
{
public:
	BasicFileMapping(BasicFileMapping&& rhs):
		mData(rhs.mData)
#ifdef INTRA_DEBUG
		, mFilePath(Cpp::Move(rhs.mFilePath))
#endif
	{rhs.mData = null;}

	BasicFileMapping& operator=(BasicFileMapping&& rhs)
	{
		Cpp::Swap(mData, rhs.mData);
#ifdef INTRA_DEBUG
		mFilePath = Cpp::Move(rhs.mFilePath);
#endif
		return *this;
	}

	BasicFileMapping(const BasicFileMapping&) = delete;
	BasicFileMapping& operator=(const BasicFileMapping&) = delete;

	size_t Length() const {return mData.Length();}

	void Close();

	bool operator==(null_t) const {return mData == null;}
	bool operator!=(null_t) const {return mData != null;}

protected:
	Span<byte> mData;
	String mFilePath;

	BasicFileMapping() {}
	BasicFileMapping(StringView fileName, ulong64 startByte, size_t bytes, bool writeAccess, ErrorStatus& status);
	~BasicFileMapping() {Close();}
};

class FileMapping: public BasicFileMapping
{
public:
	FileMapping(StringView fileName, ulong64 startByte, size_t bytes, ErrorStatus& status):
		BasicFileMapping(fileName, startByte, bytes, false, status) {}

	FileMapping(StringView fileName, ErrorStatus& status):
		BasicFileMapping(fileName, 0, ~size_t(0), false, status) {}

	FileMapping(FileMapping&&) = default;
	FileMapping(const FileMapping&) = delete;

	FileMapping& operator=(FileMapping&&) = default;
	FileMapping& operator=(const FileMapping&) = delete;

	const byte* Data() const {return mData.Data();}

	CSpan<byte> AsRange() const {return mData;}

	template<typename T> Meta::EnableIf<
		Meta::IsTriviallySerializable<T>::_,
	CSpan<T>> AsRangeOf() const {return CSpanOfRaw<T>(mData.Data(), mData.Length());}
};

class WritableFileMapping: public BasicFileMapping
{
public:
	WritableFileMapping(StringView fileName, ulong64 startByte, size_t bytes, ErrorStatus& status):
		BasicFileMapping(fileName, startByte, bytes, true, status) {}

	WritableFileMapping(StringView fileName, ErrorStatus& status):
		BasicFileMapping(fileName, 0, ~size_t(0), true, status) {}

	WritableFileMapping(WritableFileMapping&&) = default;
	WritableFileMapping(const WritableFileMapping&) = delete;

	WritableFileMapping& operator=(WritableFileMapping&&) = default;
	WritableFileMapping& operator=(const WritableFileMapping&) = delete;

	void Flush();

	byte* Data() const {return mData.Data();}

	Span<byte> AsRange() const {return mData;}

	template<typename T> Meta::EnableIf<
		Meta::IsTriviallySerializable<T>::_,
	Span<T>> AsRangeOf() const {return SpanOfRaw<T>(mData.Data(), mData.Length());}
};

}}

INTRA_WARNING_POP


text:
package cni

import (
	"encoding/json"
	"errors"
	"fmt"
	"math"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/containernetworking/cni/libcni"
	cnitypes "github.com/containernetworking/cni/pkg/types"
	"k8s.io/apimachinery/pkg/util/wait"
	runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
	"k8s.io/klog"
	kubeletconfig "k8s.io/kubernetes/pkg/kubelet/apis/config"
	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
	"k8s.io/kubernetes/pkg/kubelet/dockershim/network"
	"k8s.io/kubernetes/pkg/util/bandwidth"
	utilexec "k8s.io/utils/exec"
)

const (
	CNIPluginName = "cni"

	// defaultSyncConfigPeriod is the default period to sync CNI config
	// TODO: consider making this value configurable or to be a more appropriate value.
	defaultSyncConfigPeriod = time.Second * 5
)

type cniNetworkPlugin struct {
	network.NoopNetworkPlugin

	loNetwork *cniNetwork

	sync.RWMutex
	defaultNetwork *cniNetwork

	host        network.Host
	execer      utilexec.Interface
	nsenterPath string
	confDir     string
	binDirs     []string
	podCidr     string
}

type cniNetwork struct {
	name          string
	NetworkConfig *libcni.NetworkConfigList
	CNIConfig     libcni.CNI
}

// cniPortMapping maps to the standard CNI portmapping Capability
// see: https://github.com/containernetworking/cni/blob/master/CONVENTIONS.md
type cniPortMapping struct {
	HostPort      int32  `json:"hostPort"`
	ContainerPort int32  `json:"containerPort"`
	Protocol      string `json:"protocol"`
	HostIP        string `json:"hostIP"`
}

// cniBandwidthEntry maps to the standard CNI bandwidth Capability
// see: https://github.com/containernetworking/cni/blob/master/CONVENTIONS.md and
// https://github.com/containernetworking/plugins/blob/master/plugins/meta/bandwidth/README.md
type cniBandwidthEntry struct {
	// IngressRate is the bandwidth rate in bits per second for traffic through container. 0 for no limit. If ingressRate is set, ingressBurst must also be set
	IngressRate int `json:"ingressRate,omitempty"`
	// IngressBurst is the bandwidth burst in bits for traffic through container. 0 for no limit. If ingressBurst is set, ingressRate must also be set
	// NOTE: it's not used for now and default to 0.
	IngressBurst int `json:"ingressBurst,omitempty"`
	// EgressRate is the bandwidth is the bandwidth rate in bits per second for traffic through container. 0 for no limit. If egressRate is set, egressBurst must also be set
	EgressRate int `json:"egressRate,omitempty"`
	// EgressBurst is the bandwidth burst in bits for traffic through container. 0 for no limit. If egressBurst is set, egressRate must also be set
	// NOTE: it's not used for now and default to 0.
	EgressBurst int `json:"egressBurst,omitempty"`
}

// cniIpRange maps to the standard CNI ip range Capability
type cniIpRange struct {
	Subnet string `json:"subnet"`
}

// cniDNSConfig maps to the windows CNI dns Capability.
// see: https://github.com/containernetworking/cni/blob/master/CONVENTIONS.md
// Note that dns capability is only used for Windows containers.
type cniDNSConfig struct {
	// List of DNS servers of the cluster.
	Servers []string `json:"servers,omitempty"`
	// List of DNS search domains of the cluster.
	Searches []string `json:"searches,omitempty"`
	// List of DNS options.
	Options []string `json:"options,omitempty"`
}

func SplitDirs(dirs string) []string {
	// Use comma rather than colon to work better with Windows too
	return strings.Split(dirs, ",")
}

func ProbeNetworkPlugins(confDir string, binDirs []string) []network.NetworkPlugin {
	old := binDirs
	binDirs = make([]string, 0, len(binDirs))
	for _, dir := range old {
		if dir != "" {
			binDirs = append(binDirs, dir)
		}
	}

	plugin := &cniNetworkPlugin{
		defaultNetwork: nil,
		loNetwork:      getLoNetwork(binDirs),
		execer:         utilexec.New(),
		confDir:        confDir,
		binDirs:        binDirs,
	}

	// sync NetworkConfig in best effort during probing.
	plugin.syncNetworkConfig()
	return []network.NetworkPlugin{plugin}
}

func getDefaultCNINetwork(confDir string, binDirs []string) (*cniNetwork, error) {
	files, err := libcni.ConfFiles(confDir, []string{".conf", ".conflist", ".json"})
	switch {
	case err != nil:
		return nil, err
	case len(files) == 0:
		return nil, fmt.Errorf("No networks found in %s", confDir)
	}

	sort.Strings(files)
	for _, confFile := range files {
		var confList *libcni.NetworkConfigList
		if strings.HasSuffix(confFile, ".conflist") {
			confList, err = libcni.ConfListFromFile(confFile)
			if err != nil {
				klog.Warningf("Error loading CNI config list file %s: %v", confFile, err)
				continue
			}
		} else {
			conf, err := libcni.ConfFromFile(confFile)
			if err != nil {
				klog.Warningf("Error loading CNI config file %s: %v", confFile, err)
				continue
			}
			// Ensure the config has a "type" so we know what plugin to run.
			// Also catches the case where somebody put a conflist into a conf file.
			if conf.Network.Type == "" {
				klog.Warningf("Error loading CNI config file %s: no 'type'; perhaps this is a .conflist?", confFile)
				continue
			}

			confList, err = libcni.ConfListFromConf(conf)
			if err != nil {
				klog.Warningf("Error converting CNI config file %s to list: %v", confFile, err)
				continue
			}
		}
		if len(confList.Plugins) == 0 {
			klog.Warningf("CNI config list %s has no networks, skipping", confFile)
			continue
		}

		klog.V(4).Infof("Using CNI configuration file %s", confFile)

		network := &cniNetwork{
			name:          confList.Name,
			NetworkConfig: confList,
			CNIConfig:     &libcni.CNIConfig{Path: binDirs},
		}
		return network, nil
	}
	return nil, fmt.Errorf("No valid networks found in %s", confDir)
}

func (plugin *cniNetworkPlugin) Init(host network.Host, hairpinMode kubeletconfig.HairpinMode, nonMasqueradeCIDR string, mtu int) error {
	err := plugin.platformInit()
	if err != nil {
		return err
	}

	plugin.host = host

	plugin.syncNetworkConfig()

	// start a goroutine to sync network config from confDir periodically to detect network config updates in every 5 seconds
	go wait.Forever(plugin.syncNetworkConfig, defaultSyncConfigPeriod)

	return nil
}

func (plugin *cniNetworkPlugin) syncNetworkConfig() {
	network, err := getDefaultCNINetwork(plugin.confDir, plugin.binDirs)
	if err != nil {
		klog.Warningf("Unable to update cni config: %s", err)
		return
	}
	plugin.setDefaultNetwork(network)
}

func (plugin *cniNetworkPlugin) getDefaultNetwork() *cniNetwork {
	plugin.RLock()
	defer plugin.RUnlock()
	return plugin.defaultNetwork
}

func (plugin *cniNetworkPlugin) setDefaultNetwork(n *cniNetwork) {
	plugin.Lock()
	defer plugin.Unlock()
	plugin.defaultNetwork = n
}

func (plugin *cniNetworkPlugin) checkInitialized() error {
	if plugin.getDefaultNetwork() == nil {
		return errors.New("cni config uninitialized")
	}

	// If the CNI configuration has the ipRanges capability, we need a PodCIDR assigned
	for _, p := range plugin.getDefaultNetwork().NetworkConfig.Plugins {
		if p.Network.Capabilities["ipRanges"] {
			if plugin.podCidr == "" {
				return errors.New("no PodCIDR set")
			}
			break
		}
	}
	return nil
}

// Event handles any change events. The only event ever sent is the PodCIDR change.
// No network plugins support changing an already-set PodCIDR
func (plugin *cniNetworkPlugin) Event(name string, details map[string]interface{}) {
	if name != network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE {
		return
	}

	plugin.Lock()
	defer plugin.Unlock()

	podCIDR, ok := details[network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE_DETAIL_CIDR].(string)
	if !ok {
		klog.Warningf("%s event didn't contain pod CIDR", network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE)
		return
	}

	if plugin.podCidr != "" {
		klog.Warningf("Ignoring subsequent pod CIDR update to %s", podCIDR)
		return
	}

	plugin.podCidr = podCIDR
}

func (plugin *cniNetworkPlugin) Name() string {
	return CNIPluginName
}

func (plugin *cniNetworkPlugin) Status() error {
	// Can't set up pods if we don't have any CNI network configs yet
	return plugin.checkInitialized()
}

func (plugin *cniNetworkPlugin) SetUpPod(namespace string, name string, id kubecontainer.ContainerID, annotations, options map[string]string) error {
	if err := plugin.checkInitialized(); err != nil {
		return err
	}
	netnsPath, err := plugin.host.GetNetNS(id.ID)
	if err != nil {
		return fmt.Errorf("CNI failed to retrieve network namespace path: %v", err)
	}

	// Windows doesn't have loNetwork. It comes only with Linux
	if plugin.loNetwork != nil {
		if _, err = plugin.addToNetwork(plugin.loNetwork, name, namespace, id, netnsPath, annotations, options); err != nil {
			return err
		}
	}

	_, err = plugin.addToNetwork(plugin.getDefaultNetwork(), name, namespace, id, netnsPath, annotations, options)
	return err
}

func (plugin *cniNetworkPlugin) TearDownPod(namespace string, name string, id kubecontainer.ContainerID) error {
	if err := plugin.checkInitialized(); err != nil {
		return err
	}

	// Lack of namespace should not be fatal on teardown
	netnsPath, err := plugin.host.GetNetNS(id.ID)
	if err != nil {
		klog.Warningf("CNI failed to retrieve network namespace path: %v", err)
	}

	return plugin.deleteFromNetwork(plugin.getDefaultNetwork(), name, namespace, id, netnsPath, nil)
}

func podDesc(namespace, name string, id kubecontainer.ContainerID) string {
	return fmt.Sprintf("%s_%s/%s", namespace, name, id.ID)
}

func (plugin *cniNetworkPlugin) addToNetwork(network *cniNetwork, podName string, podNamespace string, podSandboxID kubecontainer.ContainerID, podNetnsPath string, annotations, options map[string]string) (cnitypes.Result, error) {
	rt, err := plugin.buildCNIRuntimeConf(podName, podNamespace, podSandboxID, podNetnsPath, annotations, options)
	if err != nil {
		klog.Errorf("Error adding network when building cni runtime conf: %v", err)
		return nil, err
	}

	pdesc := podDesc(podNamespace, podName, podSandboxID)
	netConf, cniNet := network.NetworkConfig, network.CNIConfig
	klog.V(4).Infof("Adding %s to network %s/%s netns %q", pdesc, netConf.Plugins[0].Network.Type, netConf.Name, podNetnsPath)
	res, err := cniNet.AddNetworkList(netConf, rt)
	if err != nil {
		klog.Errorf("Error adding %s to network %s/%s: %v", pdesc, netConf.Plugins[0].Network.Type, netConf.Name, err)
		return nil, err
	}
	klog.V(4).Infof("Added %s to network %s: %v", pdesc, netConf.Name, res)
	return res, nil
}

func (plugin *cniNetworkPlugin) deleteFromNetwork(network *cniNetwork, podName string, podNamespace string, podSandboxID kubecontainer.ContainerID, podNetnsPath string, annotations map[string]string) error {
	rt, err := plugin.buildCNIRuntimeConf(podName, podNamespace, podSandboxID, podNetnsPath, annotations, nil)
	if err != nil {
		klog.Errorf("Error deleting network when building cni runtime conf: %v", err)
		return err
	}

	pdesc := podDesc(podNamespace, podName, podSandboxID)
	netConf, cniNet := network.NetworkConfig, network.CNIConfig
	klog.V(4).Infof("Deleting %s from network %s/%s netns %q", pdesc, netConf.Plugins[0].Network.Type, netConf.Name, podNetnsPath)
	err = cniNet.DelNetworkList(netConf, rt)
	// The pod may not get deleted successfully at the first time.
	// Ignore "no such file or directory" error in case the network has already been deleted in previous attempts.
	if err != nil && !strings.Contains(err.Error(), "no such file or directory") {
		klog.Errorf("Error deleting %s from network %s/%s: %v", pdesc, netConf.Plugins[0].Network.Type, netConf.Name, err)
		return err
	}
	klog.V(4).Infof("Deleted %s from network %s/%s", pdesc, netConf.Plugins[0].Network.Type, netConf.Name)
	return nil
}

func (plugin *cniNetworkPlugin) buildCNIRuntimeConf(podName string, podNs string, podSandboxID kubecontainer.ContainerID, podNetnsPath string, annotations, options map[string]string) (*libcni.RuntimeConf, error) {
	rt := &libcni.RuntimeConf{
		ContainerID: podSandboxID.ID,
		NetNS:       podNetnsPath,
		IfName:      network.DefaultInterfaceName,
		Args: [][2]string{
			{"IgnoreUnknown", "1"},
			{"K8S_POD_NAMESPACE", podNs},
			{"K8S_POD_NAME", podName},
			{"K8S_POD_INFRA_CONTAINER_ID", podSandboxID.ID},
		},
	}

	// port mappings are a cni capability-based args, rather than parameters
	// to a specific plugin
	portMappings, err := plugin.host.GetPodPortMappings(podSandboxID.ID)
	if err != nil {
		return nil, fmt.Errorf("could not retrieve port mappings: %v", err)
	}
	portMappingsParam := make([]cniPortMapping, 0, len(portMappings))
	for _, p := range portMappings {
		if p.HostPort <= 0 {
			continue
		}
		portMappingsParam = append(portMappingsParam, cniPortMapping{
			HostPort:      p.HostPort,
			ContainerPort: p.ContainerPort,
			Protocol:      strings.ToLower(string(p.Protocol)),
			HostIP:        p.HostIP,
		})
	}
	rt.CapabilityArgs = map[string]interface{}{
		"portMappings": portMappingsParam,
	}

	ingress, egress, err := bandwidth.ExtractPodBandwidthResources(annotations)
	if err != nil {
		return nil, fmt.Errorf("Error reading pod bandwidth annotations: %v", err)
	}
	if ingress != nil || egress != nil {
		bandwidthParam := cniBandwidthEntry{}
		if ingress != nil {
			// see: https://github.com/containernetworking/cni/blob/master/CONVENTIONS.md and
			// https://github.com/containernetworking/plugins/blob/master/plugins/meta/bandwidth/README.md
			// Rates are in bits per second, burst values are in bits.
			bandwidthParam.IngressRate = int(ingress.Value())
			bandwidthParam.IngressBurst = math.MaxInt32 // no limit
		}
		if egress != nil {
			bandwidthParam.EgressRate = int(egress.Value())
			bandwidthParam.EgressBurst = math.MaxInt32 // no limit
		}
		rt.CapabilityArgs["bandwidth"] = bandwidthParam
	}

	// Set the PodCIDR
	rt.CapabilityArgs["ipRanges"] = [][]cniIpRange{{{Subnet: plugin.podCidr}}}

	// Set dns capability args.
	if dnsOptions, ok := options["dns"]; ok {
		dnsConfig := runtimeapi.DNSConfig{}
		err := json.Unmarshal([]byte(dnsOptions), &dnsConfig)
		if err != nil {
			return nil, fmt.Errorf("failed to unmarshal dns config %q: %v", dnsOptions, err)
		}
		if dnsParam := buildDNSCapabilities(&dnsConfig); dnsParam != nil {
			rt.CapabilityArgs["dns"] = *dnsParam
		}
	}

	return rt, nil
}


text:
package nl.mawoo.smokesignal.protocol.models;

/**
 * {message}
 *
 * @author Bob van der Valk
 */
public class Location implements MessageType {
    private String latitude;
    private String longitude;

    public Location(String latitude, String longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongitude() {
        return longitude;
    }
}


text:
#ifndef _ALPHA_IRQ_H
#define _ALPHA_IRQ_H

#include <linux/linkage.h>

extern void disable_irq(unsigned int);
extern void enable_irq(unsigned int);

#define __STR(x) #x
#define STR(x) __STR(x)

#define SAVE_ALL "xx"

#define SAVE_MOST "yy"

#define RESTORE_MOST "zz"

#define ACK_FIRST(mask) "aa"

#define ACK_SECOND(mask) "dummy"

#define UNBLK_FIRST(mask) "dummy"

#define UNBLK_SECOND(mask) "dummy"

#define IRQ_NAME2(nr) nr##_interrupt(void)
#define IRQ_NAME(nr) IRQ_NAME2(IRQ##nr)
#define FAST_IRQ_NAME(nr) IRQ_NAME2(fast_IRQ##nr)
#define BAD_IRQ_NAME(nr) IRQ_NAME2(bad_IRQ##nr)

#define BUILD_IRQ(chip,nr,mask) \
asmlinkage void IRQ_NAME(nr); \
asmlinkage void FAST_IRQ_NAME(nr); \
asmlinkage void BAD_IRQ_NAME(nr); \
asm code comes here

#endif


text:
<?php

namespace Zitec\RuleEngineBundle\Service;

use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;

/**
 * Provides functions for comparing array values in expressions.
 */
class ArrayExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{

    /**
     * @return ExpressionFunction[]
     */
    public function getFunctions()
    {
        return [
            new ExpressionFunction(
                'disjoint',
                function () {
                    return 'empty(array_intersect($parameter, explode(\',\', $value)))';
                },
                function ($variables, $parameter, $value) {
                    return empty(array_intersect($parameter, explode(',', $value)));
                }
            ),
            new ExpressionFunction(
                'intersecting',
                function () {
                    return '!empty(array_intersect($parameter, explode(\',\', $value)))';
                },
                function ($variables, $parameter, $value) {
                    return !empty(array_intersect($parameter, explode(',', $value)));
                }
            ),
            new ExpressionFunction(
                'included',
                function () {
                    return 'empty(array_diff($parameter, explode(\',\', $value)))';
                },
                function ($variables, $parameter, $value) {
                    return empty(array_diff($parameter, explode(',', $value)));
                }
            ),
            new ExpressionFunction(
                'identical',
                function () {
                    return '$values = is_array($value) ? $value : explode(\',\', $value);
                    return empty(array_diff($parameter, $values)) && empty(array_diff($values, $parameter));';
                },
                function ($variables, $parameter, $value) {
                    $values = is_array($value) ? $value : explode(',', $value);

                    return empty(array_diff($parameter, $values)) && empty(array_diff($values, $parameter));
                }
            ),
            new ExpressionFunction(
                'includes',
                function () {
                    return 'empty(array_diff(explode(\',\', $value), $parameter))';
                },
                function ($variables, $parameter, $value) {
                    return empty(array_diff(explode(',', $value), $parameter));
                }
            ),
            new ExpressionFunction(
                'uniqount',
                function () {
                    return 'count(array_unique($value))';
                },
                function ($variables, $value) {
                    return count(array_unique($value));
                }
            ),
        ];
    }
}


text:
<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">

	<parent>
		<groupId>org.wso2.carbon.storagemgt</groupId>
		<artifactId>hdfs</artifactId>
		<version>4.3.0-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<modelVersion>4.0.0</modelVersion>
	<groupId>org.wso2.carbon.storagemgt</groupId>
	<artifactId>org.wso2.carbon.hdfs.datanode</artifactId>
	<packaging>bundle</packaging>
	<name>WSO2 Carbon HDFS Data Node</name>
	<url>http://wso2.org</url>

	<dependencies>
		<dependency>
			<groupId>org.wso2.carbon</groupId>
			<artifactId>org.wso2.carbon.core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.wso2.carbon</groupId>
			<artifactId>org.wso2.carbon.user.api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.wso2.carbon</groupId>
			<artifactId>org.wso2.carbon.logging</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop.wso2</groupId>
			<artifactId>hadoop-core</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mortbay.wso2</groupId>
			<artifactId>jetty</artifactId>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-scr-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
						<Bundle-Name>${project.name}</Bundle-Name>
						<!-- Bundle-Activator>org.wso2.carbon.hdfs.datanode.HDFSDataNodeController</Bundle-Activator -->
						<!-- Private-Package>org.wso2.carbon.hdfs.datanode</Private-Package -->
						<Export-Package>
							org.wso2.carbon.hdfs.datanode.*;-split-package:=merge-first
						</Export-Package>
						<Import-Package>! org.wso2.carbon.hdfs.datanode.*,
							*;resolution:=optional,
						</Import-Package>
						<DynamicImport-Package>*</DynamicImport-Package>
					</instructions>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
it("should not have a require.onError function by default", function() {
	(typeof require.onError).should.be.eql("undefined"); // expected to fail in browsertests
});


text:
import axios from 'axios';

import { getPageDetails } from '../actions/getAllRecipes';
import { GET_USER_RECIPES, GET_USER_RECIPES_ERROR } from '../actions/actionTypes';
import { setFetching, unsetFetching } from '../actions/fetching';

/**
 * @returns {object} action
 *
 * @param {array} recipes
 */
const getUserRecipeSuccess = recipes => ({
  type: GET_USER_RECIPES,
  recipes
});

/**
 * @returns {object} action
 *
 */
const getUserRecipeFailure = () => ({
  type: GET_USER_RECIPES_ERROR
});

/**
 * @returns {promise} axios promise
 *
 * @param {number} page
 */
const getUserRecipes = page => (dispatch) => {
  page = page || 1;
  const token = localStorage.getItem('token');
  dispatch(setFetching());
  return axios({
    method: 'GET',
    url: `/api/v1/recipes/user/all?page=${page}`,
    headers: {
      'x-access-token': token
    }
  })
    .then((response) => {
      const { currentPage, limit, numberOfItems, pages, recipes } = response.data;
      const paginationInfo = { currentPage, limit, numberOfItems, pages };
      dispatch(getUserRecipeSuccess(recipes));
      dispatch(getPageDetails(paginationInfo));
      dispatch(unsetFetching());
    })
    .catch(() => {
      dispatch(getUserRecipeFailure());
      dispatch(unsetFetching());
    });
};
export default getUserRecipes;


text:
namespace Plugins.CountlySDK.Persistance.Entities
{
    public class EventNumberInSameSessionEntity : IEntity
    {
        public long Id;
        public string EventKey;
        public int Number;

        public long GetId()
        {
            return Id;
        }
    }
}


text:
Ik heb een color picker gemaakt om te gebruiken als je een film aan het kijken bent. Wanneer je op pauze (spatiebalk) klikt verschijnen er onderaan de 3 kleuren die het meest voorkomend zijn in het beeld wat je op pauze hebt gezet. Daarnaast zie je ook een kleurenbalk waarin je kleuren kan kiezen.

Je klikt een kleur aan die je graag wil veranderen en klikt daarna in de kleurenbalk waarin je jou kleur selecteerd. Hierna zie je dat de kleur is veranderd. Zo kan jij zelf bepalen hoe jou film eruit gaat zien. En zo kan je zelf ook de sfeer van je film bepalen.

### Concept & Sketch

[hoe werkt het](hoewerkthet.pdf)

### Prototype

[color picker uitleg](procesprint.pdf)

## Your Own Tool

color picker for movies

### Concept

Omdat ik soms kleuren in films niet erg mooi vind, zou ik ze maar al te graag soms willen veranderen. Doormiddel van gewoon een kleur te kunnen selecteren en veranderen zodat het door de hele film die kleur blijft. Bijvoorbeeld als je niet houdt van de kleur blauw, verander je die kleur gewoon in rood.

Daarom is er de color picker for movies, doormiddel van gewoon op pauze te klikken (spatiebalk) krijg je direct de 3 meest voorkomende kleuren in beeld die je kan veranderen in een andere kleur. Die kleur wordt doorgevoerd door de hele film.

### Sketch

### Demo

[demo color picker for movies](https://vimeo.com/159327212)

[demo Colorpicker for movies 2](https://vimeo.com/159337120)

### How to install and use

## Other Homework


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

public class ClassWithAsyncMethod
{
    [Time]
    public async Task MethodWithAwaitAsync()
    {
        await Task.Delay(500);
    }

    [Time]
    public async Task MethodWithAwaitAndExceptionAsync()
    {
        await Task.Factory.StartNew(() => { throw new Exception("Expected exception"); });
    }

    bool isRunning;
    bool isQueued;

    [Time]
    public async Task MethodWithFastPathAsync(bool recurse)
    {
        if (isRunning)
        {
            isQueued = true;
            return;
        }

        isRunning = true;

        await Task.Delay(500);

        if (recurse)
        {
            await MethodWithFastPathAsync(false);
        }

        isRunning = false;
    }
}


text:
using System.Diagnostics;

namespace sparkiy.Connectors.IoT.Windows.Models
{
	/// <summary>
	/// Machine name.
	/// </summary>
	[DebuggerDisplay("ComputerName: {ComputerName}")]
	public class MachineName
	{
		/// <summary>
		/// Gets or sets the name of the computer.
		/// </summary>
		/// <value>
		/// The name of the computer.
		/// </value>
		public string ComputerName { get; set; }
	}
}