text:
package test;

import test2.Target2;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Class used as part of the class loading tests. This class uses
 * other classes, some of which should have come from the same jar/dex
 * file and others of which should have come from a different jar/dex
 * file. Each test method in this class is called from the same-named
 * method in {@code DexClassLoaderTest}.
 */
public class TestMethods {
    /*
     * The following are all simple utility methods which, under
     * normal circumstances, would be part of other libraries
     * (specifically, JUnit and the Android libcore support library).
     *
     * However, this file gets compiled as an independent unit without
     * any dependencies. We could theoretically add dependencies on other
     * libraries, but that would make things much more complicated and
     * fragile, and for very little benefit.
     */

    /**
     * Simple sameness assertion checker.
     */
    public static void assertSame(Object expected, Object actual) {
        if (expected != actual) {
            throw new RuntimeException(
                "EXPECTED: " + expected + "; ACTUAL: " + actual);
        }
    }

    /**
     * Simple sameness assertion checker.
     */
    public static void assertSame(int expected, int actual) {
        if (expected != actual) {
            throw new RuntimeException(
                "EXPECTED: " + expected + "; ACTUAL: " + actual);
        }
    }

    /**
     * Fully read the contents of the given stream.
     */
    public static byte[] readFully(InputStream in) throws IOException {
        // This is a copy of the same-named method in libcore.io.Streams.
        byte[] buffer = new byte[1024];
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        while (true) {
            int byteCount = in.read(buffer);
            if (byteCount == -1) {
                return bytes.toByteArray();
            }
            bytes.write(buffer, 0, byteCount);
        }
    }

    /*
     * Test methods that use another class from the same dex/jar file
     */

    /**
     * Test that an instance of a sibling class can be constructed.
     */
    public static void test_constructor() {
        new Target();
    }

    /**
     * Test calling a static method on a sibling class.
     */
    public static void test_callStaticMethod() {
        assertSame("blort", Target.blort());
    }

    /**
     * Test getting a static variable of a sibling class.
     */
    public static void test_getStaticVariable() {
        Target.setStaticVariable(22);
        assertSame(22, Target.staticVariable);
    }

    /**
     * Test calling an instance method on a sibling class.
     */
    public static void test_callInstanceMethod() {
        Target target = new Target();
        assertSame("zorch", target.zorch());
    }

    /**
     * Test getting an instance variable of a sibling class.
     */
    public static void test_getInstanceVariable() {
        Target target = new Target();
        target.setInstanceVariable(10098);
        assertSame(10098, target.instanceVariable);
    }

    /**
     * Test getting a resource which should be in the same jar
     * file as this class.
     */
    public static void test_getResourceAsStream() throws IOException {
        ClassLoader cl = TestMethods.class.getClassLoader();
        InputStream in = cl.getResourceAsStream("test/Resource1.txt");
        byte[] contents = readFully(in);
        String s = new String(contents, "UTF-8");

        assertSame("Muffins are tasty!\n", s.intern());
    }

    /*
     * Test methods that use a class from a different dex/jar file
     */

    /**
     * Test that an instance of a cousin class can be constructed.
     */
    public static void test_diff_constructor() {
        new Target2();
    }

    /**
     * Test calling a static method on a cousin class.
     */
    public static void test_diff_callStaticMethod() {
        assertSame("frotz", Target2.frotz());
    }

    /**
     * Test getting a static variable of a cousin class.
     */
    public static void test_diff_getStaticVariable() {
        Target2.setStaticIgram(220);
        assertSame(220, Target2.staticIgram);
    }

    /**
     * Test calling an instance method on a cousin class.
     */
    public static void test_diff_callInstanceMethod() {
        Target2 target = new Target2();
        assertSame("fizmo", target.fizmo());
    }

    /**
     * Test getting an instance variable of a cousin class.
     */
    public static void test_diff_getInstanceVariable() {
        Target2 target = new Target2();
        target.setInstanceMagri(10098);
        assertSame(10098, target.instanceMagri);
    }

    /**
     * Test getting a resource which should be in a different jar
     * file as this class.
     */
    public static void test_diff_getResourceAsStream() throws IOException {
        ClassLoader cl = TestMethods.class.getClassLoader();
        InputStream in = cl.getResourceAsStream("test2/Resource2.txt");
        byte[] contents = readFully(in);
        String s = new String(contents, "UTF-8");

        assertSame("Who doesn't like a good biscuit?\n", s.intern());
    }
}


text:
<?php
// Include required library files.
require_once('../includes/config.php');
require_once('../autoload.php');

// Create PayPal object.
$PayPalConfig = array(
					  'Sandbox' => $sandbox,
					  'DeveloperAccountEmail' => $developer_account_email,
					  'ApplicationID' => $application_id,
					  'DeviceID' => $device_id,
					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
					  'APIUsername' => $api_username,
					  'APIPassword' => $api_password,
					  'APISignature' => $api_signature,
					  'APISubject' => $api_subject,
					  'PrintHeaders' => $print_headers,
					  'LogResults' => $log_results,
					  'LogPath' => $log_path,
					);

$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);

// Prepare request arrays
$SetFundingSourceConfirmedFields = array(
										'AccountID' => '', 													// The ID number of the PayPal account for which a bank account is added.  You must specify either AccountID or EmailAddress for this request.
										'EmailAddress' => '', 												// The email address of the PayPal account holder.  You must specify either AccountID or EmailAddress.
										'FundingSourceKey' => ''											// The funding source key reeturned in the AddBankAccount or AddPaymentCard response.
										);

$PayPalRequestData = array('SetFundingSourceConfirmedFields' => $SetFundingSourceConfirmedFields);

// Pass data into class for processing with PayPal and load the response array into $PayPalResult
$PayPalResult = $PayPal->SetFundingSourceConfirmed($PayPalRequestData);

// Write the contents of the response array to the screen for demo purposes.
echo '<pre />';
print_r($PayPalResult);
?>

redpajama_set_name: RedPajamaGithub


text:
package tagging

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestTagSliceToMap(t *testing.T) {
	tags := []string{"foo:bar", "baz:gorch", "blerg"}
	mappedTags := ParseTagSliceToMap(tags)
	assert.Equal(t, "bar", mappedTags["foo"])
	assert.Equal(t, "gorch", mappedTags["baz"])
	assert.Equal(t, "", mappedTags["blerg"])
}


text:
namespace Octo.Core.ServiceBus.Common
{
    public class MessageContext : Context
    {
        public MessageContext(Context parentContext, IMessageEnvelop messageEnvelop)
            : base(parentContext)
        {
            Set(messageEnvelop);
        }

        protected MessageContext(Context parentContext)
            : base(parentContext)
        {
        }

        public IMessageEnvelop MessageEnvelop
        {
            get { return Get<IMessageEnvelop>(); }
            set { Set(value); }
        }
    }
}


text:
var gulp = require('gulp'),
    less = require('gulp-less'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    cssmin = require('gulp-cssmin');
var webpack = require('webpack-stream');

/*
gulp.task('site-copy-fonts', function() {
    gulp.src('bower_components/fontawesome/fonts/*')
        .pipe(gulp.dest('html/fonts/'));
});
*/

/*
gulp.task('site-copy-scripts', function() {
    gulp.src('src/Site/Webroot/Scripts/*')
        .pipe(gulp.dest('html/scripts/'));
});

gulp.task('site-design', function() {
    gulp.src([
            'src/Webroot/Styles/bootstrap.min.css',
            'src/Webroot/Styles/bootstrap-theme.min.css',
            'src/Webroot/Styles/font-awesome.min.css',
            'src/Webroot/Styles/main.css'
        ])
        //   .pipe(less())
        .pipe(concat('style.css'))
        //   .pipe(cssmin())
        .pipe(gulp.dest('html/styles/'));
});

gulp.task('site-scripts', function() {
    gulp.src([
            // jQuery
            'bower_components/jquery/jquery.js',
            'bower_components/bootstrap/dist/js/bootstrap.js',

        ])
        .pipe(concat('scripts.js'))
        //  .pipe(uglify())
        .pipe(gulp.dest('html/scripts/'));
});
*/

gulp.task('default', function() {
    return gulp.src('src/webroot/index.js')
        .pipe(webpack( require('./webpack.config.js') ))
        .pipe(gulp.dest('./'));
});


text:
<?php

namespace Mage\Adminhtml\Test\Block\Promo\Quote\Edit\Tab;

use Mage\Adminhtml\Test\Block\Widget\Tab;
use Magento\Mtf\Client\Element\SimpleElement as Element;
use Magento\Mtf\Client\Locator;

/**
 * Backend sales rule information tab.
 */
class RuleInformation extends Tab
{
    /**
     * Web site field.
     *
     * @var string
     */
    protected $websiteField = '#rule_website_ids';

    /**
     * Fill data to labels fields on labels tab.
     *
     * @param array $fields
     * @param Element|null $element
     * @return $this
     */
    public function fillFormTab(array $fields, Element $element = null)
    {
        parent::fillFormTab($fields, $element);
        $webSiteField = $this->_rootElement->find($this->websiteField, Locator::SELECTOR_CSS, 'multiselect');
        if ($webSiteField->isVisible()) {
            $webSiteFieldValue = $webSiteField->getValue();
            if (empty($webSiteFieldValue)) {
                $webSiteField->setValue('Main Website');
            }
        }

        return $this;
    }
}


text:
<resources>

    <color name="md__transparent">#00000000</color>

    <color name="md__defaultBackground">#FF555555</color>
</resources>


text:
salt.modules.parallels
======================

.. automodule:: salt.modules.parallels
    :members:


text:
using System;
using System.Linq;
using System.ComponentModel;

namespace nHydrate.Dsl.Design.Converters
{
	internal class EntityFieldConverter : TypeConverter
	{
		public EntityFieldConverter()
		{
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			if (destinationType == typeof(string)) return true;
			return base.CanConvertTo(context, destinationType);
		}

		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType == typeof(string))
			{
				var indexColumn = context.Instance as IndexColumn;
				var field = indexColumn.Index.Entity.Fields.FirstOrDefault(x => x.Id == indexColumn.FieldID);
				if (field != null)
					value = field.Name;
				return value;
			}
			return null;
		}

		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			return false;
		}

		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			return value;
		}

	}
}


text:
package org.codehaus.enunciate;

/**
 * A project artifact.
 *
 * @author Ryan Heaton
 */
public class Artifact {

  private String enunciateArtifactId;
  private String classifier;
  private String artifactType;

  /**
   * The id of the enunciate artifact that is to be a project artifact.
   *
   * @return The id of the enunciate artifact that is to be a project artifact.
   */
  public String getEnunciateArtifactId() {
    return enunciateArtifactId;
  }

  /**
   * The id of the enunciate artifact that is to be a project artifact.
   *
   * @param enunciateArtifactId The id of the enunciate artifact that is to be a project artifact.
   */
  public void setEnunciateArtifactId(String enunciateArtifactId) {
    this.enunciateArtifactId = enunciateArtifactId;
  }

  /**
   * The artifact id.
   *
   * @return The artifact id.
   */
  public String getClassifier() {
    return classifier;
  }

  /**
   * The artifact id.
   *
   * @param classifier The artifact id.
   */
  public void setClassifier(String classifier) {
    this.classifier = classifier;
  }

  /**
   * The packaging of the artifact.
   *
   * @return The packaging of the artifact.
   */
  public String getArtifactType() {
    return artifactType;
  }

  /**
   * The packaging of the artifact.
   *
   * @param artifactType The packaging of the artifact.
   */
  public void setArtifactType(String artifactType) {
    this.artifactType = artifactType;
  }
}


text:
'Copyright 2019 Esri

'Licensed under the Apache License, Version 2.0 (the "License");
'you may not use this file except in compliance with the License.
'You may obtain a copy of the License at

'    http://www.apache.org/licenses/LICENSE-2.0

'Unless required by applicable law or agreed to in writing, software
'distributed under the License is distributed on an "AS IS" BASIS,
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

'See the License for the specific language governing permissions and
'limitations under the License.
' Copyright 2010 ESRI
'
' All rights reserved under the copyright laws of the United States
' and applicable international laws, treaties, and conventions.
'
' You may freely redistribute and use this sample code, with or
' without modification, provided you include the original copyright
' notice and use restrictions.
'
' See the use restrictions at &ltyour ArcGIS install location&gt/DeveloperKit10.0/userestrictions.txt.
'
Partial Class frmDatasetTemplateName
	Inherits System.Windows.Forms.Form
	''' <summary>
	''' Required designer variable.
	''' </summary>
	Private components As System.ComponentModel.IContainer = Nothing

	''' <summary>
	''' Clean up any resources being used.
	''' </summary>
	''' <param name="disposing">true if managed resources should be disposed otherwise, false.</param>
	Protected Overrides Sub Dispose(ByVal disposing As Boolean)

		If (disposing AndAlso (components IsNot Nothing)) Then
			components.Dispose()
		End If
		MyBase.Dispose(disposing)
	End Sub

#Region "Windows Form Designer generated code"

	''' <summary>
	''' Required method for Designer support - do not modify
	''' the contents of this method with the code editor.
	''' </summary>
	Private Sub InitializeComponent()
		Me.btnNext = New System.Windows.Forms.Button
		Me.label1 = New System.Windows.Forms.Label
		Me.label2 = New System.Windows.Forms.Label
		Me.txtDatasetName = New System.Windows.Forms.TextBox
		Me.txtTemplateName = New System.Windows.Forms.TextBox
		Me.btnCancel = New System.Windows.Forms.Button
		Me.chkVertices = New System.Windows.Forms.CheckBox
		Me.SuspendLayout()
		'
		'btnNext
		'
		Me.btnNext.DialogResult = System.Windows.Forms.DialogResult.OK
		Me.btnNext.Enabled = False
		Me.btnNext.Location = New System.Drawing.Point(183, 118)
		Me.btnNext.Margin = New System.Windows.Forms.Padding(2)
		Me.btnNext.Name = "btnNext"
		Me.btnNext.Size = New System.Drawing.Size(56, 19)
		Me.btnNext.TabIndex = 0
		Me.btnNext.Text = "Next >"
		Me.btnNext.UseVisualStyleBackColor = True
		'
		'label1
		'
		Me.label1.AutoSize = True
		Me.label1.Location = New System.Drawing.Point(9, 19)
		Me.label1.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0)
		Me.label1.Name = "label1"
		Me.label1.Size = New System.Drawing.Size(78, 13)
		Me.label1.TabIndex = 1
		Me.label1.Text = "Dataset Name:"
		'
		'label2
		'
		Me.label2.AutoSize = True
		Me.label2.Location = New System.Drawing.Point(9, 47)
		Me.label2.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0)
		Me.label2.Name = "label2"
		Me.label2.Size = New System.Drawing.Size(85, 13)
		Me.label2.TabIndex = 2
		Me.label2.Text = "Template Name:"
		'
		'txtDatasetName
		'
		Me.txtDatasetName.Location = New System.Drawing.Point(90, 16)
		Me.txtDatasetName.Margin = New System.Windows.Forms.Padding(2)
		Me.txtDatasetName.Name = "txtDatasetName"
		Me.txtDatasetName.Size = New System.Drawing.Size(150, 20)
		Me.txtDatasetName.TabIndex = 3
		'
		'txtTemplateName
		'
		Me.txtTemplateName.Location = New System.Drawing.Point(98, 45)
		Me.txtTemplateName.Margin = New System.Windows.Forms.Padding(2)
		Me.txtTemplateName.Name = "txtTemplateName"
		Me.txtTemplateName.Size = New System.Drawing.Size(143, 20)
		Me.txtTemplateName.TabIndex = 4
		'
		'btnCancel
		'
		Me.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
		Me.btnCancel.Location = New System.Drawing.Point(122, 118)
		Me.btnCancel.Margin = New System.Windows.Forms.Padding(2)
		Me.btnCancel.Name = "btnCancel"
		Me.btnCancel.Size = New System.Drawing.Size(56, 19)
		Me.btnCancel.TabIndex = 5
		Me.btnCancel.Text = "Cancel"
		Me.btnCancel.UseVisualStyleBackColor = True
		'
		'chkVertices
		'
		Me.chkVertices.AutoSize = True
		Me.chkVertices.Location = New System.Drawing.Point(11, 73)
		Me.chkVertices.Margin = New System.Windows.Forms.Padding(2)
		Me.chkVertices.Name = "chkVertices"
		Me.chkVertices.Size = New System.Drawing.Size(126, 17)
		Me.chkVertices.TabIndex = 6
		Me.chkVertices.Text = "Use digitized vertices"
		Me.chkVertices.UseVisualStyleBackColor = True
		'
		'frmDatasetTemplateName
		'
		Me.AcceptButton = Me.btnNext
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(251, 141)
		Me.ControlBox = False
		Me.Controls.Add(Me.chkVertices)
		Me.Controls.Add(Me.btnCancel)
		Me.Controls.Add(Me.txtTemplateName)
		Me.Controls.Add(Me.txtDatasetName)
		Me.Controls.Add(Me.label2)
		Me.Controls.Add(Me.label1)
		Me.Controls.Add(Me.btnNext)
		Me.Margin = New System.Windows.Forms.Padding(2)
		Me.Name = "frmDatasetTemplateName"
		Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
		Me.Text = "Dataset and Template Name"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub

#End Region

	Public btnNext As System.Windows.Forms.Button
	Private label1 As System.Windows.Forms.Label
	Private label2 As System.Windows.Forms.Label
	Public txtDatasetName As System.Windows.Forms.TextBox
	Public txtTemplateName As System.Windows.Forms.TextBox
	Public btnCancel As System.Windows.Forms.Button
	Private chkVertices As System.Windows.Forms.CheckBox
End Class


text:
(function () {
    function ChatroomCtrl(Room, roomInfo, Message, $cookies) {
        console.log(roomInfo);
        var chatRoomId = roomInfo[0]
        this.messageList = roomInfo[1]
        this.sendMessage = function () {
            //content,username,roomId
            var messageInfo = {
                contents: this.messageText,
                username: $cookies.get('blocChatCurrentUser'),
                roomId: chatRoomId
            }
            console.log(messageInfo);
            Message.send(messageInfo);
        }
    }

    angular
        .module('blocChat')
        .controller('ChatroomCtrl', ['Room', 'roomInfo', 'Message', '$cookies', ChatroomCtrl]);
})();


text:
require "rails_helper"

RSpec.describe Organisation do

  context "When you have an organisation with memberships and contact details" do
    let(:person) { Person.create(first_name: "Baby", last_name: "Bear") }
    let(:organisation) { Organisation.create(name: "Bear family") }
    let(:contact_details) { ContactDetails.create(email: "bear@bigwoods.com") }

    before do
      organisation.people << person
      organisation.contact_details = contact_details
      organisation.save
    end

    it "delete memberships when destroyed" do
      expect{
        organisation.destroy
      }.to change{ Organisation::Membership.count }.by(-1)
    end

    it "delete contact details when destroyed" do
      expect{
        organisation.destroy
      }.to change{ ContactDetails.count }.by(-1)
    end

    it "not delete people when destroyed" do
      expect{
        organisation.destroy
      }.to_not change{ Person.count }
    end
  end

end


text:
package io.katharsis.module;

class TestResource {

	private int id;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
}


text:
{{ partial "head" . }}
{{ partial "nav" . }}

If you are not automatically redirected, please click here.

{{ partial "footer" . }}


text:
from django.db import models
from what_apps.commerce.models import Exchange
from what_apps.hwtrack.models import Computer
from what_apps.products.models import BeverageInstance
import os

class PointOfSale(Computer):
    has_cash_drawer = models.BooleanField()

    def kick(self):
        if self.has_cash_drawer: #If everything goes well, this will return a 0.
            return os.system("ssh -i /home/slashroot_poke/.ssh/id_rsa catapult@" + self.ip_address + ''' "cmd /c 'type c:\kick.bat>COM3'" ''')
        else: #We don't have a cash drawer.  We can't comply.
            return True

    class Meta:
        verbose_name_plural = "Points of Sale"

class TemporarySaleModel(models.Model):
    item = models.CharField(max_length=65)
    size = models.CharField(max_length= 7, choices = [('small','small'), ('medium','medium'), ('large', 'large')])
    milk = models.CharField(max_length=25)
    price = models.DecimalField(max_digits= 7, decimal_places=2)
    taxable = models.BooleanField()


text:
<?php

namespace Symfony\Component\Form\Extension\Core\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 * Deprecated. You should extend FormType instead.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @deprecated Deprecated since version 2.1, to be removed in 2.3.
 */
class FieldType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'field';
    }
}


text:
DROP DATABASE IF EXISTS vinyl;
CREATE DATABASE vinyl;

\c vinyl;

CREATE TABLE albums (
  album_id SERIAL PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  artist VARCHAR(255) NOT NULL
);

CREATE TABLE users (
  user_id SERIAL PRIMARY KEY,
  username VARCHAR(20) NOT NULL UNIQUE,
  email VARCHAR(255) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL,
  picture VARCHAR(255) DEFAULT 'http://www.pieglobal.com/wp-content/uploads/2015/10/placeholder-user.png',
  join_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE reviews (
  review_id SERIAL PRIMARY KEY,
  user_id INT,
  album_id INT,
  content VARCHAR(1000) NOT NULL,
  review_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(user_id),
  FOREIGN KEY (album_id) REFERENCES albums(album_id)
);


text:
package org.radargun.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Defines the target namespace for this class when generating elements in XML schema.
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) // TODO: allow package level annotation?
public @interface Namespace {
   static final String NO_DEPRECATED_NAME = "__no_deprecated_name__";

   String name();
   String deprecatedName() default NO_DEPRECATED_NAME;
}


text:
import { TypedIpcRenderer } from '../../common/ipc'
import { FileBrowserEntry, FileBrowserEntryType } from './file-browser-types'

const ipcRenderer = new TypedIpcRenderer()

function splitExtension(filename: string): [base: string, ext: string] {
  const extensionAt = filename.lastIndexOf('.')
  if (extensionAt === -1) {
    return [filename, '']
  } else {
    return [filename.slice(0, extensionAt), filename.slice(extensionAt + 1)]
  }
}

export default async function readFolder(folderPath: string): Promise<FileBrowserEntry[]> {
  try {
    const entries = (await ipcRenderer.invoke('fsReadDir', folderPath, { withFileTypes: true }))!
    return await Promise.all(
      entries.map(async entry => {
        const isFolder = entry.isDirectory
        const [name, extension] = isFolder ? [entry.name, ''] : splitExtension(entry.name)
        const stats = await ipcRenderer.invoke('fsStat', folderPath + '\\' + entry.name)
        const path = folderPath + '\\' + entry.name

        return isFolder
          ? {
              type: FileBrowserEntryType.Folder,
              name,
              path,
            }
          : {
              type: FileBrowserEntryType.File,
              name,
              path,
              extension: extension.toLowerCase(),
              date: stats?.mtime ?? new Date(0),
            }
      }),
    )
  } catch (err) {
    if ((err as any).code === 'ENOENT') {
      throw new Error('Filepath ' + folderPath + " doesn't exist")
    }
    throw err
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using TwilioParty.Models;

namespace TwilioParty.Controllers
{
    [AllowAnonymous]
    public class AuthController : Controller
    {
        // GET: Login
        public ActionResult LogIn(string returnUrl)
        {
            var model = new LogIn
            {
                ReturnUrl = returnUrl
            };

            return View(model);
        }

        [HttpPost]
        public ActionResult LogIn(LogIn model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            // this is bad and will have to go
            if (model.Email == "admin@admin.com" && model.Password == "password")
            {
                var identity = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.Name, "Marcos"),
                new Claim(ClaimTypes.Email, "mplacona@twilio.com"),
                new Claim(ClaimTypes.Country, "England")
            },
                    "ApplicationCookie");

                var ctx = Request.GetOwinContext();
                var authManager = ctx.Authentication;

                authManager.SignIn(identity);

                return Redirect(GetRedirectUrl(model.ReturnUrl));
            }

            // user authN failed
            ModelState.AddModelError("", "Invalid email or password");
            return View();
        }

        public ActionResult LogOut()
        {
            var ctx = Request.GetOwinContext();
            var authManager = ctx.Authentication;

            authManager.SignOut("ApplicationCookie");
            return RedirectToAction("index", "home");
        }

        private string GetRedirectUrl(string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
            {
                return Url.Action("index", "home");
            }

            return returnUrl;
        }
    }

}


text:
using System;

namespace Oneview.Client.Base.Events
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Should never have a need for a finalizer, hence no need for Dispole(bool)")]
    public class SubscriptionToken : IEquatable<SubscriptionToken>, IDisposable
    {
        private readonly Guid _token;
        private Action<SubscriptionToken> _unsubscribeAction;

        public SubscriptionToken(Action<SubscriptionToken> unsubscribeAction)
        {
            _unsubscribeAction = unsubscribeAction;
            _token = Guid.NewGuid();
        }

        public bool Equals(SubscriptionToken other)
        {
            return null != other && other._token == _token;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;
            return Equals(obj as SubscriptionToken);
        }

        public override int GetHashCode()
        {
            return _token.GetHashCode();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Should never have need for a finalizer, hence no need for Dispose(bool).")]
        public virtual void Dispose()
        {
            if (_unsubscribeAction != null)
            {
                _unsubscribeAction(this);
                _unsubscribeAction = null;
            }

            GC.SuppressFinalize(this);
        }
    }
}


text:
package org.yu55.yagga.handler.generic.command;

import java.io.File;

import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.springframework.stereotype.Component;
import org.yu55.yagga.handler.api.DvcsRepository;

@Component
public class CommandExecutorFactory {

    public CommandExecutor factorize(Command command) {
        return factorize(new File("."), null, command);
    }

    public CommandExecutor factorize(DvcsRepository repository, Command command) {
        return factorize(repository.getDirectory().toFile(), repository.getDirectoryName(), command);
    }

    private CommandExecutor factorize(File dir, String name, Command command) {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(dir);
        CommandExecutorStreamHandler executorStreamHandler = new CommandExecutorStreamHandler(name);
        executor.setStreamHandler(new PumpStreamHandler(executorStreamHandler));
        return new CommandExecutor(command, executor, executorStreamHandler::getOutput);
    }

}


text:
<?php

namespace spec\Genesis\API\Request\NonFinancial;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class AccountVerificationSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Genesis\API\Request\NonFinancial\AccountVerification');
    }

    function it_can_build_stucture()
    {
        $this->setRequestParameters();
        $this->getDocument()->shouldNotBeEmpty();
    }

    function it_should_fail_when_no_parameters()
    {
        $this->shouldThrow('\Genesis\Exceptions\ErrorParameter')->during('getDocument');
    }

    function it_should_fail_when_missing_required_parameters()
    {
        $this->setRequestParameters();
        $this->setCardHolder(null);
        $this->shouldThrow()->during('getDocument');
    }

    function setRequestParameters()
    {
        $faker = \Faker\Factory::create();

        $faker->addProvider(new \Faker\Provider\en_US\Person($faker));
        $faker->addProvider(new \Faker\Provider\Payment($faker));
        $faker->addProvider(new \Faker\Provider\en_US\Address($faker));
        $faker->addProvider(new \Faker\Provider\en_US\PhoneNumber($faker));
        $faker->addProvider(new \Faker\Provider\Internet($faker));

        $this->setTransactionId(mt_rand(PHP_INT_SIZE, PHP_INT_MAX));

        $this->setCurrency('USD');
        $this->setAmount(mt_rand(100, 100000));
        $this->setUsage('Genesis PHP Client Automated Request');
        $this->setRemoteIp($faker->ipv4);
        $this->setCardHolder($faker->name);
        $this->setCardNumber('4200000000000000');
        $this->setCvv(sprintf("%03s", mt_rand(1, 999)));
        $this->setExpirationMonth(mt_rand(01, 12));
        $this->setExpirationYear(mt_rand(2015, 2020));
        $this->setCustomerEmail($faker->email);
        $this->setCustomerPhone($faker->phoneNumber);
        $this->setBillingFirstName($faker->firstName);
        $this->setBillingLastName($faker->lastName);
        $this->setBillingAddress1($faker->streetAddress);
        $this->setBillingZipCode($faker->postcode);
        $this->setBillingCity($faker->city);
        $this->setBillingState($faker->state);
        $this->setBillingCountry($faker->countryCode);
    }

    public function getMatchers()
    {
        return array(
            'beEmpty' => function ($subject) {
                return empty($subject);
            },
        );
    }
}


text:
package org.zalando.catwatch.backend.service.comparator;

import org.zalando.catwatch.backend.model.Project;

import java.util.Comparator;

/**
 * Created by pmaji on 7/27/15.
 */
public class ProjectStarComparator implements Comparator<Project>{

    @Override
    public int compare(Project p1, Project p2) {
        return p1.getStarsCount()-p2.getStarsCount();
    }
}


text:
from steerclear import app, db
from steerclear.models import User
from flask import url_for
from tests.base import base

"""
SteerClearTestCase
------------------
TestCase for driver side management
"""
class SteerClearTestCase(base.SteerClearBaseTestCase):

    """
    test_heartbeat
    --------------
    tests that server is up and running and that the
    '/' route returns a 200 status code and "pulse"
    """
    def test_heartbeat(self):
        response = self.client.get('/')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(response.get_data(), "pulse")

    """
    test_get_index_requires_login
    -----------------------------
    Tests that index page requires login
    """
    def test_get_index_requires_login(self):
        response = self.client.get(url_for('driver_portal.index'))
        self.assertEquals(response.status_code, 401)

    """
    test_get_index
    --------------
    Tests that only logged in users can access the index page
    """
    def test_get_index(self):
        self._login()
        response = self.client.get(url_for('driver_portal.index'))
        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed('index.html')


text:
clear all
load('errors_all.mat');

% Extract the errors for the different numbers of components

total = size(errors_all,1);

breakpoint = total/3;

range_50 = 1:breakpoint;
range_100= breakpoint+1:breakpoint*2;
range_200= 2*breakpoint+1:total;

% now just pick the final iteration for each image
Q = 55; % total events
its = 25; %iterations per event

% indexes for the final iterations:
offsets = 25:25:length(range_50);

% let's start with all the 50s

errors_50 = errors_all(range_50);
errors_50_final = errors_50(offsets);
stddev(1) = std(errors_50_final);
m(1) = mean(errors_50_final);
% 100s
errors_100 = errors_all(range_100);
errors_100_final = errors_100(offsets);
stddev(2) = std(errors_100_final);
m(2) = mean(errors_100_final);
% 200s
errors_200 = errors_all(range_200);
errors_200_final = errors_200(offsets);
stddev(3) = std(errors_200_final);
m(3) = mean(errors_200_final);

h = figure()
errorbar(m,stddev)
xlabel('Components')
ylabel('Reconstruction error (RMS)')
title('Error bars for reconstruction RMS');


text:
import type { CodeKeywordDefinition, ErrorNoParams, AnySchema } from "../../types";
export declare type NotKeywordError = ErrorNoParams<"not", AnySchema>;
declare const def: CodeKeywordDefinition;
export default def;


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Item extends CI_Controller {
  public function index()
  {
    $data['items'] = $this->Item_Model->getItems();

    $data['title'] = "Items";
    $data['active'] = 0;

    $this->template->load('base', 'item/index', $data);
  }

  public function view($id)
  {
    $data['item'] = $this->Item_Model->getItem($id);

    $data['title'] = $data['item']['title']. " - Item ". $data['item']['id'];
  	$data['active'] = 0;

    $this->template->load('base', 'item/view', $data);
  }

  public function edit($id)
  {
    $data['item'] = $this->Item_Model->getItem($id);

    if ($this->input->post() != null){ // If POST data has been submitted
      $updateReturn = $this->Item_Model->updateItem($this->input->post());

      redirect("/item/view/$id", 'refresh');
    }

    $data['title'] = "Editing: ". $data['item']['title']. " - Item ". $data['item']['id'];
  	$data['active'] = 0;

    $this->template->load('base', 'item/edit', $data);
  }

  public function create()
  {
    $data['alert'] = array('visible' => false);

    if ($this->input->post() != null){ // If POST data has been submitted
      $newItemID = $this->Item_Model->saveItem($this->input->post());

      redirect("/item/view/$newItemID", 'refresh');
    }

    $data['title'] = "Create Item";
  	$data['active'] = -1;

    $this->template->load('base', 'item/create', $data);
  }
}


text:
http_path = "/"
http_stylesheets_path = "/css"
http_images_path = "/img"
http_generated_images_path = "/img/sprites"
http_javascripts_path = "/js"

project_path = "site"
css_dir = "css"
images_dir = "img"
generated_images_dir = "img/sprites"
javascripts_dir = "js"

sass_path = "scss"
sprite_load_path = ["sprites"];

relative_assets = false


text:
/**
 * A WebDAV protocol compatible client
 */
define(function(require, exports, module) {

    var List = require('collections/List');

    var ArrayUtil = require('utils/ArrayUtil');

    var File = require('webdav/File');

    var PathUtil = require('utils/PathUtil');

    var $ = require('real/jquery');

    var WebDavClient = function(rootPath) {

        var self = {};

        // ----------------------------------------- Private members --------------------------------------------------
        var path = '';
        var folders = {};
        var files = new List();

        // ----------------------------------------- Public methods ---------------------------------------------------
        self.getCurrentPath = function() {
            return rootPath + path;
        };

        self.getCurrentFile = function() {
            return currentFile;
        };

        self.getFiles = function() {
            return files;
        };

        self.navigate = function(url) {
            path = url;
            self.update();
        };

        self.createFolder = function(filename) {
            $.ajax({
                type: 'MKCOL',
                url: self.getCurrentPath() + filename,
                success: function() {
                    self.update();
                }
                // TODO: Handle failure
            });
        };

        self.delete = function(file) {
            $.ajax({
                type: 'DELETE',
                url: file.getPath(),
                success: function() {
                    self.update();
                }
                // TODO: Handle failure
            });
        };

        self.update = function() {
            var propsBody = document.implementation.createDocument('DAV:', 'propfind', null);
            propsBody.documentElement.appendChild(propsBody.createElementNS('DAV:', 'allprop'));
            var serializer = new XMLSerializer();
            var str = '<?xml version="1.0" encoding="utf-8" ?>' + serializer.serializeToString(propsBody);

            $.ajax({
                type: 'PROPFIND',
                url: self.getCurrentPath(),
                data: str,
                dataType: 'xml',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('Depth', '1');
                    xhr.setRequestHeader('Content-Type', 'application/xml');
                },
                success: function(xml) {
                    var newFiles = readXml(xml);
                    files.copy(newFiles);
                }
                // TODO: Handle failure
            });
        };

        // ----------------------------------------- Private methods --------------------------------------------------

        var readXml = function(xml) {
            var files = new List();

            // Translate the XML into File objects
            $(xml.documentElement).children('D\\:response').each(function(index, response) {
                var file = new File(response, rootPath);
                if(file.getContentType() === File.TYPE.DIRECTORY) {
                    folders[file.getPath()] = file;
                }
                files.addItem(file);
            });

            // Artificially add the parent folder
            var parentPath = PathUtil.getParentPath(self.getCurrentPath());
            var parentFolder = folders[parentPath];
            if(parentFolder) {
                files.addItem(parentFolder);
            }

            // Sort
            files.sort(File.COMPARATOR);

            return files;
        };

        // ------------------------------------------- Constructor ----------------------------------------------------
        var ctor = function() {
            self.update();
        };

        ctor();

        return self;
    };

    return WebDavClient;
});


text:
import collections
import itertools
import pytest

@pytest.fixture(autouse=True)
def wait_for_first_block(web3, wait_for_block, skip_if_testrpc):
    skip_if_testrpc(web3)
    wait_for_block(web3)

def test_eth_getTransactionFromBlock(web3, extra_accounts, wait_for_transaction):
    current_block_number = web3.eth.blockNumber

    transaction_hashes = []

    for _ in range(5):
        transaction_hashes.append(web3.eth.sendTransaction({
            "from": web3.eth.coinbase,
            "to": extra_accounts[1],
            "value": 1,
        }))

    # wait for them to resolve
    for txn_hash in transaction_hashes:
        wait_for_transaction(web3, txn_hash)

    # gather all receipts and sort/group them by block number.
    all_receipts = sorted(
        [web3.eth.getTransactionReceipt(txn_hash) for txn_hash in transaction_hashes],
        key=lambda r: r['blockNumber'],
    )
    all_receipts_by_block = {
        key: tuple(value)
        for key, value in itertools.groupby(all_receipts, lambda r: r['blockNumber'])
    }

    for block_number, block_receipts in all_receipts_by_block.items():
        block = web3.eth.getBlock(block_number)
        block_hash = block['hash']
        block_transactions = block['transactions']

        for txn_idx, txn_hash in enumerate(block_transactions):
            for block_identifier in [block_number, block_hash]:
                txn = web3.eth.getTransactionFromBlock(block_identifier, txn_idx)
                assert txn['hash'] == txn_hash


text:
"""
问题描述:分别用递归和非递归方式实现二叉树的先序、中序、和后续遍历

思路:使用非递归的方式需要使用辅助栈代替函数栈
"""

from binarytree.toolcls import Node

class RecursiveVisit:
    @classmethod
    def visit_in_first_order(cls, head):
        if head is None:
            return
        print(head.value, end=' ')
        cls.visit_in_first_order(head.left)
        cls.visit_in_first_order(head.right)

    @classmethod
    def visit_in_mid_order(cls, head):
        if head is None:
            return
        cls.visit_in_mid_order(head.left)
        print(head.value, end=' ')
        cls.visit_in_mid_order(head.right)

    @classmethod
    def visit_in_last_order(cls, head):
        if head is None:
            return
        cls.visit_in_last_order(head.left)
        cls.visit_in_last_order(head.right)
        print(head.value, end=' ')

class LoopVisit:
    @classmethod
    def visit_in_first_order(cls, head):
        if head is None:
            return
        stack = list()
        stack.append(head)
        while len(stack) > 0:
            node = stack.pop()
            print(node.value, end=' ')

            if node.right is not None:
                stack.append(node.right)
            if node.left is not None:
                stack.append(node.left)

    @classmethod
    def visit_in_mid_order(cls, head):
        if head is None:
            return
        stack = list()
        cur = head
        while len(stack) > 0 or cur is not None:
            if cur is not None:
                stack.append(cur)
                cur = cur.left
            else:
                cur = stack.pop()
                print(cur.value, end=' ')
                cur = cur.right

    @classmethod
    def visit_in_last_order(cls, head):
        if head is None:
            return
        stack1 = list()
        stack2 = list()

        cur = head
        stack1.append(cur)

        while len(stack1) > 0:
            cur = stack1.pop()
            if cur.left is not None:
                stack1.append(cur.left)
            if cur.right is not None:
                stack1.append(cur.right)

            stack2.append(cur.value)

        while len(stack2) > 0:
            print(stack2.pop(), end=' ')

if __name__ == '__main__':
    head = Node(5)
    head.left = Node(3)
    head.right = Node(8)
    head.left.left = Node(2)
    head.left.right = Node(4)
    head.left.left.left = Node(1)
    head.right.left = Node(7)
    head.right.left.left = Node(6)
    head.right.right = Node(10)
    head.right.right.left = Node(9)
    head.right.right.right = Node(11)

    RecursiveVisit.visit_in_first_order(head)
    print()
    LoopVisit.visit_in_first_order(head)
    print()
    print('===========================')

    RecursiveVisit.visit_in_mid_order(head)
    print()
    LoopVisit.visit_in_mid_order(head)
    print()
    print('===========================')
    RecursiveVisit.visit_in_last_order(head)
    print()
    LoopVisit.visit_in_last_order(head)
    print()


text:
import React, {Component, PropTypes} from 'react';
import {Grid, Row, Col, Panel} from 'react-bootstrap';
import {connect} from 'react-redux';
import connectData from 'helpers/connectData';
import DocumentMeta from 'react-document-meta';
import config from '../../config';
import {initialize} from 'redux-form';
import {pushState} from 'redux-router';
import {filter as filterServices} from 'redux/modules/services';
import {filter as filterSuppliers} from 'redux/modules/suppliers';
import {save} from 'redux/modules/contracts';
import {ContractForm} from 'components';

function fetchData(getState, dispatch) {
  const promises = [];
  promises.push(dispatch(filterSuppliers('')));
  promises.push(dispatch(filterServices('')));
  return Promise.all(promises);
}

@connectData(fetchData)
@connect(state => ({
  suppliers: state.suppliers.data,
  services: state.services.data,
  error: state.contracts.error,
  loading: state.contracts.loading
}), {initialize, pushState, save, filterServices, filterSuppliers})
export default class ContractNew extends Component {
  static propTypes = {
    suppliers: PropTypes.array,
    services: PropTypes.array,
    initialize: PropTypes.func.isRequired,
    pushState: PropTypes.func.isRequired,
    save: PropTypes.func.isRequired,
    error: PropTypes.object,
    loading: PropTypes.bool
  }

  handleSubmit = (data) => {
    console.log(JSON.stringify(data));
    this.props.save(data);
    if (this.props.error) {
      console.log(this.props.error);
    } else {
      this.props.initialize('contract', {});
      this.props.pushState(null, '/contracts');
    }
  }

  render() {
    return (
      <div className="container">
        <DocumentMeta title={config.app.title + ': Novo contrato'}/>
        <Panel header="Novo contrato" bsStyle="primary">
          <Grid fluid>
            <Row>
              <Col xs={ 12 } md={ 12 } sm={ 12 } lg={ 12 }>
                <ContractForm onSubmit={this.handleSubmit}
                  serviceOptions={this.props.services}
                  supplierOptions={this.props.suppliers}/>
              </Col>
            </Row>
          </Grid>
        </Panel>
      </div>
    );
  }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('api', '0008_merge_20161114_0228'),
    ]

    operations = [
        migrations.AlterField(
            model_name='volunteer',
            name='email',
            field=models.CharField(max_length=50),
        ),
        migrations.AlterField(
            model_name='volunteer',
            name='jacket',
            field=models.CharField(max_length=30),
        ),
        migrations.AlterField(
            model_name='volunteer',
            name='years_of_service',
            field=models.CharField(max_length=3),
        ),
    ]


text:
using System;

namespace TradingApi.Client.Framework.DTOs
{
    public class ApiTradeHistoryDTO
    {
        public Int32 OrderId { get; set; }

        public Int32 MarketId { get; set; }

        public String MarketName { get; set; }

        public String Direction { get; set; }

        public Decimal OriginalQuantity { get; set; }

        public Decimal Price { get; set; }

        public Int32 TradingAccountId { get; set; }
        /// <summary>
        /// The trade currency
        /// </summary>

        public String Currency { get; set; }

        public String LastChangedDateTimeUtc { get; set; }
    }
}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// System.String
struct String_t;

#include "codegen/il2cpp-codegen.h"
#include "UnityEngine_UnityEngine_AnimatorStateInfo4162640357.h"
#include "mscorlib_System_String968488902.h"

// System.Boolean UnityEngine.AnimatorStateInfo::IsName(System.String)
extern "C"  bool AnimatorStateInfo_IsName_m1653922768 (AnimatorStateInfo_t4162640357 * __this, String_t* ___name, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 UnityEngine.AnimatorStateInfo::get_fullPathHash()
extern "C"  int32_t AnimatorStateInfo_get_fullPathHash_m3257074542 (AnimatorStateInfo_t4162640357 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 UnityEngine.AnimatorStateInfo::get_nameHash()
extern "C"  int32_t AnimatorStateInfo_get_nameHash_m453823205 (AnimatorStateInfo_t4162640357 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 UnityEngine.AnimatorStateInfo::get_shortNameHash()
extern "C"  int32_t AnimatorStateInfo_get_shortNameHash_m994885515 (AnimatorStateInfo_t4162640357 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Single UnityEngine.AnimatorStateInfo::get_normalizedTime()
extern "C"  float AnimatorStateInfo_get_normalizedTime_m2531821060 (AnimatorStateInfo_t4162640357 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Single UnityEngine.AnimatorStateInfo::get_length()
extern "C"  float AnimatorStateInfo_get_length_m3147284742 (AnimatorStateInfo_t4162640357 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Single UnityEngine.AnimatorStateInfo::get_speed()
extern "C"  float AnimatorStateInfo_get_speed_m247405833 (AnimatorStateInfo_t4162640357 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Single UnityEngine.AnimatorStateInfo::get_speedMultiplier()
extern "C"  float AnimatorStateInfo_get_speedMultiplier_m489756842 (AnimatorStateInfo_t4162640357 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 UnityEngine.AnimatorStateInfo::get_tagHash()
extern "C"  int32_t AnimatorStateInfo_get_tagHash_m3543262078 (AnimatorStateInfo_t4162640357 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean UnityEngine.AnimatorStateInfo::IsTag(System.String)
extern "C"  bool AnimatorStateInfo_IsTag_m119936877 (AnimatorStateInfo_t4162640357 * __this, String_t* ___tag, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean UnityEngine.AnimatorStateInfo::get_loop()
extern "C"  bool AnimatorStateInfo_get_loop_m1495892586 (AnimatorStateInfo_t4162640357 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;

// Methods for marshaling
struct AnimatorStateInfo_t4162640357;
struct AnimatorStateInfo_t4162640357_marshaled_pinvoke;

extern "C" void AnimatorStateInfo_t4162640357_marshal_pinvoke(const AnimatorStateInfo_t4162640357& unmarshaled, AnimatorStateInfo_t4162640357_marshaled_pinvoke& marshaled);
extern "C" void AnimatorStateInfo_t4162640357_marshal_pinvoke_back(const AnimatorStateInfo_t4162640357_marshaled_pinvoke& marshaled, AnimatorStateInfo_t4162640357& unmarshaled);
extern "C" void AnimatorStateInfo_t4162640357_marshal_pinvoke_cleanup(AnimatorStateInfo_t4162640357_marshaled_pinvoke& marshaled);

// Methods for marshaling
struct AnimatorStateInfo_t4162640357;
struct AnimatorStateInfo_t4162640357_marshaled_com;

extern "C" void AnimatorStateInfo_t4162640357_marshal_com(const AnimatorStateInfo_t4162640357& unmarshaled, AnimatorStateInfo_t4162640357_marshaled_com& marshaled);
extern "C" void AnimatorStateInfo_t4162640357_marshal_com_back(const AnimatorStateInfo_t4162640357_marshaled_com& marshaled, AnimatorStateInfo_t4162640357& unmarshaled);
extern "C" void AnimatorStateInfo_t4162640357_marshal_com_cleanup(AnimatorStateInfo_t4162640357_marshaled_com& marshaled);


text:
layout: post
title: Keynote at Rugged DevOps 2016
date: '2016-03-15T10:28:53+00:00'
tags:
- Keynote
- Video
excerpt: My keynote at Rugged DevOps 2016. Compliance at Velocity!
---

<figure class="video_container">
	<iframe width="560" height="315" src="https://www.youtube.com/embed/tGoSH45v-qA" frameborder="0" allowfullscreen></iframe>
</figure>


text:
import React from 'react';
import { assert } from 'chai';
import { createShallow, createMount } from '../test-utils';
import Step from './Step';

describe('<Step />', () => {
  let shallow;
  let mount;

  before(() => {
    shallow = createShallow({ dive: true });
    mount = createMount();
  });

  after(() => {
    mount.cleanUp();
  });

  it('merges styles and other props into the root node', () => {
    const wrapper = shallow(
      <Step
        index={1}
        style={{ paddingRight: 200, color: 'purple', border: '1px solid tomato' }}
        role="Menuitem"
        orientation="horizontal"
      />,
    );
    const { style, role } = wrapper.props();
    assert.strictEqual(style.paddingRight, 200);
    assert.strictEqual(style.color, 'purple');
    assert.strictEqual(style.border, '1px solid tomato');
    assert.strictEqual(role, 'Menuitem');
  });

  describe('rendering children', () => {
    it('renders children', () => {
      const children =
Hello World
;
      const wrapper = shallow(
        <Step label="Step One" index={1} orientation="horizontal">
          {children}
        </Step>,
      );
      assert.strictEqual(wrapper.find('.hello-world').length, 1);
    });

    it('renders children with all props passed through', () => {
      const children = [

          Hello World

,

          How are you?

,
      ];
      const wrapper = shallow(
        <Step active={false} completed disabled index={0} orientation="horizontal">
          {children}
        </Step>,
      );
      const child1 = wrapper.find('.hello-world');
      const child2 = wrapper.find('.hay');
      [child1, child2].forEach(child => {
        assert.strictEqual(child.length, 1);
        assert.strictEqual(child.props().active, false);
        assert.strictEqual(child.props().completed, true);
        assert.strictEqual(child.props().disabled, true);
        assert.strictEqual(child.props().icon, 1);
      });
    });

    it('honours children overriding props passed through', () => {
      const children = (

          Hello World

      );
      const wrapper = shallow(
        <Step active label="Step One" orientation="horizontal" index={0}>
          {children}
        </Step>,
      );
      const childWrapper = wrapper.find('.hello-world');
      assert.strictEqual(childWrapper.props().active, false);
    });
  });
});


text:
using System.Collections;
using UnityEngine;

public class TutorialHandler : MonoBehaviour
{
    public GameObject TutorialText;
    private TutText _tutText;

    public AudioSource TutSound;

    public GameObject Hand;
    public string[] AnimationQueueH;
    private int _handIndex = 0;

    public GameObject Arrow1;
    public string[] AnimationQueueA1;
    private int _a1Index = 0;

    public GameObject Arrow2;
    public string[] AnimationQueueA2;
    private int _a2Index = 0;

    public GameObject Arrow3;
    public string[] AnimationQueueA3;
    private int _a3Index = 0;

    public GameObject Circle;
    public string[] AnimationQueueCircle;
    private int _circleIndex = 0;

    public GameObject PlayGameButton;
    public int PlayButtonAppearIndex = 0;

	void Start () {
        InputManager.Instance.Tap += OnTap;
	    _tutText = TutorialText.GetComponent<TutText>();

	}

    public void OnTap(Vector2 pos, TapState tapState)
    {
        if (tapState != TapState.Tapped) return;

        if (TutSound != null)
            TutSound.Play();

        _tutText.CurrentIndex++;
        _circleIndex++;
        _handIndex ++;
        _a1Index ++;
        _a2Index ++;
        _a3Index ++;

        if (_handIndex < AnimationQueueH.Length)
        {
            Hand.animation.Play(AnimationQueueH[_handIndex]);
        }

        if (_a1Index < AnimationQueueA1.Length)
        {
            Arrow1.animation.Play(AnimationQueueA1[_a1Index]);
        }

        if (_a2Index < AnimationQueueA2.Length)
        {
            Arrow2.animation.Play(AnimationQueueA2[_a2Index]);
        }

        if (_a3Index < AnimationQueueA2.Length)
        {
            Arrow3.animation.Play(AnimationQueueA3[_a3Index]);
        }

        if (_circleIndex < AnimationQueueCircle.Length)
        {
            Circle.animation.Play(AnimationQueueCircle[_circleIndex]);
        }

        if (_tutText.CurrentIndex >= PlayButtonAppearIndex)
        {
            PlayGameButton.SetActive(true);
        }

    }

    void OnDestroy()
    {
        if ( InputManager.Instance != null )
            InputManager.Instance.Tap -= OnTap;
    }

}


text:
package simenv

import "sync"

/*
SimEnv - это ядро симуляции.

Именно через эту структуру происходит синхронзация работы всех агентов.

Симуляция разбита на дискретные "тики" в рамках которой агенты меняют свои состояния.
*/
type SimEnv struct {
	tick          int
	agents        map[string]Agent
	tickBroadcast []chan int
	inProgress    bool
}

// New - инициализатор
func New() *SimEnv {
	return &SimEnv{
		agents: make(map[string]Agent),
	}
}

// Add добавляет агентов в симуляцию
func (simenv *SimEnv) Add(agents ...Agent) {
	for _, agent := range agents {
		simenv.agents[agent.Name()] = agent
	}
}

// Find ищет агента по имени
func (simenv SimEnv) Find(agentName string) Agent {
	return simenv.agents[agentName]
}

// Run запускает всех агентов и симуляцию
func (simenv *SimEnv) Run() error {
	group := runAgentGroup(simenv)

	for {
		simenv.tick++
		for _, tickChan := range simenv.tickBroadcast {
			tickChan <- simenv.tick
		}

		group.WaitForState(StateReady)
		group.StartWork()
		group.WaitForState(StateIdle)
		group.FinishWork()

		if group.StopFlag() {
			break
		}
	}

	return nil
}

// CurrentTick возвращает структуру, которая всегда содержит текущий тик симуляции
func (simenv *SimEnv) CurrentTick() *CurrentTick {
	ct := &CurrentTick{simenv.tick, new(sync.Mutex)}
	channel := make(chan int)

	simenv.tickBroadcast = append(simenv.tickBroadcast, channel)

	go ct.connect(channel)

	return ct
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app/App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('app')
);


text:
package com.link_intersystems.maven.plugin.dbtools.exportGoal;

import java.io.OutputStream;

import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.excel.XlsDataSetWriter;

public class XLSDataSetWriter extends TypedDataSetWriter<OutputStream> {

	@Override
	protected void write(IDataSet dataSet, OutputStream writeTarget)
			throws Exception {
		XlsDataSetWriter xlsDataSetWriter = new XlsDataSetWriter();
		xlsDataSetWriter.write(dataSet, writeTarget);
	}

}


text:
package org.commcare.utils;

import org.commcare.android.database.user.models.FormRecord;
import org.commcare.views.notifications.MessageTag;
import org.commcare.views.notifications.NotificationMessage;
import org.commcare.views.notifications.NotificationMessageFactory;
import org.commcare.views.notifications.ProcessIssues;
import org.javarosa.core.services.locale.Localization;

/**
 * Created by amstone326 on 9/25/17.
 */

public class QuarantineUtil {

    public static String getQuarantineReasonDisplayString(FormRecord r, boolean includeDetail) {
        String displayString = "";
        switch (r.getQuarantineReasonType()) {
            case FormRecord.QuarantineReason_LOCAL_PROCESSING_ERROR:
                displayString += Localization.get("quarantine.reason.local.processing");
                break;
            case FormRecord.QuarantineReason_SERVER_PROCESSING_ERROR:
                displayString += Localization.get("quarantine.reason.server.processing");
                break;
            case FormRecord.QuarantineReason_RECORD_ERROR:
                displayString += Localization.get("quarantine.reason.record.error");
                break;
            case FormRecord.QuarantineReason_MANUAL:
                displayString += Localization.get("quarantine.reason.manual");
                break;
            case FormRecord.QuarantineReason_FILE_NOT_FOUND:
                displayString += Localization.get("quarantine.reason.fnf");
                break;
            default:
                displayString += Localization.get("quarantine.reason.unknown");
        }

        if (includeDetail) {
            String detail = r.getQuarantineReasonDetail();
            if (detail != null) {
                displayString += (": " + detail);
            }
        }

        return displayString;
    }

    public static NotificationMessage getQuarantineNotificationMessage(FormRecord r) {
        MessageTag tag;
        switch (r.getQuarantineReasonType()) {
            case FormRecord.QuarantineReason_LOCAL_PROCESSING_ERROR:
                tag = ProcessIssues.RecordQuarantinedLocalProcessingIssue;
                break;
            case FormRecord.QuarantineReason_SERVER_PROCESSING_ERROR:
                tag = ProcessIssues.RecordQuarantinedServerIssue;
                break;
            case FormRecord.QuarantineReason_RECORD_ERROR:
                tag = ProcessIssues.RecordQuarantinedRecordIssue;
                break;
            case FormRecord.QuarantineReason_FILE_NOT_FOUND:
                tag = ProcessIssues.RecordFilesMissing;
                break;
            case FormRecord.QuarantineReason_MANUAL:
            default:
                return null;
        }
        return NotificationMessageFactory.message(tag);
    }
}


text:
bool GEO2DLineRasterStyle::apply(ICanvas* canvas) const {
  const bool applied = (_width > 0) && (!_color.isFullTransparent());

  if (applied) {
    canvas->setLineColor(_color);
    canvas->setLineWidth(_width);
    canvas->setLineCap(_cap);
    canvas->setLineJoin(_join);
    canvas->setLineMiterLimit(_miterLimit);

    canvas->setLineDash(_dashLengths,
                        _dashCount,
                        _dashPhase);
  }

  return applied;
}


text:
var Sequelize;

Sequelize = require('sequelize');

module.exports = (function() {
  return new Sequelize(process.env.LINKR_DB_NAME || 'linkr', process.env.LINKR_DB_USER || 'linkr', process.env.LINKR_DB_PASS || 'linkr', {
    host: process.env.LINKR_HOST || 'localhost'
  });
})();


text:
@interface LBMineCenterOrderDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIButton *cancelBt;
@property (weak, nonatomic) IBOutlet UITableView *tableview;

@end

@implementation LBMineCenterOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.title = @"订单详情";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableview.tableFooterView = [UIView new];

    [self.tableview registerNib:[UINib nibWithNibName:@"LBMineCenterOrderDetailOneTableViewCell" bundle:nil] forCellReuseIdentifier:@"LBMineCenterOrderDetailOneTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"LBMineCenterOrderDetailTwoTableViewCell" bundle:nil] forCellReuseIdentifier:@"LBMineCenterOrderDetailTwoTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"LBMineCenterOrderDetailThreeTableViewCell" bundle:nil] forCellReuseIdentifier:@"LBMineCenterOrderDetailThreeTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"LBMineCenterOrderDetailFiveTableViewCell" bundle:nil] forCellReuseIdentifier:@"LBMineCenterOrderDetailFiveTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"LBMineCenterOrderDetailSixTableViewCell" bundle:nil] forCellReuseIdentifier:@"LBMineCenterOrderDetailSixTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"LBMineCenterOrderDetailSevenTableViewCell" bundle:nil] forCellReuseIdentifier:@"LBMineCenterOrderDetailSevenTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"LBMineCenterOrderDetailFourTableViewCell" bundle:nil] forCellReuseIdentifier:@"LBMineCenterOrderDetailFourTableViewCell"];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 8;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 0) {
        return 60;
    }else if (indexPath.row == 1){
        return 70;
    }else if (indexPath.row == 2){
        return 80;
    }else if (indexPath.row == 3){
        return 180;
    }else if (indexPath.row == 4){
        return 44;
    }else if (indexPath.row == 5){
        return 44;
    }else if (indexPath.row == 6){
        return 70;
    }else if (indexPath.row == 7){
        return 70;
    }
    return 0;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 0) {
        LBMineCenterOrderDetailOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LBMineCenterOrderDetailOneTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;

    }else if (indexPath.row == 1){
        LBMineCenterOrderDetailTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LBMineCenterOrderDetailTwoTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }else if (indexPath.row == 2){
        LBMineCenterOrderDetailThreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LBMineCenterOrderDetailThreeTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }else if (indexPath.row == 3){
        LBMineCenterOrderDetailFourTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LBMineCenterOrderDetailFourTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }else if (indexPath.row == 4){
        LBMineCenterOrderDetailFiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LBMineCenterOrderDetailFiveTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }else if (indexPath.row == 5){
        LBMineCenterOrderDetailFiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LBMineCenterOrderDetailFiveTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }else if (indexPath.row == 6){
        LBMineCenterOrderDetailSixTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LBMineCenterOrderDetailSixTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }else if (indexPath.row == 7){
        LBMineCenterOrderDetailSevenTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LBMineCenterOrderDetailSevenTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }

    return [[UITableViewCell alloc]init];

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

//取消订单
- (IBAction)cancelorder:(UIButton *)sender {

}

-(void)updateViewConstraints{

    [super updateViewConstraints];

    self.cancelBt.layer.cornerRadius = 3;
    self.cancelBt.clipsToBounds = YES;

    self.cancelBt.layer.borderColor = YYSRGBColor(198, 51, 14, 1).CGColor;
    self.cancelBt.layer.borderWidth = 1;

}

@end


text:
package shared

import (
	"reflect"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/tools/cache"

	buildapi "github.com/openshift/origin/pkg/build/api"
	oscache "github.com/openshift/origin/pkg/client/cache"
)

type BuildConfigInformer interface {
	Informer() cache.SharedIndexInformer
	Indexer() cache.Indexer
	Lister() oscache.StoreToBuildConfigLister
}

type buildConfigInformer struct {
	*sharedInformerFactory
}

func (f *buildConfigInformer) Informer() cache.SharedIndexInformer {
	f.lock.Lock()
	defer f.lock.Unlock()

	informerObj := &buildapi.BuildConfig{}
	informerType := reflect.TypeOf(informerObj)
	informer, exists := f.informers[informerType]
	if exists {
		return informer
	}

	informer = cache.NewSharedIndexInformer(
		&cache.ListWatch{
			ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
				return f.originClient.BuildConfigs(metav1.NamespaceAll).List(options)
			},
			WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
				return f.originClient.BuildConfigs(metav1.NamespaceAll).Watch(options)
			},
		},
		informerObj,
		f.defaultResync,
		cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc, oscache.ImageStreamReferenceIndex: oscache.ImageStreamReferenceIndexFunc},
	)
	f.informers[informerType] = informer

	return informer
}

func (f *buildConfigInformer) Indexer() cache.Indexer {
	informer := f.Informer()
	return informer.GetIndexer()
}

func (f *buildConfigInformer) Lister() oscache.StoreToBuildConfigLister {
	informer := f.Informer()
	return &oscache.StoreToBuildConfigListerImpl{Indexer: informer.GetIndexer()}
}


text:
/*
 * scheduler.cpp - scheduler implementations
 *
 * author: Samuel Groß <dev@samuel-gross.de>
 */

#include "scheduler.h"

using namespace orb;

Scheduler* orb::scheduler;

Scheduler::Scheduler()
    : processes(), cycles(0) {}

void Scheduler::tick()
{
    List<Process*>::Iterator it;
    for (it = processes.begin(); it != processes.end(); it++) {
        Process* curr = *it;
		if (cycles % curr->get_nice() == 0) {
			curr->tick();
		}
	}

	cycles++;
}


text:
<?php

namespace Kendo\Dataviz\UI;

class ChartXAxisItemLabelsDateFormats extends \kendo\SerializableObject {
//>> Properties

    /**
    * The format used when xAxis.baseUnit is set to "days".
    * @param string $value
    * @return \Kendo\Dataviz\UI\ChartXAxisItemLabelsDateFormats
    */
    public function days($value) {
        return $this->setProperty('days', $value);
    }

    /**
    * The format used when xAxis.baseUnit is set to "hours".
    * @param string $value
    * @return \Kendo\Dataviz\UI\ChartXAxisItemLabelsDateFormats
    */
    public function hours($value) {
        return $this->setProperty('hours', $value);
    }

    /**
    * The format used when xAxis.baseUnit is set to "months".
    * @param string $value
    * @return \Kendo\Dataviz\UI\ChartXAxisItemLabelsDateFormats
    */
    public function months($value) {
        return $this->setProperty('months', $value);
    }

    /**
    * The format used when xAxis.baseUnit is set to "weeks".
    * @param string $value
    * @return \Kendo\Dataviz\UI\ChartXAxisItemLabelsDateFormats
    */
    public function weeks($value) {
        return $this->setProperty('weeks', $value);
    }

    /**
    * The format used when xAxis.baseUnit is set to "years".
    * @param string $value
    * @return \Kendo\Dataviz\UI\ChartXAxisItemLabelsDateFormats
    */
    public function years($value) {
        return $this->setProperty('years', $value);
    }

//<< Properties
}

?>


text:
package plugin

import (
	"fmt"

	cnitypes "github.com/containernetworking/cni/pkg/types"

	"github.com/openshift/origin/pkg/sdn/plugin/cniserver"
)

func (m *podManager) setup(req *cniserver.PodRequest) (*cnitypes.Result, *runningPod, error) {
	return nil, nil, fmt.Errorf("openshift-sdn is unsupported on this OS!")
}

func (m *podManager) update(req *cniserver.PodRequest) (uint32, error) {
	return 0, fmt.Errorf("openshift-sdn is unsupported on this OS!")
}

// Clean up all pod networking (clear OVS flows, release IPAM lease, remove host/container veth)
func (m *podManager) teardown(req *cniserver.PodRequest) error {
	return fmt.Errorf("openshift-sdn is unsupported on this OS!")
}


text:
      STUDENT CATEGORY

Erika Jeana Carino

            <input tab-switches type="checkbox" data-name="student" data-toggle="switch"
              data-on-color="primary" data-off-color="default" ng-model="student" data-value="Erika Jeana Carino"/>

Jay Arcie Carreon

            <input tab-switches type="checkbox" data-name="student" data-toggle="switch"
              data-on-color="primary" data-off-color="default" ng-model="student" data-value="Jay Arcie Carreon"/>

Nikolai Cayanan

            <input tab-switches type="checkbox" data-name="student" data-toggle="switch"
              data-on-color="primary" data-off-color="default" ng-model="student" data-value="Nikolai Cayanan"/>

Kathleen Kaye Tiglao

            <input tab-switches type="checkbox" data-name="student" data-toggle="switch"
              data-on-color="primary" data-off-color="default" ng-model="student" data-value="Kathleen Kaye Tiglao"/>