text:
unless defined?(STANDARD_OBJECT_PUBLIC_INSTANCE_METHODS)
  STANDARD_OBJECT_PUBLIC_INSTANCE_METHODS = Object.public_instance_methods
end

$:.unshift File.expand_path(File.join(File.dirname(__FILE__), "..", "lib"))
$:.unshift File.expand_path(File.join(File.dirname(__FILE__)))
$:.unshift File.expand_path(File.join(File.dirname(__FILE__), 'unit'))
$:.unshift File.expand_path(File.join(File.dirname(__FILE__), 'unit', 'parameter_matchers'))
$:.unshift File.expand_path(File.join(File.dirname(__FILE__), 'acceptance'))

require 'test/unit'

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var BaseTypes = require('../../data-types')
  , util = require('util')
  , _ = require('lodash');

BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://msdn.microsoft.com/en-us/library/ms187752%28v=sql.110%29.aspx';

var STRING = function() {
  if (!(this instanceof STRING)) return new STRING();
  BaseTypes.STRING.apply(this, arguments);
};
util.inherits(STRING, BaseTypes.STRING);

STRING.prototype.toSql = function() {
  if (!this._binary) {
    return 'NVARCHAR(' + this._length + ')';
  } else{
    return 'BINARY(' + this._length + ')';
  }
};

BaseTypes.TEXT.prototype.toSql = function() {
  // TEXT is deprecated in mssql and it would normally be saved as a non-unicode string.
  // Using unicode is just future proof
  if (this._length) {
    if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8
      this.warn('MSSQL does not support TEXT with the `length` = `tiny` option. `NVARCHAR(256)` will be used instead.');
      return 'NVARCHAR(256)';
    }
    this.warn('MSSQL does not support TEXT with the `length` option. `NVARCHAR(MAX)` will be used instead.');
  }
  return 'NVARCHAR(MAX)';
};

var BOOLEAN = function() {
  if (!(this instanceof BOOLEAN)) return new BOOLEAN();
  BaseTypes.BOOLEAN.apply(this, arguments);
};
util.inherits(BOOLEAN, BaseTypes.BOOLEAN);

BOOLEAN.prototype.toSql = function() {
  return 'BIT';
};

BaseTypes.BLOB.prototype.toSql = function() {
  if (this._length) {
    if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8
      this.warn('MSSQL does not support BLOB with the `length` = `tiny` option. `VARBINARY(256)` will be used instead.');
      return 'VARBINARY(256)';
    }
    this.warn('MSSQL does not support BLOB with the `length` option. `VARBINARY(MAX)` will be used instead.');
  }
  return 'VARBINARY(MAX)';
};

var UUID = function() {
  if (!(this instanceof UUID)) return new UUID();
  BaseTypes.UUID.apply(this, arguments);
};
util.inherits(UUID, BaseTypes.UUID);

UUID.prototype.toSql = function() {
  return 'CHAR(36)';
};

var NOW = function() {
  if (!(this instanceof NOW)) return new NOW();
  BaseTypes.NOW.apply(this, arguments);
};
util.inherits(NOW, BaseTypes.NOW);

NOW.prototype.toSql = function() {
  return 'GETDATE()';
};

var DATE = function() {
  if (!(this instanceof DATE)) return new DATE();
  BaseTypes.DATE.apply(this, arguments);
};
util.inherits(DATE, BaseTypes.DATE);

DATE.prototype.toSql = function() {
  return 'DATETIME2';
};

var INTEGER = function() {
  if (!(this instanceof INTEGER)) return new INTEGER();
  BaseTypes.INTEGER.apply(this, arguments);

  // MSSQL does not support any options for integer
  if (this._length || this.options.length || this._unsigned || this._zerofill) {
    this.warn('MSSQL does not support INTEGER with options. Plain `INTEGER` will be used instead.');
    this._length = undefined;
    this.options.length = undefined;
    this._unsigned = undefined;
    this._zerofill = undefined;
  }
};
util.inherits(INTEGER, BaseTypes.INTEGER);

var BIGINT = function() {
  if (!(this instanceof BIGINT)) return new BIGINT();
  BaseTypes.BIGINT.apply(this, arguments);

  // MSSQL does not support any options for bigint
  if (this._length || this.options.length || this._unsigned || this._zerofill) {
    this.warn('MSSQL does not support BIGINT with options. Plain `BIGINT` will be used instead.');
    this._length = undefined;
    this.options.length = undefined;
    this._unsigned = undefined;
    this._zerofill = undefined;
  }
};
util.inherits(BIGINT, BaseTypes.BIGINT);

var REAL = function() {
  if (!(this instanceof REAL)) return new REAL();
  BaseTypes.REAL.apply(this, arguments);

  // MSSQL does not support any options for real
  if (this._length || this.options.length || this._unsigned || this._zerofill) {
    this.warn('MSSQL does not support REAL with options. Plain `REAL` will be used instead.');
    this._length = undefined;
    this.options.length = undefined;
    this._unsigned = undefined;
    this._zerofill = undefined;
  }
};
util.inherits(REAL, BaseTypes.REAL);

var FLOAT = function() {
  if (!(this instanceof FLOAT)) return new FLOAT();
  BaseTypes.FLOAT.apply(this, arguments);

  // MSSQL does only support lengths as option.
  // Values between 1-24 result in 7 digits precision (4 bytes storage size)
  // Values between 25-53 result in 15 digits precision (8 bytes storage size)
  // If decimals are provided remove these and print a warning
  if (this._decimals) {
    this.warn('MSSQL does not support Float with decimals. Plain `FLOAT` will be used instead.');
    this._length = undefined;
    this.options.length = undefined;
  }
  if (this._unsigned) {
    this.warn('MSSQL does not support Float unsigned. `UNSIGNED` was removed.');
    this._unsigned = undefined;
  }
  if (this._zerofill) {
    this.warn('MSSQL does not support Float zerofill. `ZEROFILL` was removed.');
    this._zerofill = undefined;
  }
};
util.inherits(FLOAT, BaseTypes.FLOAT);

BaseTypes.ENUM.prototype.toSql = function() {
  return 'VARCHAR(255)';
};

module.exports = {
  BOOLEAN: BOOLEAN,
  STRING: STRING,
  UUID: UUID,
  DATE: DATE,
  NOW: NOW,
  INTEGER: INTEGER,
  BIGINT: BIGINT,
  REAL: REAL,
  FLOAT: FLOAT
};

_.forIn(module.exports, function (DataType, key) {
  if (!DataType.key) DataType.key = key;
  if (!DataType.extend) {
    DataType.extend = function(oldType) {
      return new DataType(oldType.options);
    };
  }
});


text:
package com.exp.cemk.webservice;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import com.exp.cemk.util.ReturnJson;
import com.exp.cemk.webMethods.AndroidRegistration;
import com.exp.cemk.webMethods.DataEntry;
import com.exp.cemk.webMethods.GetExpenseData;
import com.exp.cemk.webMethods.GetHomePageData;
import com.exp.cemk.webMethods.GetIndividualExpense;
import com.exp.cemk.webMethods.GetNotificationData;
import com.exp.cemk.webMethods.GetPaymentData;
import com.exp.cemk.webMethods.GetProfileImage;
import com.exp.cemk.webMethods.GetUserAndItem;
import com.exp.cemk.webMethods.Login;

@Path("/service")
public class IhalkhataWebservice {
	@POST
	@Path("/doLogin")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson doLogin(MultivaluedMap<String, String> formParams) {
		return Login.userLogin(formParams.getFirst("param1"),
				formParams.getFirst("param2"));

	}

	@POST
	@Path("/home")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson getHomepageData(MultivaluedMap<String, String> formParams) {
		return GetHomePageData.getData(formParams.getFirst("param1"),
				formParams.getFirst("param2"));

	}

	@POST
	@Path("/payment")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson getPaymentData(MultivaluedMap<String, String> formParams) {
		return GetPaymentData.getPaymentDataTask(formParams);
	}

	@POST
	@Path("/paymentsDone")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson getPaymentsDoneData(
			MultivaluedMap<String, String> formParams) {
		return GetPaymentData.getPaymentsDoneDataTask(formParams);
	}

	@POST
	@Path("/image")
	@Produces("image/*")
	@Consumes("application/x-www-form-urlencoded")
	public Response getProfileImage(MultivaluedMap<String, String> formParams) {
		return GetProfileImage.getImage(formParams);
	}

	@POST
	@Path("/expense")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson getExpenseData(MultivaluedMap<String, String> formParams) {
		return GetExpenseData.getData(formParams);
	}

	@POST
	@Path("/individual")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson getIndividualData(
			MultivaluedMap<String, String> formParams) {
		return GetIndividualExpense.getData(formParams);
	}

	@POST
	@Path("/usersanditemdata")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson getUserAndItemsData(
			MultivaluedMap<String, String> formParams) {
		return GetUserAndItem.getUserAndItemsData(formParams);
	}

	@POST
	@Path("/enterdata")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson doDataEntry(MultivaluedMap<String, String> formParams) {
		return DataEntry.doDataEntry(formParams);
	}

	@POST
	@Path("/androidRegistration")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson doAndroidRegistration(
			MultivaluedMap<String, String> formParams) {
		return AndroidRegistration.doAndroidRegistration(formParams);
	}

	@POST
	@Path("/getNotification")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes("application/x-www-form-urlencoded")
	public ReturnJson getNotification(MultivaluedMap<String, String> formParams) {
		return GetNotificationData.getNotificationData(formParams);
	}
}


text:
#pragma once
#include <aws/frauddetector/FraudDetector_EXPORTS.h>
#include <aws/frauddetector/FraudDetectorRequest.h>
#include <aws/frauddetector/model/Rule.h>
#include <utility>

namespace Aws
{
namespace FraudDetector
{
namespace Model
{

  /**
   */
  class AWS_FRAUDDETECTOR_API DeleteRuleRequest : public FraudDetectorRequest
  {
  public:
    DeleteRuleRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeleteRule"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    inline const Rule& GetRule() const{ return m_rule; }

    inline bool RuleHasBeenSet() const { return m_ruleHasBeenSet; }

    inline void SetRule(const Rule& value) { m_ruleHasBeenSet = true; m_rule = value; }

    inline void SetRule(Rule&& value) { m_ruleHasBeenSet = true; m_rule = std::move(value); }

    inline DeleteRuleRequest& WithRule(const Rule& value) { SetRule(value); return *this;}

    inline DeleteRuleRequest& WithRule(Rule&& value) { SetRule(std::move(value)); return *this;}

  private:

    Rule m_rule;
    bool m_ruleHasBeenSet;
  };

} // namespace Model
} // namespace FraudDetector
} // namespace Aws


text:
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;

using LibrarySystem.Models;
using LibrarySystem.Models.Enumerations;

namespace LibrarySystem.Data.Migrations
{
    /// <summary>
    /// Represent a <see cref="Configuration"/> class, heir of <see cref="DbMigrationsConfiguration"/>.
    /// </summary>
    internal sealed class Configuration : DbMigrationsConfiguration<LibrarySystemDbContext>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration"/> class.
        /// </summary>
        public Configuration()
        {
            this.AutomaticMigrationsEnabled = false;
            this.AutomaticMigrationDataLossAllowed = false;
        }

        /// <summary>
        /// Runs after upgrading to the latest migration to allow seed data to be updated.
        /// </summary>
        /// <param name="context">Context to be used for updating seed data.</param>
        protected override void Seed(LibrarySystemDbContext context)
        {
            Author markSeemann = context.Authors
                .Where(a => a.LastName == "Seemann")
                .FirstOrDefault() ?? new Author { FirstName = "Mark", LastName = "Seemann", GenderType = GenderType.Male };

            Author royOsherove = context.Authors
                .Where(a => a.LastName == "Osherove")
                .FirstOrDefault() ?? new Author { FirstName = "Roy", LastName = "Osherove", GenderType = GenderType.Male };

            Author martinFowler = context.Authors
                .Where(a => a.LastName == "Fowler")
                .FirstOrDefault() ?? new Author { FirstName = "Martin", LastName = "Fowler", GenderType = GenderType.Male };

            Publisher manning = context.Publishers
                .Where(p => p.Name == "Manning")
                .SingleOrDefault() ?? new Publisher { Name = "Manning" };

            Publisher addisonWesley = context.Publishers
                .Where(p => p.Name == "Addison-Wesley")
                .SingleOrDefault() ?? new Publisher { Name = "Addison-Wesley" };

            Genre software = context.Genres
                .Where(g => g.Name == "Software")
                .SingleOrDefault() ?? new Genre { Name = "Software" };

            Book theBook = context.Books
                .Where(b => b.ISBN == "9781935182504")
                .SingleOrDefault() ?? new Book
                {
                    Title = "Dependency Injection in .NET",
                    ISBN = "9781935182504",
                    Description = @"Dependency Injection in .NET introduces DI and provides a practical guide for applying it in .NET applications.
                                    The book presents the core patterns in plain C#, so you'll fully understand how DI works. Then you'll learn to integrate DI
                                    with standard Microsoft technologies like ASP.NET MVC, and to use DI frameworks like StructureMap, Castle Windsor, and Unity.
                                    By the end of the book, you'll be comfortable applying this powerful technique in your everyday .NET development.",
                    PageCount = 584,
                    YearOfPublishing = 2011,
                    Quantity = 42,
                    Available = 42,
                    Publisher = manning,
                    Authors = new HashSet<Author>()
                    {
                        markSeemann
                    },
                    Genres = new HashSet<Genre>()
                    {
                        software
                    }
                };

            Book theArtOfUnitTesting = context.Books
                .Where(b => b.ISBN == "9781933988276")
                .SingleOrDefault() ?? new Book
                {
                    Title = "The Art of Unit Testing",
                    ISBN = "9781933988276",
                    Description = @"The Art of Unit Testing builds on top of what's already been written about this important topic. It guides you step by step
                                    from simple tests to tests that are maintainable, readable, and trustworthy. It covers advanced subjects like mocks, stubs,
                                    and frameworks such as Typemock Isolator and Rhino Mocks. And you'll learn about advanced test patterns and organization,
                                    working with legacy code and even untestable code. The book discusses tools you need when testing databases and other technologies.",
                    PageCount = 320,
                    YearOfPublishing = 2009,
                    Quantity = 37,
                    Available = 37,
                    Publisher = manning,
                    Authors = new HashSet<Author>()
                    {
                        royOsherove
                    },
                    Genres = new HashSet<Genre>()
                    {
                        software
                    }
                };

            Book patternsOfEnterpriseAppArchitecture = context.Books
                .Where(b => b.ISBN == "9780321127426")
                .SingleOrDefault() ?? new Book
                {
                    Title = "Patterns of Enterprise Application Architecture",
                    ISBN = "9780321127426",
                    Description = @"These pages are a brief overview of each of the patterns in P of EAA. They aren't intended to stand alone, but merely as a quick
                                    aide-memoire for those familiar with them, and a handy link if you want to refer to one online. In the future I may add some
                                    post-publication comments into the material here, but we'll see how that works out.",
                    PageCount = 533,
                    YearOfPublishing = 2003,
                    Quantity = 31,
                    Available = 31,
                    Publisher = addisonWesley,
                    Authors = new HashSet<Author>()
                    {
                        martinFowler
                    },
                    Genres = new HashSet<Genre>()
                    {
                        software
                    }
                };

            context.Books.AddOrUpdate(b => b.ISBN, theBook, theArtOfUnitTesting, patternsOfEnterpriseAppArchitecture);
        }
    }
}


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>01_开启ThreeJs之旅</title>
    <script src="../js/three.js"></script>
</head>
<body>
    <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        var geometry = new THREE.BoxGeometry(1, 1, 1);
        var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        var cube = new THREE.Mesh(geometry, material);
        scene.add(cube);

        camera.position.set(0, 0, 5);

        var render = function () {
            requestAnimationFrame(render);
            cube.rotation.x += 0.01;
            cube.rotation.y += 0.01;
            renderer.render(scene, camera);
        }
        render();
    </script>
</body>
</html>


text:
% showclusts() - Visualize getclusts() clusters. Opens several figures:
%                -  A figure with sorted silhouette values of each cluster
%                -  A figure showing clusters in 3-D, with brightness of
%                     each point proportional to its silhouette value
%                -  Multiple 2-D plots, each for one cluster. Background
%                     color shows interpolated silhouette value. A bright
%                     background means the component fits well in the cluster;
%                     a dark background means it belongs near equally
%                     to another cluster or to no cluster.
% Usage:
%              >>  mutual_info = mi_pairs(activities);
%              >>  clusters = getclusts(mutual_info);
%        Then
%              >>  showclusts(clusters)
%        else  >>  showclusts(clusters,compplotfunc)
% Input:
%
% clusters:    - cluster structure created by getclusts()
%
% Optional Input:
%
% compplotfunc - function call to plot a graphic represenation
%                for each component (for example, 2-D or 3-D
%                scalp maps of ICA components). See example below.
%                The function should use the component number (below, x)
%                as its first input parameter {default: Plot a circle
%                for each component with radius proportional to
%                the component's silhouette value in the cluster}.
% Example:
%
%  % Plot mutual information clusters by plotting component maps
%  %    in the 2-D MDS projection.
%  >>   plotTopo = @(x) topoplot(EEG.icawinv(:,x), EEG.chanlocs,'electrodes','off');
%  >>   showclusts(EEG.miclust,plotTopo);
%
% See also: getclusts(), eeg_miclust(), mi_pairs(), mdscale(), silhouette()
%
% Author: Nima Bigdely Shamlo, SCCN/INC/UCSD, 2006

% Copyright (C) 2006 Nima Bigdely Shamlo, SCCN/INC/UCSD, nima@sccn.ucsd.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function showclusts(miclusters,plotComponentFunction, showAdditionalFigures ,mapSizeCoeff)

if nargin < 3
    showAdditionalFigures = true;
end;

if nargin < 4
    mapSizeCoeff = 1;
end;

if ~isstruct(miclusters)
    error('miclusters input must be a getclusts() output structure');
end

t2d = miclusters.coord2d;
t3d = miclusters.coord3d;
t_manyd = miclusters.coord_manyd;
IDX=miclusters.clusterIDs;
number_of_clusters = miclusters.number_of_clusters;
components = miclusters.allcomponents;

t2d = [t2d components'];        % put component number in the third row
t2d = [t2d IDX];                % put cluster number in the fourth row
t2d = [t2d (1:size(t2d,1))'];   % put original row index number in the fifth row
t3d = [t3d (1:size(t2d,1))'];

%
% Plot silhouette
%

SilhouetteFigureHandle = figure;
[silh h] = silhouette(t_manyd,IDX);
set(gcf,'Name','Cluster Silhouette');
mapAxisSize = 0.09 * mapSizeCoeff;
silhouetteColorSaturation = 3;
silhColor3D= 0.3+((silh*2+1)/2);
silhColor3D = max(0.5,silhColor3D);
silhColor3D = min(1,silhColor3D);
if ~showAdditionalFigures
    close(SilhouetteFigureHandle);
end;

%
% Define cluster colors
%
clusterColormap = colorDeSaturate([0 0 1; 1 0 0; 0 1 0; 1 1 0;1 0 1]);
if number_of_clusters<=5
    cluster_colors=clusterColormap;
else
    cluster_colors=jet(number_of_clusters);
end;

colors = [];
for i=1:size(t2d,1)
    colors = [colors; cluster_colors(IDX(i),:)];
end;

%
%  Plot 3-D Clusters
%
figure3Dhandle = figure('Name','Clusters in 3D','NumberTitle','off');
sphereSize = max(max(t3d(:,1:3))-min(t3d(:,1:3)))/38;

hold on;
legends = '1';
for i=1:number_of_clusters
    t3d_forcluster = t3d(IDX==i,:);
    legends = char(legends,['Cluster ' num2str(i)]);

    %    micluster.cluster{i} =
    %   scatter3(t3d_forcluster(:,1),t3d_forcluster(:,2),t3d_forcluster(:,3),50,IDX(find(IDX==i),:),'filled');
    %     scatter3(t3d_forcluster(:,1),t3d_forcluster(:,2),t3d_forcluster(:,3),50,colors(find(IDX==i),:),'filled');
    %   plot3(t3d_forcluster(:,1),t3d_forcluster(:,2),t3d_forcluster(:,3),'o','MarkerSize',12,'MarkerFaceColor',[.49 1 .63]);

    for j=1:size(t3d_forcluster,1)
        patchHandle(i) =  putSpehere(t3d_forcluster(j,1),...
            t3d_forcluster(j,2),...
            t3d_forcluster(j,3),...
            colors(find(IDX==i,1),:) ...
            * silhColor3D(t3d_forcluster(j,4)),sphereSize);
    end;
%end;

%
% Scale 2-D coordinates to figure dimensions ([0 1)
%
%   t2d_for_axes = t2d(IDX==i,:);
if size(t3d_forcluster,1)>1
    p = pdist(miclusters.cluster{i}.coord2d);
    if isempty(p) || min(p)/max(p)>.05 % check if some are too close. If so,
        % use global 2-D coordinates instead
        t2d_for_axes = [miclusters.cluster{i}.coord2d ...
            miclusters.cluster{i}.components' ...
            repmat(i,size(miclusters.cluster{i}.coord2d,1))];
        t2d_for_axes(:,1) = t2d_for_axes(:,1) - mean(t2d_for_axes(:,1));
        % place their centroid at (0,0)
        t2d_for_axes(:,2) = t2d_for_axes(:,2) - mean(t2d_for_axes(:,2));
    else
        t2d_for_axes = t2d(IDX==i,:);
    end;

    if size(t2d_for_axes,1) > 1
        max_range= max((max(t2d_for_axes(:,1)) - min(t2d_for_axes(:,1))),...
            (max(t2d_for_axes(:,2)) - min(t2d_for_axes(:,2))));
        t2d_for_axes(:,1) = t2d_for_axes(:,1)/ max_range; % set the range in (0,1)
        t2d_for_axes(:,2) = t2d_for_axes(:,2)/ max_range;
        max_range= max((max(t2d_for_axes(:,1)) - min(t2d_for_axes(:,1))),...
            (max(t2d_for_axes(:,2)) - min(t2d_for_axes(:,2))));
    end;

    t2d_for_axes(:,1) = t2d_for_axes(:,1) - min(t2d_for_axes(:,1));
    % place their centroid at (0,0)
    t2d_for_axes(:,2) = t2d_for_axes(:,2) - min(t2d_for_axes(:,2));

    t2d_for_axes(:,1) = 0.5 +  ( t2d_for_axes(:,1) - mean(t2d_for_axes(:,1)));
    % center on (0.5,0.5) of the figure;
    t2d_for_axes(:,2) = 0.5 +  (t2d_for_axes(:,2) - mean(t2d_for_axes(:,2)));

    x = t2d_for_axes(:,1);
    t2d_for_axes(find(x<0.1),1) = 0.1;
    t2d_for_axes(find(x>0.9),1) = 0.9;
    y = t2d_for_axes(:,2);
    t2d_for_axes(find(y<0.1),2) = 0.1;
    t2d_for_axes(find(y>0.9),2) = 0.9;
else
    t2d_for_axes = [.5 .5 miclusters.cluster{i}.components' i i];
end;

positions =t2d_for_axes(:,1:2);
relaxedPositions = relaxCoordinates(positions, mapAxisSize);
t2d_for_axes(:,1:2) = relaxedPositions;

comp_cluster{i} =t2d_for_axes;
miclusters.cluster{i}.t2d_for_axes = comp_cluster{i};

end; %?

hold off;
axis equal;
view(-60,60);
set(gca,'projection','perspective');set(gca,'box','on');
set(gca,'xtick',[]);set(gca,'ytick',[]);set(gca,'ztick',[]);
legends(1,:) = [];

legend(patchHandle,legends);
camlight headlight;
lighting phong;
material shiny;

h = axes('position',[0.42 0.95 0.2 0.09],'Visible','off');
text(.15,.15,['Mutual Information Clusters']);

if ~showAdditionalFigures
    close(figure3Dhandle);
end;

%
% Plot 2D Clusters
%
for cluster_counter = 1:number_of_clusters

    fg = figure('Name',['Cluster ' num2str(cluster_counter)],'NumberTitle','off');
    %
    % adding interpolated silhoette background image
    %
    figureColor = [0.9300    0.9600    1.0000];
    set(gcf,'Color',figureColor);
    h = axes('position',[0 0 1 1],'Visible','off');
    [XI,YI] = meshgrid(0:0.005:1,0:0.005:1);
    if length(find(IDX==cluster_counter))>1
        try
        ZI = griddata(comp_cluster{cluster_counter}(:,1),comp_cluster{cluster_counter}(:,2),...
            silh(find(IDX==cluster_counter)),XI,YI,'v4');
        catch
            ZI = ones(size(XI,1),size(XI,2)) * silh(find(IDX==cluster_counter, 1));
        end;
    else
        ZI = ones(size(XI,1),size(XI,2)) * silh(find(IDX==cluster_counter));
    end;
    axis tight;axis ij;
    z= (ZI*silhouetteColorSaturation+1)/2;  z = max(0,z); z = min(1,z);
    im=zeros(size(z,1),size(z,2),3);
    im(:,:,1) = z*figureColor(1);im(:,:,2) = z*figureColor(2);im(:,:,3) = z*figureColor(3);
    im = flipdim(im,1);
    image([min(XI(:)),max(XI(:))],[min(YI(:)),max(YI(:))],im);  axis off;axis tight;

    for i=1:size(comp_cluster{cluster_counter},1)
        % change axis size according to silhuoette value
        silhAxisSize= (silh(comp_cluster{cluster_counter}(i,5))*.5+1)/2;
        silhAxisSize = max(0.3,silhAxisSize);
        silhAxisSize = min(1,silhAxisSize);

        % for now only, an additional parajeter should be assigned for this
        % later
        if showAdditionalFigures
            mapAxisSize = 0.09 * silhAxisSize*1.5 * mapSizeCoeff;
        end;

        rect = [comp_cluster{cluster_counter}(i,1) - mapAxisSize/2 ...
            comp_cluster{cluster_counter}(i,2) - mapAxisSize/2 mapAxisSize mapAxisSize];
        h = axes('position',rect);
        axis tight;
        silhColor= 1-((silh(comp_cluster{cluster_counter}(i,5))*silhouetteColorSaturation+1)/2);
        silhColor = max(0,silhColor); silhColor = min(1,silhColor);
        % silhColor = 1 - ...
        %             im(round((-mapAxisSize/2 + comp_cluster{cluster_counter}(i,1))*size(im,1)),...
        %             round((comp_cluster{cluster_counter}(i,2))*size(im,2)));
        if silhColor <.5
            silhColor= .3;
        else
            silhColor = 1;
        end;

        % if showHead
        %   headplot(EEG.icawinv(:,comp_cluster{cluster_counter}(i,3)),spline_file ,...
        %                'electrodes','off');
        % else
        %   tmpobj = topoplot(EEG.icawinv(:,comp_cluster{cluster_counter}(i,3)), ...
        %               EEG.chanlocs);
        % end;

        figure(fg);
        if nargin>1
            if nargin(plotComponentFunction)==1
                plotComponentFunction(comp_cluster{cluster_counter}(i,3));
            else
                plotComponentFunction(comp_cluster{cluster_counter}(i,3),cluster_counter);
            end;
            title(num2str(comp_cluster{cluster_counter}(i,3)),'color',silhColor*[1 1 1]);
            %,'BackgroundColor',(1-silhColor)*[1 1 1]
        else
            set(h,'visible','off');
            rectangle('Position',[0,0,1,1],'Curvature',[1,1],...
                'FaceColor',cluster_colors(cluster_counter,:));

            % text(.5,.4,num2str(comp_cluster{cluster_counter}(i,3)),...
            %        'FontSize',14,'color',imcomplement(cluster_colors(cluster_counter,:)),...
            %        'HorizontalAlignment','center','VerticalAlignment','middle');

            annotation('textbox',[comp_cluster{cluster_counter}(i,1) - mapAxisSize/2 ...
                comp_cluster{cluster_counter}(i,2) - mapAxisSize/2 ...
                mapAxisSize mapAxisSize],...
                'string',num2str(comp_cluster{cluster_counter}(i,3)),...
                'color',imcomplement(cluster_colors(cluster_counter,:)),...
                'LineStyle','none',...
                'HorizontalAlignment','center',...
                'VerticalAlignment','middle');
            daspect([1,1,1])
        end;

        axes(h);
        drawnow;
    end;

    h = axes('position',[0.4 0.9 0.2 0.09],'Visible','off');
    text(.15,.15,...
        ['Cluster ' num2str(cluster_counter)],...
        'BackgroundColor',cluster_colors(cluster_counter,:),...
        'color',imcomplement(cluster_colors(cluster_counter,:)));
    axcopy;
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%% Sub-functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function hs = putSpehere(x,y,z,c,sphereSize)
[Xs Ys Zs]=sphere(20);
hs = surf((Xs*sphereSize)+x, ...
    (Ys*sphereSize)+y, ...
    (Zs*sphereSize)+z);
set(hs,'EdgeColor','none', ...
    'FaceColor',c, ...
    'FaceLighting','phong', ...
    'AmbientStrength',0.4, ...
    'DiffuseStrength',0.8, ...
    'SpecularStrength',0.1, ...
    'SpecularExponent',20, ...
    'BackFaceLighting','lit');

function desatcolor = colorDeSaturate(color)
maxSaturation = .85;
hsv = rgb2hsv(color);
t = hsv(:,2);
t(t>maxSaturation) =maxSaturation;
hsv(:,2) = t;
desatcolor = hsv2rgb(hsv);

% push overlapping ICs apart
function coord = relaxCoordinates(coord, radius)
% if there is more than one point
if size(coord, 1) > 1
    counter = 1;
    while counter ==1 | (length(find((displacementLengths(:)>1e-9))>0) && counter < 5000)
        distances = squareform(pdist(coord));
        displacementLengths = 0.01 * (radius - distances) / radius;
        displacementLengths(displacementLengths<0) = 0;
        displacementLengths = displacementLengths - diag(diag(displacementLengths));

        xs = repmat(coord(:,1),1,size(coord,1));
        ys = repmat(coord(:,2),1,size(coord,1));
        xDifferences = xs - xs';
        yDifferences = ys - ys';

        xChanges = xDifferences .* displacementLengths;
        yChanges = yDifferences .* displacementLengths;

        for i=1:size(coord,1)
            coord(i,1) = coord(i,1) + sum(xChanges(i,:));
            coord(i,2) = coord(i,2) + sum(yChanges(i,:));
        end;
        counter = counter + 1;
    end;
end;


text:
import pln_inco.bioscope as bioscope
import pln_inco.bioscope.util
import os.path
import time
import sys
import yaml
import sqlite3
from xml.etree.ElementTree import *
from operator import itemgetter, attrgetter

def obtener_texto(tokens,start,end):
	#Devuelve un string con las palabras del array tokens entre start y end

	#if 'Jurkat' in [x[1] for x in tokens if (x[0]>=start and x[0]<end)]:
	#	print [x[1] for x in tokens if (x[0]>=start and x[0]<end)]
	#	print "Devuelvo:", ' '.join([x[1] for x in tokens if (x[0]>=start and x[0]<end)])+' ',"#"

	text=' '.join([x[1] for x in tokens if (x[0]>=start and x[0]<end)])
	if text:
		return text+' '
	else:
		return text

working_dir=os.path.expandvars('$BIOSCOPE')
dbname=os.path.join(working_dir,'bioscope.db')
conn= sqlite3.connect(dbname)
conn.text_factory = str
conn.row_factory=sqlite3.Row
c=conn.cursor()
c1=conn.cursor()
c2=conn.cursor()
c3=conn.cursor()
c4=conn.cursor()

c.execute('select document_id from bioscope_train group by document_id')
sentences=[]
for row in c:
	c1.execute('select sentence_id from bioscope_train  where document_id=? group by sentence_id order by sentence_id',(row['document_id'],))
	for row1 in c1:

		# Armo una lista con las palabras y sus posiciones
		c4.execute('select token_num,word from bioscope_train  where document_id=? and sentence_id=? order by token_num',(row['document_id'],row1['sentence_id']))
		tokens=c4.fetchall()
		sentence_text=obtener_texto(tokens,1,10000)
		sentences.append(sentence_text)

for s in sentences:
	print s


text:
<form method="post">{% csrf_token %}
    <hgroup>

Dodaj item

    </hgroup>
    {% if form.errors and not form.non_field_errors %}

Please correct the errors below and submit the form again.

    {% endif %}
    {{ form.non_field_errors }}
    {% for field in form %}
            {% if not field.is_hidden %}
                    <fieldset>
                            {{ field.label_tag }}
                            {% if field.help_text %}

{{ field.help_text|safe }}

                            {% endif %}
                            {{ field }}
                    </fieldset>
            {% else %}
                    {{ field }}
            {% endif %}
    {% endfor %}
    <button type="submit" value="OK">Zarejestruj się</button>
</form>


text:
//*****************************************************************************
//
//  sdhost.c
//
//  Driver for the SD Host (SDHost) Interface
//
//*****************************************************************************

//*****************************************************************************
//
//! \addtogroup Secure_Digital_Host_api
//! @{
//
//*****************************************************************************

#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_mmchs.h"
#include "inc/hw_ints.h"
#include "inc/hw_apps_config.h"
#include "interrupt.h"
#include "sdhost.h"

//*****************************************************************************
//
//! Configures SDHost module.
//!
//! \param ulBase is the base address of SDHost module.
//!
//! This function configures the SDHost module, enabling internal sub-modules.
//!
//! \return None.
//
//*****************************************************************************
void
SDHostInit(unsigned long ulBase)
{
  //
  // Assert module reset
  //
  HWREG(ulBase + MMCHS_O_SYSCONFIG) = 0x2;

  //
  // Wait for soft reset to complete
  //
  while( !(HWREG(ulBase + MMCHS_O_SYSCONFIG) & 0x1) )
  {

  }

  //
  // Assert internal reset
  //
  HWREG(ulBase + MMCHS_O_SYSCTL) |= (1 << 24);

  //
  // Wait for Reset to complete
  //
  while( (HWREG(ulBase + MMCHS_O_SYSCTL) & (0x1 << 24)) )
  {

  }

  //
  // Set capability register, 1.8 and 3.0 V
  //
  HWREG(ulBase + MMCHS_O_CAPA) = (0x7 <<24);

  //
  // Select bus voltage, 3.0 V
  //
  HWREG(ulBase + MMCHS_O_HCTL) |= 0x7 << 9;

  //
  // Power up the bus
  //
  HWREG(ulBase + MMCHS_O_HCTL) |= 1 << 8;

  //
  // Wait for power on
  //
  while( !(HWREG(ulBase + MMCHS_O_HCTL) & (1<<8)) )
  {

  }

  HWREG(ulBase + MMCHS_O_CON) |= 1 << 21;

  //
  // Un-mask all events
  //
  HWREG(ulBase + MMCHS_O_IE) = 0xFFFFFFFF;
}

//*****************************************************************************
//
//! Resets SDHost command line
//!
//! \param ulBase is the base address of SDHost module.
//!
//! This function assers a soft reset for the command line
//!
//! \return None.
//
//*****************************************************************************
void
SDHostCmdReset(unsigned long ulBase)
{
  HWREG(ulBase + MMCHS_O_SYSCTL) |= 1 << 25;
  while( (HWREG(ulBase + MMCHS_O_SYSCTL) & (1 << 25)) )
  {

  }
}

//*****************************************************************************
//
//! Sends command over SDHost interface
//!
//! \param ulBase is the base address of SDHost module.
//! \param ulCmd is the command to send.
//! \param ulArg is the argument for the command.
//!
//! This function send command to the attached card over the SDHost interface.
//!
//! The \e ulCmd parameter can be one of \b SDHOST_CMD_0 to \b SDHOST_CMD_63.
//! It can be logically ORed with one or more of the following:
//! - \b SDHOST_MULTI_BLK for multi-block transfer
//! - \b SDHOST_WR_CMD          if command is followed by write data
//! - \b SDHOST_RD_CMD          if command is followed by read data
//! - \b SDHOST_DMA_EN          if SDHost need to generate DMA request.
//! - \b SDHOST_RESP_LEN_136    if 136 bit response is expected
//! - \b SDHOST_RESP_LEN_48     if 48 bit response is expected
//! - \b SDHOST_RESP_LEN_48B    if 48 bit response with busy bit is expected
//!
//! The parameter \e ulArg is the argument for the command
//!
//! \return Returns 0 on success, -1 otherwise.
//
//*****************************************************************************
long
SDHostCmdSend(unsigned long ulBase, unsigned long ulCmd, unsigned ulArg)
{
  //
  // Set Data Timeout
  //
  HWREG(ulBase + MMCHS_O_SYSCTL) |= 0x000E0000;

  //
  // Check for cmd inhabit
  //
  if( (HWREG(ulBase + MMCHS_O_PSTATE) & 0x1))
  {
    return -1;
  }

  //
  // Set the argument
  //
  HWREG(ulBase + MMCHS_O_ARG) = ulArg;

  //
  // Send the command
  //
  HWREG(ulBase + MMCHS_O_CMD) = ulCmd;

  return 0;
}

//*****************************************************************************
//
//! Writes a data word into the SDHost write buffer.
//!
//! \param ulBase is the base address of SDHost module.
//! \param ulData is data word to be transfered.
//!
//! This function writes a single data word into the SDHost write buffer. The
//! function returns \b true if there was a space available in the buffer else
//! returns \b false.
//!
//! \return Return \b true on success, \b false otherwise.
//
//*****************************************************************************
tBoolean
SDHostDataNonBlockingWrite(unsigned long ulBase, unsigned long ulData)
{

  //
  // See if there is a space in the write buffer
  //
  if( (HWREG(ulBase + MMCHS_O_PSTATE) & (1<<10)) )
  {
    //
    // Write the data into the buffer
    //
    HWREG(ulBase + MMCHS_O_DATA) = ulData;

    //
    // Success.
    //
    return(true);
  }
  else
  {
    //
    // No free sapce, failure.
    //
    return(false);
  }
}

//*****************************************************************************
//
//! Waits to write a data word into the SDHost write buffer.
//!
//! \param ulBase is the base address of SDHost module.
//! \param ulData is data word to be transfered.
//!
//! This function writes \e ulData into the SDHost write buffer. If there is no
//! space in the write buffer this function waits until there is a space
//! available before returning.
//!
//! \return None.
//
//*****************************************************************************
void
SDHostDataWrite(unsigned long ulBase, unsigned long ulData)
{
  //
  // Wait until space is available
  //
  while( !(HWREG(ulBase + MMCHS_O_PSTATE) & (1<<10)) )
  {

  }

  //
  // Write the data
  //
  HWREG(ulBase + MMCHS_O_DATA) = ulData;
}

//*****************************************************************************
//
//! Waits for a data word from the SDHost read buffer
//!
//! \param ulBase is the base address of SDHost module.
//! \param pulData is pointer to read data variable.
//!
//! This function reads a single data word from the SDHost read buffer. If there
//! is no data available in the buffer the function will wait until a data
//! word is received before returning.
//!
//! \return None.
//
//*****************************************************************************
void
SDHostDataRead(unsigned long ulBase, unsigned long *pulData)
{
  //
  // Wait until data is available
  //
  while( !(HWREG(ulBase + MMCHS_O_PSTATE) & (1<<11)) )
  {

  }

  //
  // Read the data
  //
  *pulData = HWREG(ulBase + MMCHS_O_DATA);
}

//*****************************************************************************
//
//! Reads single data word from the SDHost read buffer
//!
//! \param ulBase is the base address of SDHost module.
//! \param pulData is pointer to read data variable.
//!
//! This function reads a data word from the SDHost read buffer. The
//! function returns \b true if there was data available in to buffer else
//! returns \b false.
//!
//! \return Return \b true on success, \b false otherwise.
//
//*****************************************************************************
tBoolean
SDHostDataNonBlockingRead(unsigned long ulBase, unsigned long *pulData)
{

  //
  // See if there is any data in the read buffer.
  //
  if( (HWREG(ulBase + MMCHS_O_PSTATE) & (1<<11)) )
  {
    //
    // Read the data word.
    //
    *pulData = HWREG(ulBase + MMCHS_O_DATA);

    //
    // Success
    //
    return(true);
  }
  else
  {
    //
    // No data available, failure.
    //
    return(false);
  }
}

//*****************************************************************************
//
//! Registers the interrupt handler for SDHost interrupt
//!
//! \param ulBase is the base address of SDHost module
//! \param pfnHandler is a pointer to the function to be called when the
//! SDHost interrupt occurs.
//!
//! This function does the actual registering of the interrupt handler.  This
//! function enables the global interrupt in the interrupt controller; specific
//! SDHost interrupts must be enabled via SDHostIntEnable(). It is the
//! interrupt handler's responsibility to clear the interrupt source.
//!
//! \sa IntRegister() for important information about registering interrupt
//! handlers.
//!
//! \return None.
//
//*****************************************************************************
void
SDHostIntRegister(unsigned long ulBase, void (*pfnHandler)(void))
{
  //
  // Register the interrupt handler.
  //
  IntRegister(INT_MMCHS, pfnHandler);

  //
  // Enable the SDHost interrupt.
  //
  IntEnable(INT_MMCHS);
}

//*****************************************************************************
//
//! Unregisters the interrupt handler for SDHost interrupt
//!
//! \param ulBase is the base address of SDHost module
//!
//! This function does the actual unregistering of the interrupt handler.  It
//! clears the handler to be called when a SDHost interrupt occurs.  This
//! function also masks off the interrupt in the interrupt controller so that
//! the interrupt handler no longer is called.
//!
//! \sa IntRegister() for important information about registering interrupt
//! handlers.
//!
//! \return None.
//
//*****************************************************************************
void
SDHostIntUnregister(unsigned long ulBase)
{
  //
  // Disable the SDHost interrupt.
  //
  IntDisable(INT_MMCHS);

  //
  // Unregister the interrupt handler.
  //
  IntUnregister(INT_MMCHS);
}

//*****************************************************************************
//
//! Enable individual interrupt source for the specified SDHost
//!
//! \param ulBase is the base address of SDHost module.
//! \param ulIntFlags is a bit mask of the interrupt sources to be enabled.
//!
//! This function enables the indicated SDHost interrupt sources.  Only the
//! sources that are enabled can be reflected to the processor interrupt;
//! disabled sources have no effect on the processor.
//!
//! The \e ulIntFlags parameter is the logical OR of any of the following:
//! - \b SDHOST_INT_CC    Command Complete interrupt
//! - \b SDHOST_INT_TC    Transfer Complete interrupt
//! - \b SDHOST_INT_BWR   Buffer Write Ready interrupt
//! - \b SDHOST_INT_BRR   Buffer Read Ready interrupt
//! - \b SDHOST_INT_ERRI  Error interrupt
//! - \b SDHOST_INT_CTO   Command Timeout error interrupt
//! - \b SDHOST_INT_CEB   Command End Bit error interrupt
//! - \b SDHOST_INT_DTO   Data Timeout error interrupt
//! - \b SDHOST_INT_DCRC  Data CRC error interrupt
//! - \b SDHOST_INT_DEB   Data End Bit error
//! - \b SDHOST_INT_CERR  Cart Status Error interrupt
//! - \b SDHOST_INT_BADA  Bad Data error interrupt
//! - \b SDHOST_INT_DMARD Read DMA done interrupt
//! - \b SDHOST_INT_DMAWR Write DMA done interrupt
//!
//!     Note that SDHOST_INT_ERRI can only be used with \sa SDHostIntStatus()
//! and is internally logical OR of all error status bits. Setting this bit
//! alone as \e ulIntFlags doesn't generates any interrupt.
//!
//! \return None.
//
//*****************************************************************************
void
SDHostIntEnable(unsigned long ulBase,unsigned long ulIntFlags)
{
  //
  // Enable DMA done interrupts
  //
  HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_MASK_CLR) =
                                                          (ulIntFlags >> 30);

  //
  // Enable the individual interrupt sources
  //
  HWREG(ulBase + MMCHS_O_ISE) |= (ulIntFlags & 0x3FFFFFFF);
}

//*****************************************************************************
//
//! Enable individual interrupt source for the specified SDHost
//!
//! \param ulBase is the base address of SDHost module.
//! \param ulIntFlags is a bit mask of the interrupt sources to be enabled.
//!
//! This function disables the indicated SDHost interrupt sources.  Only the
//! sources that are enabled can be reflected to the processor interrupt;
//! disabled sources have no effect on the processor.
//!
//! The \e ulIntFlags parameter has the same definition as the \e ulIntFlags
//! parameter to SDHostIntEnable().
//!
//! \return None.
//
//*****************************************************************************
void
SDHostIntDisable(unsigned long ulBase,unsigned long ulIntFlags)
{
  //
  // Disable DMA done interrupts
  //
  HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_MASK_SET) =
                                                          (ulIntFlags >> 30);
  //
  // Disable the individual interrupt sources
  //
  HWREG(ulBase + MMCHS_O_ISE) &= ~(ulIntFlags & 0x3FFFFFFF);
}

//*****************************************************************************
//
//! Gets the current interrupt status.
//!
//! \param ulBase is the base address of SDHost module.
//!
//! This function returns the interrupt status for the specified SDHost.
//!
//! \return Returns the current interrupt status, enumerated as a bit field of
//! values described in SDHostIntEnable().
//
//*****************************************************************************
unsigned long
SDHostIntStatus(unsigned long ulBase)
{
  unsigned long ulIntStatus;

  //
  // Get DMA done interrupt status
  //
  ulIntStatus = HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_STS_RAW);
  ulIntStatus = (ulIntStatus << 30);

  //
  // Return the status of individual interrupt sources
  //
  ulIntStatus |= (HWREG(ulBase + MMCHS_O_STAT) & 0x3FFFFFFF);

  return(ulIntStatus);
}

//*****************************************************************************
//
//! Clears the individual interrupt sources.
//!
//! \param ulBase is the base address of SDHost module.
//! \param ulIntFlags is a bit mask of the interrupt sources to be cleared.
//!
//! The specified SDHost interrupt sources are cleared, so that they no longer
//! assert.  This function must be called in the interrupt handler to keep the
//! interrupt from being recognized again immediately upon exit.
//!
//! The \e ulIntFlags parameter has the same definition as the \e ulIntFlags
//! parameter to SDHostIntEnable().
//!
//! \return None.
//
//*****************************************************************************
void
SDHostIntClear(unsigned long ulBase,unsigned long ulIntFlags)
{
  //
  // Clear DMA done interrupts
  //
  HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_ACK) =
                                                          (ulIntFlags >> 30);
  //
  // Clear the individual interrupt sources
  //
  HWREG(ulBase + MMCHS_O_STAT) = (ulIntFlags & 0x3FFFFFFF);
}

//*****************************************************************************
//
//! Sets the card status error mask.
//!
//! \param ulBase is the base address of SDHost module
//! \param ulErrMask is the bit mask of card status errors to be enabled
//!
//! This function sets the card status error mask for response type R1, R1b,
//! R5, R5b and R6 response. The parameter \e ulErrMask is the bit mask of card
//! status errors to be enabled, if the corresponding bits in the 'card status'
//! field of a respose are set then the host controller indicates a card error
//! interrupt status. Only bits referenced as type E (error) in status field in
//! the response can set a card status error.
//!
//! \return None
//
//*****************************************************************************
void
SDHostCardErrorMaskSet(unsigned long ulBase, unsigned long ulErrMask)
{
  //
  // Set the card status error mask
  //
  HWREG(ulBase + MMCHS_O_CSRE) = ulErrMask;
}

//*****************************************************************************
//
//! Gets the card status error mask.
//!
//! \param ulBase is the base address of SDHost module
//!
//! This function gets the card status error mask for response type R1, R1b,
//! R5, R5b and R6 response.
//!
//! \return Returns the current card status error.
//
//*****************************************************************************
unsigned long
SDHostCardErrorMaskGet(unsigned long ulBase)
{
  //
  // Return the card status error mask
  //
  return(HWREG(ulBase + MMCHS_O_CSRE));
}

//*****************************************************************************
//
//! Sets the SD Card clock.
//!
//! \param ulBase is the base address of SDHost module
//! \param ulSDHostClk is the rate of clock supplied to SDHost module
//! \param ulCardClk is the required SD interface clock
//!
//! This function configures the SDHost interface to supply the specified clock
//! to the connected card.
//!
//! \return None.
//
//*****************************************************************************
void
SDHostSetExpClk(unsigned long ulBase, unsigned long ulSDHostClk,
             unsigned long ulCardClk)
{
  unsigned long ulDiv;

  //
  // Disable card clock
  //
  HWREG(ulBase + MMCHS_O_SYSCTL) &= ~0x4;

  //
  // Enable internal clock
  //
  HWREG(ulBase + MMCHS_O_SYSCTL) |= 0x1;

  ulDiv = ((ulSDHostClk/ulCardClk) & 0x3FF);

  //
  // Set clock divider,
  //
  HWREG(ulBase + MMCHS_O_SYSCTL) = ((HWREG(ulBase + MMCHS_O_SYSCTL) &
                                     ~0x0000FFC0)| (ulDiv) << 6);

  //
  // Wait for clock to stablize
  //
  while( !(HWREG(ulBase + MMCHS_O_SYSCTL) & 0x2) )
  {

  }

  //
  // Enable card clock
  //
  HWREG(ulBase + MMCHS_O_SYSCTL) |= 0x4;
}

//*****************************************************************************
//
//! Get the response for the last command.
//!
//! \param ulBase is the base address of SDHost module
//! \param ulRespnse is 128-bit response.
//!
//! This function gets the response from the SD card for the last command
//! send.
//!
//! \return None.
//
//*****************************************************************************
void
SDHostRespGet(unsigned long ulBase, unsigned long ulRespnse[4])
{

  //
  // Read the responses.
  //
  ulRespnse[0] = HWREG(ulBase + MMCHS_O_RSP10);
  ulRespnse[1] = HWREG(ulBase + MMCHS_O_RSP32);
  ulRespnse[2] = HWREG(ulBase + MMCHS_O_RSP54);
  ulRespnse[3] = HWREG(ulBase + MMCHS_O_RSP76);

}

//*****************************************************************************
//
//! Set the block size for data transfer
//!
//! \param ulBase is the base address of SDHost module
//! \param ulBlkSize is the transfer block size in bytes
//!
//! This function sets the block size the data transfer.
//!
//! The parameter \e ulBlkSize is size of each data block in bytes.
//! This should be in range 0 - 2^10.
//!
//! \return None.
//
//*****************************************************************************
void
SDHostBlockSizeSet(unsigned long ulBase, unsigned short ulBlkSize)
{
  //
  // Set the block size
  //
  HWREG(ulBase + MMCHS_O_BLK) = ((HWREG(ulBase + MMCHS_O_BLK) & 0x00000FFF)|
                                  (ulBlkSize & 0xFFF));
}

//*****************************************************************************
//
//! Set the block size and count for data transfer
//!
//! \param ulBase is the base address of SDHost module
//! \param ulBlkCount is the number of blocks
//!
//! This function sets block count for the data transfer. This needs to be set
//! for each block transfer. \sa SDHostBlockSizeSet()
//!
//! \return None.
//
//*****************************************************************************
void
SDHostBlockCountSet(unsigned long ulBase, unsigned short ulBlkCount)
{
  unsigned long ulRegVal;

  //
  // Read the current value
  //
  ulRegVal = HWREG(ulBase + MMCHS_O_BLK);

  //
  // Set the number of blocks
  //
  HWREG(ulBase + MMCHS_O_BLK) = ((ulRegVal & 0x0000FFFF)|
                                  (ulBlkCount << 16));
}

//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************


text:
package org.lumongo.client.result;

import org.lumongo.cluster.message.Lumongo.AssociatedDocument;
import org.lumongo.cluster.message.Lumongo.Metadata;

import java.util.HashMap;
import java.util.Map;

public class AssociatedResult {

	private AssociatedDocument associatedDocument;

	public AssociatedResult(AssociatedDocument associatedDocument) {
		this.associatedDocument = associatedDocument;
	}

	public Map<String, String> getMeta() {
		HashMap<String, String> metadata = new HashMap<String, String>();
		for (Metadata md : associatedDocument.getMetadataList()) {
			metadata.put(md.getKey(), md.getValue());
		}
		return metadata;
	}

	public String getFilename() {
		return associatedDocument.getFilename();
	}

	public String getDocumentUniqueId() {
		return associatedDocument.getDocumentUniqueId();
	}

	public byte[] getDocumentAsBytes() {
		if (hasDocument()) {
			return associatedDocument.getDocument().toByteArray();
		}
		return null;
	}

	public String getDocumentAsUtf8() {
		if (hasDocument()) {
			String contents = associatedDocument.getDocument().toStringUtf8();
			return contents;
		}
		return null;
	}

	public boolean hasDocument() {
		return associatedDocument.hasDocument();
	}

	public boolean getCompressed() {
		return associatedDocument.getCompressed();
	}

	public long getTimestamp() {
		return associatedDocument.getTimestamp();
	}

}


text:
(function() {
  describe("Timer", function() {
    var subject;
    subject = null;
    context("starting from 0 secs", function() {
      beforeEach(function() {
        return subject = new Timer;
      });
      it("starts with value 0 secs", function() {
        return expect(subject.value()).toBe(0);
      });
      return it("displays the value as 00:00", function() {
        return expect(subject.text()).toBe('00:00');
      });
    });
    return context("starting from 10 mins", function() {
      beforeEach(function() {
        return subject = new Timer(10 * 60);
      });
      it("starts with value 600 secs", function() {
        return expect(subject.value()).toBe(600);
      });
      return it("displays the value as 10:00", function() {
        return expect(subject.text()).toBe('10:00');
      });
    });
  });
}).call(this);


text:
package com.gmail.woodyc40.commons;

import com.gmail.woodyc40.commons.collect.AbstractHashStruct;
import com.gmail.woodyc40.commons.misc.Table;
import lombok.*;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/*
A_TROLL implementation:
Retrieving word list
Reading word list
Finished reading word list
Word count: 7999
Starting hash process
Finished hashing
Mapping...
Collisions: 49.8812351543943%
Average hash time: 1612ns
Done

JAVA implementation:
Retrieving word list
Reading word list
Finished reading word list
Word count: 7999
Starting hash process
Finished hashing
Mapping...
Collisions: 71.6589573696712%
Average hash time: 1528ns
Done

MURMUR implementation:
Retrieving word list
Reading word list
Finished reading word list
Word count: 7999
Starting hash process
Finished hashing
Mapping...
Collisions: 49.36867108388549%
Average hash time: 3428ns
Done
 */
public class HashFunctionMapper {
    @Getter private final Map<HashFunctionMapper.Coords, Long> map  = new HashMap<>();
    @Getter private final Collection<String>                   list = new ArrayList<>();

    @Getter private final Collection<Long> averageTimes = new ArrayList<>();

    public static void main(String... args) throws IOException {
        HashFunctionMapper mapper = new HashFunctionMapper();
        mapper.readWords();

        System.out.println("Starting hash process");
        for (String word : mapper.getList()) {
            long start = System.nanoTime();
            long hash = mapper.hash(word);
            long nanos = System.nanoTime() - start;

            mapper.getAverageTimes().add(nanos);

            if (!mapper.getMap().containsValue(hash)) {
                mapper.getMap().put(new HashFunctionMapper.Coords(hash, 1), hash);
            } else {
                int max = 1;
                for (HashFunctionMapper.Coords coords : mapper.getMap().keySet())
                    if (mapper.getMap().get(coords).equals(hash))
                        if (coords.getY() > max)
                            max = coords.getY();

                mapper.getMap().put(new HashFunctionMapper.Coords(hash, max + 1), hash);
            }
        }
        System.out.println("Finished hashing");

        System.out.println("Mapping...");
        mapper.printResults();
        System.out.println("Done");
    }

    public void readWords() throws IOException {
        System.out.println("Retrieving word list");
        URL url = new URL("http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt");
        URLConnection connection = url.openConnection();
        @Cleanup BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        System.out.println("Reading word list");
        int i = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            i++;
            if (i == 8000)
                break;
            this.list.add(line);
        }
        System.out.println("Finished reading word list");

        System.out.println("Word count: " + this.list.size());
    }

    public void printResults() {
        int collisions = 0;
        for (HashFunctionMapper.Coords coords : this.map.keySet())
            if (coords.getY() > 1)
                collisions++;

        long total = 0L;
        for (Long t : this.averageTimes) {
            total += t;
        }

        System.out.println("Collisions: " + (double) collisions / (double) this.list.size() * 100.0 + '%');
        System.out.println("Average hash time: " + total / (long) this.averageTimes.size() + "ns");
    }

    public void map() {
        Table table = new Table();
        table.setNames("Hash", "Collisions");
        for (Long values : new HashSet<>(this.map.values())) {
            int max = 1;
            for (HashFunctionMapper.Coords coords : this.map.keySet())
                if (coords.getY() == values)
                    if (coords.getY() > max)
                        max = coords.getY();

            table.createRow().setColumn(0, String.valueOf(values)).setColumn(1, String.valueOf(max));
        }

        table.print(System.out);
    }

    public long hash(String string) {
        return (long) AbstractHashStruct.HashStrategy.A_TROLL.hash(string, this.map.size() + 1);
        //return (long) AbstractHashStruct.HashStrategy.JAVA.hash(string, this.map.size() + 1);
        //return (long) AbstractHashStruct.HashStrategy.MURMUR.hash(string, this.map.size() + 1);
    }

    @Data
    public static class Coords {
        private final long x;
        private final int  y;
    }
}


text:
package org.xins.common.ant;

import java.io.File;
import java.util.StringTokenizer;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.XSLTProcess;
import org.apache.tools.ant.types.Mapper;
import org.apache.tools.ant.util.FileNameMapper;

/**
 * Apache Ant task similar to the <xslt> task with the option that allow to never
 * overwrite the destination.
 *
 * @version $Revision: 1.4 $ $Date: 2007/09/18 11:20:46 $
 * @author Anthony Goubard
 *
 * @since XINS 2.1
 */
public class XsltPlusTask extends XSLTProcess {

   /**
    * Name of the property to store that the target should never be overwritten.
    */
   private boolean neverOverwrite = false;

   /**
    * Store the names of the files as it may change.
    */
   private String implicitIncludes;

   /**
    * Store the mapper if any.
    */
   private Mapper mapper;

   /**
    * Store the destination directory.
    */
   private File destDir;

   /**
    * Sets to never overwrite the destination.
    *
    * @param neverOverwrite
    *    true if the destination should never be overwritten,
    *    false otherwise.
    */
   public void setNeverOverwrite(boolean neverOverwrite) {
      this.neverOverwrite = neverOverwrite;
   }

   /**
    * Sets the files to include in the transformation.
    *
    * @param includes
    *    The files to tranform.
    */
   public void setIncludes(String includes) {
      this.implicitIncludes = includes;
   }

   /**
    * Sets the mapper.
    *
    * @param mapper
    *    The mapper.
    */
   public void addMapper(Mapper mapper) {
      super.addMapper(mapper);
      this.mapper = mapper;
   }

   /**
    * Sets the destination directory.
    *
    * @param destDir
    *    The destination directory.
    */
   public void setDestdir(File destDir) {
      super.setDestdir(destDir);
      this.destDir = destDir;
   }

   /**
    * Called by the project to let the task do its work.
    *
    * @throws BuildException
    *    if something goes wrong with the build.
    */
   public void execute() throws BuildException {

      if (neverOverwrite) {
         //if (mapper == null) mapper = new GlobPatternMapper(
         if (mapper == null) {
            throw new BuildException("Please specify a mapper");
         }
         FileNameMapper mapperImpl = mapper.getImplementation();
         String newIncludes = "";
         StringTokenizer stIncludes = new StringTokenizer(implicitIncludes, " ,");
         while (stIncludes.hasMoreTokens()) {
            String nextInclude = stIncludes.nextToken();
            String includeDest = mapperImpl.mapFileName(nextInclude)[0];
            File destination = new File(destDir, includeDest);
            if (!destination.exists()) {
               if (newIncludes.equals("")) {
                  newIncludes = nextInclude;
               } else {
                  newIncludes += "," + nextInclude;
               }
            }
         }
         super.setIncludes(newIncludes);
         if (newIncludes.equals("")) {
            return;
         }
      } else {
         super.setIncludes(implicitIncludes);
      }
      super.execute();
   }
}


text:
package com.pineone.icbms.so.resources.registry;

/**
 * Key-value Registry interface

 * Created by uni4love on 2010. 1. 15..
 */
public interface IKeyValueRegistry<K, V> extends IRegistry
{
	/**
	 * register service

	 *
	 * @param key
	 *            key for value
	 * @param value
	 *            value
	 */
	void addValue(K key, V value);

	/**
	 * remove key-value

	 *
	 * @param key
	 *            key: class name(ex: class name with full package name)
	 * @return removed value
	 */
	V removeValue(K key);

	/**
	 * get value

	 *
	 * @param key
	 *            key for value
	 * @return value
	 */
	V getValue(K key);
}


text:
require 'minitest/autorun'
require 'rack/test'

require 'olaf'
require 'olaf/service'

class FirstEmbeddedService < Olaf::Service
  service_name "FirstEmbeddedService"

  route_name :hello_embedded
  get "/helloembedded" do
    "Ok"
  end

  route_name :hello_stranger
  get "/hello/:stranger" do
    "Hello, #{params[:stranger]}"
  end

  route_name :post_hello
  post "/helloembedded" do
    "params: #{params.inspect}"
  end

  route_name :throw_an_error
  get "/throw-me-an-error" do
    puts "Throwing OLArgumentError"
    raise ::Olaf::OLArgumentError
  end

end

class SecondEmbeddedService < Olaf::Service
  service_name "SecondEmbeddedService"

  route_name :call_through
  get "/call_through" do
    FirstEmbeddedService.client.hello_embedded!({})
  end

  param :stranger, String, "Who to say hi to"
  route_name :call_through_arg
  get "/call_through_arg" do
    FirstEmbeddedService.client.hello_stranger!(:stranger => params[:stranger])
  end

  route_name :call_through_raiseless
  get "/call_through_raiseless" do
    val, ctx = FirstEmbeddedService.client.hello_embedded!({}, :raise => false)
    val
  end
end

# No URL - they're embedded in the same process.
Olaf::add_resource(:name => "FirstEmbeddedService",
                          :service => FirstEmbeddedService)
Olaf::add_resource(:name => "SecondEmbeddedService",
                          :service => SecondEmbeddedService)

class TestEmbeddedServiceClient < MiniTest::Unit::TestCase
  include Rack::Test::Methods

  def app
    SecondEmbeddedService.application
  end

  def test_embedded_basic
    get "/call_through"
    assert_equal ["Ok"], [last_response.body].flatten
  end

  def test_embedded_with_arg
    get "/call_through_arg", :stranger => "Bob"
    assert_equal ["Hello, Bob"], [last_response.body].flatten
  end

  def test_embedded_raiseless
    get "/call_through_raiseless"
    assert_equal ["Ok"], [last_response.body].flatten
  end

  def test_client_rethrows
    # RestClient allows specifying "params" in the headers, but we don't.
    e = assert_raises ::Olaf::Error do
      FirstEmbeddedService.client.throw_an_error!( {} )
    end

    assert_equal e.error_code, 1006
    #assert_equal e.error_code, 1006
  end
end


text:
#ifndef XEN_TASK_DECL_H
#define XEN_TASK_DECL_H

typedef void *xen_task;

struct xen_task_set;
struct xen_task_record;
struct xen_task_record_set;
struct xen_task_record_opt;
struct xen_task_record_opt_set;

#endif


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'GlobalRegion.icon_path'
        db.add_column('location_globalregion', 'icon_path',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True),
                      keep_default=False)

        # Adding field 'GlobalRegion.icon_title'
        db.add_column('location_globalregion', 'icon_title',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'GlobalRegion.icon_path'
        db.delete_column('location_globalregion', 'icon_path')

        # Deleting field 'GlobalRegion.icon_title'
        db.delete_column('location_globalregion', 'icon_title')

    models = {
        'location.country': {
            'Meta': {'ordering': "['name']", 'unique_together': "(('parent', 'slug'),)", 'object_name': 'Country'},
            'description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'gn_id': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
            'gn_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'on_delete': 'models.PROTECT', 'to': "orm['location.GlobalRegion']"}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
        },
        'location.globalregion': {
            'Meta': {'ordering': "['name']", 'object_name': 'GlobalRegion'},
            'description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'gn_id': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
            'gn_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'icon_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'icon_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
        },
        'location.locality': {
            'Meta': {'ordering': "['name']", 'unique_together': "(('parent', 'slug'),)", 'object_name': 'Locality'},
            'description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'gn_id': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
            'gn_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'on_delete': 'models.PROTECT', 'to': "orm['location.RegionDistrict']"}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
        },
        'location.place': {
            'Meta': {'ordering': "['id']", 'object_name': 'Place'},
            'australian_state': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
            'country': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'gn_id': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
            'gn_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_corrected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
            'region': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'})
        },
        'location.region': {
            'Meta': {'object_name': 'Region'},
            'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'})
        },
        'location.regiondistrict': {
            'Meta': {'ordering': "['name']", 'unique_together': "(('parent', 'slug'),)", 'object_name': 'RegionDistrict'},
            'description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'gn_id': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
            'gn_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'on_delete': 'models.PROTECT', 'to': "orm['location.StateProvince']"}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
        },
        'location.stateprovince': {
            'Meta': {'ordering': "['name']", 'unique_together': "(('parent', 'slug'),)", 'object_name': 'StateProvince'},
            'description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'gn_id': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
            'gn_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'on_delete': 'models.PROTECT', 'to': "orm['location.Country']"}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
        }
    }

    complete_apps = ['location']


text:
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;

namespace CycleSalesPublicSite.Conventions
{
    public class MyKeyConvention : Convention
    {
        public MyKeyConvention()
        {
            this.Properties()
                .Where(p => p.Name == p.DeclaringType.Name + "_Id")
                .Configure(p => p.IsKey());
        }
    }
}


text:
import del from "del"

import {task} from "../task"
import {build_dir} from "../paths"

task("clean:all", async () => {
  await del(build_dir.all)
})

task("clean:scripts", async () => {
  await del(build_dir.js)
})

task("clean:styles", async () => {
  await del(build_dir.css)
})

task("clean", ["clean:scripts", "clean:styles"])


text:
@implementation BOSwitchTableViewCell

- (void)setup {
	self.toggleSwitch = [UISwitch new];
	[self.toggleSwitch addTarget:self action:@selector(toggleSwitchValueDidChange) forControlEvents:UIControlEventValueChanged];
	[self.contentView addSubview:self.toggleSwitch];

	NSLayoutConstraint *centerYConstraint = [NSLayoutConstraint constraintWithItem:self.toggleSwitch attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.toggleSwitch.superview attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
	NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:self.toggleSwitch attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.toggleSwitch.superview attribute:NSLayoutAttributeRightMargin multiplier:1 constant:0];

	self.toggleSwitch.translatesAutoresizingMaskIntoConstraints = NO;
	[self.toggleSwitch.superview addConstraints:@[centerYConstraint, rightConstraint]];
}

- (void)updateAppearance {
	self.toggleSwitch.onTintColor = self.secondaryColor;
}

- (NSString *)footerTitle {
	if (self.onFooterTitle || self.offFooterTitle) {
		return [self.setting.value boolValue] ? self.onFooterTitle : self.offFooterTitle;
	}

	return [super footerTitle];
}

- (void)toggleSwitchValueDidChange {
	self.setting.value = @(self.toggleSwitch.on);
}

- (void)settingValueDidChange {
	[self.toggleSwitch setOn:[self.setting.value boolValue] animated:[UIView areAnimationsEnabled]];
}

@end


text:
using System;

/// <summary>
/// Attribute to set the property to
/// プロパティに設定する属性
/// </summary>
public class DataPropertyAttribute : Attribute
{
    /// <summary>
    /// Data types that are stored in the database
    /// データベースで格納しているデータ型
    /// </summary>
    public enum SQLITE_TYPE
    {
        /// <summary>
        /// PropertyType is string
        /// プロパティのタイプがstring
        /// </summary>
        TEXT,

        /// <summary>
        /// Type of property is a numeric type(int,float,double)
        /// プロパティのタイプが数値型(int,float,double)
        /// </summary>
        NUMERIC,

        /// <summary>
        /// PropertyType is bool
        /// プロパティのタイプがbool
        /// </summary>
        BOOLEAN,

        /// <summary>
        /// PropertyType is List <string>. Data to be stored is a comma ( , ) separator
        /// プロパティのタイプがList<string> 。格納されるデータがカンマ(,)区切り
        /// </summary>
        ARRAY,

        /// <summary>
        /// PropertyType is DateTime
        /// プロパティのタイプがDateTime
        /// </summary>
        DATETIME,
    }

    /// <summary>
    /// MaxLength
    /// 最大文字数
    /// </summary>
    public int MaxLength { get; set; }

    /// <summary>
    /// Data types that are stored in the database
    /// データベースで格納しているデータ型
    /// </summary>
    public SQLITE_TYPE SqliteType { get; set; }

    /// <summary>
    /// NULL permission settings (NUll = true, Not Null = false)
    /// NULL許可設定 (NUll = true, Not Null = false)
    /// </summary>
    public bool NullOk { get; set; }

    /// <summary>
    /// Primary Key Settings (PrimaryKey = true, Not PrimaryKey = false)
    /// プライマリキー設定 (PrimaryKey = true, Not PrimaryKey = false)
    /// </summary>
    public bool IsPrimaryKey { get; set; }

    /// <summary>
    /// constructor
    /// コンストラクタ
    /// </summary>
    /// <param name="maxLength"></param>
    /// <param name="sqliteType"></param>
    /// <param name="nullOk"></param>
    /// <param name="isPrimaryKey"></param>
    public DataPropertyAttribute(int maxLength, SQLITE_TYPE sqliteType, bool nullOk, bool isPrimaryKey)
    {
        this.MaxLength = maxLength;
        this.SqliteType = sqliteType;
        this.NullOk = nullOk;
        this.IsPrimaryKey = isPrimaryKey;
    }
}


text:
package com.google.cloud.hive.bigquery.connector.output.direct;

import static org.junit.jupiter.api.Assertions.assertEquals;

import com.google.cloud.bigquery.TableId;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.TaskAttemptID;
import org.junit.jupiter.api.Test;

public class DirectUtilsTest {

  @Test
  public void testGetTaskTempStreamFileNamePrefix() {
    TableId tableId = TableId.of("myproject", "mydataset", "mytable");
    String prefix = DirectUtils.getTaskTempStreamFileNamePrefix(tableId);
    assertEquals("myproject_mydataset_mytable", prefix);
  }

  @Test
  public void testGetTaskTempStreamFile() {
    Configuration conf = new Configuration();
    conf.set("hive.query.id", "query123");
    conf.set("bq.work.dir.parent.path", "/my/workdir");
    TableId tableId = TableId.of("myproject", "mydataset", "mytable");
    TaskAttemptID taskAttemptID = new TaskAttemptID();
    Path path = DirectUtils.getTaskTempStreamFile(conf, tableId, taskAttemptID);
    assertEquals(
        "/my/workdir/bq-hive-query123/myproject_mydataset_mytable_task__0000_r_000000.stream",
        path.toString());
  }
}


text:
using Amadevus.RecordGenerator;
using EOLib.Domain.Character;
using System.Collections.Generic;

namespace EOLib.Domain.Trade
{
    [Record(Features.Default | Features.EquatableEquals | Features.ObjectEquals)]
    public sealed partial class TradeOffer
    {
        public bool Agrees { get; }

        public short PlayerID { get; }

        public string PlayerName { get; }

        public IReadOnlyList<InventoryItem> Items { get; }
    }
}


text:
package sulfur.factories.exceptions;

import sulfur.factories.SPageConfigFactory;

/**
 * @author Ivan De Marino
 */
public class SPageConfigsLocationNotProvidedException extends RuntimeException {

    public SPageConfigsLocationNotProvidedException() {
        super();
    }

    @Override
    public String getMessage() {
        return String.format("NOTE: It's MANDATORY to set the System Property '%s'.\n",
                SPageConfigFactory.SYSPROP_PAGE_CONFIGS_DIR_PATH);
    }
}


text:
<?php

namespace Sendmail\Model;

use Zend\InputFilter\Factory as InputFactory;     // <-- Add this import
use Zend\InputFilter\InputFilter;                 // <-- Add this import
use Zend\InputFilter\InputFilterAwareInterface;   // <-- Add this import
use Zend\InputFilter\InputFilterInterface;        // <-- Add this import
use Zend\View\Model\ViewModel;
use Sendmail\Model\Plugin\SendMailHelper;

class Sendmail extends \Base\Model\BaseModel implements InputFilterAwareInterface{

    protected $inputFilter;

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
            throw new \Exception("Not used");
    }

    public function getInputFilter()
    {
            if (!$this->inputFilter) {
                    $inputFilter = new InputFilter();
                    $factory     = new InputFactory();

                    $inputFilter->add($factory->createInput(array(
                                    'name'     => 'name',
                                    'required' => true,
                                    'filters'  => array(
                                                    array('name' => 'StripTags'),
                                                    array('name' => 'StringTrim'),
                                    ),
                                    'validators' => array(
                                                    array(
                                                                    'name'    => 'StringLength',
                                                                    'options' => array(
                                                                                'encoding' => 'UTF-8',
                                                                                'min'      => 3,
                                                                                'max'      => 50,
                                                                    ),
                                                    ),
                                    ),
                    )));

                    $inputFilter->add($factory->createInput(array(
                                    'name'     => 'header',
                                    'required' => true,
                                    'filters'  => array(
                                                    array('name' => 'StringTrim'),
                                    ),
                                    'validators' => array(
                                                    array(
                                                                    'name'    => 'StringLength',
                                                                    'options' => array(
                                                                                'encoding' => 'UTF-8',
                                                                                'min'      => 6,
                                                                    ),
                                                    ),
                                    ),
                    )));

                    $inputFilter->add($factory->createInput(array(
                                    'name'     => 'footer',
                                    'required' => true,
                                    'filters'  => array(
                                                    array('name' => 'StringTrim'),
                                    ),
                                    'validators' => array(
                                                    array(
                                                                    'name'    => 'StringLength',
                                                                    'options' => array(
                                                                                'encoding' => 'UTF-8',
                                                                                'min'      => 6,
                                                                    ),
                                                    ),
                                    ),
                    )));

                    $inputFilter->add($factory->createInput(array(
                                    'name'     => 'message',
                                    'required' => true,
                                    'filters'  => array(
                                                    array('name' => 'StringTrim'),
                                    ),
                                    'validators' => array(
                                                    array(
                                                                    'name'    => 'StringLength',
                                                                    'options' => array(
                                                                                'encoding' => 'UTF-8',
                                                                                'min'      => 6,
                                                                    ),
                                                    ),
                                    ),
                    )));

                    $this->inputFilter = $inputFilter;
            }

            return $this->inputFilter;
    }

    protected function isValidName($object){
            if($this->checkItem(array('name'=>$object->getData()->getName()))){
                    $object->get('name')->setMessages(array('Sendmail with this name already exists'));
                    return false;
            }
            return true;
    }

    public function isValidModel($object){
            return $this->isValidName($object);
    }

    public function isValidModelOnEdit($object){
            if($this->checkItem(array(
                            'id'=>$object->getData()->getId(),
                            'name'=>$object->getData()->getName()))
            ){
                    return true;
            }
            return $this->isValidName($object);
    }

    public function getContent($id){
        $sendmailHelper = new Plugin\SendMailHelper($this->_serviceManager);
        $where = array(
            'id'=>$id,
        );
        $data = array();
        $content= $sendmailHelper->getContent($where, $data);
        return $content;
    }

    public function save($object) {

        if($object->getAction()){
            $item = $this->getItemBy(array('action' => $object->getAction()), true);
            if(isset($item)){
                $item->setAction(0);
                parent::save($item);
            }
        }
        parent::save($object);
    }

    public function update($object){
        if($object->getAction()){
            $item = $this->getItemBy(array('action' => $object->getAction()), true);
            if(isset($item)){
                if($object->getId() != $item->getId()){
                    $item->setAction(0);
                    parent::save($item);
                }
            }
        }
        parent::save($object);
    }

    public function getSendmailCollection($page = false) {

        return parent::getCollection($page);
    }

    public function sendMailOnEdit($to, array $data){
        $sendmailHelper = new SendMailHelper($this->_serviceManager);
        $where = array(
            'action'=> SendMailHelper::RESERVATION,
        );
        $emailData = array(
            'title' => 'Reservation',
            'data' => $data,
        );
        $isSend = $sendmailHelper->sendEmail(SendMailHelper::FROM,
                $to, $emailData['title'], $emailData, $where);
        return $isSend;
    }

    public function sendMailOnReservation($to, array $data, $subject, array $params = null){
        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("template/templates/reservation1.phtml");

        $html = $viewRender->render($viewModel);
        $sendmail = $this->getItemBy(array('action'=> SendMailHelper::RESERVATION), true);
        $viewModel->data = $data;
        if($params){
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        }
        if($sendmail){
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);

        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

    public function sendMail($to, array $data, $subject, $template, $action, array $params = null){
        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate($template);
        $sendmail = $this->getItemBy(array('action'=> $action), true);
        $viewModel->data = $data;
        if($params){
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        }
        if($sendmail){
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);
        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

    public function sendMailOnLead($to,$subject,$message,$cc){
        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("lead-template");
      //  $sendmail = $this->getItemBy(array('action'=> SendMailHelper::Reservation), true);

      // d($cc);
   //     d($subject);
        $viewModel->data = $data;
    /*    if($params){
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        } */
      /*  if($sendmail){
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        } */
        $html = $viewRender->render($viewModel);

       // d($html);
        $from = SendMailHelper::FROM;
    //    $to="test@mailinator.com ";
        return Plugin\SendMail::sendMail($from, $to, $subject, $message,$cc);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <EditTextPreference
        android:title="@string/perf_location_label"
        android:key="@string/perf_location_key"
        android:defaultValue="@string/perf_location_default"
        android:inputType="text"
        android:singleLine="true"/>

    <ListPreference
        android:title="@string/perf_units_label"
        android:key="@string/perf_units_key"
        android:defaultValue="@string/perf_units_metric"
        android:entryValues="@array/perf_units_values"
        android:entries="@array/perf_units_options"/>

</PreferenceScreen>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sunlighter.CanonicalTypes.Parsing
{
    public struct PosLenId : IEquatable<PosLenId>, IComparable<PosLenId>
    {
        private int pos;
        private int len;
        private long id;

        public PosLenId(int pos, int len, long id)
        {
            this.pos = pos;
            this.len = len;
            this.id = id;
        }

        public int Position => pos;
        public int Length => len;
        public long Id => id;

        public override string ToString()
        {
            return $"{{ pos = {pos}, len = {len}, id = {id} }}";
        }

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

        public override bool Equals(object obj)
        {
            if (obj is PosLenId)
            {
                PosLenId pObj = (PosLenId)obj;
                return (pos == pObj.pos) && (len == pObj.len) && (id == pObj.id);
            }
            else return false;
        }

        public bool Equals(PosLenId other)
        {
            return (pos == other.pos) && (len == other.len) && (id == other.id);
        }

        public int CompareTo(PosLenId other)
        {
            if (pos < other.pos) return -1;
            if (pos > other.pos) return 1;
            if (len < other.len) return -1;
            if (len > other.len) return 1;
            if (id < other.id) return -1;
            if (id > other.id) return 1;
            return 0;
        }

        public static bool operator == (PosLenId a, PosLenId b)
        {
            return (a.pos == b.pos) && (a.len == b.len) && (a.id == b.id);
        }

        public static bool operator < (PosLenId a, PosLenId b)
        {
            if (a.pos < b.pos) return true;
            if (a.pos > b.pos) return false;
            if (a.len < b.len) return true;
            if (a.len > b.len) return false;
            if (a.id < b.id) return true;
            return false;
        }

        public static bool operator !=(PosLenId a, PosLenId b) { return !(a == b); }

        public static bool operator >(PosLenId a, PosLenId b) { return (b < a); }

        public static bool operator >=(PosLenId a, PosLenId b) { return !(a < b); }

        public static bool operator <=(PosLenId a, PosLenId b) { return !(b < a); }
    }
}