text:
@interface ScheduleViewController ()

@end

@implementation ScheduleViewController

@synthesize sections = _sections;
@synthesize sectionToDayMap = _sectionToDayMap;
@synthesize bodyArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.separatorInset = UIEdgeInsetsZero;
        self.tableView.userInteractionEnabled = YES;
    self.tableView.bounces = YES;

}
- (void)viewWillAppear:(BOOL)animated
{
    self.tableView.userInteractionEnabled = YES;
    [self loadObjects];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (id)initWithCoder:(NSCoder *)aCoder
{
    self = [super initWithCoder:aCoder];
    if (self) {

        //Parse class name
        self.parseClassName = @"Event";

        //Default display
        self.textKey = @"name";

        self.pullToRefreshEnabled = NO;
        self.paginationEnabled = NO;
        self.objectsPerPage = 150;
        self.sections = [NSMutableDictionary dictionary];
        self.sectionToDayMap = [NSMutableDictionary dictionary];

    }
    return self;
}

- (PFQuery *)queryForTable {
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];

    // If Pull To Refresh is enabled, query against the network by default.
    if (self.pullToRefreshEnabled) {
        query.cachePolicy = kPFCachePolicyNetworkOnly;
    }

    // If no objects are loaded in memory, we look to the cache first to fill the table
    // and then subsequently do a query against the network.
    if (self.objects.count == 0) {
        query.cachePolicy = kPFCachePolicyCacheThenNetwork;
    }

    // Order by Day
    [query orderByAscending:@"time"];

    query.cachePolicy = kPFCachePolicyCacheThenNetwork;

    return query;

}

- (NSString *)dayForSection:(NSInteger)section {
    return [self.sectionToDayMap objectForKey:[NSNumber numberWithInt:section]];
}

- (void)objectsDidLoad:(NSError *)error {
    [super objectsDidLoad:error];

    // This method is called every time objects are loaded from Parse via the PFQuery

    [self.sections removeAllObjects];
    [self.sectionToDayMap removeAllObjects];

    NSInteger section = 0;
    NSInteger rowIndex = 0;
    for (PFObject *object in self.objects) {

        NSDate *time = [object objectForKey:@"time"];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [dateFormatter setDateFormat:@"EEEE, MMMM dd"];
        NSString *day= [dateFormatter stringFromDate:time];
        NSLog(@"day: %@", day);

        NSMutableArray *objectsInSection = [self.sections objectForKey:day];
        if (!objectsInSection) {
            objectsInSection = [NSMutableArray array];

            // this is the first time we see this day- increment the section index
            [self.sectionToDayMap setObject:day forKey:[NSNumber numberWithInt:section++]];
        }

        [objectsInSection addObject:[NSNumber numberWithInt:rowIndex++]];
        [self.sections setObject:objectsInSection forKey:day];
    }
    [self.tableView reloadData];
}

- (PFObject *)objectAtIndexPath:(NSIndexPath *)indexPath {
    NSString *day= [self dayForSection:indexPath.section];

    NSArray *rowIndecesInSection = [self.sections objectForKey:day];
    NSNumber *rowIndex = [rowIndecesInSection objectAtIndex:indexPath.row];
    return [self.objects objectAtIndex:[rowIndex intValue]];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sections.allKeys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *day= [self dayForSection:section];
    NSArray *rowIndecesInSection = [self.sections objectForKey:day];
    return rowIndecesInSection.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *day= [NSString stringWithFormat:@"   %@",[self dayForSection:section]];
    return day;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 23.0;
}

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

    NSString *bodyString = [[self.objects objectAtIndex:indexPath.row]objectForKey:@"description"];
    //set the desired size of your textbox
    CGSize constraint = CGSizeMake(295, MAXFLOAT);
    //set your text attribute dictionary
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13.0] forKey:NSFontAttributeName];
    //get the size of the text box
    CGRect textsize = [bodyString boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    //calculate your size
    float textHeight = textsize.size.height + 10;
    NSLog(@"%f", textHeight + 30);
    return textHeight + 30 ;
}

#pragma mark - UITableViewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
    static NSString *simpleTableIdentifier = @"ScheduleCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    // Configure the cell

    UILabel *nameLabel = (UILabel*) [cell viewWithTag:100];
    nameLabel.text = [object objectForKey:@"name"];

    UILabel *detailsLabel = (UILabel*) [cell viewWithTag:104];
    NSString *detailsString =[object objectForKey:@"description"];

    CGSize constraint = CGSizeMake(295, MAXFLOAT);
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13.0] forKey:NSFontAttributeName];
    CGRect newFrame = [detailsString boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    detailsLabel.frame = CGRectMake(16,28,newFrame.size.width, newFrame.size.height);

    detailsLabel.text = detailsString;
    [detailsLabel sizeToFit];

   UILabel *timeLabel = (UILabel*) [cell viewWithTag:101];
    NSDate *time = [object objectForKey:@"time"];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    [dateFormatter setDateFormat:@"h:mm a"];
    timeLabel.text = [dateFormatter stringFromDate:time];

    return cell;
}

@end


text:
using System;
using System.Runtime.InteropServices;

namespace Net.Sf.Pkcs11.Wrapper
{
	public class AttributeUtil
	{
		public static CK_ATTRIBUTE CreateClassAttribute(){
			return createAttribute((uint)CKA.CLASS,new byte[0]);

		}

		public static CK_ATTRIBUTE CreateClassAttribute(CKO objectClass){

			return createAttribute((uint)CKA.CLASS,BitConverter.GetBytes((uint)objectClass));
		}

		public static CK_ATTRIBUTE createAttribute(uint type, byte[]val ){

			CK_ATTRIBUTE attr= new CK_ATTRIBUTE();
			attr.type=type;
			if(val!=null && val.Length>0){
				attr.ulValueLen=(uint)val.Length;
				attr.pValue=Marshal.AllocHGlobal(val.Length);
				Marshal.Copy(val,0,attr.pValue,val.Length);
			}else{
				attr.ulValueLen=(uint)val.Length;
				attr.pValue=IntPtr.Zero;

			}
			return attr;
		}

		public static CK_ATTRIBUTE createAttribute(uint type, int size ){
			return createAttribute(type,new byte[size]);
		}

		public static CK_ATTRIBUTE createAttribute(CKA type, int size ){
			return createAttribute((uint)type,new byte[size]);
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
$(function() {
  // Slick Carousel
  $('.carousel').slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 5000,
    dots: true,
    infinite: true,
    speed: 1000,
    adaptiveHeight: true,
    fade: true,
    cssEase: 'linear'
  });
  $('.carousel').on('afterChange',positionFooter);
})


text:
'
' Lightbox Gallery Module for DotNetNuke
' Project Contributors - Will Strohl (http://www.WillStrohl.com), Armand Datema (http://www.schwingsoft.com)
'
'Copyright (c) 2009-2016, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list
'of conditions and the following disclaimer in the documentation and/or other
'materials provided with the distribution.
'
'Neither the name of Will Strohl, Armand Datema, Lightbox Gallery, nor the names of its contributors may be
'used to endorse or promote products derived from this software without specific prior
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
'DAMAGE.
'

Imports DotNetNuke.Services.Exceptions
Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Web.SessionState

Namespace WillStrohl.Modules.Lightbox

    Partial Public Class OrderHandler
        Implements IHttpHandler, IRequiresSessionState

#Region " Private Members "

        Private p_ModuleId As Integer = Null.NullInteger
        Private p_Order As String = Null.NullString

#End Region

#Region " Properties "

        Private ReadOnly Property ModuleId() As Integer
            Get
                Return Me.p_ModuleId
            End Get
        End Property

        Private ReadOnly Property Order() As String
            Get
                If Me.p_Order.EndsWith(",") Then
                    Me.p_Order = Me.p_Order.Substring(0, Me.p_Order.Length - 1)
                End If
                Return Me.p_Order
            End Get
        End Property

#End Region

        Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

            Try

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
                context.Response.ContentType = "text/plain"

                If Not context.Request.QueryString("mid") Is Nothing Then
                    Try
                        Me.p_ModuleId = Integer.Parse(context.Request.QueryString("mid").ToString, Globalization.NumberStyles.Integer)
                    Catch
                        Me.HandleError(context, "The mid parameter was not in the correct format.")
                    End Try
                Else
                    Me.HandleError(context, "The mid parameter is missing.")
                End If

                If Not context.Request.QueryString("order") Is Nothing Then
                    Me.p_Order = context.Request.QueryString("order").ToString
                    If Not Regex.IsMatch(Me.p_Order, "^[\d,]+$") Then
                        Me.HandleError(context, "The order parameter was not in the correct format.")
                    End If
                Else
                    Me.HandleError(context, "The order parameter is missing.")
                End If

                Me.SaveOrder()

                context.Response.Write("true")

            Catch ex As Exception
                LogException(ex)
                If IsEditMode() Then
                    Me.HandleError(context, String.Concat(ex.Message, Environment.NewLine, ex.StackTrace))
                End If
            End Try

        End Sub

        Private Sub SaveOrder()

            Dim arrId() As Integer = Me.GetIdArray
            Dim intCount As Integer = 1
            Dim ctlModule As New LightboxController
            Dim album As LightboxInfo = Nothing

            For Each oId As Integer In arrId
                If oId > 0 Then
                    album = ctlModule.GetLightbox(oId)
                    album.DisplayOrder = intCount
                    ctlModule.UpdateLightbox(album)
                End If

                intCount += 1
            Next

        End Sub

        Private Function GetIdArray() As Integer()

            Dim arrStr() As String = Split(Me.Order, ",")
            Dim arrInt(arrStr.Length) As Integer
            Dim intCount As Integer = 0

            For Each oStr As String In arrStr
                arrInt(intCount) = Integer.Parse(oStr, Globalization.NumberStyles.Integer)
                intCount += 1
            Next

            Return arrInt

        End Function

        Private Sub HandleError(ByVal context As System.Web.HttpContext, ByVal ErrorText As String)

            context.Response.Write(ErrorText)
            context.Response.End()

        End Sub

#Region " IHttpHandler Implementation "

        Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
            Get
                Return True
            End Get
        End Property

#End Region

    End Class

End Namespace


text:
require 'spec_helper'

describe Mongo::Operation::Write::Insert do

  let(:documents) do
    [{ :name => 'test' }]
  end

  let(:spec) do
    { :documents     => documents,
      :db_name       => TEST_DB,
      :coll_name     => TEST_COLL,
      :write_concern => Mongo::WriteConcern::Mode.get(:w => 1),
      :ordered       => true
    }
  end

  let(:insert) do
    described_class.new(spec)
  end

  describe '#initialize' do

    context 'spec' do

      it 'sets the spec' do
        expect(insert.spec).to eq(spec)
      end
    end
  end

  describe '#==' do

    context 'spec' do

      context 'when two inserts have the same specs' do

        let(:other) do
          described_class.new(spec)
        end

        it 'returns true' do
          expect(insert).to eq(other)
        end
      end

      context 'when two inserts have different specs' do

        let(:other_docs) do
          [{ :bar => 1 }]
        end

        let(:other_spec) do
          { :documents     => other_docs,
            :db_name       => 'test',
            :coll_name     => 'test_coll',
            :write_concern => { 'w' => 1 },
            :ordered       => true
          }
        end

        let(:other) do
          described_class.new(other_spec)
        end

        it 'returns false' do
          expect(insert).not_to eq(other)
        end
      end
    end
  end

  describe '#dup' do

    context 'deep copy' do

      it 'copies the list of updates' do
        copy = insert.dup
        expect(copy.spec[:documents]).to_not be(insert.spec[:documents])
      end
    end
  end

  describe '#merge' do

    context 'when the collection and database are the same' do

      let(:other_docs) do
        [{ :bar => 1 }]
      end

      let(:other_spec) do
        { :documents     => other_docs,
          :db_name       => TEST_DB,
          :coll_name     => TEST_COLL
        }
      end

      let(:other) do
        described_class.new(other_spec)
      end

      it 'merges the two inserts' do
        expect{ insert.merge(other) }.not_to raise_exception
      end
    end

    context 'when the databases differ' do

      let(:other_docs) do
        [{ :bar => 1 }]
      end

      let(:other_spec) do
        { :documents     => other_docs,
          :db_name       => 'different',
          :coll_name     => TEST_COLL
        }
      end

      let(:other) do
        described_class.new(other_spec)
      end

      it 'raises an exception' do
        expect{ insert.merge(other) }.to raise_exception
      end
    end

    context 'when the collections differ' do

      let(:other_docs) do
        [{ :bar => 1 }]
      end

      let(:other_spec) do
        { :documents     => other_docs,
          :db_name       => TEST_DB,
          :coll_name     => 'different'
        }
      end

      let(:other) do
        described_class.new(other_spec)
      end

      it 'raises an exception' do
        expect{ insert.merge(other) }.to raise_exception
      end
    end

    context 'when the command types differ' do

      let(:other) do
        Mongo::Write::Update.new(spec)
      end

      it 'raises an exception' do
        expect{ insert.merge(other) }.to raise_exception
      end
    end

    context 'when the merge is valid' do

      let(:other_docs) do
        [{ :bar => 1 }]
      end

      let(:other_spec) do
        { :documents     => other_docs,
          :db_name       => TEST_DB,
          :coll_name     => TEST_COLL
        }
      end

      let(:other) do
        described_class.new(other_spec)
      end

      let(:expected) do
        documents << other_docs
      end

      it 'merges the list of documents' do
        expect(insert.merge(other).spec[:documents]).to eq(expected)
      end

      it 'keeps the original spec immutable'do
        expect(insert.merge(other)).not_to be(insert)
      end
    end
  end

  describe '#merge!' do

    context 'when collection and database are the same' do

      let(:other_docs) do
        [{ :bar => 1 }]
      end

      let(:other_spec) do
        { :documents     => other_docs,
          :db_name       => TEST_DB,
          :coll_name     => TEST_COLL
        }
      end

      let(:other) do
        described_class.new(other_spec)
      end

      it 'merges the two inserts' do
        expect{ insert.merge!(other) }.not_to raise_exception
      end
    end

    context 'when the database differs' do

      let(:other_docs) do
        [{ :bar => 1 }]
      end

      let(:other_spec) do
        { :documents     => other_docs,
          :db_name       => 'different',
          :coll_name     => TEST_COLL
        }
      end

      let(:other) do
        described_class.new(other_spec)
      end

      it 'raises an exception' do
        expect{ insert.merge!(other) }.to raise_exception
      end
    end

    context 'when the collection differs' do

      let(:other_docs) do
        [{ :bar => 1 }]
      end

      let(:other_spec) do
        { :documents     => other_docs,
          :db_name       => TEST_DB,
          :coll_name     => 'different'
        }
      end

      let(:other) do
        described_class.new(other_spec)
      end

      it 'raises an exception' do
        expect{ insert.merge!(other) }.to raise_exception
      end
    end

    context 'when the command type differs' do

      let(:other) do
        Mongo::Write::Update.new(spec)
      end

      it 'raises an exception' do
        expect{ insert.merge!(other) }.to raise_exception
      end
    end

    context 'when the commands can be merged' do

      let(:other_docs) do
        [{ :bar => 1 }]
      end

      let(:other_spec) do
        { :documents     => other_docs,
          :db_name       => TEST_DB,
          :coll_name     => TEST_COLL
        }
      end

      let(:other) do
        described_class.new(other_spec)
      end

      let(:expected) do
        documents << other_docs
      end

      it 'merges the list of documents' do
        expect(insert.merge!(other).spec[:documents]).to eq(expected)
      end

      it 'mutates the original spec' do
        expect(insert.merge!(other)).to be(insert)
      end
    end
  end

  describe '#slice' do

    context 'number of inserts is evenly divisible by divisor' do
      let(:documents) do
        [ { :a => 1 },
          { :b => 1 },
          { :c => 1 },
          { :d => 1 },
          { :e => 1 },
          { :f => 1 } ]
      end
      let(:divisor) { 3 }

      it 'slices the insert into the divisor number of children inserts' do
        expect(insert.slice(divisor).size).to eq(divisor)
      end

      it 'divides the inserts evenly between children inserts' do
        inserts = insert.slice(divisor)
        slice_size = documents.size / divisor

        divisor.times do |i|
          start_index = i * slice_size
          expect(inserts[i].spec[:documents]).to eq(documents[start_index, slice_size])
        end
      end
    end

    context 'number of inserts is not evenly divisible by divisor' do
      let(:documents) do
        [ { :a => 1 },
          { :b => 1 },
          { :c => 1 },
          { :d => 1 },
          { :e => 1 },
          { :f => 1 } ]
      end
      let(:divisor) { 4 }

      it 'slices the insert into the divisor number of children inserts' do
        expect(insert.slice(divisor).size).to eq(divisor)
      end

      it 'divides the inserts evenly between children inserts' do
        inserts = insert.slice(divisor)
        slice_size = documents.size / divisor

        divisor.times do |i|
          start_index = i * slice_size
          if i == divisor - 1
            expect(inserts[i].spec[:documents]).to eq(documents[start_index..-1])
          else
            expect(inserts[i].spec[:documents]).to eq(documents[start_index, slice_size])
          end
        end
      end
    end
  end

  describe '#set_order' do

    context 'when an order has been set' do
      let(:order) { 5 }
      let(:documents) do
        [ { :a => 1 },
          { :b => 1 },
          { :c => 1 } ]
      end
      let(:expected) do
        [ { :a => 1, :ord => order },
          { :b => 1, :ord => order },
          { :c => 1, :ord => order } ]
      end

      it 'sets the order on each insert spec document' do
        insert.set_order(order)
        expect(insert.spec[:documents]).to eq(expected)
      end
    end
  end

  describe '#execute' do

    before do
      authorized_collection.indexes.ensure({ name: 1 }, { unique: true })
    end

    after do
      authorized_collection.find.remove_many
      authorized_collection.indexes.drop({ name: 1 })
    end

    context 'when inserting a single document' do

      context 'when the insert succeeds' do

        let(:response) do
          insert.execute(authorized_primary.context)
        end

        it 'inserts the documents into the database', if: write_command_enabled? do
          expect(response.written_count).to eq(1)
        end

        it 'inserts the documents into the database', unless: write_command_enabled? do
          expect(response.written_count).to eq(0)
        end
      end

      context 'when the insert fails' do

        let(:documents) do
          [{ name: 'test' }]
        end

        let(:spec) do
          { :documents     => documents,
            :db_name       => TEST_DB,
            :coll_name     => TEST_COLL,
            :write_concern => Mongo::WriteConcern::Mode.get(:w => 1)
          }
        end

        let(:failing_insert) do
          described_class.new(spec)
        end

        it 'raises an error' do
          expect {
            failing_insert.execute(authorized_primary.context)
            failing_insert.execute(authorized_primary.context)
          }.to raise_error(Mongo::Operation::Write::Failure)
        end
      end
    end

    context 'when inserting multiple documents' do

      context 'when the insert succeeds' do

        let(:documents) do
          [{ name: 'test1' }, { name: 'test2' }]
        end

        let(:response) do
          insert.execute(authorized_primary.context)
        end

        it 'inserts the documents into the database', if: write_command_enabled? do
          expect(response.written_count).to eq(2)
        end

        it 'inserts the documents into the database', unless: write_command_enabled? do
          expect(response.written_count).to eq(0)
        end
      end

      context 'when the insert fails on the last document' do

        let(:documents) do
          [{ name: 'test3' }, { name: 'test' }]
        end

        let(:spec) do
          { :documents     => documents,
            :db_name       => TEST_DB,
            :coll_name     => TEST_COLL,
            :write_concern => Mongo::WriteConcern::Mode.get(:w => 1)
          }
        end

        let(:failing_insert) do
          described_class.new(spec)
        end

        it 'raises an error' do
          expect {
            failing_insert.execute(authorized_primary.context)
            failing_insert.execute(authorized_primary.context)
          }.to raise_error(Mongo::Operation::Write::Failure)
        end
      end

      context 'when the insert fails on the first document' do

        let(:documents) do
          [{ name: 'test' }, { name: 'test4' }]
        end

        let(:spec) do
          { :documents     => documents,
            :db_name       => TEST_DB,
            :coll_name     => TEST_COLL,
            :write_concern => Mongo::WriteConcern::Mode.get(:w => 1)
          }
        end

        let(:failing_insert) do
          described_class.new(spec)
        end

        it 'raises an error' do
          expect {
            failing_insert.execute(authorized_primary.context)
            failing_insert.execute(authorized_primary.context)
          }.to raise_error(Mongo::Operation::Write::Failure)
        end
      end
    end
  end
end


text:
begin;
insert into variavel_interesse (id, sigla, nome) values (1,'B','Biomassa');
insert into variavel_interesse (id, sigla, nome) values (2,'C','Carbono');
insert into variavel_interesse (id, sigla, nome) values (3,'V','Volume');
commit;

# --- !Downs
delete from variavel_interesse;


text:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace Cpln.Enigmos.Enigmas.Utils
{
    ///
    /// This kind of label allows the rotation at an angle.
    ///
    class RotatingLabel : Label
    {
        private double angle;

        ///
        /// Sets or gets the angle of rotation in degrees.
        /// rotatingLabel.Angle = 360.0; being equal to rotatingLabel.Angle = 0.0;
        ///
        public double Angle
        {
            get
            {
                return angle * 180 / Math.PI;
            }
            set
            {
                angle = Math.PI / 180 * value;
                Size linearSize = TextRenderer.MeasureText(Text, Font);
                Size = new Size((int)(Math.Abs(Math.Cos(angle) * linearSize.Width) + Math.Abs(Math.Sin(angle) * linearSize.Height)), (int)(Math.Abs(Math.Sin(angle) * linearSize.Width) + Math.Abs(Math.Cos(angle) * linearSize.Height)));
                Invalidate();
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            double realAngle = angle;
            while (realAngle < 0)
            {
                realAngle += 2 * Math.PI;
            }
            while (realAngle > 2 * Math.PI)
            {
                realAngle -= 2 * Math.PI;
            }

            Size linearSize = TextRenderer.MeasureText(Text, Font);
            Brush b = new SolidBrush(this.ForeColor);

            if (realAngle <= Math.PI / 2)
            {
                e.Graphics.TranslateTransform((float)(Math.Sin(angle) * linearSize.Height), 0);
            }
            else if (realAngle <= Math.PI)
            {
                e.Graphics.TranslateTransform((float)Size.Width, (float)(-Math.Cos(angle) * linearSize.Height));
            }
            else if (realAngle <= 3 * Math.PI / 2)
            {
                e.Graphics.TranslateTransform((float)(-Math.Cos(angle) * linearSize.Width), Size.Height);
            }
            else
            {
                e.Graphics.TranslateTransform(0f, (float)(-Math.Sin(angle) * linearSize.Width));
            }
            e.Graphics.RotateTransform((float)Angle);
            e.Graphics.DrawString(Text, Font, b, 0f, 0f);
        }
    }
}


text:
"""Test HexGraph and DualHexGraph."""
from nose.tools import (assert_true, assert_false, assert_equal,
                        assert_almost_equal)
from numpy.testing import assert_array_equal, assert_array_almost_equal
import numpy as np

from landlab.graph import DualHexGraph

ROOT_3_OVER_2 = np.sqrt(3.) * .5

def test_create():
    """Test creating a dual hex graph with rectangular layout."""
    graph = DualHexGraph((4, 3), node_layout='rect')

    assert_equal(graph.number_of_nodes, 12)
    assert_equal(graph.number_of_links, 23)
    assert_equal(graph.number_of_patches, 12)

    assert_equal(graph.number_of_corners, 10)
    assert_equal(graph.number_of_faces, 11)
    assert_equal(graph.number_of_cells, 2)

def test_create_hex():
    """Test creating a dual hex graph with hex layout."""
    graph = DualHexGraph((4, 3), node_layout='hex')

    assert_equal(graph.number_of_nodes, 16)
    assert_equal(graph.number_of_links, 34)
    assert_equal(graph.number_of_patches, 19)

    assert_equal(graph.number_of_corners, 19)
    assert_equal(graph.number_of_faces, 23)
    assert_equal(graph.number_of_cells, 5)

def test_create_rect1():
    """Test creating a dual hex graph."""
    graph = DualHexGraph((4, 3), node_layout='rect1')

    assert_equal(graph.number_of_nodes, 14)
    assert_equal(graph.number_of_links, 28)
    assert_equal(graph.number_of_patches, 15)

    assert_equal(graph.number_of_corners, 13)
    assert_equal(graph.number_of_faces, 15)
    assert_equal(graph.number_of_cells, 3)

def test_spacing():
    """Test spacing of nodes."""
    graph = DualHexGraph((20, 31), node_layout='rect1')
    assert_array_almost_equal(graph.length_of_link, 1.)

    graph = DualHexGraph((31, 20), spacing=2, node_layout='rect1')
    assert_array_almost_equal(graph.length_of_link, 2.)

def test_origin():
    """Test setting the origin."""
    graph = DualHexGraph((4, 3))

    assert_almost_equal(graph.y_of_node[0], 0.)
    assert_almost_equal(graph.x_of_node[0], 0.)
    assert_almost_equal(graph.x_of_corner[0], 1.5)

    graph = DualHexGraph((4, 3), origin=(.5, .25))

    assert_almost_equal(graph.y_of_node[0], .5)
    assert_almost_equal(graph.x_of_node[0], .25)
    assert_almost_equal(graph.x_of_corner[0], 1.75)

def test_orientation():
    """Test vertical and horizontal orientation."""
    graph = DualHexGraph((3, 4), orientation='vertical')
    assert_array_almost_equal(graph.y_of_corner,
                              [.5, .5, 1, 1, 1, 1.5, 1.5, 1.5, 2, 2])

    graph = DualHexGraph((4, 3), orientation='horizontal')
    assert_array_almost_equal(graph.x_of_corner,
                              [1.5, 1, 2, 1, 2, .5, 1.5, .5, 1.5, 1])


text:
require_relative '../../api2400/synergy/uplink_set'

module OneviewSDK
  module API2600
    module Synergy
      # Uplink set resource implementation for API2600 Synergy
      class UplinkSet < OneviewSDK::API2400::Synergy::UplinkSet
      end
    end
  end
end


text:
<?php

class OmniwebShowtimes_AdminPageFramework_Property_page_meta_box extends OmniwebShowtimes_AdminPageFramework_Property_post_meta_box {
    public $_sPropertyType = 'page_meta_box';
    public $aPageSlugs = array();
    public $oAdminPage;
    public $aHelpTabs = array();
    public $_sFormRegistrationHook = 'admin_enqueue_scripts';
    public function __construct($oCaller, $sClassName, $sCapability = 'manage_options', $sTextDomain = 'omniweb-showtimes', $sStructureType = 'page_meta_box') {
        unset($this->oAdminPage, $this->aHelpTabs);
        parent::__construct($oCaller, $sClassName, $sCapability, $sTextDomain, $sStructureType);
        $GLOBALS['aOmniwebShowtimes_AdminPageFramework']['aMetaBoxForPagesClasses'] = $this->getElementAsArray($GLOBALS, array('aOmniwebShowtimes_AdminPageFramework', 'aMetaBoxForPagesClasses'));
        $GLOBALS['aOmniwebShowtimes_AdminPageFramework']['aMetaBoxForPagesClasses'][$sClassName] = $oCaller;
    }
    protected function _getOptions() {
        return $this->oAdminPage->oProp->aOptions;
    }
    public function _getScreenIDOfPage($sPageSlug) {
        $_oAdminPage = $this->_getOwnerObjectOfPage($sPageSlug);
        return $_oAdminPage ? $_oAdminPage->oProp->aPages[$sPageSlug]['_page_hook'] . (is_network_admin() ? '-network' : '') : '';
    }
    public function isPageAdded($sPageSlug = '') {
        $_oAdminPage = $this->_getOwnerObjectOfPage($sPageSlug);
        return $_oAdminPage ? $_oAdminPage->oProp->isPageAdded($sPageSlug) : false;
    }
    public function isCurrentTab($sTabSlug) {
        $_sCurrentPageSlug = $this->getElement($_GET, 'page');
        if (!$_sCurrentPageSlug) {
            return false;
        }
        $_sCurrentTabSlug = $this->getElement($_GET, 'tab', $this->getDefaultInPageTab($_sCurrentPageSlug));
        return ($sTabSlug === $_sCurrentTabSlug);
    }
    public function getCurrentPageSlug() {
        return isset($_GET['page']) ? $_GET['page'] : '';
    }
    public function getCurrentTabSlug($sPageSlug) {
        $_oAdminPage = $this->_getOwnerObjectOfPage($sPageSlug);
        return $_oAdminPage ? $_oAdminPage->oProp->getCurrentTabSlug($sPageSlug) : '';
    }
    public function getCurretTab($sPageSlug) {
        return $this->getCurrentTabSlug($sPageSlug);
    }
    public function getDefaultInPageTab($sPageSlug) {
        if (!$sPageSlug) {
            return '';
        }
        return ($_oAdminPage = $this->_getOwnerObjectOfPage($sPageSlug)) ? $_oAdminPage->oProp->getDefaultInPageTab($sPageSlug) : '';
    }
    public function getOptionKey($sPageSlug) {
        if (!$sPageSlug) {
            return '';
        }
        return ($_oAdminPage = $this->_getOwnerObjectOfPage($sPageSlug)) ? $_oAdminPage->oProp->sOptionKey : '';
    }
    private function _getOwnerObjectOfPage($sPageSlug) {
        $_aPageClasses = $this->getElementAsArray($GLOBALS, array('aOmniwebShowtimes_AdminPageFramework', 'aPageClasses'));
        foreach ($_aPageClasses as $_oAdminPage) {
            if ($_oAdminPage->oProp->isPageAdded($sPageSlug)) {
                return $_oAdminPage;
            }
        }
        return null;
    }
    public function __get($sName) {
        if ('oAdminPage' === $sName) {
            $this->oAdminPage = $this->_getOwnerObjectOfPage($_GET['page']);
            if (is_object($this->oAdminPage)) {
                $this->oAdminPage->oProp->bEnableForm = true;
            }
            return $this->oAdminPage;
        }
        if ('aHelpTabs' == $sName) {
            $this->aHelpTabs = $this->oAdminPage->oProp->aHelpTabs;
            return $this->aHelpTabs;
        }
        return parent::__get($sName);
    }
}


text:
<?php

if (!@include __DIR__ . '/../vendor/autoload.php') {
    die("You must set up the project dependencies, run the following commands:
wget http://getcomposer.org/composer.phar
php composer.phar install --dev
");
}

gc_enable();

define('ROOT_TESTS', realpath(__DIR__));

// Autoload test classes
spl_autoload_register(function($class) {
    $filename = str_replace("\\", DIRECTORY_SEPARATOR, $class) . '.php';
    if (file_exists(ROOT_TESTS . DIRECTORY_SEPARATOR . $filename)) {
        include_once $filename;
    }
    return class_exists($class, false);
});


text:
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using OpenSim.Server.Base;
using OpenMetaverse;

namespace OpenSim.Services.Connectors
{
    public class FriendsServicesConnector : IFriendsService
    {
        private static readonly ILog m_log =
                LogManager.GetLogger(
                MethodBase.GetCurrentMethod().DeclaringType);

        private string m_ServerURI = String.Empty;

        public FriendsServicesConnector()
        {
        }

        public FriendsServicesConnector(string serverURI)
        {
            m_ServerURI = serverURI.TrimEnd('/');
        }

        public FriendsServicesConnector(IConfigSource source)
        {
            Initialise(source);
        }

        public virtual void Initialise(IConfigSource source)
        {
            IConfig gridConfig = source.Configs["FriendsService"];
            if (gridConfig == null)
            {
                m_log.Error("[FRIENDS CONNECTOR]: FriendsService missing from OpenSim.ini");
                throw new Exception("Friends connector init error");
            }

            string serviceURI = gridConfig.GetString("FriendsServerURI",
                    String.Empty);

            if (serviceURI == String.Empty)
            {
                m_log.Error("[FRIENDS CONNECTOR]: No Server URI named in section FriendsService");
                throw new Exception("Friends connector init error");
            }
            m_ServerURI = serviceURI;
        }

        #region IFriendsService

        public FriendInfo[] GetFriends(UUID PrincipalID)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["PRINCIPALID"] = PrincipalID.ToString();
            sendData["METHOD"] = "getfriends";

            string reqString = ServerUtils.BuildQueryString(sendData);

            try
            {
                string reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/friends",
                        reqString);
                if (reply != string.Empty)
                {
                    Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                    if (replyData != null)
                    {
                        if (replyData.ContainsKey("result") && (replyData["result"].ToString().ToLower() == "null"))
                        {
                        return new FriendInfo[0];
                        }

                        List<FriendInfo> finfos = new List<FriendInfo>();
                        Dictionary<string, object>.ValueCollection finfosList = replyData.Values;
                        //m_log.DebugFormat("[FRIENDS CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count);
                        foreach (object f in finfosList)
                        {
                            if (f is Dictionary<string, object>)
                            {
                                FriendInfo finfo = new FriendInfo((Dictionary<string, object>)f);
                                finfos.Add(finfo);
                            }
                            else
                                m_log.DebugFormat("[FRIENDS CONNECTOR]: GetFriends {0} received invalid response type {1}",
                                    PrincipalID, f.GetType());
                        }

                        // Success
                        return finfos.ToArray();
                    }

                    else
                        m_log.DebugFormat("[FRIENDS CONNECTOR]: GetFriends {0} received null response",
                            PrincipalID);

                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[FRIENDS CONNECTOR]: Exception when contacting friends server: {0}", e.Message);
            }

            return new FriendInfo[0];

        }

        public bool StoreFriend(UUID PrincipalID, string Friend, int flags)
        {
            FriendInfo finfo = new FriendInfo();
            finfo.PrincipalID = PrincipalID;
            finfo.Friend = Friend;
            finfo.MyFlags = flags;

            Dictionary<string, object> sendData = finfo.ToKeyValuePairs();

            sendData["METHOD"] = "storefriend";

            string reply = string.Empty;
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/friends",
                        ServerUtils.BuildQueryString(sendData));
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[FRIENDS CONNECTOR]: Exception when contacting friends server: {0}", e.Message);
                return false;
            }

            if (reply != string.Empty)
            {
                Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if ((replyData != null) && replyData.ContainsKey("Result") && (replyData["Result"] != null))
                {
                    bool success = false;
                    Boolean.TryParse(replyData["Result"].ToString(), out success);
                    return success;
                }
                else
                    m_log.DebugFormat("[FRIENDS CONNECTOR]: StoreFriend {0} {1} received null response",
                        PrincipalID, Friend);
            }
            else
                m_log.DebugFormat("[FRIENDS CONNECTOR]: StoreFriend received null reply");

            return false;

        }

        public bool Delete(UUID PrincipalID, string Friend)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();
            sendData["PRINCIPALID"] = PrincipalID.ToString();
            sendData["FRIEND"] = Friend;
            sendData["METHOD"] = "deletefriend";

            string reply = string.Empty;
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/friends",
                        ServerUtils.BuildQueryString(sendData));
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[FRIENDS CONNECTOR]: Exception when contacting friends server: {0}", e.Message);
                return false;
            }

            if (reply != string.Empty)
            {
                Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if ((replyData != null) && replyData.ContainsKey("Result") && (replyData["Result"] != null))
                {
                    bool success = false;
                    Boolean.TryParse(replyData["Result"].ToString(), out success);
                    return success;
                }
                else
                    m_log.DebugFormat("[FRIENDS CONNECTOR]: DeleteFriend {0} {1} received null response",
                        PrincipalID, Friend);
            }
            else
                m_log.DebugFormat("[FRIENDS CONNECTOR]: DeleteFriend received null reply");

            return false;
        }

        #endregion
    }
}


text:
VIXL: AArch64 Runtime Code Generation Library Version 1.13
==========================================================

**NB.** VIXL development continues in [a new repository at Linaro][linaro].

Contents:

 * Overview
 * Licence
 * Requirements
 * Known limitations
 * Usage

Overview
========

VIXL contains three components.

 1. A programmatic **assembler** to generate A64 code at runtime. The assembler
    abstracts some of the constraints of the A64 ISA; for example, most
    instructions support any immediate.
 2. A **disassembler** that can print any instruction emitted by the assembler.
 3. A **simulator** that can simulate any instruction emitted by the assembler.
    The simulator allows generated code to be run on another architecture
    without the need for a full ISA model.

The VIXL git repository can be found [on GitHub][vixl].

Changes from previous versions of VIXL can be found in the
[Changelog](doc/changelog.md).

Licence
=======

This software is covered by the licence described in the [LICENCE](LICENCE)
file.

Requirements
============

To build VIXL the following software is required:

 1. Python 2.7
 2. SCons 2.0
 3. GCC 4.8+ or Clang 3.4+

A 64-bit host machine is required, implementing an LP64 data model. VIXL has
been tested using GCC on AArch64 Debian, GCC and Clang on amd64 Ubuntu
systems.

To run the linter and code formatting stages of the tests, the following
software is also required:

 1. Git
 2. [Google's `cpplint.py`][cpplint]
 3. clang-format-3.6

Refer to the 'Usage' section for details.

Known Limitations
=================

VIXL was developed for JavaScript engines so a number of features from A64 were
deemed unnecessary:

 * Limited rounding mode support for floating point.
 * Limited support for synchronisation instructions.
 * Limited support for system instructions.
 * A few miscellaneous integer and floating point instructions are missing.

The VIXL simulator supports only those instructions that the VIXL assembler can
generate. The `doc` directory contains a
[list of supported instructions](doc/supported-instructions.md).

The VIXL simulator was developed to run on 64-bit amd64 platforms. Whilst it
builds and mostly works for 32-bit x86 platforms, there are a number of
floating-point operations which do not work correctly, and a number of tests
fail as a result.

VIXL may not build using Clang 3.7, due to a compiler warning. A workaround is
to disable conversion of warnings to errors, or to delete the offending
`return` statement reported and rebuild. This problem will be fixed in the next
release.

Debug Builds
------------

Your project's build system must define `VIXL_DEBUG` (eg. `-DVIXL_DEBUG`)
when using a VIXL library that has been built with debug enabled.

Some classes defined in VIXL header files contain fields that are only present
in debug builds, so if `VIXL_DEBUG` is defined when the library is built, but
not defined for the header files included in your project, you will see runtime
failures.

Exclusive-Access Instructions
-----------------------------

All exclusive-access instructions are supported, but the simulator cannot
accurately simulate their behaviour as described in the ARMv8 Architecture
Reference Manual.

 * A local monitor is simulated, so simulated exclusive loads and stores execute
   as expected in a single-threaded environment.
 * The global monitor is simulated by occasionally causing exclusive-access
   instructions to fail regardless of the local monitor state.
 * Load-acquire, store-release semantics are approximated by issuing a host
   memory barrier after loads or before stores. The built-in
   `__sync_synchronize()` is used for this purpose.

The simulator tries to be strict, and implements the following restrictions that
the ARMv8 ARM allows:

 * A pair of load-/store-exclusive instructions will only succeed if they have
   the same address and access size.
 * Most of the time, cache-maintenance operations or explicit memory accesses
   will clear the exclusive monitor.
    * To ensure that simulated code does not depend on this behaviour, the
      exclusive monitor will sometimes be left intact after these instructions.

Instructions affected by these limitations:
  `stxrb`, `stxrh`, `stxr`, `ldxrb`, `ldxrh`, `ldxr`, `stxp`, `ldxp`, `stlxrb`,
  `stlxrh`, `stlxr`, `ldaxrb`, `ldaxrh`, `ldaxr`, `stlxp`, `ldaxp`, `stlrb`,
  `stlrh`, `stlr`, `ldarb`, `ldarh`, `ldar`, `clrex`.

Usage
=====

Running all Tests
-----------------

The helper script `tools/test.py` will build and run every test that is provided
with VIXL, in both release and debug mode. It is a useful script for verifying
that all of VIXL's dependencies are in place and that VIXL is working as it
should.

By default, the `tools/test.py` script runs a linter to check that the source
code conforms with the code style guide, and to detect several common errors
that the compiler may not warn about. This is most useful for VIXL developers.
The linter has the following dependencies:

 1. Git must be installed, and the VIXL project must be in a valid Git
    repository, such as one produced using `git clone`.
 2. `cpplint.py`, [as provided by Google][cpplint], must be available (and
    executable) on the `PATH`.

It is possible to tell `tools/test.py` to skip the linter stage by passing
`--nolint`. This removes the dependency on `cpplint.py` and Git. The `--nolint`
option is implied if the VIXL project is a snapshot (with no `.git` directory).

Additionally, `tools/test.py` tests code formatting using `clang-format-3.6`.
If you don't have `clang-format-3.6`, disable the test using the
`--noclang-format` option.

Also note that the tests for the tracing features depend upon external `diff`
and `sed` tools. If these tools are not available in `PATH`, these tests will
fail.

Getting Started
---------------

A short introduction to using VIXL can be found [here](doc/getting-started.md).
Example source code is provided in the [examples](examples) directory. You can
build all the examples with `scons examples` from the root directory, or use
`scons --help` to get a detailed list of available build targets.

Using VIXL
----------

In addition to [getting started](doc/getting-started.md) and the
[examples](examples), you can find documentation and guides on various topics
that may be helpful [here](doc/topics/index.md).

[cpplint]: http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py
           "Google's cpplint.py script."

[vixl]: https://github.com/armvixl/vixl
        "The VIXL repository on GitHub."

[linaro]: https://git.linaro.org/arm/vixl.git
          "The new VIXL repository at Linaro."


text:
(* ::Package:: *)

(*

   Ref: https://code.google.com/p/cuda-convnet/
   Ref: https://code.google.com/p/cuda-convnet/source/browse/trunk/example-layers/layers-18pct.cfg
   Ref: Alex Krizhevsky

   Not completely faithful implementation.
   He uses RELU and a contrast normalisation layer.

   Epoch: 112 Note this has overtrained, we had achieved validation cross entropy loss of around .95
   Training Cross Entropy: .33
   Validation Cross Entropy: 1.01

*)

<<"C:/users/julian/documents/github/Machine-Vision/NeuralNetworks/NeuralNetwork.m"

<<"C:/users/julian/documents/github/Machine-Vision/NeuralNetworks/CIFAR10/CIFAR10Data.m"

SeedRandom[1234];
CIFARNet3={
   PadFilterBank[2],ConvolveFilterBankToFilterBankInit[3,32,5],Tanh,
   MaxPoolingFilterBankToFilterBank,
   PadFilterBank[2],ConvolveFilterBankToFilterBankInit[32,32,5],Tanh,
   MaxPoolingFilterBankToFilterBank,
   PadFilterBank[2],ConvolveFilterBankToFilterBankInit[32,64,5],Tanh,
   MaxPoolingFilterBankToFilterBank,
   Adaptor3DTo1D[64,4,4],
   FullyConnected1DTo1DInit[64*4*4,10],
   Softmax
};

CIFAR10NetTrainingInputs=ColTrainingImages[[1;;4000]]*1.;
CIFAR10NetTrainingOutputs=Map[ReplacePart[ConstantArray[0,10],(#+1)->1]&,TrainingLabels];

CIFAR10NetValidationInputs=ColValidationImages[[All]]*1.;
CIFAR10NetValidationOutputs=Map[ReplacePart[ConstantArray[0,10],(#+1)->1]&,ValidationLabels];

wl=CIFARNet3;
TrainingHistory={};
ValidationHistory={};
\[Lambda]=.01;

TrainNet3MB:=MiniBatchGradientDescent[
      wl,ColTrainingImages,CIFAR10NetTrainingOutputs,
      NNGrad,ClassificationLoss,
        {MaxEpoch->500000,
         ValidationInputs->ColValidationImages[[1;;500]],
         ValidationTargets->CIFAR10NetValidationOutputs[[1;;500]],
         InitialLearningRate->\[Lambda]}];

CIFAR10Output[probs_]:=BarChart[probs[[Reverse[Ordering[probs,-3]]]],ChartLabels->WordLabels[[Reverse[Ordering[probs,-3]]]]];

CIFAR10Outputs[probs_,pics_]:=MapThread[{Image[#2,Interleaving->False],CIFAR10Output[#1]}&,{probs,pics}];


text:
Ansible playbook to deploy my homelab (as of right now, a single Raspberry Pi 1 B+... yeah)

## Usage

```sh
ansible-playbook -i hosts/pi playbook.yml [--tags "dyndns,pi"]
```

Add `--limit pi` to only run on the Raspberry Pi.

### First run only

Obviously, SSH public key authentication won't work on the first run. You'll need to login via password:

Install sshpass on the control machine
```sh
sudo apt install sshpass
```

Add `--extra-var ansible_pass=raspberrypi` which is the default password for the Rpi.


text:
package br.edu.ufcg.computacao.si1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class InitialPoint {

	private static final String[] REQUEST_METHOD_SUPPORTED = { "GET", "POST", "PUT", "DELETE"};

	public static void main(String[] args) {
		SpringApplication.run(InitialPoint.class, args);
	}

	@Bean
	public WebMvcConfigurer corsConfigurer() {
		return new WebMvcConfigurerAdapter() {
			@Override
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*")
						.allowedMethods(REQUEST_METHOD_SUPPORTED);
			}
		};
	}
}


text:
#ifndef _LINUX_SWAP_H
#define _LINUX_SWAP_H

#include <linux/config.h>

#define MAX_SWAPFILES 32

#ifdef __KERNEL__

#include <linux/spinlock.h>
#include <asm/page.h>

#define SWAP_FLAG_PREFER	0x8000	/* set if swap priority specified */
#define SWAP_FLAG_PRIO_MASK	0x7fff
#define SWAP_FLAG_PRIO_SHIFT	0

/*
 * Magic header for a swap area. The first part of the union is
 * what the swap magic looks like for the old (limited to 128MB)
 * swap area format, the second part of the union adds - in the
 * old reserved area - some extra information. Note that the first
 * kilobyte is reserved for boot loader or disk label stuff...
 *
 * Having the magic at the end of the PAGE_SIZE makes detecting swap
 * areas somewhat tricky on machines that support multiple page sizes.
 * For 2.5 we'll probably want to move the magic to just beyond the
 * bootbits...
 */
union swap_header {
	struct
	{
		char reserved[PAGE_SIZE - 10];
		char magic[10];			/* SWAP-SPACE or SWAPSPACE2 */
	} magic;
	struct
	{
		char	     bootbits[1024];	/* Space for disklabel etc. */
		unsigned int version;
		unsigned int last_page;
		unsigned int nr_badpages;
		unsigned int padding[125];
		unsigned int badpages[1];
	} info;
};

/*
 * Max bad pages in the new format..
 */
#define __swapoffset(x) ((unsigned long)&((union swap_header *)0)->x)
#define MAX_SWAP_BADPAGES \
	((__swapoffset(magic.magic) - __swapoffset(info.badpages)) / sizeof(int))

#include <asm/atomic.h>

#define SWP_USED	1
#define SWP_WRITEOK	3

#define SWAP_CLUSTER_MAX 32

#define SWAP_MAP_MAX	0x7fff
#define SWAP_MAP_BAD	0x8000

/*
 * The in-memory structure used to track swap areas.
 */
struct swap_info_struct {
	unsigned int flags;
	kdev_t swap_device;
	spinlock_t sdev_lock;
	struct dentry * swap_file;
	struct vfsmount *swap_vfsmnt;
	unsigned short * swap_map;
	unsigned int lowest_bit;
	unsigned int highest_bit;
	unsigned int cluster_next;
	unsigned int cluster_nr;
	int prio;			/* swap priority */
	int pages;
	unsigned long max;
	int next;			/* next entry on swap list */
};

extern int nr_swap_pages;

/* Swap 50% full? Release swapcache more aggressively.. */
#define vm_swap_full() (nr_swap_pages*2 < total_swap_pages)

extern unsigned int nr_free_pages(void);
extern unsigned int nr_free_buffer_pages(void);
extern unsigned int freeable_lowmem(void);
extern int nr_active_pages;
extern int nr_inactive_pages;
extern unsigned long page_cache_size;
extern atomic_t buffermem_pages;

extern spinlock_cacheline_t pagecache_lock_cacheline;
#define pagecache_lock (pagecache_lock_cacheline.lock)

extern void __remove_inode_page(struct page *);

/* Incomplete types for prototype declarations: */
struct task_struct;
struct vm_area_struct;
struct sysinfo;

struct zone_t;

/* linux/mm/swap.c */
extern void FASTCALL(lru_cache_add(struct page *));
extern void FASTCALL(__lru_cache_del(struct page *));
extern void FASTCALL(lru_cache_del(struct page *));

extern void FASTCALL(activate_page(struct page *));

extern void swap_setup(void);

/* linux/mm/vmscan.c */
extern wait_queue_head_t kswapd_wait;
extern int FASTCALL(try_to_free_pages_zone(zone_t *, unsigned int));
extern int FASTCALL(try_to_free_pages(unsigned int));
extern int vm_vfs_scan_ratio, vm_cache_scan_ratio, vm_lru_balance_ratio, vm_passes, vm_gfp_debug, vm_mapped_ratio, vm_anon_lru;

/* linux/mm/page_io.c */
extern void rw_swap_page(int, struct page *);
extern void rw_swap_page_nolock(int, swp_entry_t, char *);

/* linux/mm/page_alloc.c */

/* linux/mm/swap_state.c */
#define SWAP_CACHE_INFO
#ifdef SWAP_CACHE_INFO
extern void show_swap_cache_info(void);
#endif
extern int add_to_swap_cache(struct page *, swp_entry_t);
extern void __delete_from_swap_cache(struct page *page);
extern void delete_from_swap_cache(struct page *page);
extern void free_page_and_swap_cache(struct page *page);
extern struct page * lookup_swap_cache(swp_entry_t);
extern struct page * read_swap_cache_async(swp_entry_t);

/* linux/mm/oom_kill.c */
extern void out_of_memory(void);

/* linux/mm/swapfile.c */
extern int total_swap_pages;
extern unsigned int nr_swapfiles;
extern struct swap_info_struct swap_info[];
extern int is_swap_partition(kdev_t);
extern void si_swapinfo(struct sysinfo *);
extern swp_entry_t get_swap_page(void);
extern void get_swaphandle_info(swp_entry_t, unsigned long *, kdev_t *,
					struct inode **);
extern int swap_duplicate(swp_entry_t);
extern int valid_swaphandles(swp_entry_t, unsigned long *);
extern void swap_free(swp_entry_t);
extern void free_swap_and_cache(swp_entry_t);
struct swap_list_t {
	int head;	/* head of priority-ordered swapfile list */
	int next;	/* swapfile to be used next */
};
extern struct swap_list_t swap_list;
asmlinkage long sys_swapoff(const char *);
asmlinkage long sys_swapon(const char *, int);

extern spinlock_cacheline_t pagemap_lru_lock_cacheline;
#define pagemap_lru_lock pagemap_lru_lock_cacheline.lock

extern void FASTCALL(mark_page_accessed(struct page *));

/*
 * List add/del helper macros. These must be called
 * with the pagemap_lru_lock held!
 */
#define DEBUG_LRU_PAGE(page)			\
do {						\
	if (!PageLRU(page))			\
		BUG();				\
	if (PageActive(page))			\
		BUG();				\
} while (0)

extern void delta_nr_active_pages(struct page *page, long delta);
#define inc_nr_active_pages(page) delta_nr_active_pages(page, 1)
#define dec_nr_active_pages(page) delta_nr_active_pages(page, -1)

extern void delta_nr_inactive_pages(struct page *page, long delta);
#define inc_nr_inactive_pages(page) delta_nr_inactive_pages(page, 1)
#define dec_nr_inactive_pages(page) delta_nr_inactive_pages(page, -1)

#define add_page_to_active_list(page)		\
do {						\
	DEBUG_LRU_PAGE(page);			\
	SetPageActive(page);			\
	list_add(&(page)->lru, &active_list);	\
	inc_nr_active_pages(page);		\
} while (0)

#define add_page_to_inactive_list(page)		\
do {						\
	DEBUG_LRU_PAGE(page);			\
	list_add(&(page)->lru, &inactive_list);	\
	inc_nr_inactive_pages(page);		\
} while (0)

#define del_page_from_active_list(page)		\
do {						\
	list_del(&(page)->lru);			\
	ClearPageActive(page);			\
	dec_nr_active_pages(page);		\
} while (0)

#define del_page_from_inactive_list(page)	\
do {						\
	list_del(&(page)->lru);			\
	dec_nr_inactive_pages(page);		\
} while (0)

extern void delta_nr_cache_pages(struct page *page, long delta);
#define inc_nr_cache_pages(page) delta_nr_cache_pages(page, 1)
#define dec_nr_cache_pages(page) delta_nr_cache_pages(page, -1)

extern spinlock_t swaplock;

#define swap_list_lock()	spin_lock(&swaplock)
#define swap_list_unlock()	spin_unlock(&swaplock)
#define swap_device_lock(p)	spin_lock(&p->sdev_lock)
#define swap_device_unlock(p)	spin_unlock(&p->sdev_lock)

extern int shmem_unuse(swp_entry_t entry, struct page *page);

#endif /* __KERNEL__*/

#endif /* _LINUX_SWAP_H */


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.github.xiaofei_dev.gank">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:name=".util.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">
        <activity
            android:name=".ui.activity.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.Launcher">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".ui.activity.SimpleMeiZhiActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
            android:label="@string/fu_li"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.simple">
        </activity>
        <activity
            android:name=".ui.activity.SimpleWebActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
            android:theme="@style/AppTheme.NoActionBar.simple">
        </activity>
        <activity
            android:name=".ui.activity.AboutActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
            android:theme="@style/Dialog">
        </activity>
        <activity
            android:name=".ui.activity.SearchActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.simple">
        </activity>
        <activity android:name=".ui.activity.CollectionActivity"
                  android:theme="@style/AppTheme.NoActionBar.simple"
            android:label="@string/collect">
        </activity>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.github.xiaofei_dev.gank.fileProvider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>

</manifest>


text:
/* tslint:disable */
/* eslint-disable */
/**
 * Swaggy Jenkins
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * The version of the OpenAPI document: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

import { exists, mapValues } from '../runtime';
import {
    GithubScmlinks,
    GithubScmlinksFromJSON,
    GithubScmlinksFromJSONTyped,
    GithubScmlinksToJSON,
} from './GithubScmlinks';

/**
 *
 * @export
 * @interface GithubScm
 */
export interface GithubScm {
    /**
     *
     * @type {string}
     * @memberof GithubScm
     */
    _class?: string;
    /**
     *
     * @type {GithubScmlinks}
     * @memberof GithubScm
     */
    links?: GithubScmlinks;
    /**
     *
     * @type {string}
     * @memberof GithubScm
     */
    credentialId?: string;
    /**
     *
     * @type {string}
     * @memberof GithubScm
     */
    id?: string;
    /**
     *
     * @type {string}
     * @memberof GithubScm
     */
    uri?: string;
}

export function GithubScmFromJSON(json: any): GithubScm {
    return GithubScmFromJSONTyped(json, false);
}

export function GithubScmFromJSONTyped(json: any, ignoreDiscriminator: boolean): GithubScm {
    if ((json === undefined) || (json === null)) {
        return json;
    }
    return {

        '_class': !exists(json, '_class') ? undefined : json['_class'],
        'links': !exists(json, '_links') ? undefined : GithubScmlinksFromJSON(json['_links']),
        'credentialId': !exists(json, 'credentialId') ? undefined : json['credentialId'],
        'id': !exists(json, 'id') ? undefined : json['id'],
        'uri': !exists(json, 'uri') ? undefined : json['uri'],
    };
}

export function GithubScmToJSON(value?: GithubScm | null): any {
    if (value === undefined) {
        return undefined;
    }
    if (value === null) {
        return null;
    }
    return {

        '_class': value._class,
        '_links': GithubScmlinksToJSON(value.links),
        'credentialId': value.credentialId,
        'id': value.id,
        'uri': value.uri,
    };
}


text:
package com.github.ladutsko.isbn;

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URI;

import org.junit.Test;

/**
 * @author George Ladutsko
 */
public class ISBNTest {

  @Test(expected=IllegalArgumentException.class)
  public void parseIsbnThrowIllegalArgumentExceptionForNull() throws Exception {
    ISBN.parseIsbn(null);
  }

  @Test(expected=IllegalArgumentException.class)
  public void parseIsbnThrowIllegalArgumentExceptionForEmpty() throws Exception {
    ISBN.parseIsbn("");
  }

  @Test(expected=ISBNException.class)
  public void parseIsbnThrowISBNExceptionForNotWelFormed() throws Exception {
    ISBN.parseIsbn("qwertyuiop");
  }

  @Test(expected=ISBNException.class)
  public void parseIsbnThrowISBNExceptionForWrongCheckDigit() throws Exception {
    ISBN.parseIsbn("0123456780");
  }

  @Test
  public void equalsReturnTrueForTheSame() throws Exception {
    ISBN isbn = ISBN.parseIsbn("0123456789");

    assertThat(isbn.equals(isbn), is(true));
  }

  @Test
  public void equalsReturnFalseForNull() throws Exception {
    assertThat(ISBN.parseIsbn("0123456789").equals(null), is(false));
  }

  @Test
  public void equalsReturnFalseForOtherType() throws Exception {
    assertThat(ISBN.parseIsbn("0123456789").equals(new Object()), is(false));
  }

  @Test
  public void equalsReturnTrueForSimilar() throws Exception {
    assertThat(ISBN.parseIsbn("0123456789").equals(ISBN.parseIsbn("0123456789")), is(true));
  }

  @Test
  public void equalsReturnFalseForOther() throws Exception {
    assertThat(ISBN.parseIsbn("0470747722").equals(ISBN.parseIsbn("111800759X")), is(false));
  }

  @Test
  public void serializationTest() throws Exception {
    // construct test object
    ISBN isbn = ISBN.parseIsbn("0123456789");

    // serialize
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeObject(isbn);
    oos.close();

    byte[] pickled = out.toByteArray();

    assertThat(pickled.length, is(97));

    // deserialize
    InputStream in = new ByteArrayInputStream(pickled);
    ObjectInputStream ois = new ObjectInputStream(in);
    Object o = ois.readObject();
    ISBN copy = (ISBN) o;

    // test the result
    assertThat(isbn, is(not(sameInstance(copy))));
    assertThat(isbn.getIsbn13(), is(copy.getIsbn13()));
    assertThat(isbn.getIsbn10(), is(copy.getIsbn10()));
  }

  @Test
  public void toURITest() throws Exception {
    URI uri = ISBN.parseIsbn("0123456789").toURI();

    assertThat(uri.toString(), is("urn:isbn:9780123456786"));
  }

  @Test
  public void toStringTest() throws Exception {
    String s = ISBN.parseIsbn("0123456789").toString();

    assertThat(s, containsString(ISBN.class.getName()));
    assertThat(s, containsString("isbn13"));
    assertThat(s, containsString("isbn10"));
  }

  @Test
  public void hashCodeIsStable() throws Exception {
    int hashCode = ISBN.parseIsbn("0123456789").hashCode();

    assertThat(ISBN.parseIsbn("0123456789").hashCode(), is(hashCode));
    assertThat(ISBN.parseIsbn("0123456789").hashCode(), is(hashCode));
  }

  @Test
  public void hashCodeIsDifferent() throws Exception {
    int hashCode = ISBN.parseIsbn("0123456789").hashCode();

    assertThat(ISBN.parseIsbn("0470747722").hashCode(), is(not(hashCode)));
    assertThat(ISBN.parseIsbn("111800759X").hashCode(), is(not(hashCode)));
  }

  @Test
  public void isbn10ShouldBeAlwaysUpperCase() throws Exception {
    assertThat(ISBN.parseIsbn("111800759X").getIsbn10(), is("111800759X"));
    assertThat(ISBN.parseIsbn("111800759x").getIsbn10(), is("111800759X"));
  }
}


text: This repo is containing common recursion coding questions.


text:
bind '"\e[A": history-search-backward'
bind '"\e[B": history-search-forward'
bind '"\e[C": forward-char'
bind '"\e[D": backward-char'

# Ignore case sensitivity when using auto-complete
bind "set completion-ignore-case on"
# Make hyphens and underscores interchangeable when using auto-complete
bind "set completion-map-case on"
bind "set show-all-if-ambiguous on"
bind "set mark-symlinked-directories on"


text:
wchar_t* vscAllocateAndCopy(const gtString& str);

char* vscAllocateAndCopy(const std::string& str);

std::string vscWstrToStr(std::wstring const& text);

#endif // vscCoreInternalUtils_h__


text:
using Omu.ValueInjecter;
using Omu.ValueInjecter.Injections;
using OnlineLibrary.Classes;
using OnlineLibrary.Controllers;
using OnlineLibrary.Domain.Entities;
using OnlineLibrary.Models;
using OnlineLibrary.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OnlineLibrary.Controllers
{
  public class BooksController : Controller
  {
    const int pageSize = 10;
    public IBookService service { get; set; }

    public BooksController(IBookService service)
    {
      this.service = service;
    }

    // GET: Books
    public ActionResult Index(int? page, string sort, string sortdir, string searchString)
    {
      Session["searchString"] = searchString;
      var pageNumber = page.HasValue ? page.Value : 1;
      ViewBag.CurrentPage = pageNumber;
      ViewBag.SearchString = searchString;
      ViewBag.Action = null;

      var model=CreateBooksModel(pageNumber,sort, sortdir,searchString);
      ViewBag.Count = model.Count();
      ViewBag.TotalPages = Math.Ceiling((double)ViewBag.Count / pageSize);
      ViewBag.PageSize = pageSize;
      Session["books_model"] = model;

      if (searchString != null && searchString !="")
      {
        ViewBag.Title = "Search Result";
        ViewBag.SubTitle = "Search result: ";
        ViewBag.Action = "search";

        return PartialView("_Books", model.Skip((pageNumber - 1) * pageSize).Take(pageSize));
      }

        ViewBag.Title = "Our Books";
        ViewBag.SubTitle = "You can loan from ";

      try
      {
        if (Session["user_name"] == null)
        {
          ViewBag.Message = "Hello " + Session["userName"];
        }
      }
      catch
      {
        ViewBag.Message = "Sign in please!";
      }
      if (searchString == null)
      {
        return View(model.Skip((pageNumber - 1) * pageSize).Take(pageSize));
      }
      else
      {
        ViewBag.Title = "Search Result";
        ViewBag.SubTitle = "Search result: 0 books";
        ViewBag.Action = "search";

        return PartialView("_NotFound");
      }
    }

    private List<BookViewModel> CreateBooksModel(int pageNumber, string sort, string sortdir, string searchString)
    {

      List<BookViewModel> booksList = new List<BookViewModel>();

      var booksDbList = service.GetAllRecords();

      booksList.InjectFrom(booksDbList);
      for (var i = 0; i < booksList.Count; i++)
      {
        booksList[i].Author = booksDbList[i].Author.FullName;
        booksList[i].Category = booksDbList[i].Category.Category;
        booksList[i].Publishing = booksDbList[i].Publishing.Publishing;
        //booksList[i].Availability = booksDbList[i].NoOfBooks - booksDbList[i].Loans.Where(l => l.BookID == booksDbList[i].ID).Count();
        booksList[i].Availability = booksDbList[i].NoOfBooks - booksDbList[i].Loans.Count();
        //booksList[i].AvailabilityDate = (booksDbList[i].Loans.Where(l => l.BookID == booksDbList[i].ID).Count() != 0) ?
        //             booksDbList[i].Loans.Where(l => l.BookID == booksDbList[i].ID).OrderBy(l => l.loanDate).First().loanDate.ToString("dd-MM-yyyy") : "";
        booksList[i].AvailabilityDate = (booksDbList[i].Loans.Count() != 0) ?
                     booksDbList[i].Loans.OrderBy(l => l.loanDate).First().loanDate.ToString("dd-MM-yyyy") : "";
      }
      if (searchString != null && searchString !="")
      {
        var booksListSearch=CreateSearchBooksModel(booksList);
        return booksListSearch.ToList();
      }
      return booksList;
    }

    private List<BookViewModel> CreateSearchBooksModel(List<BookViewModel> booksList)
    {
      int yearParsed = 0;
      string searchString = Session["searchString"].ToString();
      bool isNumeric = int.TryParse(searchString, out yearParsed);

      string searchStringLower = searchString.ToLower();
      var booksListSearch = booksList.Where(x => x.Title.ToLower().Contains(searchStringLower)
                              || x.Category.ToLower().Contains(searchStringLower)
                              || x.Author.ToLower().Contains(searchStringLower)
                              || x.ISBN.ToLower().Contains(searchStringLower)
                              || x.Publishing.ToLower().Contains(searchStringLower)
                              || x.Year == yearParsed);
      return booksListSearch.ToList();
    }

    [HttpPost]
    public ActionResult FilterBooks(int? page, FormCollection collection)
    {

      string categories = collection["CategoriesID"];
      string publishings = collection["PublishingsID"];
      string authors = collection["AuthorsID"];
      string years = collection["Year"];

      var pageNumber = page.HasValue ? page.Value : 1;
      ViewBag.CurrentPage = pageNumber;
      string searchString= "", sort = null, sortdir = null;

      var booksListFilter = CreateBooksModel(pageNumber, sort, sortdir, searchString);
      //var booksListFilter = model;
      if (categories == null && publishings == null && authors == null && years == null)
      {
        ViewBag.Count = service.Count();
        ViewBag.TotalPages = Math.Ceiling((double)ViewBag.Count / pageSize);
        ViewBag.PageSize = pageSize;
        ViewBag.Title = "Our Books";
        ViewBag.SubTitle = "You can loan from: ";
        ViewBag.Action = "index";
        Session["books_model"] = booksListFilter;
        return PartialView("_Books", booksListFilter.ToList().Skip((pageNumber - 1) * pageSize).Take(pageSize));

      }
      else
      {

        string[] cats = (categories != null)?categories.Split(','): new string[0];
        string[] pubs = (publishings != null)? publishings.Split(','): new string[0];
        string[] aths = (authors != null)? authors.Split(',') : new string[0];
        string[] year = (years != null)? years.Split(','): new string[0];

        booksListFilter = booksListFilter.Where(x => cats.Contains(x.CategoriesID.ToString())
                              || pubs.Contains(x.PublishingsID.ToString())
                              || aths.Contains(x.AuthorID.ToString())
                              || year.Contains(x.Year.ToString())
                              ).ToList();

        ViewBag.Count = booksListFilter.Count();
        ViewBag.TotalPages = Math.Ceiling((double)ViewBag.Count / pageSize);
        ViewBag.PageSize = pageSize;
        ViewBag.Title = "Filter Result";
        ViewBag.SubTitle = "Filter result: ";
        ViewBag.Action = "filter";
        Session["books_model"] = booksListFilter;
        return PartialView("_Books", booksListFilter.Skip((pageNumber - 1) * pageSize).Take(pageSize));

      }

    }

    [HttpPost]
    public ActionResult SortBooks(int? page,string orderby)
    {

      var pageNumber = page.HasValue ? page.Value : 1;
      ViewBag.CurrentPage = pageNumber;
      ViewBag.Title = "Sorted Books";
      ViewBag.Action = "sort";
      ViewBag.OrderBy = orderby;
      List<BookViewModel> model = (List<BookViewModel>)Session["books_model"];
      List<BookViewModel> sortModel=new List<BookViewModel>();
      switch (orderby)
      {
        case "category":
          sortModel = model.OrderBy(m => m.Category).ToList();
          ViewBag.SubTitle = "Sort by Category ";
          break;

        case "author":
          sortModel = model.OrderBy(m => m.Author.Split(' ').Last()).ToList();
          ViewBag.SubTitle = "Sort by Author ";
          break;

        case "title":
          sortModel = model.OrderBy(m => m.Title).ToList();
          ViewBag.SubTitle = "Sort by Title ";
          break;

        case "publishing":
          sortModel = model.OrderBy(m => m.Publishing).ToList();
          ViewBag.SubTitle = "Sort by Publishing ";
          break;

        case "year":
          sortModel = model.OrderBy(m => m.Year).ToList();
          ViewBag.SubTitle = "Sort by Year ascending ";
          break;

        case "year-desc":
          sortModel = model.OrderByDescending(m => m.Year).ToList();
          ViewBag.SubTitle = "Sort by Year descending ";
          break;

      }

      ViewBag.Count = sortModel.Count();
      ViewBag.TotalPages = Math.Ceiling((double)ViewBag.Count / pageSize);
      ViewBag.PageSize = pageSize;

      return PartialView("_Books", sortModel.Skip((pageNumber - 1) * pageSize).Take(pageSize));
    }
    [HttpPost]
    public ActionResult LoadModal(string bookId)
    {
      List<BookViewModel> model = (List<BookViewModel>)Session["books_model"];

      return PartialView("_BookDetail", model.Where(m => m.ID.ToString() == bookId));
    }

  }
}


text:
package flat

import (
	flatbuffers "github.com/google/flatbuffers/go"
)
type DiskUsage struct {
	_tab flatbuffers.Table
}

func GetRootAsDiskUsage(buf []byte, offset flatbuffers.UOffsetT) *DiskUsage {
	n := flatbuffers.GetUOffsetT(buf[offset:])
	x := &DiskUsage{}
	x.Init(buf, n + offset)
	return x
}

func (rcv *DiskUsage) Init(buf []byte, i flatbuffers.UOffsetT) {
	rcv._tab.Bytes = buf
	rcv._tab.Pos = i
}

func (rcv *DiskUsage) Timestamp() int64 {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
	if o != 0 {
		return rcv._tab.GetInt64(o + rcv._tab.Pos)
	}
	return 0
}

func (rcv *DiskUsage) TimeDelta() int64 {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
	if o != 0 {
		return rcv._tab.GetInt64(o + rcv._tab.Pos)
	}
	return 0
}

func (rcv *DiskUsage) Device(obj *Device, j int) bool {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
	if o != 0 {
		x := rcv._tab.Vector(o)
		x += flatbuffers.UOffsetT(j) * 4
		x = rcv._tab.Indirect(x)
	if obj == nil {
		obj = new(Device)
	}
		obj.Init(rcv._tab.Bytes, x)
		return true
	}
	return false
}

func (rcv *DiskUsage) DeviceLength() int {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
	if o != 0 {
		return rcv._tab.VectorLen(o)
	}
	return 0
}

func DiskUsageStart(builder *flatbuffers.Builder) { builder.StartObject(3) }
func DiskUsageAddTimestamp(builder *flatbuffers.Builder, Timestamp int64) { builder.PrependInt64Slot(0, Timestamp, 0) }
func DiskUsageAddTimeDelta(builder *flatbuffers.Builder, TimeDelta int64) { builder.PrependInt64Slot(1, TimeDelta, 0) }
func DiskUsageAddDevice(builder *flatbuffers.Builder, Device flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(2, flatbuffers.UOffsetT(Device), 0) }
func DiskUsageStartDeviceVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(4, numElems, 4)
}
func DiskUsageEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { return builder.EndObject() }


text:
<?php
/**
 * Shop System SDK:
 * - Terms of Use can be found under:
 * https://github.com/wirecard/paymentSDK-php/blob/master/_TERMS_OF_USE
 * - License can be found under:
 * https://github.com/wirecard/paymentSDK-php/blob/master/LICENSE
 */

namespace Wirecard\PaymentSdk\Formatter;

/**
 * @package Wirecard\PaymentSdk\Formatter
 *
 * Implementation of a PropertyFormatter
 * It can be used to format Dates
 * @since 3.8.0
 */
class DateFormatter implements PropertyFormatter
{
    /** @var string FORMATTER_NAME */
    const FORMATTER_NAME = 'dateFormatter';
    /** @var string PARAM_DATE_FORMAT_KEY */
    const PARAM_DATE_FORMAT_KEY = 'dateFormat';
    /** @const string DATE_FORMAT Default date format */
    const DATE_FORMAT = 'Ymd';

    /**
     * @param \DateTime $date
     * @param array $params
     * @return mixed
     * @since 3.8.0
     */
    public function formatProperty($date, $params)
    {
        if (isset($params[self::PARAM_DATE_FORMAT_KEY])) {
            return $this->formatDateWithDateFormat($date, $params[self::PARAM_DATE_FORMAT_KEY]);
        }

        return $this->formatDateWithDateFormat($date, self::DATE_FORMAT);
    }

    /**
     * @param \DateTime $date
     * @param $format
     * @return mixed
     * @since 3.8.0
     */
    private function formatDateWithDateFormat($date, $format)
    {
        return $date->format($format);
    }
}


text:
def prep_auto(df, col_names):
    import pandas as pd
    import numpy as np

    ## Assign names to columns
    df.columns = col_names

    ## Drop unneeded columns
    drop_list = ['symboling', 'normalizedlosses', 'makeid']
    df.drop(drop_list, axis = 1, inplace = True)

    ## Remove rows with missing values
    df = df[~pd.isnull(df).any(axis=1)]

    ## Add a log transformed column for price
    df['lnprice'] = np.log(df['price'].as_matrix())

    ## Remove duplicate rows
    df.drop_duplicates(inplace = True)

    ## Create a column with new levels for the number of cylinders
    df['cylinders'] = ['four-or-less' if x in ['two', 'three', 'four'] else
                                 ('five-six' if x in ['five', 'six'] else
                                 'eight-twelve') for x in df['cylinders']]
    return df

def azureml_main(df):
    ## Define column names
    col_names = ['symboling', 'normalizedlosses', 'makeid', 'fueltype', 'aspiration', 'doors',
       'body', 'drive', 'engineloc', 'wheelbase',
       'length', 'width', 'height', 'weight', 'enginetype',
       'cylinders', 'enginesize', 'fuelsystem', 'bore', 'stroke',
       'compression', 'horsepower', 'rpm', 'citympg',
       'highwaympg', 'price', 'make']

    ## Call function to prep auto data and return
    return prep_auto(df, col_names)