text:
<?php
  //This php code is for updating a course
  include("../connect.php");
    $code = $_POST["code"];
	$name = $_POST["name"];
	$description = $_POST["description"];
	$unit = $_POST["unit"];
	$phase_code = $_POST["phase_code"];
	$department_code = $_POST["department_code"];
	$start_regular_defense_week = $_POST["start_regular_defense_week"];
	$end_regular_defense_week = $_POST["end_regular_defense_week"];
	$regular_defense_minute = $_POST["regular_defense_minute"];
	$regular_defense_applicable = isset($_POST["regular_defense_applicable"]) ? $_POST['regular_defense_applicable'] : 0;
	$start_redefense_week = $_POST["start_redefense_week"];
	$end_redefense_week = $_POST["end_redefense_week"];
	$redefense_minute = $_POST["redefense_minute"];
	$redefense_applicable = isset($_POST["redefense_applicable"]) ? $_POST['redefense_applicable'] : 0;
	$start_outstanding_defense_week = $_POST["start_outstanding_defense_week"];
	$end_outstanding_defense_week = $_POST["end_outstanding_defense_week"];
	$outstanding_defense_minute = $_POST["outstanding_defense_minute"];
	$outstanding_defense_applicable = isset($_POST["outstanding_defense_applicable"]) ? $_POST['outstanding_defense_applicable'] : 0;
	$deadline_of_deliverable_week = $_POST["deadline_of_deliverable_week"];

    mysql_query("UPDATE course SET name='$name', description='$description', unit='$unit', phase_code='$phase_code',
	             department_code='$department_code', start_regular_defense_week='$start_regular_defense_week',
		         end_regular_defense_week='$end_regular_defense_week', regular_defense_minute='$regular_defense_minute',
				 regular_defense_applicable='$regular_defense_applicable', start_redefense_week='$start_redefense_week',
				 end_redefense_week='$end_redefense_week', redefense_minute='$redefense_minute', redefense_applicable='$redefense_applicable',
				 start_outstanding_defense_week='$start_outstanding_defense_week', end_outstanding_defense_week='$end_outstanding_defense_week',
				 outstanding_defense_minute='$outstanding_defense_minute', outstanding_defense_applicable='$outstanding_defense_applicable',
				 deadline_of_deliverable_week='$deadline_of_deliverable_week'
				 WHERE code='$code'");

echo json_encode(mysql_affected_rows());
?>


text:
import React from 'react';
import ReactTestUtils from 'react-dom/test-utils';
import toggleSwitchDriverFactory from './ToggleSwitch.driver';
import {createDriverFactory} from '../test-common';
import {toggleSwitchTestkitFactory} from '../../testkit';
import ToggleSwitch from './ToggleSwitch';
import {toggleSwitchTestkitFactory as enzymeToggleSwitchTestkitFactory} from '../../testkit/enzyme';
import {mount} from 'enzyme';

describe('ToggleSwitch', () => {

  const createDriver = createDriverFactory(toggleSwitchDriverFactory);

  describe('checked attribute', () => {
    it('should pass down to input', () => {
      const driver = createDriver(<ToggleSwitch checked onChange={() => {}}/>);
      expect(driver.isChecked()).toBeTruthy();
    });

    it('should pass down to input', () => {
      const driver = createDriver(<ToggleSwitch checked={false} onChange={() => {}}/>);
      expect(driver.isChecked()).toBeFalsy();
    });
  });

  describe('onChange attribute', () => {
    it('should be called when the input is clicked', () => {
      const onChange = jest.fn();
      const driver = createDriver(<ToggleSwitch checked={false} onChange={onChange}/>);

      driver.click();
      expect(onChange).toBeCalled();
    });
  });

  describe('size attribute', () => {
    it('should create a large toggle by default', () => {
      const driver = createDriver(<ToggleSwitch checked={false} onChange={() => {}}/>);
      expect(driver.isXSmall()).toBeFalsy();
      expect(driver.isSmall()).toBeFalsy();
      expect(driver.isLarge()).toBeTruthy();
    });

    it('should create a small toggle once given size', () => {
      const driver = createDriver(<ToggleSwitch checked={false} onChange={() => {}} size="small"/>);
      expect(driver.isXSmall()).toEqual(false);
      expect(driver.isSmall()).toEqual(true);
      expect(driver.isLarge()).toEqual(false);
    });

    it('should create a x-small toggle once given size', () => {
      const driver = createDriver(<ToggleSwitch checked={false} onChange={() => {}} size="x-small"/>);
      expect(driver.isXSmall()).toEqual(true);
      expect(driver.isSmall()).toEqual(false);
      expect(driver.isLarge()).toEqual(false);
    });
  });

  describe('testkit', () => {
    it('should exist', () => {
      const div = document.createElement('div');
      const dataHook = 'myDataHook';
      const wrapper = div.appendChild(ReactTestUtils.renderIntoDocument(
<ToggleSwitch dataHook={dataHook}/>
));
      const toggleSwitchTestkit = toggleSwitchTestkitFactory({wrapper, dataHook});
      expect(toggleSwitchTestkit.exists()).toBeTruthy();
    });
  });

  describe('enzyme testkit', () => {
    it('should exist', () => {
      const dataHook = 'myDataHook';
      const wrapper = mount(<ToggleSwitch dataHook={dataHook}/>);
      const toggleSwitchTestkit = enzymeToggleSwitchTestkitFactory({wrapper, dataHook});
      expect(toggleSwitchTestkit.exists()).toBeTruthy();
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
/*–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
Basic Style Sheet (launching soon plugin by Vinsol)
version: 1
author: Bhavesh Dhupar
email: bhavesh@vinsol.com
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/

* { margin : 0; padding : 0;}
body { color: #eee; font-size: 62.5%; font-family: Arial, Verdana; background: url(/images/launching_soon/bkgImg.jpg) repeat left top; }
.clear { overflow: hidden; }
h3 { color: #fff; font-size: 2.2em; }
.container { width: 100%; }
.header { width: 100%; height: 202px; background: url(/images/launching_soon/headerBkgImg.jpg) repeat left top; }
.logo { width: 1022px; margin: 0 auto; position: relative; }
.logo h1 { top: 68px; left: 27%; width: 447px; height: 190px; position: absolute; text-indent: -999em; background: url(/images/launching_soon/logo.jpg) no-repeat left top; }
.tagline { color: #fff; width: 723px; font-size: 2.2em; margin: 85px auto 50px; font-style: italic; font-family: georgia; }
#messageBox { width: 723px; margin: 0 auto; padding: 20px 0 0; background: url(/images/launching_soon/divider.jpg) repeat-x left top; }
#messageBox .clear { padding-bottom: 20px; background: url(/images/launching_soon/divider.jpg) repeat-x left bottom; }
.notifyForm { float: left; width: 300px; padding-right: 15px; }
.notifyForm .subscriberEmail { color: #555; border: none; width: 299px; margin: 10px 0; font-size: 1.6em; font-weight: bold; padding: 11px 0 10px 5px; background: url(/images/launching_soon/inputImg.jpg) no-repeat left top; }
.notifyMeButton { border: none; width: 151px; height: 40px; background: url(/images/launching_soon/bttnImg.jpg) no-repeat left top; }
.notifyForm span { display: block; margin: 10px 0 0; font-size: 1.4em; font-style: italic; font-family: georgia; }
.aboutBlk { float: right; width: 300px; padding-left: 15px; }
.aboutBlk p { padding: 10px 0; font-size: 1.4em; line-height: 22px; }
.aboutBlk p a, #footer span a  { color: #fffdc0; text-decoration: none; }
.aboutBlk div { height: 29px; padding-left: 33px; background: url(/images/launching_soon/twitterIcon.png) no-repeat left center; }
.aboutBlk div a { color: #fff; font-size: 1.2em; font-style: italic; font-family: georgia; text-decoration: underline; }
.lauchTime { width: 100%; margin: 30px 0 40px; }
.lauchTime p { font-size: 1.9em; text-align: center; font-family: georgia; }
.lauchTime p label { font-size: 1.2em; font-weight: bold; font-family: Arial; }
.note { font-size: 1.4em; font-style: italic; margin-bottom: 20px; font-family: georgia; }
#errorMessage, #successMessage { width: 290px; color: #D63430; font-size: 1.4em; margin: 10px 0 15px; font-family: georgia; border: 1px dotted #A34041; padding: 10px 10px 10px 60px; background: url(/images/launching_soon/error.png) no-repeat 5px center; }
#successMessage { color: #339124; border: 1px dotted #336d32; background: url(/images/launching_soon/success.png) no-repeat 5px center; }
#footer { width: 723px; margin:30px auto 0px; font-size: 14px; text-align: center; border-top:1px solid #333; padding:15px 0 20px;}

/*Example CSS to create LCD countdown look*/
.lcdstyle{ font-weight: bold; padding-left: 10px; color:#FFFDC0; }


text:
package checkspec.eclipse.util;

import java.util.function.Supplier;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Display;

import checkspec.util.Wrapper;

public class DisplayUtils {

	public static Display getDisplay() {
		Display display = Display.getCurrent();
		if (display == null) {
			display = Display.getDefault();
		}
		return display;
	}

	public static <T> T get(Supplier<T> supplier) {
		return new SyncUiThreadRunner<T>().get(supplier);
	}

	public static <T> T getWithException(SupplierWithCoreException<T> supplier) throws CoreException {
		SyncUiThreadRunner<Wrapper<T, CoreException>> runner = new SyncUiThreadRunner<>();
		Wrapper<T, CoreException> result = runner.get(() -> {
			try {
				return Wrapper.ofValue(supplier.get());
			} catch (CoreException e) {
				return Wrapper.ofThrowable(e);
			}
		});
		if (result.hasValue()) {
			return result.getValue();
		} else {
			throw result.getThrowable();
		}
	}

	public static void syncExec(Runnable runnable) {
		getDisplay().syncExec(runnable);
	}

	public static void asyncExec(Runnable runnable) {
		getDisplay().asyncExec(runnable);
	}

	private static class SyncUiThreadRunner<T> {

		private T result;

		public T get(Supplier<T> supplier) {
			getDisplay().syncExec(() -> {
				result = supplier.get();
			});
			return result;
		}
	}

	public static interface SupplierWithCoreException<T> {

		T get() throws CoreException;
	}
}


text:
"use strict";

module OrganizationRegister
{
    export interface IUserRoute extends angular.route.IRouteParamsService
    {
        id: string;
        organizationId: string;
    }
}


text:
    var oauthToken = null;

    function login() {
        var userLogin = $('#loginField').val();
        var userPassword = $('#passwordField').val();
        console.log ( '#someButton was clicked' );
        $.post({
            url: 'http://localhost:8080/app/rest/v2/oauth/token',
            headers: {
                'Authorization': 'Basic Y2xpZW50OnNlY3JldA==',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            data: {grant_type: 'password', username: userLogin, password: userPassword},
            success: function (data) {
                oauthToken = data.access_token;
                $('#loggedInStatus').show();
                $('#loginForm').hide();
                loadRecentOrders();
            }
        })
    }

    function loadRecentOrders() {
        $.get({
            url: 'http://localhost:8080/app/rest/v2/entities/workshop$Order?view=_local',
            headers: {
                'Authorization': 'Bearer ' + oauthToken,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: function (data) {
                $('#recentOrders').show();
                $.each(data, function (i, order) {
                    $('#ordersList').append("<li>" + order.description + "</li>");
                });
            }
        });
    }


text:
using System;
using System.Net;
using Utilities.Web.Extras;

namespace Utilities.Web
{
    public enum HttpMethod
    {
        Get,
        Post
    }

    public enum HttpProtocol
    {
        Version10 = 10,
        Version11 = 11
    }

    public class HttpOptions
    {
        public HttpOptions()
        {
            ProtocolVersion     = HttpProtocol.Version11;
            HttpMethod          = HttpMethod.Get;
            HttpAcceptHeader    = "*/*";
            UserAgent           = UserAgents.GetRandomUserAgent();
            DecompressionMethod = DecompressionMethods.GZip;
            AllowAutoRedirect   = true;
        }

        /// <summary>
        ///     Allows the WebRequest to be redirected by responding server.
        ///     <para>Default is True</para>
        /// </summary>
        public bool AllowAutoRedirect { get; set; }

        /// <summary>
        ///     Decompresses data that is compressed by some websites.
        ///     <para>Default is DecompressionMethods.GZip</para>
        /// </summary>
        public DecompressionMethods DecompressionMethod { get; set; }

        /// <summary>
        ///     Add headers to be sent to the server.
        /// </summary>
        public WebHeaderCollection HeaderCollection { get; set; }

        /// <summary>
        ///     The accept header.
        ///     <para>Default is "*/*"</para>
        /// </summary>
        public string HttpAcceptHeader { get; set; }

        /// <summary>
        ///     The HTTP method to use. GET / POST
        ///     <para>Default is Get</para>
        /// </summary>
        public HttpMethod HttpMethod { get; set; }

        /// <summary>
        ///     The data to post to server when using HTTP method POST
        /// </summary>
        public string PostData { get; set; }

        /// <summary>
        ///     HTTP Protocol version to use
        ///     <para>Default is Version 1.1</para>
        /// </summary>
        public HttpProtocol ProtocolVersion { get; set; }

        /// <summary>
        ///     Proxy settings
        /// </summary>
        public WebProxy Proxy { get; set; }

        /// <summary>
        ///     The referrer string.
        ///     <para>Default is null</para>
        /// </summary>
        public string Referer { get; set; }

        /// <summary>
        ///     The amount of time to wait for the server to respond
        /// </summary>
        public TimeSpan RequestTimeout { get; set; }

        /// <summary>
        ///     The URL of the website to visit
        /// </summary>
        public string Url { get; set; }

        /// <summary>
        ///     The user agent you want to pose as
        ///     <para>Default is randomly selected</para>
        /// </summary>
        public string UserAgent { get; set; }

        public CookieContainer Cookies { get; set; }

        internal Version ParseHttpVersion()
        {
            if (ProtocolVersion == HttpProtocol.Version10) return HttpVersion.Version10;

            return HttpVersion.Version11;
        }
    }
}


text:
const EventBus = require('./event-bus');
const error = require('./error');

module.exports = {
  EventBus,
  error,
};


text:
struct UniqueId_t;
class CUtlBuffer;

//-----------------------------------------------------------------------------
// Defines a globally unique ID
//-----------------------------------------------------------------------------
struct UniqueId_t
{
	unsigned char m_Value[16];
};

//-----------------------------------------------------------------------------
// Methods related to unique ids
//-----------------------------------------------------------------------------
void CreateUniqueId( UniqueId_t *pDest );
void InvalidateUniqueId( UniqueId_t *pDest );
bool IsUniqueIdValid( const UniqueId_t &id );
bool IsUniqueIdEqual( const UniqueId_t &id1, const UniqueId_t &id2 );
void UniqueIdToString( const UniqueId_t &id, char *pBuf, int nMaxLen );
bool UniqueIdFromString( UniqueId_t *pDest, const char *pBuf, int nMaxLen = 0 );
void CopyUniqueId( const UniqueId_t &src, UniqueId_t *pDest );
bool Serialize( CUtlBuffer &buf, const UniqueId_t &src );
bool Unserialize( CUtlBuffer &buf, UniqueId_t &dest );

inline bool operator ==( const UniqueId_t& lhs, const UniqueId_t& rhs )
{
	return !Q_memcmp( (void *)&lhs.m_Value[ 0 ], (void *)&rhs.m_Value[ 0 ], sizeof( lhs.m_Value ) );
}

#endif // UNIQUEID_H


text:
package org.apache.camel.spring.interceptor;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spring.SpringRouteBuilder;

/**
 * Easier transaction configuration as we do not have to setup a transaction error handler
 */
public class TransactionalClientDataSourceTransactedWithChoiceRedeliveryTest extends TransactionalClientDataSourceTest {

    protected RouteBuilder createRouteBuilder() throws Exception {
        return new SpringRouteBuilder() {
            public void configure() throws Exception {
                // will try at most 3 times
                errorHandler(transactionErrorHandler().maximumRedeliveries(3));

                from("direct:okay")
                    .transacted()
                    .choice()
                        .when(body().contains("Hello")).to("log:hello")
                    .otherwise()
                        .to("log:other")
                    .end()
                    .to("direct:tiger")
                    .setBody(constant("Elephant in Action")).bean("bookService");

                from("direct:tiger")
                    .transacted()
                    .setBody(constant("Tiger in Action")).bean("bookService");

                from("direct:donkey")
                    // notice this one is not marked as transacted but since the exchange is transacted
                    // the default error handler will not handle it and thus not interfeer
                    .setBody(constant("Donkey in Action")).bean("bookService");

                // marks this route as transacted that will use the single policy defined in the registry
                from("direct:fail")
                    .transacted()
                    .setBody(constant("Tiger in Action")).bean("bookService")
                    .to("direct:donkey");
            }
        };
    }

}


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");

class LoaderOptionsPlugin {
	constructor(options) {
		if(typeof options !== "object") options = {};
		if(!options.test) options.test = {
			test: () => true
		};
		this.options = options;
	}

	apply(compiler) {
		let options = this.options;
		compiler.plugin("compilation", (compilation) => {
			compilation.plugin("normal-module-loader", (context, module) => {
				let resource = module.resource;
				if(!resource) return;
				let i = resource.indexOf("?");
				if(ModuleFilenameHelpers.matchObject(options, i < 0 ? resource : resource.substr(0, i))) {
					let filterSet = new Set(["include", "exclude", "test"]);
					Object.keys(options)
						.filter((key) => !filterSet.has(key))
						.forEach((key) => context[key] = options[key]);
				}
			});
		});
	}
}

module.exports = LoaderOptionsPlugin;


text:
import csv
import psycopg2

# Open the data file
f = open('data/routes.dat')
reader = csv.reader(f)

# Read each line in the data file
records = []
for row in reader:
    airline_id, from_airport_id, to_airport_id, equipment = \
        row[1], row[3], row[5], row[8]

    if not airline_id.isdigit():
        continue

    if not from_airport_id.isdigit():
        continue

    if not to_airport_id.isdigit():
        continue

    record = {
        'airline_id': airline_id,
        'from_airport_id': from_airport_id,
        'to_airport_id': to_airport_id,
        'equipment': equipment,
    }
    records.append(record)

# Open a database connection
conn = psycopg2.connect('')
cursor = conn.cursor()

# Clear the existing entries
cursor.execute('delete from routes')

# Build and execute our insert statement
statement = '''
    insert into routes (airline_id, from_airport_id, to_airport_id, equipment)
    values (%(airline_id)s, %(from_airport_id)s, %(to_airport_id)s, %(equipment)s);
'''
cursor.executemany(statement, records)

# Commit and close the database connection
conn.commit()
conn.close()


text:
/* ***** BEGIN LICENSE BLOCK *****
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * ***** END LICENSE BLOCK ***** */

#include <hb-ot.h>

#include "third_party/blink/renderer/platform/fonts/opentype/open_type_caps_support.h"

namespace blink {

bool OpenTypeCapsSupport::SupportsOpenTypeFeature(hb_script_t script,
                                                  uint32_t tag) const {
  hb_face_t* const face = hb_font_get_face(harfbuzz_face_->GetScaledFont());
  DCHECK(face);

  DCHECK(
      (tag == HB_TAG('s', 'm', 'c', 'p') || tag == HB_TAG('c', '2', 's', 'c') ||
       tag == HB_TAG('p', 'c', 'a', 'p') || tag == HB_TAG('c', '2', 'p', 'c') ||
       tag == HB_TAG('s', 'u', 'p', 's') || tag == HB_TAG('s', 'u', 'b', 's') ||
       tag == HB_TAG('t', 'i', 't', 'l') || tag == HB_TAG('u', 'n', 'i', 'c') ||
       tag == HB_TAG('v', 'e', 'r', 't')));

  if (!hb_ot_layout_has_substitution(face))
    return false;

  // Get the OpenType tag(s) that match this script code
  DCHECK_EQ(HB_TAG_NONE, 0u);
  hb_tag_t script_tags[2] = {};
  unsigned num_returned_script_tags = std::size(script_tags);
  hb_ot_tags_from_script_and_language(
      static_cast<hb_script_t>(script), HB_LANGUAGE_INVALID,
      &num_returned_script_tags, script_tags, nullptr, nullptr);

  const hb_tag_t kGSUB = HB_TAG('G', 'S', 'U', 'B');
  unsigned script_index = 0;
  // Identify for which script a GSUB table is available.
  hb_ot_layout_table_select_script(face, kGSUB, num_returned_script_tags,
                                   script_tags, &script_index, nullptr);

  if (hb_ot_layout_language_find_feature(face, kGSUB, script_index,
                                         HB_OT_LAYOUT_DEFAULT_LANGUAGE_INDEX,
                                         tag, nullptr)) {
    return true;
  }
  return false;
}

}  // namespace blink


text:
/**
 * Created by blajv on 22.06.2017.
 */
import React from 'react';
import {fetchCandidateEducation} from "../actions/CandidateActions";
/**
 * Component used to display all the education data of the selected candidate
 * by accessing the Education tab.
 */
export default class EducationList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            educationType: "",
            provider: "",
            description: ""
        };
    }

    componentDidMount() {
        let result = fetchCandidateEducation(this.props.educationLink).payload;
        result.then( (response) => {
            if(response) {
                this.setState({
                    educationType: response.educationType,
                    provider: response.provider,
                    description: response.description
                });
            }
        });
    }

    render() {

        return (

                    {this.state.educationType}

                    {this.state.provider}

                    {this.state.description}

        )
    }
}


text: Made with  by Availity


text:
//
// immer: immutable data structures for C++
// Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente
//
// This software is distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
//

#pragma once

#include <cstdlib>

namespace immer {

/*!
 * A heap that simply passes on to the parent heap.
 */
template <typename Base>
struct identity_heap : Base
{
    template <typename... Tags>
    static void* allocate(std::size_t size, Tags... tags)
    {
        return Base::allocate(size, tags...);
    }

    template <typename... Tags>
    static void deallocate(std::size_t size, void* data, Tags... tags)
    {
        Base::deallocate(size, data, tags...);
    }
};

} // namespace immer


text:
If you want to contribute changes to the project, please make sure to following these guidelines:

1. Pull requests should be made against the [`dev`](https://github.com/fairmanager/fm-timepicker/tree/dev) branch.
2. Commit messages should have a prefix that indicate the type of change:
	- `[FIX]` for bug fixes
	- `[FEATURE]` for new features
	- `[TASK]` for minor corrections that don't affect the behavior of the component


text:
package org.archive.resource.warc;

import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.archive.format.http.HttpHeader;
import org.archive.format.http.HttpResponse;
import org.archive.resource.AbstractResource;
import org.archive.resource.MetaData;
import org.archive.resource.ResourceConstants;
import org.archive.resource.ResourceContainer;
import org.archive.resource.ResourceParseException;
import org.archive.util.Base32;
import org.archive.util.StreamCopy;
import org.archive.util.io.EOFNotifyingInputStream;
import org.archive.util.io.EOFObserver;
import org.archive.util.io.PushBackOneByteInputStream;

import com.google.common.io.ByteStreams;
import com.google.common.io.CountingInputStream;

public class WARCResource extends AbstractResource implements EOFObserver, ResourceConstants {
	CountingInputStream countingIS;
	private HttpResponse response;
	private DigestInputStream digIS;
	private MetaData envelope;

	public WARCResource(MetaData metaData, ResourceContainer container,
			HttpResponse response) throws ResourceParseException {

		super(metaData.createChild(PAYLOAD_METADATA),container);
		envelope = metaData;
		this.response = response;

		long length = -1;
		metaData.putString(ENVELOPE_FORMAT, ENVELOPE_FORMAT_WARC_1_0);
		metaData.putLong(WARC_HEADER_LENGTH, response.getHeaderBytes());
		MetaData fields = metaData.createChild(WARC_HEADER_METADATA);
		for(HttpHeader h : response.getHeaders()) {
			String name = h.getName();
			String value = h.getValue();
			fields.putString(name,value);
			if(name.toLowerCase().equals("content-length")) {
				// TODO: catch formatexception
				length = Long.parseLong(value);
			}
		}

		if(length >= 0) {
			countingIS = new CountingInputStream(
					ByteStreams.limit(response, length));
		} else {
			throw new ResourceParseException(null);
		}
		try {
			digIS = new DigestInputStream(countingIS,
					MessageDigest.getInstance("sha1"));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	public InputStream getInputStream() {
		return new EOFNotifyingInputStream(digIS, this);
	}

	public void notifyEOF() throws IOException {
		String digString = Base32.encode(digIS.getMessageDigest().digest());
		if(container.isCompressed()) {
			metaData.putLong(PAYLOAD_LENGTH, countingIS.getCount());
			metaData.putLong(PAYLOAD_SLOP_BYTES, StreamCopy.readToEOF(response));
			metaData.putString(PAYLOAD_DIGEST, "sha1:"+digString);
		} else {
			// consume trailing bytes if we can...
			InputStream raw = response.getInner();
			if(raw instanceof PushBackOneByteInputStream) {
				PushBackOneByteInputStream pb1bis =
					(PushBackOneByteInputStream) raw;
				long numNewlines = StreamCopy.skipChars(pb1bis, CR_NL_CHARS);
				if(numNewlines > 0) {
					metaData.putLong(PAYLOAD_LENGTH, countingIS.getCount());
					metaData.putLong(PAYLOAD_SLOP_BYTES, numNewlines);
					metaData.putString(PAYLOAD_DIGEST, "sha1:"+digString);
				}
			}
		}
	}
	public MetaData getEnvelopeMetaData() {
		return envelope;
	}
}


text:
import os
import sys
try:
    from setuptools import setup
except:
    from distutils.core import setup

import buildlet

def find_packages():
    packages = []
    for (dir, subdirs, files) in os.walk('buildlet'):
        package = dir.replace(os.path.sep, '.')
        if '__init__.py' in files:
            packages.append(package)
    return packages

setup_kwds = {}

if sys.version_info[0] >= 3:
    setup_kwds['use_2to3'] = True

setup(
    name='buildlet',
    version=buildlet.__version__,
    packages=find_packages(),
    author=buildlet.__author__,
    author_email='aka.tkf@gmail.com',
    url='https://github.com/tkf/buildlet',
    license=buildlet.__license__,
    description='buildlet - build tool like functionality as a Python module',
    long_description=buildlet.__doc__,
    keywords='build, task, dependency',
    classifiers=[
        "Development Status :: 3 - Alpha",
        # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers
    ],
    **setup_kwds
)


text:
%% MODIFIED by Tom Morin (05/01/2015) from script by Daniel Chonde

function type = metcor_bld2(blood_ffile,met_ffile,fit_source,batoffset,iteration,figrows,figcols)
    % This creates the various metabolite correction bld files & BAT
    % correction bld files.
    % INPUT:
    % - blood_ffile = File containing fitted TAC blood data (i.e plasma_art_Feng.bld)
    % - met_ffile = File containing Parent Fraction data (i.e. parent_fraction_hill.bld)
    % - fit_source = name of the Parent Fraction fit (i.e. hill, exp, etc.)
    % - batoffset = Bolus Arrival Time offset in seconds (calculated previously)
    % - Iteration, figrows, & figcols, were all used to organize the
    % aesthetics of the subplots/figures.  These are no longer needed in
    % the final report, so they are no longer produced.
    % OUTPUT:
    % - bld files for the met correction & BAT correction of each model fit
    % - type = A name describing the model fit & its met correciton (i.e. Feng_Hill, L3Exp_Power, etc.)

    % Read in data & create necessary matrices
    raw_data=dlmread('plasma_art.bld','\t',1,0);
    plasma_art=dlmread(blood_ffile,'\t',1,0);
    parentfraction=dlmread(met_ffile,'\t',1,0);

    %This method for finding sigfigs doesn't work when the last value is a
    %whole number
%     teststr=num2str(plasma_art(find(plasma_art(:,2)>0,1,'last'),2));
%     splits=regexp(teststr,'\.','split');
%     sf=size(splits{2},2);
    fid=fopen(blood_ffile,'r');
    fgetl(fid);
    teststr=fgetl(fid);
    splits=regexp(teststr,'\.','split');
    sf=length(splits{end});
    fclose(fid);

    if length(plasma_art(:,1))==length(parentfraction(:,1))
        plasma_art_metcor(:,1)=plasma_art(:,1);
        plasma_art_metcor(:,2)=plasma_art(:,2).*parentfraction(:,2);
    else
        error('Dimensions do not match');
    end

    % Set file name
    name = regexprep(blood_ffile, '.bld', '_metcor');
    name = strcat(name, '_', fit_source);
    type = regexprep(name, 'plasma_art_', '');
    type = regexprep(type, strcat('_metcor_', fit_source), '');

% * * The Plots generated below are no longer used in the final report. * *
% =========================================================================
%     % Plot some shit
%     if iteration == 1
%         figure
%     end
%     subplot(figrows.*2,figcols./2,((iteration.*2)-1));plot(plasma_art(:,1),plasma_art(:,2));hold on;
%     plot(plasma_art_metcor(:,1),plasma_art_metcor(:,2),'r');
%     %plot(raw_data(:,1),raw_data(:,2),'xk');
%     set(gca,'XScale','log', 'FontSize', 7);
%
%     ylabel('kBq/ml', 'FontSize', 7);
%     if iteration == 1
%         legend({'uncorrected','met corrected'}, 'Location', 'NorthEast', 'FontSize', 6, 'Orientation', 'vertical')
%         title(strcat(type, ' Fits'), 'FontSize', 12, 'FontWeight', 'bold')
%     else
%         legend('off');
%     end
%     subplot(figrows.*2,figcols./2,(iteration.*2));plot(parentfraction(:,1),parentfraction(:,2), 'm')
%     title(strcat(upper(fit_source), ' Fit Parent-Fraction'), 'FontSize', 9, 'FontWeight', 'bold');
%     ylabel('Fraction', 'FontSize', 7);
%     xlabel('Time (s)', 'FontSize', 7);
%     set(gca, 'FontSize', 7);
%     %hold off;
%
%     set(gcf, 'Position', [50 50 750 800]);
% =========================================================================
% * * The Plots generated above are no longer used in the final report. * *

    % Save JPG image of graph
    % saveas(gcf,fullfile(pwd,strcat(name, '.bmp')));
    % set(gca,'XScale','log');

    % Save BLD file with fit data
    names=textread(blood_ffile,'%s',1,'delimiter','\n');
    hdrnames=regexp(names,'\t','split');
    print_list(hdrnames{:},plasma_art_metcor,strcat(name, '.bld'),sf);

    % Apply BAT Offset & Save BLD file
    A=zeros(batoffset,2);
    [len,~]=size(A);
    for m=1:len-1
        A(m,1) = m;
    end
    for m=1:length(plasma_art_metcor)
        plasma_art_metcor(m,1) = plasma_art_metcor(m,1) + batoffset;
    end
    bat_cor = cat(1, A, plasma_art_metcor);
    print_list(hdrnames{:},bat_cor,strcat(name, '_BATcor.bld'),sf);
end


text:
package org.itsnat.droid.impl.xmlinflated.drawable;

import android.content.Context;
import android.graphics.drawable.Drawable;

import org.itsnat.droid.impl.ItsNatDroidImpl;
import org.itsnat.droid.impl.browser.PageImpl;
import org.itsnat.droid.impl.dom.drawable.XMLDOMDrawable;
import org.itsnat.droid.impl.xmlinflated.InflatedXMLResource;

/**
 * Created by jmarranz on 7/11/14.
 */
public abstract class InflatedXMLDrawable extends InflatedXMLResource<Drawable>
{
    protected Drawable drawable;

    public InflatedXMLDrawable(ItsNatDroidImpl itsNatDroid, XMLDOMDrawable xmlDOMDrawable, Context ctx)
    {
        super(itsNatDroid, xmlDOMDrawable,ctx);
    }

    public static InflatedXMLDrawable createInflatedDrawable(ItsNatDroidImpl itsNatDroid, XMLDOMDrawable xmlDOMDrawable, Context ctx, PageImpl page)
    {
        return page != null ? new InflatedXMLDrawablePage(itsNatDroid, xmlDOMDrawable, ctx,page) : new InflatedXMLDrawableStandalone(itsNatDroid, xmlDOMDrawable, ctx);
    }

    public XMLDOMDrawable getXMLDOMDrawable()
    {
        return (XMLDOMDrawable) xmlDOM;
    }

    public Drawable getDrawable()
    {
        return drawable;
    }

    public void setDrawable(Drawable drawable)
    {
        this.drawable = drawable;
    }

}


text:
namespace llvm {

/// MSP430MachineFunctionInfo - This class is derived from MachineFunction and
/// contains private MSP430 target-specific information for each MachineFunction.
class MSP430MachineFunctionInfo : public MachineFunctionInfo {
  virtual void anchor();

  /// CalleeSavedFrameSize - Size of the callee-saved register portion of the
  /// stack frame in bytes.
  unsigned CalleeSavedFrameSize;

  /// ReturnAddrIndex - FrameIndex for return slot.
  int ReturnAddrIndex;

  /// VarArgsFrameIndex - FrameIndex for start of varargs area.
  int VarArgsFrameIndex;

  /// SRetReturnReg - Some subtargets require that sret lowering includes
  /// returning the value of the returned struct in a register. This field
  /// holds the virtual register into which the sret argument is passed.
  unsigned SRetReturnReg;

public:
  MSP430MachineFunctionInfo() : CalleeSavedFrameSize(0) {}

  explicit MSP430MachineFunctionInfo(MachineFunction &MF)
    : CalleeSavedFrameSize(0), ReturnAddrIndex(0), SRetReturnReg(0) {}

  unsigned getCalleeSavedFrameSize() const { return CalleeSavedFrameSize; }
  void setCalleeSavedFrameSize(unsigned bytes) { CalleeSavedFrameSize = bytes; }

  unsigned getSRetReturnReg() const { return SRetReturnReg; }
  void setSRetReturnReg(unsigned Reg) { SRetReturnReg = Reg; }

  int getRAIndex() const { return ReturnAddrIndex; }
  void setRAIndex(int Index) { ReturnAddrIndex = Index; }

  int getVarArgsFrameIndex() const { return VarArgsFrameIndex;}
  void setVarArgsFrameIndex(int Index) { VarArgsFrameIndex = Index; }
};

} // End llvm namespace

#endif


text:
using System;

namespace PSWinCom.Gateway.Client.MessageFormatters
{
	/// <summary>
	/// Well known values used when generating a WDP (Wireless Datagram Protocol) header
	/// </summary>
	public class WDP
	{
		public const byte INFORMATIONELEMENT_IDENTIFIER_APPLICATIONPORT = 0x05;
	}
}


text:
<script src="./games/flap/game.js"></script>
<script src="./games/target/game.js"></script>
<script src="./games/rhythm/game.js"></script>

<!--
	  INSTRUCTIONS
      Copy the below script div, paste it at the end of the list of scripts
      above, uncomment it and insert the name of your game folder in
      the place indicated

     <script src="./games/{INSERT-GAME-NAME-HERE>/game.js"></script>
-->


text:
The scripts are executed at system boot through rc.local. An example of the rc.local file is part of this folder.

Disabling the executing can be done by temporarly set dw_run.sh to non-execute by

# chmod -x dw_run.sh

and re-enable by

# chmod +x dw_run.sh

--

$ svn ls https://github.com/VolpeUSDOT/CV-PEP.git/trunk/scripts/data_warehouse/staging_loading/
$ svn export https://github.com/VolpeUSDOT/CV-PEP.git/trunk/scripts/data_warehouse/staging_loading

--force


text:
package com.github.dkellenb.formulaevaluator.term.operator.bigdecimal;

import java.math.BigDecimal;

import com.github.dkellenb.formulaevaluator.FormulaEvaluatorConfiguration;
import com.github.dkellenb.formulaevaluator.term.operator.GenericStackableOperatorTerm;
import com.github.dkellenb.formulaevaluator.definition.Operator;
import com.github.dkellenb.formulaevaluator.term.Term;

/**
 * BigDecimal && Operator.
 */
public class BigDecimalLogicalAndOperator extends GenericStackableOperatorTerm<BigDecimal>
  implements BigDecimalOperator {

  /**
   * C'tor.
   *
   * @param base base value
   * @param applicants further terms (not null)
   */
  @SafeVarargs
  public BigDecimalLogicalAndOperator(Term<BigDecimal> base, Term<BigDecimal>... applicants) {
    super(base, applicants);
  }

  @Override
  public String getOperatorName() {
    return Operator.LOGICAL_AND.getOperatorName();
  }

  @Override
  public BigDecimal calculateDefault(FormulaEvaluatorConfiguration conf, BigDecimal v1, BigDecimal v2) {
    boolean b1 = !zero().equals(v1);
    boolean b2 = !zero().equals(v2);
    return b1 && b2 ? one() : zero();
  }

}


text:
{-# LANGUAGE NoMonomorphismRestriction #-}

module Crypto.Boring.Test.TestVectors
  ( getTestVectors
  , HashVector(..)
  , hashVectors
  , MonteCarloVectors(..)
  , monteCarloVectors
  , MacVector(..)
  , macVectors
  , CipherDirection(..)
  , CipherVector(..)
  , cipherVectors

  , toHex
  , vectorString
  ) where

import Control.Applicative
import Control.Exception (throwIO)
import Control.Monad
import Data.Void
import Numeric
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L
import qualified Data.ByteString as BS
import Path

data HashVector = HashVector
  { hvInput :: BS.ByteString
  , hvDigest :: BS.ByteString
  }

data MonteCarloVectors = MonteCarloVectors
  { mcvSeed :: BS.ByteString
  , mcvIterations :: [ BS.ByteString ]
  }

data MacVector = MacVector
  { mvKey :: BS.ByteString
  , mvInput :: BS.ByteString
  , mvDigest :: BS.ByteString
  }

data CipherDirection = CDEncrypt | CDDecrypt

data CipherVector = CipherVector
  { cvKey :: BS.ByteString
  , cvIv :: Maybe BS.ByteString
  , cvInput :: BS.ByteString
  , cvOutput :: BS.ByteString
  , cvDirection :: CipherDirection
  }

type Parser = Parsec Void String

hexString :: Parser BS.ByteString
hexString = fmap BS.pack $ some $ do
  nibbles <- replicateM 2 hexDigitChar
  case readHex nibbles of
    [ ( val, "" ) ] -> return val
    _ -> fail "hexadecimal byte"

skipSpace :: Parser ()
skipSpace = L.space
  (void spaceChar)
  (L.skipLineComment "#")
  empty

lexeme :: Parser a -> Parser a
lexeme = L.lexeme skipSpace

param :: String -> Parser a -> Parser a
param name value = do
  _ <- lexeme $ string name
  _ <- lexeme $ char '='
  lexeme value

hashVectors :: Parser [ HashVector ]
hashVectors = do
  skipSpace

  mbMdLen <- optional $ do
    void $ lexeme $ string "[L"
    void $ lexeme $ char '='
    mdLen <- lexeme L.decimal
    void $ lexeme $ char ']'
    skipSpace
    return mdLen

  let vector = do
        len <- param "Len" L.decimal
        msg <- param "Msg" hexString
        md <- param "MD" hexString
        realMsg <-
          if
            | maybe False (/= BS.length md) mbMdLen -> fail "invalid Md length"
            | len == 0 && msg == BS.singleton 0 -> return BS.empty
            | BS.length msg * 8 /= len -> fail "invalid Msg length"
            | otherwise -> return msg
        return HashVector
          { hvInput = realMsg
          , hvDigest = md
          }

  vecs <- many (vector <* skipSpace)
  eof
  return vecs

monteCarloVectors :: Parser MonteCarloVectors
monteCarloVectors = do
  skipSpace

  mbMdLen <- optional $ do
    void $ lexeme $ string "[L"
    void $ lexeme $ char '='
    mdLen <- lexeme L.decimal
    void $ lexeme $ char ']'
    skipSpace
    return mdLen

  let vectors curCount = do
        vecCount <- param "COUNT" L.decimal
        unless (vecCount == curCount) $ fail "Invalid COUNT"
        md <- param "MD" hexString
        when (maybe False (/= BS.length md) mbMdLen) $
          fail "invalid Md length"

        mds <- option [] $ vectors (curCount + 1)
        return (md : mds)

  seed <- param "Seed" hexString
  vecs <- vectors (0 :: Int)
  eof
  return $ MonteCarloVectors
    { mcvSeed = seed
    , mcvIterations = vecs
    }

macVectors :: Parser [ MacVector ]
macVectors = do
  skipSpace

  mbMdLen <- optional $ do
    void $ lexeme $ string "[L"
    void $ lexeme $ char '='
    mdLen <- lexeme L.decimal
    void $ lexeme $ char ']'
    skipSpace
    return mdLen

  let vector = do
        len <- param "Len" L.decimal
        key <- param "Key" hexString
        msg <- param "Msg" hexString
        md <- param "MD" hexString
        realMsg <-
          if
            | maybe False (/= BS.length md) mbMdLen -> fail "invalid Md length"
            | len == 0 && msg == BS.singleton 0 -> return BS.empty
            | BS.length msg * 8 /= len -> fail "invalid Msg length"
            | otherwise -> return msg
        return MacVector
          { mvKey = key
          , mvInput = realMsg
          , mvDigest = md
          }

  vecs <- many (vector <* skipSpace)
  eof
  return vecs

cipherVectors :: Parser [ CipherVector ]
cipherVectors = do
  skipSpace

  let parseDirection =
        (CDEncrypt <$ lexeme (string "[ENCRYPT]")) <|>
        (CDDecrypt <$ lexeme (string "[DECRYPT]"))

  let vectors currentDirection curCount = do
        ( newDir, newCount ) <- option ( currentDirection, curCount ) $ try $ do
          dir <- parseDirection
          return ( dir, 0 )

        vecCount <- param "COUNT" L.decimal
        unless (vecCount == newCount) $ fail "Invalid COUNT"
        key <- param "KEY" hexString
        iv <- optional $ param "IV" hexString
        ( input, output ) <- case newDir of
          CDEncrypt -> do
            plainText <- param "PLAINTEXT" hexString
            cipherText <- param "CIPHERTEXT" hexString
            return ( plainText, cipherText )
          CDDecrypt -> do
            cipherText <- param "CIPHERTEXT" hexString
            plainText <- param "PLAINTEXT" hexString
            return ( cipherText, plainText )

        let vec = CipherVector
              { cvKey = key
              , cvIv = iv
              , cvInput = input
              , cvOutput = output
              , cvDirection = newDir
              }

        otherVecs <- option [] $ vectors newDir (newCount + 1)
        return (vec : otherVecs)

  initialDir <- parseDirection

  vecs <- vectors initialDir (0 :: Int)
  eof
  return vecs

getTestVectors :: Parser a -> Path Rel File -> IO a
getTestVectors parser path = do
  let basePath = $(mkRelDir "third_party/python-cryptography/vectors/cryptography_vectors")
  vecString <- readFile $ toFilePath (basePath </> path)
  case runParser parser (toFilePath path) vecString of
    Left err -> throwIO err
    Right vectors -> return vectors

toHex :: BS.ByteString -> String
toHex bs = flip concatMap (BS.unpack bs) $ \d -> case showHex d "" of
      [ l ] -> [ '0', l ]
      hl -> hl

vectorString :: BS.ByteString -> BS.ByteString -> String
vectorString input output = trimmedInput ++ " -> " ++ toHex output
  where
    inputHex = toHex input
    trimmedInput
      | length inputHex > 50 = take 50 inputHex ++ "..."
      | otherwise = inputHex


text:
using System.ComponentModel;
using System.Runtime.Serialization;

namespace ChargeBee.Models.Enums
{
    public enum NotifyReferralSystemEnum
    {

        [EnumMember(Value = "Unknown Enum")]
        UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
                dotnet-client version incompatibility. We suggest you to upgrade to the latest version */

        [EnumMember(Value = "none")]
         None,

        [EnumMember(Value = "first_paid_conversion")]
         FirstPaidConversion,

        [EnumMember(Value = "all_invoices")]
         AllInvoices,

    }
}


text:
CSSUxOverbond hackathon at the University of Toronto (June 16-19 2016)

Event link: https://www.eventbrite.ca/e/cssu-x-overbond-hackathon-tickets-25935089551


text:
module Hancock
  module Matchers

    class LoginForm
      include Webrat::Methods
      include Webrat::Matchers
      def matches?(target)
        target.should have_selector("form[action='/sso/login'][method='POST']")
        target.should have_selector("form[action='/sso/login'][method='POST'] input[type='text'][name='email']")
        target.should have_selector("form[action='/sso/login'][method='POST'] input[type='password'][name='password']")
        target.should have_selector("form[action='/sso/login'][method='POST'] input[type='submit'][value='Login']")
        true
      end

      def failure_message
        puts "Expected a login form to be displayed, it wasn't"
      end
    end

    def be_a_login_form
      LoginForm.new
    end

    class SignupForm
      include Webrat::Methods
      include Webrat::Matchers
      def matches?(target)
        target.should have_selector("form[action='/sso/signup'][method='POST']")
        target.should have_selector("form[action='/sso/signup'][method='POST'] input[type='text'][name='email']")
        target.should have_selector("form[action='/sso/signup'][method='POST'] input[type='text'][name='first_name']")
        target.should have_selector("form[action='/sso/signup'][method='POST'] input[type='text'][name='last_name']")
        target.should have_selector("form[action='/sso/signup'][method='POST'] input[type='submit'][value='Signup']")
        true
      end

      def failure_message
        puts "Expected a signup form to be displayed, it wasn't"
      end
    end

    def be_a_signup_form
      SignupForm.new
    end

  end
end


text:
/*
This C++ programme runs single transactions through a single
endianness conversion function, then through a simple memory model,
then converts it back.
Takes the initial memory state as input and provides the final
memory state as output.
*/

#define BUFFER_SIZE 2048

#include<systemc>
#include "tlm.h"
#include<iostream>
#include<time.h>
#include <fstream>

using namespace std;
using namespace tlm;
using namespace sc_dt;

// simple set of types with known sizeof(), for testing //
template<int SIZE> class dt {
  char content[SIZE];
};

#define convert(function) \
  switch(data_width) { \
    case 1:  function<dt<1> >(&txn,bus_width); break; \
    case 2:  function<dt<2> >(&txn,bus_width); break; \
    case 4:  function<dt<4> >(&txn,bus_width); break; \
    case 8:  function<dt<8> >(&txn,bus_width); break; \
    case 16:  function<dt<16> >(&txn,bus_width); break; \
    case 32:  function<dt<32> >(&txn,bus_width); break; \
    default:  cout << "bad data width\n"; \
    exit(1); \
  }

// forward declarations - see below
template<class DATAWORD> inline void
local_single_tohe(tlm_generic_payload *txn, unsigned int sizeof_databus);
template<class DATAWORD> inline void
local_single_fromhe(tlm_generic_payload *txn, unsigned int sizeof_databus);

void test_a_conversion(char cmd, tlm_generic_payload &txn, std::ifstream & fin) {

  if(cmd == 'R') txn.set_read();
  else txn.set_write();

  fin.ignore(10000,'=');
  uint64 a;
  fin >> a;
  txn.set_address(a);

  fin.ignore(10000,'=');
  int l;
  fin >> l;
  txn.set_data_length(l);

  int bus_width;
  fin.ignore(10000,'=');  fin >> bus_width;

  int data_width;
  fin.ignore(10000,'=');  fin >> data_width;

  int initiator_offset;
  fin.ignore(10000,'=');  fin >> initiator_offset;

  unsigned char *original_byte_enable = 0;
  unsigned char *byte_enable_legible =
    new unsigned char[txn.get_data_length() + 1];
  memset(byte_enable_legible, 0, txn.get_data_length() + 1);
  fin.ignore(10000,'=');
  for(unsigned b=0; b<txn.get_data_length(); b++) {
    char tmp; fin >> tmp;
    if((tmp=='0')||(tmp=='1')||(tmp=='x')) byte_enable_legible[b]=tmp;
    else break;
  }
  if((byte_enable_legible[0] == '1') || (byte_enable_legible[0] == '0')) {
    txn.set_byte_enable_ptr(new unsigned char[txn.get_data_length()]);
    txn.set_byte_enable_length(txn.get_data_length());
    original_byte_enable = txn.get_byte_enable_ptr();
    for(unsigned int i=0; i<txn.get_data_length(); i++) {
      if(byte_enable_legible[i] == '0') {
        txn.get_byte_enable_ptr()[i] = TLM_BYTE_DISABLED;
      } else if(byte_enable_legible[i] == '1') {
        txn.get_byte_enable_ptr()[i] = TLM_BYTE_ENABLED;
      } else {
        // not enough byte enables
        txn.set_byte_enable_length(i);
        break;
      }
    }
  } else {
    txn.set_byte_enable_ptr(0);
    txn.set_byte_enable_length(0);
  }

  int stream_width;
  fin.ignore(10000,'=');  fin >> stream_width;
  txn.set_streaming_width(stream_width);

  cout << "enter initiator memory state = ("<< BUFFER_SIZE << " characters)\n";
  unsigned char initiator_mem[BUFFER_SIZE+1];
  memset(initiator_mem, 0, BUFFER_SIZE+1);
  fin.ignore(10000,'=');  fin >> initiator_mem;

  txn.set_data_ptr(initiator_mem + initiator_offset);

  cout << "enter target memory state = ("<< BUFFER_SIZE << " characters)\n";
  unsigned char target_mem[BUFFER_SIZE+1];
  memset(target_mem, 0, BUFFER_SIZE+1);
  fin.ignore(10000,'=');  fin >> target_mem;

  cout << "enter converter choice = (0 => generic, 1 => word, 2 => aligned, 3 => single)\n";
  int converter;
  fin.ignore(10000,'=');  fin >> converter;

  cout << "Initiator Intent\n";
  cout << "  Cmd = " << cmd << endl;
  cout << "  Addr = " << txn.get_address() << endl;
  cout << "  Len = " << txn.get_data_length() << endl;
  cout << "  Bus Width = " << bus_width << endl;
  cout << "  Data Word = " << data_width << endl;
#ifdef VERBOSE
  cout << "  Initiator offset and txn data pointer = " << initiator_offset << ", " << int(txn.get_data_ptr()) << endl;
  cout << "  Byte enables and byte enable pointer = " << byte_enable_legible << ", " << int(txn.get_byte_enable_ptr()) << endl;
#else
  cout << "  Initiator offset = " << initiator_offset << endl;
  cout << "  Byte enables = " << byte_enable_legible << endl;
#endif
  cout << "  Byte enable length = " << txn.get_byte_enable_length() << endl;
  cout << "  Streaming width = " << txn.get_streaming_width() << endl;
  cout << "  Initiator memory = " << initiator_mem << endl;
  cout << "  Target memory = " << target_mem << endl;
  cout << "  Converter = " << converter << endl << endl;

  // initiator //
  switch(converter) {
    case 0:  convert(tlm_to_hostendian_generic); break;
    case 1:  convert(tlm_to_hostendian_word); break;
    case 2:  convert(tlm_to_hostendian_aligned); break;
    case 3:  convert(tlm_to_hostendian_single); break;
    case 4:  convert(local_single_tohe); break;
    default:  cout << "no such converter as " << converter << endl;
    exit(1);
  }

  cout << "Converted Transaction\n";
  cout << "  Addr = " << txn.get_address() << endl;
  cout << "  Len = " << txn.get_data_length() << endl;
#ifdef VERBOSE
  cout << "  Txn data pointer = " << int(txn.get_data_ptr()) << endl;
  if(txn.get_byte_enable_ptr() != 0) {
    cout << "  Byte enables and byte enable pointer = ";
    for(unsigned int i=0; i<txn.get_data_length(); i++)
      cout << (txn.get_byte_enable_ptr()[i] ? '1' : '0');
    cout << ", " << int(txn.get_byte_enable_ptr()) << endl;
  }
#else
  cout << "  Txn data pointer = " <<
    (txn.get_data_ptr() == initiator_mem+initiator_offset ? "unchanged" : "changed") << endl;
  if(txn.get_byte_enable_ptr() != 0) {
    cout << "  Byte enables and byte enable pointer = ";
    for(unsigned int i=0; i<txn.get_data_length(); i++)
      cout << (txn.get_byte_enable_ptr()[i] ? '1' : '0');
    cout << ", " <<
     (txn.get_byte_enable_ptr() == original_byte_enable ? "unchanged" : "changed") << endl;
  }
#endif
  cout << "  Byte enable length = " << txn.get_byte_enable_length() << endl;
  cout << "  Streaming width = " << txn.get_streaming_width() << endl;
  cout << endl;

  // target //
  int sw = txn.get_streaming_width();
  if((txn.get_data_length()/sw)*sw != txn.get_data_length()) {
    cout << "ERROR: Data length not a multiple of streaming width\n";
    exit(1);
  }
  for(unsigned int ss = 0; ss < txn.get_data_length(); ss += sw) {
    if(txn.get_byte_enable_ptr() == 0) {
      // simple transaction can be processed by mem-copy
      if(txn.is_read())
        memcpy(ss+txn.get_data_ptr(), target_mem+txn.get_address(), sw);
      else
        memcpy(target_mem+txn.get_address(), ss+txn.get_data_ptr(), sw);
    } else {
      // complex transaction, byte enables, maybe shorter than data
      int bel = txn.get_byte_enable_length();
      if(txn.is_read()) {
        for(int j=0; j<sw; j++) {
          if(txn.get_byte_enable_ptr()[(ss+j) % bel])
            (txn.get_data_ptr())[ss+j] = target_mem[j+txn.get_address()];
        }
      } else {
        for(int j=0; j<sw; j++) {
          if(txn.get_byte_enable_ptr()[(ss+j) % bel])
            target_mem[j+txn.get_address()] = (txn.get_data_ptr())[ss+j];
        }
      }
    }
  }

  // initiator again //
  if((rand() & 0x100) && (converter < 4)) {
#ifdef VERBOSE
    cout << "using single entry point for response\n";
#endif
    tlm_from_hostendian(&txn);
  } else {
#ifdef VERBOSE
    cout << "using specific entry point for response\n";
#endif
    switch(converter) {
      case 0:  convert(tlm_from_hostendian_generic); break;
      case 1:  convert(tlm_from_hostendian_word); break;
      case 2:  convert(tlm_from_hostendian_aligned); break;
      case 3:  convert(tlm_from_hostendian_single); break;
      case 4:  convert(local_single_fromhe); break;
      default:  cout << "no such converter as " << converter << endl;
      exit(1);
    }
  }

  // print the results //
  cout << "Memory States after Transaction\n";
  cout << "  initiator = " << initiator_mem << endl;
  cout << "  target = " << target_mem << endl << endl;

  // clean up
  delete [] byte_enable_legible;
  if(original_byte_enable != 0) delete [] original_byte_enable;
}

void pool_status() {
  cout << "Pool status: ";
  tlm_endian_context *f = global_tlm_endian_context_pool.first;
  while(f!=0) {
    cout << "(" << f->dbuf_size << "," << f->bebuf_size << ") ";
    f = f->next;
  }
  cout << endl;
}

int sc_main(int argc, char **argv) {

  #include <string>

  // no command line parameters //
  // get everything from stdin and build transaction object //
  cout << "\nTLM-2 Endianness Conversion Helper Functions Tester\n";
  cout << "March 2008\n";
  cout << "January 2012 Updated to read from endian_conv/input.txt\n\n";

  std::string filename;
  std::ifstream fin;

  if (1 == argc)
      filename = "endian_conv/input.txt";
  else if (2 == argc)
      filename = argv[1];
  else {
    std::cerr << "Too many input arguments" << std::endl;
	return 1;
  }

  fin.open(filename.c_str(), ios_base::in);
  if (!fin) {
    std::cerr << "Could not open input filename " << filename << std::endl;
    return 1;
  }

  srand(time(NULL));
  const int nr_txns_in_pool = 7;
  const int txn_to_cycle = 4;
  tlm_generic_payload *txns[nr_txns_in_pool];
  for(int i=0; i < nr_txns_in_pool; i++) txns[i] = new tlm_generic_payload;

  for(int i=0; true; i = ((i+1) % nr_txns_in_pool)) {
    cout << i << " enter {R|W}, addr=a, len=l, bus width=b, word width=w, initiator offset=i, be={x|01}, stream width=s\n";
    pool_status();
    char command;
    fin >> command;
    if(fin.eof()) break;
    if((command != 'R') && (command != 'W')) break;
    if(i==txn_to_cycle) {
      // should cause 2 extensions to get pushed to the pool once they've been used
      delete txns[i];
      pool_status();
      delete txns[i-1];
      pool_status();
      // and popped back later when these new ones establish contexts
      txns[i] = new tlm_generic_payload;
      txns[i-1] = new tlm_generic_payload;
      pool_status();
    }
    test_a_conversion(command, *txns[i], fin);
  }

  for(int i=0; i < nr_txns_in_pool; i++) {
    delete txns[i];
    pool_status();
  }
  return 0;
}

// converter functions for non-aligned single transactions
// included here for validation only.  not designed for general use.

unsigned char *original_dptr;
sc_dt::uint64 original_addr;

template<class DATAWORD> inline void
local_single_tohe(tlm_generic_payload *txn, unsigned int sizeof_databus) {
  if(txn->get_data_length() != sizeof(DATAWORD)) {
    cout << "Error:  local_single_tohe() wrongly called\n";
    exit(1);
  }

  sc_dt::uint64 mask = sizeof_databus - 1;

  // set up new buffers, length and address
  if(sizeof(DATAWORD) > sizeof_databus)
    txn->set_data_length(sizeof_databus + sizeof(DATAWORD));
  else
    txn->set_data_length(2 * sizeof_databus);
  txn->set_streaming_width(txn->get_data_length());
  unsigned char *new_data = new unsigned char[txn->get_data_length()];
  unsigned char *new_be = new unsigned char[txn->get_data_length()];
  // drive all BEs to zero initially
  for(unsigned int i=0; i<txn->get_data_length(); i++) new_be[i] = 0;
  sc_dt::uint64 new_addr = txn->get_address() & ~mask;

  // Comments assume arithmetic mode big endian initiator modelled on little
  // endian host (but the functionality is the same for LE initiator on BE host)

  // iterate over the initiator word byte by byte, MSB first
  unsigned char *curr_d = txn->get_data_ptr() + sizeof(DATAWORD) - 1;
  unsigned char *curr_b = txn->get_byte_enable_ptr() + sizeof(DATAWORD) - 1;

  // initiator intent is to put the MSB at the address given in the transaction
  sc_dt::uint64 curr_a = txn->get_address();

  // iterate copying data and byte enables
  for( ; curr_d >= txn->get_data_ptr(); curr_d--, curr_b--, curr_a++) {
    // work out the address in the TLM interpretation of the initiator's intent
    sc_dt::uint64 he_addr = curr_a ^ mask;
    int idx = he_addr - new_addr;
    if(txn->is_write()) new_data[idx] = *curr_d;
    if(txn->get_byte_enable_ptr() == 0) new_be[idx] = 1;
    else new_be[idx] = *curr_b;
  }

  // replace the pointers
  original_dptr = txn->get_data_ptr();
  txn->set_data_ptr(new_data);
  txn->set_byte_enable_ptr(new_be);
  txn->set_byte_enable_length(txn->get_data_length());
  original_addr = txn->get_address();
  txn->set_address(new_addr);
}

template<class DATAWORD> inline void
local_single_fromhe(tlm_generic_payload *txn, unsigned int sizeof_databus) {
  sc_dt::uint64 mask = sizeof_databus - 1;

  // Comments assume arithmetic mode big endian initiator modelled on little
  // endian host (but the functionality is the same for LE initiator on BE host)

  // iterate over the initiator word byte by byte, MSB first
  unsigned char *curr_d = original_dptr + sizeof(DATAWORD) - 1;

  // initiator intent is to put the MSB at the address given in the transaction
  sc_dt::uint64 curr_a = original_addr;

  // iterate copying data and byte enables
  for( ; curr_d >= original_dptr; curr_d--, curr_a++) {
    // work out the address in the TLM interpretation of the initiator's intent
    sc_dt::uint64 he_addr = curr_a ^ mask;
    int idx = he_addr - txn->get_address();
    if((txn->is_read()) && (txn->get_byte_enable_ptr()[idx] != 0))
      *curr_d = txn->get_data_ptr()[idx];
  }

  // clean up
  delete [] txn->get_data_ptr();
  delete [] txn->get_byte_enable_ptr();
}


text:
class PostsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def show
    @comments = @post.comments.all
  end

  def create
    @post = current_user.posts.new(post_params)
    if @post.save
      redirect_to root_path
    else
      redirect_to root_path, notice: @post.errors.full_messages.first
    end
  end

  def edit
  end

  def update
    @post.update(post_params)
    redirect_to @post
  end

  def destroy
    @post.destroy
    respond_to do |format|
      format.js
      format.html { redirect_to root_path }
    end
  end

  private
  def set_post
    @post = Post.find(params[:id])
  end

  def post_params
    params.require(:post).permit(:content, :attachment)
  end
end


text:
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/xattr.h>
#include "overlayfs.h"

static int ovl_copy_up_truncate(struct dentry *dentry)
{
	int err;
	struct dentry *parent;
	struct kstat stat;
	struct path lowerpath;

	parent = dget_parent(dentry);
	err = ovl_copy_up(parent);
	if (err)
		goto out_dput_parent;

	ovl_path_lower(dentry, &lowerpath);
	err = vfs_getattr(&lowerpath, &stat);
	if (err)
		goto out_dput_parent;

	stat.size = 0;
	err = ovl_copy_up_one(parent, dentry, &lowerpath, &stat);

out_dput_parent:
	dput(parent);
	return err;
}

int ovl_setattr(struct dentry *dentry, struct iattr *attr)
{
	int err;
	struct dentry *upperdentry;

	/*
	 * Check for permissions before trying to copy-up.  This is redundant
	 * since it will be rechecked later by ->setattr() on upper dentry.  But
	 * without this, copy-up can be triggered by just about anybody.
	 *
	 * We don't initialize inode->size, which just means that
	 * inode_newsize_ok() will always check against MAX_LFS_FILESIZE and not
	 * check for a swapfile (which this won't be anyway).
	 */
	err = inode_change_ok(dentry->d_inode, attr);
	if (err)
		return err;

	err = ovl_want_write(dentry);
	if (err)
		goto out;

	if (attr->ia_valid & ATTR_SIZE) {
		struct inode *realinode = d_inode(ovl_dentry_real(dentry));

		err = -ETXTBSY;
		if (atomic_read(&realinode->i_writecount) < 0)
			goto out_drop_write;
	}

	err = ovl_copy_up(dentry);
	if (!err) {
		struct inode *winode = NULL;

		upperdentry = ovl_dentry_upper(dentry);

		if (attr->ia_valid & ATTR_SIZE) {
			winode = d_inode(upperdentry);
			err = get_write_access(winode);
			if (err)
				goto out_drop_write;
		}

		if (attr->ia_valid & (ATTR_KILL_SUID|ATTR_KILL_SGID))
			attr->ia_valid &= ~ATTR_MODE;

		inode_lock(upperdentry->d_inode);
		err = notify_change(upperdentry, attr, NULL);
		if (!err)
			ovl_copyattr(upperdentry->d_inode, dentry->d_inode);
		inode_unlock(upperdentry->d_inode);

		if (winode)
			put_write_access(winode);
	}
out_drop_write:
	ovl_drop_write(dentry);
out:
	return err;
}

static int ovl_getattr(struct vfsmount *mnt, struct dentry *dentry,
			 struct kstat *stat)
{
	struct path realpath;

	ovl_path_real(dentry, &realpath);
	return vfs_getattr(&realpath, stat);
}

int ovl_permission(struct inode *inode, int mask)
{
	struct ovl_entry *oe;
	struct dentry *alias = NULL;
	struct inode *realinode;
	struct dentry *realdentry;
	bool is_upper;
	int err;

	if (S_ISDIR(inode->i_mode)) {
		oe = inode->i_private;
	} else if (mask & MAY_NOT_BLOCK) {
		return -ECHILD;
	} else {
		/*
		 * For non-directories find an alias and get the info
		 * from there.
		 */
		alias = d_find_any_alias(inode);
		if (WARN_ON(!alias))
			return -ENOENT;

		oe = alias->d_fsdata;
	}

	realdentry = ovl_entry_real(oe, &is_upper);

	if (ovl_is_default_permissions(inode)) {
		struct kstat stat;
		struct path realpath = { .dentry = realdentry };

		if (mask & MAY_NOT_BLOCK)
			return -ECHILD;

		realpath.mnt = ovl_entry_mnt_real(oe, inode, is_upper);

		err = vfs_getattr(&realpath, &stat);
		if (err)
			goto out_dput;

		err = -ESTALE;
		if ((stat.mode ^ inode->i_mode) & S_IFMT)
			goto out_dput;

		inode->i_mode = stat.mode;
		inode->i_uid = stat.uid;
		inode->i_gid = stat.gid;

		err = generic_permission(inode, mask);
		goto out_dput;
	}

	/* Careful in RCU walk mode */
	realinode = ACCESS_ONCE(realdentry->d_inode);
	if (!realinode) {
		WARN_ON(!(mask & MAY_NOT_BLOCK));
		err = -ENOENT;
		goto out_dput;
	}

	if (mask & MAY_WRITE) {
		umode_t mode = realinode->i_mode;

		/*
		 * Writes will always be redirected to upper layer, so
		 * ignore lower layer being read-only.
		 *
		 * If the overlay itself is read-only then proceed
		 * with the permission check, don't return EROFS.
		 * This will only happen if this is the lower layer of
		 * another overlayfs.
		 *
		 * If upper fs becomes read-only after the overlay was
		 * constructed return EROFS to prevent modification of
		 * upper layer.
		 */
		err = -EROFS;
		if (is_upper && !IS_RDONLY(inode) && IS_RDONLY(realinode) &&
		    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
			goto out_dput;
	}

	err = __inode_permission(realinode, mask);
out_dput:
	dput(alias);
	return err;
}

static const char *ovl_get_link(struct dentry *dentry,
				struct inode *inode,
				struct delayed_call *done)
{
	struct dentry *realdentry;
	struct inode *realinode;

	if (!dentry)
		return ERR_PTR(-ECHILD);

	realdentry = ovl_dentry_real(dentry);
	realinode = realdentry->d_inode;

	if (WARN_ON(!realinode->i_op->get_link))
		return ERR_PTR(-EPERM);

	return realinode->i_op->get_link(realdentry, realinode, done);
}

static int ovl_readlink(struct dentry *dentry, char __user *buf, int bufsiz)
{
	struct path realpath;
	struct inode *realinode;

	ovl_path_real(dentry, &realpath);
	realinode = realpath.dentry->d_inode;

	if (!realinode->i_op->readlink)
		return -EINVAL;

	touch_atime(&realpath);

	return realinode->i_op->readlink(realpath.dentry, buf, bufsiz);
}

static bool ovl_is_private_xattr(const char *name)
{
	return strncmp(name, OVL_XATTR_PRE_NAME, OVL_XATTR_PRE_LEN) == 0;
}

int ovl_setxattr(struct dentry *dentry, struct inode *inode,
		 const char *name, const void *value,
		 size_t size, int flags)
{
	int err;
	struct dentry *upperdentry;

	err = ovl_want_write(dentry);
	if (err)
		goto out;

	err = -EPERM;
	if (ovl_is_private_xattr(name))
		goto out_drop_write;

	err = ovl_copy_up(dentry);
	if (err)
		goto out_drop_write;

	upperdentry = ovl_dentry_upper(dentry);
	err = vfs_setxattr(upperdentry, name, value, size, flags);

out_drop_write:
	ovl_drop_write(dentry);
out:
	return err;
}

ssize_t ovl_getxattr(struct dentry *dentry, struct inode *inode,
		     const char *name, void *value, size_t size)
{
	struct dentry *realdentry = ovl_dentry_real(dentry);

	if (ovl_is_private_xattr(name))
		return -ENODATA;

	return vfs_getxattr(realdentry, name, value, size);
}

ssize_t ovl_listxattr(struct dentry *dentry, char *list, size_t size)
{
	struct dentry *realdentry = ovl_dentry_real(dentry);
	ssize_t res;
	int off;

	res = vfs_listxattr(realdentry, list, size);
	if (res <= 0 || size == 0)
		return res;

	/* filter out private xattrs */
	for (off = 0; off < res;) {
		char *s = list + off;
		size_t slen = strlen(s) + 1;

		BUG_ON(off + slen > res);

		if (ovl_is_private_xattr(s)) {
			res -= slen;
			memmove(s, s + slen, res - off);
		} else {
			off += slen;
		}
	}

	return res;
}

int ovl_removexattr(struct dentry *dentry, const char *name)
{
	int err;
	struct path realpath;
	enum ovl_path_type type = ovl_path_real(dentry, &realpath);

	err = ovl_want_write(dentry);
	if (err)
		goto out;

	err = -ENODATA;
	if (ovl_is_private_xattr(name))
		goto out_drop_write;

	if (!OVL_TYPE_UPPER(type)) {
		err = vfs_getxattr(realpath.dentry, name, NULL, 0);
		if (err < 0)
			goto out_drop_write;

		err = ovl_copy_up(dentry);
		if (err)
			goto out_drop_write;

		ovl_path_upper(dentry, &realpath);
	}

	err = vfs_removexattr(realpath.dentry, name);
out_drop_write:
	ovl_drop_write(dentry);
out:
	return err;
}

static bool ovl_open_need_copy_up(int flags, enum ovl_path_type type,
				  struct dentry *realdentry)
{
	if (OVL_TYPE_UPPER(type))
		return false;

	if (special_file(realdentry->d_inode->i_mode))
		return false;

	if (!(OPEN_FMODE(flags) & FMODE_WRITE) && !(flags & O_TRUNC))
		return false;

	return true;
}

struct inode *ovl_d_select_inode(struct dentry *dentry, unsigned file_flags)
{
	int err;
	struct path realpath;
	enum ovl_path_type type;

	if (d_is_dir(dentry))
		return d_backing_inode(dentry);

	type = ovl_path_real(dentry, &realpath);
	if (ovl_open_need_copy_up(file_flags, type, realpath.dentry)) {
		err = ovl_want_write(dentry);
		if (err)
			return ERR_PTR(err);

		if (file_flags & O_TRUNC)
			err = ovl_copy_up_truncate(dentry);
		else
			err = ovl_copy_up(dentry);
		ovl_drop_write(dentry);
		if (err)
			return ERR_PTR(err);

		ovl_path_upper(dentry, &realpath);
	}

	if (realpath.dentry->d_flags & DCACHE_OP_SELECT_INODE)
		return realpath.dentry->d_op->d_select_inode(realpath.dentry, file_flags);

	return d_backing_inode(realpath.dentry);
}

static const struct inode_operations ovl_file_inode_operations = {
	.setattr	= ovl_setattr,
	.permission	= ovl_permission,
	.getattr	= ovl_getattr,
	.setxattr	= ovl_setxattr,
	.getxattr	= ovl_getxattr,
	.listxattr	= ovl_listxattr,
	.removexattr	= ovl_removexattr,
};

static const struct inode_operations ovl_symlink_inode_operations = {
	.setattr	= ovl_setattr,
	.get_link	= ovl_get_link,
	.readlink	= ovl_readlink,
	.getattr	= ovl_getattr,
	.setxattr	= ovl_setxattr,
	.getxattr	= ovl_getxattr,
	.listxattr	= ovl_listxattr,
	.removexattr	= ovl_removexattr,
};

struct inode *ovl_new_inode(struct super_block *sb, umode_t mode,
			    struct ovl_entry *oe)
{
	struct inode *inode;

	inode = new_inode(sb);
	if (!inode)
		return NULL;

	inode->i_ino = get_next_ino();
	inode->i_mode = mode;
	inode->i_flags |= S_NOATIME | S_NOCMTIME;

	mode &= S_IFMT;
	switch (mode) {
	case S_IFDIR:
		inode->i_private = oe;
		inode->i_op = &ovl_dir_inode_operations;
		inode->i_fop = &ovl_dir_operations;
		break;

	case S_IFLNK:
		inode->i_op = &ovl_symlink_inode_operations;
		break;

	case S_IFREG:
	case S_IFSOCK:
	case S_IFBLK:
	case S_IFCHR:
	case S_IFIFO:
		inode->i_op = &ovl_file_inode_operations;
		break;

	default:
		WARN(1, "illegal file type: %i\n", mode);
		iput(inode);
		inode = NULL;
	}

	return inode;
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.fetchPostsClear = exports.fetchPostsFailure = exports.fetchPostsSuccess = exports.fetchPostsRequest = undefined;

var _actionType = require('./actionType');

var fetchPostsRequest = exports.fetchPostsRequest = function fetchPostsRequest(subject, model, next) {
    return {
        type: _actionType.FETCH_POSTS_REQUEST,
        subject: subject,
        model: model,
        next: next
    };
}; /**
    * Created by yjy on 2017/3/31.
    */
var fetchPostsSuccess = exports.fetchPostsSuccess = function fetchPostsSuccess(subject, response) {
    return {
        type: _actionType.FETCH_POSTS_SUCCESS,
        subject: subject,
        response: response
    };
};

var fetchPostsFailure = exports.fetchPostsFailure = function fetchPostsFailure(subject, error) {
    return {
        type: _actionType.FETCH_POSTS_FAILURE,
        subject: subject,
        error: error
    };
};

var fetchPostsClear = exports.fetchPostsClear = function fetchPostsClear(subject) {
    return {
        type: _actionType.FETCH_POSTS_CLEAR,
        subject: subject
    };
};


text:
namespace Supermarket.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;

    public class Expense
    {
        public int ExpenseId { get; set; }

        [Required]
        public int VendorId { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime ExpenseDate { get; set; }

        [Required]
        public decimal ExpenseAmount { get; set; }

        public Vendor Vendor { get; set; }
    }
}


text:
"""
Encrypted fields from Django Extensions, modified for use with mongoDB
"""
from mongoengine.base import BaseField
from django.core.exceptions import ImproperlyConfigured
from django import forms
from django.conf import settings

try:
    from keyczar import keyczar
except ImportError:
    raise ImportError('Using an encrypted field requires the Keyczar module.  You can obtain Keyczar from http://www.keyczar.org/.')

class BaseEncryptedField(BaseField):
    prefix = 'enc_str:::'
    def __init__(self, *args, **kwargs):
        if not hasattr(settings, 'ENCRYPTED_FIELD_KEYS_DIR'):
            raise ImproperlyConfigured('You must set settings.ENCRYPTED_FIELD_KEYS_DIR to your Keyczar keys directory.')
        self.crypt = keyczar.Crypter.Read(settings.ENCRYPTED_FIELD_KEYS_DIR)
        super(BaseEncryptedField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if (value.startswith(self.prefix)):
            retval = self.crypt.Decrypt(value[len(self.prefix):])
        else:
            retval = value

        return retval

    def get_db_prep_value(self, value):
        if not value.startswith(self.prefix):
            value = self.prefix + self.crypt.Encrypt(value)
        return value

class EncryptedTextField(BaseEncryptedField):

    def get_internal_type(self):
        return 'StringField'

    def formfield(self, **kwargs):
        defaults = {'widget': forms.Textarea}
        defaults.update(kwargs)
        return super(EncryptedTextField, self).formfield(**defaults)

class EncryptedCharField(BaseEncryptedField):

    def __init__(self, max_length=None, *args, **kwargs):
        if max_length:
            max_length += len(self.prefix)

        super(EncryptedCharField, self).__init__(max_length=max_length, *args, **kwargs)

    def get_internal_type(self):
        return "StringField"

    def formfield(self, **kwargs):
        defaults = {'max_length': self.max_length}
        defaults.update(kwargs)
        return super(EncryptedCharField, self).formfield(**defaults)


text:
import json
import uuid
import requests
import datetime as tmz
import pytz
import delorean

class DataConnection(object):

    def _get_csrf(self):
        """
        :return: Get the csrf from the local session
        """
        response = self.client.get(url="{}/noop/".format(self.configurator.get_config()['server']))
        return response.cookies['csrftoken']

    def __init__(self, configurator):
        self.configurator = configurator
        self.client = requests.session()
        self.csrf = self._get_csrf()

    def _api_url(self, resource_name):
        """
        Get restful endpoint for resource type
        :param resource_name: The type of resource requested (e.g. "local_computer")
        :return: The base api url to connect to the data server
        """
        return "{}/api/v1/{}/?format=json".format(self.configurator.get_config()['server'], resource_name)

    def _item_url(self, resource_name, resource_id):
        """
        Get restful endpoint for a specific instance of a resource.
        :param resource_name: The type of resource requested
        :param id: The id of the resource
        :return: A specific resource instance
        """
        return "{}/api/v1/{}/{}/?format=json".format(self.configurator.get_config()['server'], resource_name,
                                                     resource_id)

    def _data_item_url(self, resource_name, resource_id):
        """
        Add data points to the given resource
        :param resource_name: The type of resource requested
        :param id: The id of the resource
        :return: A specific data_api resource instance
        """
        return "{}/data_api/v1/{}/{}/?format=json".format(self.configurator.get_config()['server'],
                                                          resource_name, resource_id)

    def register(self, registration_token=None, file_name=None):
        """
        Call to register a new local computer.
        """
        config = self.configurator.get_config()
        if registration_token:
            config["registration_token"] = registration_token

        config["secret_uuid"] = str(uuid.uuid4())

        response = requests.post(self._api_url('local_computer'),
                                 data=json.dumps(self.configurator.get_config()),
                                 headers=self.post_header())

        new_config = json.loads(response.content)
        self.configurator.set_config(new_config)

    def update_config(self, config_location):
        """
        :param config_location: Location of local config file
        Update local config with global config.
        """
        config = self.configurator.get_config()
        url = self._item_url('local_computer', config['id'])
        response = requests.get(url, headers= self.sec_header())
        if self.check_response_ok(response):
            updated_config = json.loads(response.content)
            for key in updated_config.keys():
                config[key] = updated_config[key]
            self.configurator.write_config(config_location)

    def set_local_computer_status(self, is_running):
        """
        :param isRunning:
        """
        config = self.configurator.get_config()
        config['is_running'] = is_running
        url = self._item_url('local_computer', config['id'])
        response = requests.put(url, data=json.dumps(self.configurator.get_config()), headers=self.sec_header())

    def get_new_commands(self):
        """
        :return: Commands from the server for this local computer that should be executed.
        """
        config = self.configurator.get_config()
        id = config["id"]
        url = self._api_url('command') + "&is_local_computer_id={}&is_executed=false".format(id)
        response = requests.get(url, headers = self.sec_header())
        if self.check_response_ok(response):
            return json.loads(response.content)['objects']
        return []

    def deactivate_command(self, command):
        """
        Indicate that a command has been executed.
        :param command:
        :return:
        """
        config = self.configurator.get_config()
        id = config["id"]
        command['is_executed'] = True
        url = self._item_url('command', command['id']) + "&is_local_computer_id={}".format(id)
        response = requests.put(url, data=json.dumps(command), headers=self.sec_header())
        self.check_response_ok(response)

    def get_program(self, program_id):
        """
        :param program_id:
        :return: the program object or None if it doesn't exist
        """
        config = self.configurator.get_config()
        url = self._item_url('program', program_id)
        response = self.client.get(url, headers=self.sec_header())
        if self.check_response_ok(response):
            return json.loads(response.content)
        return None

    def get_or_create_experiment(self, experiment_name):
        """
        Get or create an experiment object for this local computer
        :param experiment_name:
        :return: The experiment object dict.
        """
        config = self.configurator.get_config()
        # print config
        url = self._api_url('experiment')
        params = {'name': experiment_name, 'local_computer_id': config['id']}

        response = self.client.get(url, params=params, headers=self.sec_header())

        if len(json.loads(response.content)['objects']) == 0:
            self.client.post(url, data=json.dumps(params), headers=self.post_header())
            response = self.client.get(url, params=params, headers=self.sec_header())

        return json.loads(response.content)['objects'][0]

    def add_signal_points(self, signal_id, signal_points):
        """ Add sorted time/value points to a signal
        :param signal_id: The id of the signal to add points to
        :param signal_points: [[<t1>,<v1>],[<t2>,<v2>
        """
        config = self.configurator.get_config()
        url = self._data_item_url('signal', signal_id)
        # print 'URL:', url
        # print 'HEADERS:', self.post_header()
        response = self.client.post(url, data=json.dumps(signal_points), headers=self.post_header())
        if not DataConnection.check_response_ok(response):
            print "Error posting signal data {}".format(response.content)
            print "Raising Exception!"
            raise Exception("Error posting signal data {}".format(response.content))

    def add_signal_points_by_name(self, signal_name, signal_points):
        """
        Add time/value points to a signal object belonging to this local_computer.
        :param signal_name:
        :param signal_points: points in format[[<value>,<millisec>], ...]
        """
        config = self.configurator.get_config()

        url = self._api_url('signal')
        response = self.client.get(url, params={'name': signal_name, 'local_computer_id': config['id']},
                                headers=self.sec_header())
        signal_id = json.loads(response.content)['objects'][0]['id']
        self.add_signal_points(signal_id, signal_points)

    def get_signal_points(self, signal_id):
        """
        Get the data points from the given signal.
        :param signal_id:
        :return: a list of signal point in format[[<value>,<millisec>], ...]
        """
        config = self.configurator.get_config()

        url = self._data_item_url('signal', signal_id)
        response = self.client.get(url,headers=self.sec_header())
        if self.check_response_ok(response):
            return json.loads(response.content)
        return []

    def get_signal_points_by_name(self, name):
        """
        Get the indicated signal from the local computer
        :param name: The name of the signal
        :return: a list of time/value points [[<value1>,<millisec>] ...]
        """
        config = self.configurator.get_config()
        url = self._api_url('signal')
        response = self.client.get(url, params={'name': name, 'local_computer_id': config['id']},
                                headers=self.sec_header())
        return self.get_signal_points(json.loads(response.content)['objects'][0]['id'])

    def get_or_create_signal(self, signal_name, experiment):
        """
        Get or create a signal object for this local computer
        :param signal_name: experiment: The experiment
        :return: The signal object dict.
        """
        config = self.configurator.get_config()
        # print config
        url = self._api_url('signal')

        params = {'name': signal_name, 'local_computer_id': config['id'],
                  'experiment_id': experiment['id']}

        response = self.client.get(url, params=params, headers=self.sec_header())
        if len(json.loads(response.content)['objects']) == 0:
            self.client.post(url, data=json.dumps(params), headers=self.post_header())
            response = self.client.get(url, params=params, headers=self.sec_header())

        return json.loads(response.content)['objects'][0]

    def get_or_create_setting(self, key, experiment):
        """
        Get or create a setting object for this local computer
        :param setting: Setting key
        :return: The setting object dict.
        """
        config =self.configurator.get_config()
        url = self._api_url('setting')
        params = {'key': key, 'local_computer_id': config['id'],
                  'experiment_id': experiment['id']}

        response = self.client.get(url, params=params, headers=self.sec_header())
        if len(json.loads(response.content)['objects']) == 0:
            self.client.post(url, data=json.dumps(params), headers=self.post_header())
            response = self.client.get(url, params=params, headers=self.sec_header())

        return json.loads(response.content)['objects'][0]

    def write_setting(self, value, setting_id):
        config =self.configurator.get_config()
        url = self._data_item_url('setting', setting_id)

        params = dict()
        params['value'] = value

        response = self.client.post(url, data=json.dumps(params), headers=self.post_header())
        if not DataConnection.check_response_ok(response):
            print "Error posting setting data {}".format(response.content)
            print "Raising Exception!"
            raise Exception("Error posting setting data {}".format(response.content))

    def get_or_create_blob(self, blob_name):
        """
        Get or create a new blob object for this local computer
        :param blob_name:
        :return: the blob object dict.
        """
        config =self.configurator.get_config()
        url = self._api_url('blob')
        params = {'name': blob_name, 'local_computer_id': config['id']}
        response = self.client.get(url, params=params, headers=self.sec_header())
        if len(json.loads(response.content)['objects']) == 0:
            response = self.client.post(url, data=json.dumps(params), headers=self.post_header())
            response = self.client.get(url, params=params, headers=self.sec_header())

        return json.loads(response.content)['objects'][0]

    def set_blob_data(self, id, blob_data):
        """
        Store data in a blob object.
        :param id:
        :param blob_data: String representation of blob to store
        :return:
        """
        url = self._data_item_url('blob', id)
        response = self.client.post(url, data=blob_data, headers=self.post_header())
        if not DataConnection.check_response_ok(response):
            print "Error posting blob data {}".format(response.content)

    def set_blob_data_by_name(self, name, blob_data):
        config = self.configurator.get_config()
        url = self._api_url('blob')
        response = self.client.get(url, params={'name': name, 'local_computer_id': config['id']},
                                headers=self.sec_header())
        self.set_blob_data(json.loads(response.content)['objects'][0]['id'], blob_data)

    def get_blob_data(self, id):
        url = self._data_item_url('blob', id)
        response = self.client.get(url, headers=self.sec_header())
        return response.content

    def get_blob_data_by_name(self, name):
        config = self.configurator.get_config()
        url = self._api_url('blob')
        response = self.client.get(url, params={'name': name, 'local_computer_id': config['id']},
                                headers=self.sec_header())
        return self.get_blob_data(json.loads(response.content)['objects'][0]['id'])

    def create_event(self, event_type, info):
        config = self.configurator.get_config()
        url = self._api_url('event')
        response = self.client.post(url, data=json.dumps({'type': event_type, 'info': info,
                                                          'local_computer_id': config['id']}),
                                    headers=self.post_header())
        if not self.check_response_ok(response):
            print "Error creating event {}: {}".format(event_type, info)

    def sec_header(self, base_header=None):
        auth_header = {'auth_key': self.configurator.get_config()["secret_uuid"],
                       'content-type': 'application/json'}
        if base_header is None:
            return auth_header
        auth_header.update(base_header)

    def post_header(self):
        auth_header = {'auth_key': self.configurator.get_config()["secret_uuid"],
                       'content-type': 'application/json', "X-CSRFToken": self.csrf}
        return auth_header

    @classmethod
    def check_response_ok(cls, response):
        """
        :return: True if http response is a 200 class response.  False info otherwise.
        """
        if 200 <= response.status_code < 300:
            return True
        else:
            response_string = "WARNING Command lookup failed: status: {} reason: {}".format(response.status_code,
                                                                                response.reason)
            if response.content:
                response_string += response.content
            print response_string
            return False

    @classmethod
    def millisec_to_utc(cls, millisec):
        return tmz.datetime.fromtimestamp(float(millisec), tz=pytz.UTC)

    @classmethod
    def utc_to_millisec(cls, dt):
#        return delorean.Delorean(dt, timezone="UTC")
#        print 'DELORRREAANN'
#        print delorean.Delorean(dt, timezone="UTC").epoch
        return delorean.Delorean(dt, timezone="UTC").epoch


text:
function isSimpleObject(obj: any) {
    if (typeof obj !== 'object' || obj === null) {
        return false;
    }
    return Object.getPrototypeOf(obj) === Object.getPrototypeOf({});
}

export function mergeObjects(listOfObjects: Array<any>) {
    function merge(obj1: any, obj2: any, keyStack: Array<string>) {
        Object.keys(obj2).forEach(function (key) {
            const obj1Value = obj1[key];
            const obj2Value = obj2[key];
            const obj1Type = typeof obj1Value;
            const obj2Type = typeof obj2Value;
            if (obj1Type === 'undefined' || obj1Value === null) {
                // undefined or null properties are always overwritable
                obj1[key] = obj2[key];
            } else if (isSimpleObject(obj1Value) && isSimpleObject(obj2Value)) {
                // thread through objects.
                keyStack.push(key);
                merge(obj1Value, obj2Value, keyStack);
                keyStack.pop();
            } else if (obj1Type === obj2Type) {
                // same typed values may be overwritten, but with a warning.
                obj1[key] = obj2[key];
            } else {
                console.error('Unmergable at ' + keyStack.join('.') + ':' + key, obj1Type, obj1Value, obj2Type, obj2Value);
                throw new Error('Unmergable at ' + keyStack.join('.') + ':' + key);
            }
        });
    }
    const base = JSON.parse(JSON.stringify(listOfObjects[0]));
    for (let i = 1; i < listOfObjects.length; i += 1) {
        merge(base, listOfObjects[i], []);
    }
    return base;
}


text:
package org.springframework.security.web.authentication.preauth;

import static org.assertj.core.api.Assertions.*;

import java.util.*;

import org.junit.Test;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.GrantedAuthoritiesContainer;
import org.springframework.security.core.userdetails.UserDetails;

/**
 *
 * @author TSARDD
 * @since 18-okt-2007
 */
public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {

	@Test(expected = IllegalArgumentException.class)
	public void testGetUserDetailsInvalidType() {
		PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
		PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
				"dummy", "dummy");
		token.setDetails(new Object());
		svc.loadUserDetails(token);
	}

	@Test(expected = IllegalArgumentException.class)
	public void testGetUserDetailsNoDetails() {
		PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
		PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
				"dummy", "dummy");
		token.setDetails(null);
		svc.loadUserDetails(token);
	}

	@Test
	public void testGetUserDetailsEmptyAuthorities() {
		final String userName = "dummyUser";
		testGetUserDetails(userName, AuthorityUtils.NO_AUTHORITIES);
	}

	@Test
	public void testGetUserDetailsWithAuthorities() {
		final String userName = "dummyUser";
		testGetUserDetails(userName, AuthorityUtils.createAuthorityList("Role1", "Role2"));
	}

	private void testGetUserDetails(final String userName,
			final List<GrantedAuthority> gas) {
		PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
		PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
				userName, "dummy");
		token.setDetails((GrantedAuthoritiesContainer) () -> gas);
		UserDetails ud = svc.loadUserDetails(token);
		assertThat(ud.isAccountNonExpired()).isTrue();
		assertThat(ud.isAccountNonLocked()).isTrue();
		assertThat(ud.isCredentialsNonExpired()).isTrue();
		assertThat(ud.isEnabled()).isTrue();
		assertThat(userName).isEqualTo(ud.getUsername());

		// Password is not saved by
		// PreAuthenticatedGrantedAuthoritiesUserDetailsService
		// assertThat(password).isEqualTo(ud.getPassword());

		assertThat(gas.containsAll(ud.getAuthorities())
						&& ud.getAuthorities().containsAll(gas)).withFailMessage("GrantedAuthority collections do not match; result: "+ ud.getAuthorities() + ", expected: " + gas).isTrue();
	}

}