text:
package com.cspinformatique.kubik.server.model.dilicom;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.OneToOne;

import com.cspinformatique.kubik.server.model.purchase.PurchaseOrder;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class DilicomOrder {
	public enum Status {
		PENDING, TRANSFERED, PROCESSED, SHIPPED, ERROR
	}

	private int id;
	private PurchaseOrder purchaseOrder;
	private Date creationDate;
	private Date transferDate;
	private Date processDate;
	private Date validationDate;
	private Status status;
	private String remoteFilename;
	private String remoteFileContent;
	private String errorMessage;

	public DilicomOrder() {

	}

	public DilicomOrder(int id, PurchaseOrder purchaseOrder, Date creationDate,
			Date transferDate, Date processDate, Date validationDate,
			Status status, String remoteFilename, String remoteFileContent, String errorMessage) {
		this.id = id;
		this.purchaseOrder = purchaseOrder;
		this.creationDate = creationDate;
		this.transferDate = transferDate;
		this.processDate = processDate;
		this.validationDate = validationDate;
		this.status = status;
		this.remoteFilename = remoteFilename;
		this.remoteFileContent = remoteFileContent;
		this.errorMessage = errorMessage;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public int getId() {
		return id;
	}

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

	@OneToOne
	public PurchaseOrder getPurchaseOrder() {
		return purchaseOrder;
	}

	public void setPurchaseOrder(PurchaseOrder purchaseOrder) {
		this.purchaseOrder = purchaseOrder;
	}

	public Date getCreationDate() {
		return creationDate;
	}

	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}

	public Date getTransferDate() {
		return transferDate;
	}

	public void setTransferDate(Date transferDate) {
		this.transferDate = transferDate;
	}

	public Date getProcessDate() {
		return processDate;
	}

	public void setProcessDate(Date processDate) {
		this.processDate = processDate;
	}

	public Date getValidationDate() {
		return validationDate;
	}

	public void setValidationDate(Date validationDate) {
		this.validationDate = validationDate;
	}

	@Enumerated(EnumType.STRING)
	public Status getStatus() {
		return status;
	}

	public void setStatus(Status status) {
		this.status = status;
	}

	public String getRemoteFilename() {
		return remoteFilename;
	}

	public void setRemoteFilename(String remoteFilename) {
		this.remoteFilename = remoteFilename;
	}

	@Lob
	@Column(columnDefinition = "text")
	public String getRemoteFileContent() {
		return remoteFileContent;
	}

	public void setRemoteFileContent(String remoteFileContent) {
		this.remoteFileContent = remoteFileContent;
	}

	@Lob
	@Column(columnDefinition = "text")
	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}
}


text:
package org.apache.jackrabbit.oak.security.authorization.restriction;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.jcr.PropertyType;
import javax.jcr.Value;

import org.apache.jackrabbit.oak.TestNameMapper;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.namepath.NamePathMapperImpl;
import org.apache.jackrabbit.oak.plugins.memory.PropertyStates;
import org.apache.jackrabbit.oak.plugins.name.Namespaces;
import org.apache.jackrabbit.oak.plugins.value.ValueFactoryImpl;
import org.apache.jackrabbit.oak.spi.security.authorization.AbstractAccessControlTest;
import org.apache.jackrabbit.oak.spi.security.authorization.restriction.Restriction;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * Tests for {@link RestrictionImpl}
 */
public class RestrictionImplTest extends AbstractAccessControlTest {

    private String name;
    private RestrictionImpl restriction;

    @Before
    public void before() throws Exception {
        super.before();

        registerNamespace(TestNameMapper.TEST_PREFIX, TestNameMapper.TEST_URI);
        NamePathMapper npMapper = new NamePathMapperImpl(new TestNameMapper(Namespaces.getNamespaceMap(root.getTree("/")), TestNameMapper.LOCAL_MAPPING));

        name = TestNameMapper.TEST_PREFIX + ":defName";
        PropertyState property = createProperty(name);
        restriction = new RestrictionImpl(property, true, npMapper);
    }

    private static PropertyState createProperty(String name) {
        return PropertyStates.createProperty(name, "value", Type.NAME);
    }

    @Test
    public void testGetName() {
        assertEquals(name, restriction.getName());
    }

    @Test
    public void testGetJcrName() {
        assertEquals(TestNameMapper.TEST_LOCAL_PREFIX + ":defName", restriction.getJcrName());
    }

    @Test
    public void testGetRequiredType() {
        assertEquals(PropertyType.NAME, restriction.getRequiredType());
    }

    @Test
    public void testIsMandatory() {
        assertTrue(restriction.isMandatory());
    }

    @Test
    public void testInvalid() {
        try {
            new RestrictionImpl(null, false, namePathMapper);
            fail("Creating RestrictionDefinition with null name should fail.");
        } catch (NullPointerException e) {
            // success
        }

        try {
            new RestrictionImpl(createProperty(name), false, null);
            fail("Creating RestrictionDefinition with null name/path mapper should fail.");
        } catch (NullPointerException e) {
            // success
        }
    }

        @Test
    public void testEquals() {
        // same definition
        assertEquals(restriction, new RestrictionImpl(createProperty(name), true, restriction.getNamePathMapper()));

        // same def but different namepathmapper.
        Restriction r2 = new RestrictionImpl(createProperty(name), true, namePathMapper);
        assertFalse(restriction.getJcrName().equals(r2.getJcrName()));
        assertEquals(restriction, r2);
    }

    @Test
    public void testNotEqual() {
        List<Restriction> rs = new ArrayList<Restriction>();
        // - different type
        rs.add(new RestrictionImpl(PropertyStates.createProperty(name, PropertyType.STRING), true, namePathMapper));
        // - different name
        rs.add(new RestrictionImpl(PropertyStates.createProperty("otherName", PropertyType.NAME), true, namePathMapper));
        // - different mandatory flag
        rs.add(new RestrictionImpl(createProperty(name), false, namePathMapper));
        // - different impl
        rs.add(new Restriction() {
            @Override
            public String getName() {
                return name;
            }
            @Override
            public String getJcrName() {
                throw new UnsupportedOperationException();
            }
            @Override
            public int getRequiredType() {
                return PropertyType.NAME;
            }
            @Override
            public boolean isMandatory() {
                return true;
            }
            @Override
            public PropertyState getProperty() {
                return createProperty(name);
            }

            @Nonnull
            @Override
            public Value getValue() {
                return ValueFactoryImpl.createValue(createProperty(name), namePathMapper);
            }
        });

        for (Restriction r : rs) {
            assertFalse(restriction.equals(r));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <skiboot.h>
#include <opal.h>
#include <opal-api.h>
#include <console.h>

/*
 * Various wrappers for platform functions
 */
static int64_t opal_cec_power_down(uint64_t request)
{
	printf("OPAL: Shutdown request type 0x%llx...\n", request);

	if (platform.cec_power_down)
		return platform.cec_power_down(request);

	return OPAL_SUCCESS;
}
opal_call(OPAL_CEC_POWER_DOWN, opal_cec_power_down, 1);

static int64_t opal_cec_reboot(void)
{
	printf("OPAL: Reboot request...\n");

#ifdef ENABLE_FAST_RESET
	/* Try a fast reset first */
	fast_reset();
#endif
	if (platform.cec_reboot)
		return platform.cec_reboot();

	return OPAL_SUCCESS;
}
opal_call(OPAL_CEC_REBOOT, opal_cec_reboot, 0);

static void generic_platform_init(void)
{
	force_dummy_console();
	fake_rtc_init();
}

static struct platform generic_platform = {
	.name	= "generic",
	.init	= generic_platform_init,
};

void probe_platform(void)
{
	struct platform *platforms = &__platforms_start;
	unsigned int i;

	platform = generic_platform;

	for (i = 0; &platforms[i] < &__platforms_end; i++) {
		if (platforms[i].probe && platforms[i].probe()) {
			platform = platforms[i];
			break;
		}
	}

	printf("PLAT: Detected %s platform\n", platform.name);
}


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NLog.MongoDB.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("NLog.MongoDB.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e11e8520-5d08-4899-bb73-964f57bba18d")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
require 'spec_helper'

try_spec do
  describe DataMapper::Types::IPAddress do
    before :all do
      @stored = '81.20.130.1'
      @input  = IPAddr.new(@stored)
    end

    describe '.dump' do
      describe 'when argument is an IP address given as Ruby object' do
        before :all do
          @result = DataMapper::Types::IPAddress.dump(@input, :property)
        end

        it 'dumps input into a string' do
          @result.should == @stored
        end
      end

      describe 'when argument is nil' do
        before :all do
          @result = DataMapper::Types::IPAddress.dump(nil, :property)
        end

        it 'returns nil' do
          @result.should be_nil
        end
      end

      describe 'when input is a blank string' do
        before :all do
          @result = DataMapper::Types::IPAddress.dump('', :property)
        end

        it 'retuns a blank string' do
          @result.should == ''
        end
      end
    end

    describe '.load' do
      describe 'when argument is a valid IP address as a string' do
        before :all do
          @result = DataMapper::Types::IPAddress.load(@stored, :property)
        end

        it 'returns IPAddr instance from stored value' do
          @result.should == @input
        end
      end

      describe 'when argument is nil' do
        before :all do
          @result = DataMapper::Types::IPAddress.load(nil, :property)
        end

        it 'returns nil' do
          @result.should be_nil
        end
      end

      describe 'when argument is a blank string' do
        before :all do
          @result = DataMapper::Types::IPAddress.load('', :property)
        end

        it 'returns IPAddr instance from stored value' do
          @result.should == IPAddr.new('0.0.0.0')
        end
      end

      describe 'when argument is an Array instance' do
        before :all do
          @operation = lambda { DataMapper::Types::IPAddress.load([], :property) }
        end

        it 'raises ArgumentError with a meaningful message' do
          @operation.should raise_error(ArgumentError, '+value+ must be nil or a String')
        end
      end
    end

    describe '.typecast' do
      describe 'when argument is an IpAddr object' do
        before :all do
          @result = DataMapper::Types::IPAddress.typecast(@input, :property)
        end

        it 'does not change the value' do
          @result.should == @input
        end
      end

      describe 'when argument is a valid IP address as a string' do
        before :all do
          @result = DataMapper::Types::IPAddress.typecast(@stored, :property)
        end

        it 'instantiates IPAddr instance' do
          @result.should == @input
        end
      end
    end
  end
end


text:
"use strict";
var logger = require("./utils/logger");
var authenticationMiddleware = require('./utils/authenticationMiddleware');
var noCacheMiddleware = require('./utils/noCacheMiddleware');
var express = require('express');
var path = require('path');
var expressValidator = require('express-validator');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var errorHandler = require('errorhandler');
var morgan = require('morgan');
var methodOverride = require('method-override');
var favicon = require('serve-favicon');
var routes = require('./routes');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
// override with different headers; last one takes precedence
app.use(methodOverride('X-HTTP-Method')); // Microsoft
app.use(methodOverride('X-HTTP-Method-Override')); // Google/GData
app.use(methodOverride('X-Method-Override')); // IBM
app.use(expressValidator([]));
app.disable('etag');
// add session support!
app.use(cookieParser());
app.use(expressSession({ secret: 'sauce', saveUninitialized: true, resave: true }));
app.use(function (req, res, next) {
    res.locals.query = req.query;
    next();
});
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// Uncomment this line to demo basic auth
// app.use(express.basicAuth((user, password) => user == "user2" && password == "password"));
// development only
if ('development' == app.get('env')) {
    app.use(errorHandler());
}
app.use(morgan("combined", { "stream": logger.stream }));
var DiConfig = require('./DiConfig');
var diConfig = new DiConfig(app);
diConfig.configureDependencies();
var RouteConfig = require('./RouteConfig');
var routeConfig = new RouteConfig(app);
routeConfig.registerRoutes();
app.route('/')
    .get(authenticationMiddleware, routes.index);
app.route('/logout')
    .get(routes.logout);
app.listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});
//# sourceMappingURL=app.js.map


text:
layout: post
title: Building a 100-Year software Company
date: 2013-09-26 08:05:46.000000000 -07:00
categories: []
tags:
- silicon valley
- software
status: publish
type: post
published: true
---

Some Silicon Valley software companies,  like Evernote most prominently, have declared that they want to be 100-year companies.  For Evernote, that helps their business and "elephant never forgets" strategy/moniker.  But that made me remember an adage that I heard about Netscape that was generalized into the statement:

Software companies have a 7 year lifespan, before their tools, technology or technical debt cripple them.

Do you think that is true?  The more interesting question might be - if you were to start a software company with the goal of longevity what decisions would you make differently than where you work now?


text:
require File.dirname(__FILE__) + '/spec_helper'

describe "merb_geokit" do
  it "should do nothing" do
    true.should == true
  end
end


text:
'use strict';

/**
 * Detailed errors.
 *
 */
class DefaultErrorResponseErrorDetailsItem {
  /**
   * Create a DefaultErrorResponseErrorDetailsItem.
   * @member {string} [code] Standardized string to programmatically identify
   * the error.
   * @member {string} [message] Detailed error description and debugging
   * information.
   * @member {string} [target] Detailed error description and debugging
   * information.
   */
  constructor() {
  }

  /**
   * Defines the metadata of DefaultErrorResponseErrorDetailsItem
   *
   * @returns {object} metadata of DefaultErrorResponseErrorDetailsItem
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'DefaultErrorResponse_error_detailsItem',
      type: {
        name: 'Composite',
        className: 'DefaultErrorResponseErrorDetailsItem',
        modelProperties: {
          code: {
            required: false,
            readOnly: true,
            serializedName: 'code',
            type: {
              name: 'String'
            }
          },
          message: {
            required: false,
            readOnly: true,
            serializedName: 'message',
            type: {
              name: 'String'
            }
          },
          target: {
            required: false,
            readOnly: true,
            serializedName: 'target',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = DefaultErrorResponseErrorDetailsItem;


text:
#pragma once

#include <app/ConcreteEventPath.h>
#include <jni.h>
#include <lib/core/CHIPError.h>
#include <lib/core/CHIPTLV.h>

namespace chip {

jobject DecodeEventValue(const chip::app::ConcreteEventPath & aPath, chip::TLV::TLVReader & aReader, CHIP_ERROR * aError);

} // namespace chip


text:
/*
 * Author: tdanford
 * Date: Dec 4, 2008
 */
package org.seqcode.ml.bayesnets;

import org.seqcode.gseutils.ArrayUtils;
import org.seqcode.gseutils.models.*;
import org.seqcode.ml.regression.DataFrame;

public class NaiveBayes<X extends Model> extends BN<X> {

	public NaiveBayes(DataFrame<X> data, String classField, String... attrs) {
		super(data, ArrayUtils.prepend(classField, attrs));
		for(int i = 0; i < attrs.length; i++) {
			graph.addEdge(classField, attrs[i]);
		}
		learnCPDs();
	}

}


text:
typedef void (^TableViewCellConfigureBlock)(id cell, id item);
typedef NSString* (^CellIdentifierForIndexPathItemBlock)(NSIndexPath *indexPath, id item);
typedef void (^TableViewCommitEditingBlock)(BOOL success);
typedef void (^TableViewShouldCommitEditingBlock)(id item, UITableViewCellEditingStyle editingStyle, TableViewCommitEditingBlock completion);

@protocol ALEditableModel <NSObject>

@required
- (BOOL)isEditable;

@optional
- (void)deleteObject;

@end

@interface APLArrayDataSource : NSObject <UITableViewDataSource>

@property (nonatomic, strong) NSArray *items;
@property (nonatomic, copy) TableViewShouldCommitEditingBlock shouldCommitEditingBlock;

- (id)initWithItems:(NSArray *)anItems
     cellIdentifier:(NSString *)aCellIdentifier
 configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;

- (id)initWithItems:(NSArray *)anItems
cellIdentifierBlock:(CellIdentifierForIndexPathItemBlock)aCellIdentifierBlock
 configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;

- (NSString*)cellIdentifierForIndexPath:(NSIndexPath*)indexPath;

- (id)itemAtIndexPath:(NSIndexPath *)indexPath;
- (NSArray*)itemsForSection:(NSInteger)section;
- (void)setItems:(NSArray*)items forSection:(NSInteger)section;

@end


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="Date-Revision-yyyymmdd" content="20180624" />
    <meta http-equiv="Content-Language" content="en" />
    <title>Play! 2.x Maven Plugin – Plugin Documentation</title>
    <link rel="stylesheet" href="./css/apache-maven-fluido-1.6.min.css" />
    <link rel="stylesheet" href="./css/site.css" />
    <link rel="stylesheet" href="./css/print.css" media="print" />

<link rel="stylesheet" href="./css/site.css" type="text/css" />

Play! 2.x Maven Plugin

Last Published: 2018-06-24|

Version: 1.0.0-rc3

Parent Project

Play! 2.x

Overview

Introduction

Goals

JavaDocs

Project Documentation

Project Information

Project Reports

Javadoc

Plugin Documentation

Plugin Documentation

Goals available for this plugin:

Goal
Description

play2:closure-compile
Compile JavaScript assets

play2:coffee-compile
Compile Coffee Script assets

play2:dist
Package Play! framework and Play! application as one zip achive
(standalone distribution).

play2:dist-exploded
Create exploded Play! framework and Play! application (standalone
distribution).

play2:ebean-enhance
Enhence Ebean entity classes

play2:enhance
Enhance Java classes

play2:help
Display help information on play2-maven-plugin.

Call mvn play2:help -Ddetail=true
-Dgoal=<goal-name> to display parameter details.

play2:less-compile
Compile Less assets

play2:routes-compile
Compile routes

play2:run
Run Play! server in development mode (sbt run
equivalent).

play2:start
Start Play! server in production mode (sbt start
equivalent).

play2:stop
Stop Play! server started in production mode (sbt stop
equivalent).

play2:template-compile
Compile Scala templates

System Requirements

The following specifies the minimum requirements to run this Maven plugin:

Maven
3.1.0

JDK
1.6

Memory
No minimum requirement.

Disk Space
No minimum requirement.

Usage

You should specify the version in your project's plugin configuration:

<project>
  ...
  <build>
    <!-- To define the plugin version in your parent POM -->
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>com.google.code.play2-maven-plugin</groupId>
          <artifactId>play2-maven-plugin</artifactId>
          <version>1.0.0-rc3</version>
        </plugin>
        ...
      </plugins>
    </pluginManagement>
    <!-- To use the plugin goals in your POM or parent POM -->
    <plugins>
      <plugin>
        <groupId>com.google.code.play2-maven-plugin</groupId>
        <artifactId>play2-maven-plugin</artifactId>
        <version>1.0.0-rc3</version>
      </plugin>
      ...
    </plugins>
  </build>
  ...
</project>

For more information, see "Guide to Configuring Plug-ins"

Copyright ©2013–2018.
All rights reserved.


text:
<?php
/**
 * File: File.php
 * User: zacharydubois
 * Date: 2016-01-26
 * Time: 10:53
 * Project: Research-Botnet
 */

namespace research;

class File {
    /**
     * Read File
     *
     * Reads a file from the disk.
     *
     * @param string $file
     * @return string
     * @throws Exception
     */
    public static function read($file) {
        if (!isset($file) || !is_string($file)) {
            throw new Exception("File is not set for read: " . $file);
        }

        if (!is_readable($file)) {
            throw new Exception("File cannot be read (permissions): " . $file);
        }

        $contents = file_get_contents($file);

        if (!$contents) {
            throw new Exception("Failed to read file (other): " . $file);
        }

        return $contents;
    }

    /**
     * Write
     *
     * Writes payload to disk.
     *
     * @param string $file
     * @param string $payload
     * @return true
     * @throws Exception
     */
    public static function write($file, $payload) {
        if (!isset($file) || !is_string($file)) {
            throw new Exception("File is not set for write: " . $file);
        }

        if (!is_writable($file)) {
            throw new Exception("File cannot be read (permissions): " . $file);
        }

        if (!isset($payload)) {
            throw new Exception("File payload is not set: " . $file);
        }

        if (!file_put_contents($file, $payload)) {
            throw new Exception("Failed to write file (other): " . $file);
        }

        return true;
    }
}


text:
(function() {
  var Fruit, db, load, models, mongodb, save,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  mongodb = require('./index');

  Fruit = (function(_super) {
    __extends(Fruit, _super);

    function Fruit() {
      return Fruit.__super__.constructor.apply(this, arguments);
    }

    Fruit.prototype.model = 'Fruit';

    Fruit.defaults({
      handle: '',
      name: '',
      price: 0.00,
      description: '',
      images: []
    });

    return Fruit;

  })(mongodb.Model);

  models = {
    Fruit: Fruit
  };

  db = new mongodb.Database('testdata', models);

  load = function() {
    return db.load('Fruit', {}, function(err, objs) {
      var obj;
      obj = objs[0];
      console.log(obj.handle);
      obj.handle = 'test';
      console.log(obj.handle);
      return console.log(err, obj);
    });
  };

  save = function(callback) {
    var f;
    f = new Fruit({
      name: 'Apple',
      handle: 'apple'
    }, {
      db: db
    });
    return f.save(callback);
  };

  db.setup(function() {
    return save(function() {
      console.log("saved");
      return load();
    });
  });

}).call(this);


text:
using UnityEngine;

public class EntityTemplateLoader : MonoBehaviour {

    public const string Path = "entitytemplates";
    private static string[] _entityTemplateTypes;
    private static EntityTemplatesContainer _ec;

    private void Start() {
        BodyPartLoader.LoadBodyParts();

        _ec = EntityTemplatesContainer.Load(Path);

        _entityTemplateTypes = new string[_ec.entityTemplates.Count];

        var index = 0;

        foreach (var e in _ec.entityTemplates) {
            _entityTemplateTypes[index] = e.Type;

            //GetEntityTemplate(e.type); //testing

            index++;
        }

    }

    public static string[] GetEntityTemplateTypes() {
        return _entityTemplateTypes;
    }

    public static string GetEntityTemplateTypeAt(int index) {
        return _entityTemplateTypes[index];
    }

    public static int GetEcLength() {
        return _entityTemplateTypes.Length;
    }

    public static EntityTemplate GetEntityTemplate(string entityTemplateType) {
        var index = _ec.entityTemplates.FindIndex(item => item.Type.Equals(entityTemplateType.ToLower()));
        var et = _ec.entityTemplates[index];

        /*
        Debug.Log("Entity Template Type: " + et.type);
        foreach (var p in et.parts) {
            Debug.Log("Part: " + p);
        }
        */

        return et;

    }
}


text:
define(
"dojox/editor/plugins/nls/nb/InsertEntity", //begin v1.x content
({
	insertEntity: "Sett inn symbol"
})
//end v1.x content
);


text:
package it.prisma.businesslayer.bizlib.paas.deployments;

import it.prisma.dal.entities.paas.deployments.PaaSDeployment;
import it.prisma.dal.entities.paas.deployments.PaaSDeploymentService;
import it.prisma.dal.entities.paas.deployments.PaaSDeploymentServiceInstance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.Stateless;

@Stateless
public class PaaSDeploymentManagementBean implements PaaSDeploymentManagement {

	@Override
	public Map<String, List<PaaSDeploymentServiceInstance>> groupByHost(
			PaaSDeployment paasDeployment) {
		Map<String, List<PaaSDeploymentServiceInstance>> hosts = new HashMap<String, List<PaaSDeploymentServiceInstance>>();

		// Group by hostId
		for (PaaSDeploymentService depSvc : paasDeployment
				.getPaaSDeploymentServices()) {
			for (PaaSDeploymentServiceInstance depInst : depSvc
					.getPaaSDeploymentServiceInstances()) {
				List<PaaSDeploymentServiceInstance> instances = hosts
						.get(depInst.getHostId());

				if (instances == null) {
					instances = new ArrayList<PaaSDeploymentServiceInstance>();
					hosts.put(depInst.getHostId(), instances);
				}

				instances.add(depInst);
			}
		}
		return hosts;
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Produção Digital</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/freelancer.css" rel="stylesheet">

    <link href="font-awesome-4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

Dia 21

                            Dada-Life

                            Aerosmith

                            Shakira

O primeiro passo para obter este artefacto foi analisar os requesitos pedidos no enunciado. Sabendo isso é possível criar um mapa mental comum entre os elementos do grupo, partilhando e registando palavras e frases relacionadas com tema.

Torna-se assim possível fazer os primeiros esboços do artefacto e com isso recolher o nome dos assets necessários.

Dia 22

                            Calvin Harris

                            Hardwell

                            Nightwish

Uma vez na posse do nome dos assets nicessários, é preciso partilhar o progresso individual delas através de uma aplicação como a Trello para todos os membros saberem o ponto da situação em termos de produção de material gráfico.

De forma a manter a coerência gráfica ao longo do trabalho é importante definir uma linguagem comum entre os elementos para poder definir regras em relação à estética.

About us

                            Nico Vinz

                            Hardwell

                            Gemelli DiVersi

Na eventualidade de haver incoerência gráfica deve-se voltar atrás e reforçar as regras para serem de fácil compreensão e execução. No caso de serem produzidos dois assets com o mesmo nome, devem ambos ser avaliados para poder escolher o melhor entre os dois.

Por fim é dado todo o material escolhido (até os assets repetidos) ao um elemento do grupo que vai juntar toda a informação produzida e organiza-la para a criação final do artefacto.


text:
package com.yheriatovych.reductor.processor.actioncreator;

import com.google.auto.common.MoreElements;
import com.squareup.javapoet.TypeName;
import com.yheriatovych.reductor.annotations.ActionCreator;
import com.yheriatovych.reductor.processor.Env;
import com.yheriatovych.reductor.processor.ValidationException;

import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActionCreatorElement {
    public final List<ActionCreatorAction> actions;
    private final TypeElement typeElement;
    private Map<String, ActionCreatorAction> actionMap;

    private ActionCreatorElement(List<ActionCreatorAction> actions, TypeElement typeElement) {
        this.actions = actions;
        this.typeElement = typeElement;
        actionMap = new HashMap<>();
        for (ActionCreatorAction action : actions) {
            actionMap.put(action.actionType, action);
        }
    }

    public boolean hasAction(String actionType, List<? extends VariableElement> reducerArgs) {
        ActionCreatorAction actionCreator = actionMap.get(actionType);
        if (actionCreator == null || reducerArgs.size() != actionCreator.arguments.size()) return false;
        List<? extends VariableElement> arguments = actionCreator.arguments;
        for (int i = 0; i < arguments.size(); i++) {
            //we are doing black magic with checking if TypeName are equals
            //instead of checking if two TypeMirrors are equals because TypeMirrors can be different for the same type
            //happens when code is processed with several number of processing steps
            TypeName creatorArgType = actionCreator.argumentTypes.get(i);
            TypeName reducerArgType = TypeName.get(reducerArgs.get(i).asType());
            if (!creatorArgType.equals(reducerArgType)) {
                return false;
            }
        }
        return true;
    }

    public String getPackageName(Env env) {
        return env.getPackageName(typeElement);
    }

    public String getName(Env env) {
        return env.getElements().getBinaryName(typeElement).toString();
    }

    public TypeMirror getType() {
        return typeElement.asType();
    }

    public static ActionCreatorElement parse(Element element, Env env) throws ValidationException {
        if (element.getKind() != ElementKind.INTERFACE) {
            throw new ValidationException(element, "%s annotated with @%s should be interface", element, ActionCreator.class.getSimpleName());
        }
        TypeElement typeElement = MoreElements.asType(element);

        List<ActionCreatorAction> actions = new ArrayList<>();
        for (Element methodElement : typeElement.getEnclosedElements()) {
            if (methodElement.getKind() != ElementKind.METHOD) continue;
            actions.add(ActionCreatorAction.parse(MoreElements.asExecutable(methodElement), env));
        }

        return new ActionCreatorElement(actions, typeElement);
    }
}


text:
package net.datastructures;

/**
 * Realization of a stack as an adaptation of a SinglyLinkedList.
 * All operations are performed in constant time.
 *
 * @author Michael T. Goodrich
 * @author Roberto Tamassia
 * @author Michael H. Goldwasser
 * @see SinglyLinkedList
 */
public class LinkedStack<E> implements Stack<E> {

    /**
     * The primary storage for elements of the stack
     */
    private SinglyLinkedList<E> list = new SinglyLinkedList<>();   // an empty list

    /**
     * Constructs an initially empty stack.
     */
    public LinkedStack() {
    }                   // new stack relies on the initially empty list

    /**
     * Returns the number of elements in the stack.
     *
     * @return number of elements in the stack
     */
    @Override
    public int size() {
        return list.size();
    }

    /**
     * Tests whether the stack is empty.
     *
     * @return true if the stack is empty, false otherwise
     */
    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    /**
     * Inserts an element at the top of the stack.
     *
     * @param element the element to be inserted
     */
    @Override
    public void push(E element) {
        list.addFirst(element);
    }

    /**
     * Returns, but does not remove, the element at the top of the stack.
     *
     * @return top element in the stack (or null if empty)
     */
    @Override
    public E top() {
        if (list.size() == 0) {
            throw new StackIsEmptyException("Stack is empty.");
        }
        return list.first();
    }

    /**
     * Removes and returns the top element from the stack.
     *
     * @return element removed (or null if empty)
     */
    @Override
    public E pop() throws StackIsEmptyException {
        if (list.size() == 0) {
            throw new StackIsEmptyException("Stack is empty.");
        }
        return list.removeFirst();
    }

    /**
     * Returns the 1-based position where an object is on this stack.
     * The topmost item on the stack is considered to be at distance 1.
     *
     * @return element removed (or null if empty)
     */
    @Override
    public int search(E element) {
        return list.search(element);
    }

    /**
     * Produces a string representation of the contents of the stack.
     * (ordered from top to bottom)
     * <p>
     * This exists for debugging purposes only.
     *
     * @return textual representation of the stack
     */
    public String toString() {
        return list.toString();
    }
}


text:
package config

import (
	"io"
	"io/ioutil"
	"strconv"

	"github.com/corestoreio/csfw/utils/log"
)

// PS path separator used in the database table core_config_data and in config.Manager
const PS = "/"

// ArgFunc Argument function to be used as variadic argument in ScopeKey() and ScopeKeyValue()
type ArgFunc func(*arg)

// ScopeWebsite wrapper helper function. See Scope()
func ScopeWebsite(r ScopeIDer) ArgFunc { return Scope(ScopeWebsiteID, r) }

// ScopeStore wrapper helper function. See Scope()
func ScopeStore(r ScopeIDer) ArgFunc { return Scope(ScopeStoreID, r) }

// Scope sets the scope using the ScopeGroup and a config.ScopeIDer.
// A config.ScopeIDer can contain an ID from a website or a store. Make sure
// the correct ScopeGroup has also been set. If config.ScopeIDer is nil
// the scope will fallback to default scope.
func Scope(s ScopeGroup, r ScopeIDer) ArgFunc {
	if s != ScopeDefaultID && r == nil {
		s = ScopeDefaultID
	}
	return func(a *arg) { a.s = s; a.r = r }
}

// Path option function to specify the configuration path. If one argument has been
// provided then it must be a full valid path. If more than one argument has been provided
// then the arguments will be joined together. Panics if nil arguments will be provided.
func Path(paths ...string) ArgFunc {
	var p string
	lp := len(paths)
	if lp > 0 {
		p = paths[0]
	}

	if lp == 3 {
		p = p + PS + paths[1] + PS + paths[2]
	}
	return func(a *arg) { a.p = p }
}

// NoBubble disables the fallback to the default scope when a value in the current
// scope not exists.
func NoBubble() ArgFunc { return func(a *arg) { a.nb = true } }

// Value sets the value for a scope key.
func Value(v interface{}) ArgFunc { return func(a *arg) { a.v = v } }

// ValueReader sets the value for a scope key using the io.Reader interface.
// If asserting to a io.Closer is successful then Close() will be called.
func ValueReader(r io.Reader) ArgFunc {
	if c, ok := r.(io.Closer); ok {
		defer c.Close()
	}
	data, err := ioutil.ReadAll(r)
	if err != nil {
		log.Error("Argument=ValueReader::ReadAll", "err", err)
	}
	return func(a *arg) {
		a.v = data
	}
}

// arg responsible for the correct scope key e.g.: stores/2/system/currency/installed => scope/scope_id/path
// which is used by the underlying configuration manager to fetch or store a value
type arg struct {
	p  string // p is the three level path e.g. a/b/c
	s  ScopeGroup
	r  ScopeIDer
	nb bool        // noBubble, if false value search: (store|website) -> default
	v  interface{} // value use for saving
}

// this "cache" should covers ~80% of all store setups
var int64Cache = []string{
	"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
}
var int64CacheLen = int64(len(int64Cache))

// newArg creates an argument container which requires different options depending on the use case.
func newArg(opts ...ArgFunc) *arg {
	var a = new(arg)
	for _, opt := range opts {
		if opt != nil {
			opt(a)
		}
	}
	return a
}

func (a *arg) isDefault() bool { return a.s == ScopeDefaultID || a.s == ScopeAbsentID }

func (a *arg) isBubbling() bool { return !a.nb }

func (a *arg) scopePath() string {
	// first part of the path is called scope in Magento and in CoreStore ScopeRange
	// e.g.: stores/2/system/currency/installed => scope/scope_id/path
	// e.g.: websites/1/system/currency/installed => scope/scope_id/path
	if a.p == "" {
		return ""
	}
	return a.scopeRange() + PS + a.scopeID() + PS + a.p
}

func (a *arg) scopePathDefault() string {
	// e.g.: default/0/system/currency/installed => scope/scope_id/path
	if a.p == "" {
		return ""
	}
	return ScopeRangeDefault + PS + "0" + PS + a.p
}

func (a *arg) scopeID() string {
	if a.r != nil {
		if a.r.ScopeID() <= int64CacheLen {
			return int64Cache[a.r.ScopeID()]
		}
		return strconv.FormatInt(a.r.ScopeID(), 10)
	}
	return "0"
}

func (a *arg) scopeRange() string {
	switch a.s {
	case ScopeWebsiteID:
		return ScopeRangeWebsites
	case ScopeStoreID:
		return ScopeRangeStores
	}
	return ScopeRangeDefault
}


text:
class EXPCL_PANDA_DISPLAY StandardMunger : public StateMunger {
public:
  StandardMunger(GraphicsStateGuardianBase *gsg, const RenderState *state,
                 int num_components, NumericType numeric_type,
                 Contents contents);
  virtual ~StandardMunger();

  INLINE GraphicsStateGuardian *get_gsg() const;

protected:
  virtual CPT(GeomVertexData) munge_data_impl(const GeomVertexData *data);
  virtual int compare_to_impl(const GeomMunger *other) const;
  virtual void munge_geom_impl(CPT(Geom) &geom, CPT(GeomVertexData) &data,
                               Thread *current_thread);
  virtual void premunge_geom_impl(CPT(Geom) &geom, CPT(GeomVertexData) &data);
  virtual int geom_compare_to_impl(const GeomMunger *other) const;
  virtual CPT(RenderState) munge_state_impl(const RenderState *state);

  INLINE RenderModeAttrib::Mode get_render_mode() const;

private:
  int _num_components;
  NumericType _numeric_type;
  Contents _contents;
  CPT(RenderModeAttrib) _render_mode;

  bool _munge_color;
  bool _munge_color_scale;
  bool _auto_shader;

  LColor _color;
  LVecBase4 _color_scale;

public:
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    StateMunger::init_type();
    register_type(_type_handle, "StandardMunger",
                  StateMunger::get_class_type());
  }
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}

private:
  static TypeHandle _type_handle;
};

#include "standardMunger.I"

#endif


text:
require 'rails_helper'

describe "SAML Forced Domains" do
  let(:password) { "abcdefghijklmnop" }
  let(:saml_user) do
    Fabricate(
      :user,
      email: "user@samlonly.example.com",
      password: password
    ).tap { |u| u.activate }
  end
  let(:other_user) do
    Fabricate(
      :user,
      email: "user@example.com",
      password: password
    ).tap { |u| u.activate }
  end

  before do
    SiteSetting.saml_enabled = true
    OmniAuth.config.test_mode = true
    SiteSetting.saml_target_url = "https://example.com/samltarget"
  end

  describe "username/password login" do
    it "works as normal when feature disabled" do
      post "/session.json", params: {
        login: saml_user.username, password: password
      }
      expect(response.status).to eq(200)
      expect(session[:current_user_id]).to eq(saml_user.id)
    end

    it "blocks logins for blocked domains" do
      SiteSetting.saml_forced_domains = "samlonly.example.com"
      post "/session.json", params: {
        login: saml_user.username, password: password
      }
      expect(response.status).to eq(200)
      expect(response.parsed_body["error"]).to eq(I18n.t("login.use_saml_auth"))
      expect(session[:current_user_id]).to eq(nil)
    end

    it "allows logins for other domains" do
      post "/session.json", params: {
        login: other_user.username, password: password
      }
      expect(response.status).to eq(200)
      expect(session[:current_user_id]).to eq(other_user.id)
    end
  end

  describe "email login" do
    it "works as normal when feature disabled" do
      post "/u/email-login.json", params: { login: saml_user.email }
      expect(response.status).to eq(200)
      expect_job_enqueued(job: :critical_user_email, args: {
        user_id: saml_user.id, type: 'email_login'
      })
    end

    it "blocks login for blocked domains" do
      SiteSetting.saml_forced_domains = "samlonly.example.com"
      post "/u/email-login.json", params: { login: saml_user.email }
      expect(response.status).to eq(403)
      expect_not_enqueued_with(job: :critical_user_email)
    end

    it "allows login for other domains" do
      SiteSetting.saml_forced_domains = "samlonly.example.com"
      post "/u/email-login.json", params: { login: other_user.email }
      expect(response.status).to eq(200)
      expect_job_enqueued(job: :critical_user_email, args: {
        user_id: other_user.id, type: 'email_login'
      })
    end
  end

  describe "external login" do
    let(:mock_auth) do
      OmniAuth::AuthHash.new(
        provider: 'google_oauth2',
        uid: '123545',
        info: OmniAuth::AuthHash::InfoHash.new(
          email: saml_user.email,
        ),
        extra: { raw_info: { email_verified: true } }
      )
    end

    before do
      SiteSetting.enable_google_oauth2_logins = true
      OmniAuth.config.mock_auth[:google_oauth2] = mock_auth
      OmniAuth.config.mock_auth[:saml] = mock_auth
    end

    it "works as normal when feature disabled" do
      get "/auth/google_oauth2/callback"
      expect(response.status).to eq(302)
      expect(session[:current_user_id]).to eq(saml_user.id)
    end

    it "blocks login for blocked domains" do
      SiteSetting.saml_forced_domains = "samlonly.example.com"
      get "/auth/google_oauth2/callback"
      expect(response.status).to eq(200)
      expect(response.body).to include(I18n.t("login.use_saml_auth"))
      expect(session[:current_user_id]).to eq(nil)
    end

    it "allows SAML login for blocked domains" do
      SiteSetting.saml_forced_domains = "samlonly.example.com"
      get "/auth/saml/callback"
      expect(response.status).to eq(302)
      expect(session[:current_user_id]).to eq(saml_user.id)
    end

    it "allows login for other domains" do
      SiteSetting.saml_forced_domains = "samlonly.example.com"
      mock_auth.info.email = other_user.email
      get "/auth/google_oauth2/callback"
      expect(response.status).to eq(302)
      expect(session[:current_user_id]).to eq(other_user.id)
    end
  end
end


text:
// Copyright 1998-2013 Epic Games, Inc. All Rights Reserved.

#pragma once
//#include "RPG.h"
#include "../../RPGSystem/Components/RPGAttributeComponent.h"
#include "RPGAttributeBaseComponent.generated.h"
/*
	In derived class we declare all needed attributes.
	It would be good idea to group them into Structs later.
	It could also be done as seprate object, although this approach is less blueprint friendly.
*/
UENUM()
enum EAttributeNames
{
	Health,
	Energy,
	Stamina
};
UCLASS(meta = (BlueprintSpawnableComponent), hidecategories = (Object, LOD, Lighting, Transform, Sockets, TextureStreaming))
class URPGAttributeBaseComponent : public URPGAttributeComponent
{
	GENERATED_UCLASS_BODY()

	virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) OVERRIDE;
	virtual void InitializeComponent() OVERRIDE;
	virtual void OnRegister() OVERRIDE;
	virtual void PostInitProperties() OVERRIDE;
protected:

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float Health;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Derived Attributes")
		float MaxHealth;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float HealthBase;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float HealthPerAttribute;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float Energy;
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float MaxEnergy;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float EnergyBase;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float EnergyPerAttribute;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float Stamina;
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float MaxStamina;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float StaminaBase;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float StaminaPerAttribute;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Base Attributes")
		float Constitution;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Base Attributes")
		float ConstitutionMod;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Base Attributes")
		float Strenght;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Base Attributes")
		float StrenghtMod;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Base Attributes")
		float Thoughness;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Base Attributes")
		float ThougnessMod;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Base Attributes")
		float Endurance;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Base Attributes")
		float EnduranceMod;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Base Attributes")
		float Intelligence;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Base Attributes")
		float IntelligenceMod;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Base Attributes")
		float WillPower;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Base Attributes")
		float WillPowerMod;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Base Attributes")
		float Magic;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Base Attributes")
		float MagicMod;

	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Derived Attributes")
		float SpellCritChance;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Derived Attributes")
		float SpellCritMultiply;

	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float CritChance;
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Derived Attributes")
		float CritMultiply;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Health Regeneration")
		bool CanRegenerateHealth;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Health Regeneration")
		float HealthRegenInterval;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Health Regeneration")
		float HealthRegenValue;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Health Regeneration")
		bool CanRegenerateEnergy;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Health Regeneration")
		float EnergyRegenInterval;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Health Regeneration")
		float EnergyRegenValue;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Health Regeneration")
		bool CanRegenerateStamina;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Health Regeneration")
		float StaminaRegenInterval;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Health Regeneration")
		float StaminaRegenValue;

	UPROPERTY(BlueprintReadOnly, Category = "Attributes|Weight")
		float EquipmentWeight;

	float SpellCastingSpeed;
	float SpellBaseCost;
	float AbilityWeightCostMod;

private:
	float currentHealthRegenInterval;
	float currentEnergyRegenInterval;
	float currentStaminaRegenInterval;
	float value;
public:

	FORCEINLINE float GetHealth() { return Health; };
	FORCEINLINE void SetHealth(float value) { Health = value; };
	FORCEINLINE void SubtractHealth(float value) { Health -= value; };
	FORCEINLINE float GetMaxHealth() { return MaxHealth; };
	FORCEINLINE void SetMaxHealth() { MaxHealth = HealthBase + (Constitution * HealthPerAttribute); };

	FORCEINLINE float GetEnergy() { return Energy; };
	FORCEINLINE void SetEnergy(float value) { Energy = value; };
	FORCEINLINE void SubtractEnergy(float value) { Energy -= value; };
	FORCEINLINE float GetMaxEnergy() { return MaxEnergy; };
	FORCEINLINE void SetMaxEnergy() { MaxEnergy = EnergyBase + (IntelligenceMod * EnergyPerAttribute); };

	FORCEINLINE float GetStamina() { return Stamina; };
	FORCEINLINE void SubtractStamina(float value) { Stamina -= value; };
	FORCEINLINE float GetMaxStamina() { return MaxStamina; };
	FORCEINLINE void SetMaxStamina() { MaxStamina = StaminaBase + (EnduranceMod * StaminaPerAttribute); };

	FORCEINLINE float GetConstitution() { return Constitution; };
	FORCEINLINE void SetConstitution(float value) { Constitution = value; };
	FORCEINLINE void SubtractConstitution(float value) { Constitution -= value; };
	FORCEINLINE void AddConstitution(float value) { Constitution += value; };
	FORCEINLINE void SetConsitutionMod() { ConstitutionMod = (Constitution - 10) / 2; };
	FORCEINLINE float GetConsitutionMod() { return ConstitutionMod; };

	FORCEINLINE float GetIntelligence() { return Intelligence; };
	FORCEINLINE void SetIntelligenceMod(){ IntelligenceMod = (Intelligence - 10) / 2; };
	FORCEINLINE float GetIntelligenceMod(){ return IntelligenceMod; };

	FORCEINLINE void SetEnduranceMod(){ EnduranceMod = (Endurance - 10) / 2; };
	FORCEINLINE float GetEnduranceMod(){ return EnduranceMod; };

	FORCEINLINE bool SpellCritted() {
		float rngNum = FMath::FRandRange(1, 100);
		/*
		*/
		if (SpellCritChance >= rngNum)
			return true;
		return false;
	}
	//this is dumb implementation we need to account for other attributes like SpellCritChance as well ;)
	FORCEINLINE void SetSpellCritChance() { SpellCritChance = IntelligenceMod * 2; };
};

/*
this is pseudocode for calculating spellDamage;
DamageType_Spell(AttributeComponent* attribute, Blueprint)
{
	//order in which calculations are made is crucial!

	int32 finalDamage = Blueprint * attribute->SpellDamage;
	if(rand() < attribute->CritChange)
	{
		finalDamage *= CritMultiply;
	}

	//SpellProtection:
	finalDamage = finalDamage - (finalDamage * SpellProtection(0-1));

	//armorProtection
	finalDamage = finalDamage - armor;

	attribute->Health -= finalDamage;
}
*/


text:
package com.networknt.sanitizer.enconding;

public class EncodingStrategy {

    public static Encoding of(String value) {
        if (EncoderRegistry.hasEncodingsRegistered()) {
            if (EncoderRegistry.getEncoding().getId().equals(value)) {
                return EncoderRegistry.getEncoding();
            }
        }

        if (value == null) {
            return new DefaultEncoding();
        }
        switch (value) {
            case "default":
                return new DefaultEncoding();
            default:
                throw new IllegalStateException(String.format("Encoding unknown: %s", value));
        }
    }
}


text:
@interface ASDPlaybackManager ()
{
    SPPlaybackManager *spPlaybackManager;
    SPPlaylist *currentPlaylist;
    NSMutableArray *playlistTrackQueue;
    int playlistTrackQueueIndex;
}

@property (readwrite, strong, nonatomic) SPTrack *currentTrack;
@property (readwrite, assign, nonatomic) NSTimeInterval trackPosition;
@property (readwrite, assign, nonatomic) BOOL isPlaying;

@end

@implementation ASDPlaybackManager

- (id)init
{
    self = [super init];
    if (self)
    {
        self.isPlaying = NO;

        // initialize spPlaybackManager
        spPlaybackManager = [[SPPlaybackManager alloc] initWithPlaybackSession:[SPSession sharedSession]];

        [self addObserver:self forKeyPath:@"spPlaybackManager.trackPosition" options:0 context:nil];
        [self addObserver:self forKeyPath:@"spPlaybackManager.currentTrack" options:0 context:nil];
        [self addObserver:self forKeyPath:@"spPlaybackManager.isPlaying" options:0 context:nil];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"spPlaybackManager.trackPosition"]) {
        self.trackPosition = spPlaybackManager.trackPosition;
    }
    else if ([keyPath isEqualToString:@"spPlaybackManager.currentTrack"]) {
        // current track has ended... play the next track
        if (spPlaybackManager.currentTrack == nil) {
            [self nextTrack];
        }
    }
    else if ([keyPath isEqualToString:@"spPlaybackManager.isPlaying"]) {
        self.isPlaying = [spPlaybackManager isPlaying];
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)playTrack:(NSURL *)trackUrl {
    [[SPSession sharedSession] trackForURL:trackUrl callback:^(SPTrack *track) {
        if (track != nil) {
            [SPAsyncLoading waitUntilLoaded:track timeout:kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedItems, NSArray *notLoadedItems) {
                [spPlaybackManager playTrack:track callback:^(NSError *error) {
                    if (error) {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cannot Play Track" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

                        [alert show];
                    }
                    else {
                        self.currentTrack = track;

                        // set the "now playing" info if that feature is available
                        Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
                        if (playingInfoCenter) {
                            NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
                            [songInfo setObject:track.name forKey:MPMediaItemPropertyTitle];
                            [songInfo setObject:track.album.name forKey:MPMediaItemPropertyAlbumTitle];
                            [songInfo setObject:[NSNumber numberWithDouble:track.duration] forKey:MPMediaItemPropertyPlaybackDuration];
                            [songInfo setObject:[NSNumber numberWithDouble:spPlaybackManager.trackPosition] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
                            [songInfo setObject:[NSNumber numberWithDouble:1.0] forKey:MPNowPlayingInfoPropertyPlaybackRate];
                            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
                        }
                    }
                }];
            }];
        }
    }];
}

- (void)updateTrackPosition:(NSTimeInterval) position {
    [spPlaybackManager seekToTrackPosition:position];
}

- (void)playPlaylist:(SPPlaylist *)playlist {
    [SPAsyncLoading waitUntilLoaded:playlist timeout:kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedItems, NSArray *notLoadedItems) {
        currentPlaylist = playlist;
        playlistTrackQueue = [NSMutableArray arrayWithArray:[playlist items]];
        [playlistTrackQueue shuffle];
        playlistTrackQueueIndex = 0;
        SPPlaylistItem *item = [playlistTrackQueue objectAtIndex:0];
        [self playTrack:[item itemURL]];
    }];
}

- (void)nextTrack {
    if (currentPlaylist != nil && playlistTrackQueue != nil
        && playlistTrackQueueIndex < [playlistTrackQueue count]) {
        playlistTrackQueueIndex++;
        SPPlaylistItem *item = [playlistTrackQueue objectAtIndex:playlistTrackQueueIndex];
        [self playTrack:[item itemURL]];
    }
}

- (void)prevTrack {
    if (currentPlaylist != nil && playlistTrackQueue != nil
        && playlistTrackQueueIndex > 0 && [playlistTrackQueue count] > 0) {
        playlistTrackQueueIndex--;
        SPPlaylistItem *item = [playlistTrackQueue objectAtIndex:playlistTrackQueueIndex];
        [self playTrack:[item itemURL]];
    }
}

- (void)pausePlayback {
    [spPlaybackManager setIsPlaying:NO];
}

- (void)resumePlayback {
    [spPlaybackManager setIsPlaying:YES];
}

@end


text:
goog.addDependency('../../../resources/main.js', ['charpicker.Main'], [
    'goog.i18n.CharPickerData',
    'goog.i18n.uChar.LocalNameFetcher',
    'goog.ui.CharPicker'], false);


text:
using System;
using LanguageExt.TypeClasses;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

namespace LanguageExt.ClassInstances
{
    public struct TDecimal : Ord<decimal>, Floating<decimal>
    {
        public static readonly TDecimal Inst = default(TDecimal);

        ///
        /// Equality test
        ///
        /// <param name="x">Left hand side of the equality operation</param>
        /// <param name="y">Right hand side of the equality operation</param>
        /// <returns>True if parameters are equal</returns>
        [Pure]
        public bool Equals(decimal x, decimal y) => x == y;

        ///
        /// Compare two values
        ///
        /// <param name="x">Left hand side of the compare operation</param>
        /// <param name="y">Right hand side of the compare operation</param>
        /// <returns>
        /// if x greater than y : 1
        ///
        /// if x less than y    : -1
        ///
        /// if x equals y       : 0
        /// </returns>
        [Pure]
        public int Compare(decimal x, decimal y) =>
            x.CompareTo(y);

        ///
        /// Find the sum of two values
        ///
        /// <param name="x">left hand side of the addition operation</param>
        /// <param name="y">right hand side of the addition operation</param>
        /// <returns>The sum of x and y</returns>
        [Pure]
        public decimal Plus(decimal x, decimal y) => x + y;

        ///
        /// Find the difference between two values
        ///
        /// <param name="x">left hand side of the subtraction operation</param>
        /// <param name="y">right hand side of the subtraction operation</param>
        /// <returns>The difference between x and y</returns>
        [Pure]
        public decimal Subtract(decimal x, decimal y) => x - y;

        ///
        /// Find the product of two values
        ///
        /// <param name="x">left hand side of the product operation</param>
        /// <param name="y">right hand side of the product operation</param>
        /// <returns>The product of x and y</returns>
        [Pure]
        public decimal Product(decimal x, decimal y) => x * y;

        ///
        /// Divide two numbers
        ///
        /// <param name="x">left hand side of the division operation</param>
        /// <param name="y">right hand side of the division operation</param>
        /// <returns>x / y</returns>
        [Pure]
        public decimal Divide(decimal x, decimal y) =>
            x / y;

        ///
        /// Find the absolute value of a number
        ///
        /// <param name="x">The value to find the absolute value of</param>
        /// <returns>The non-negative absolute value of x</returns>
        [Pure]
        public decimal Abs(decimal x) => Math.Abs(x);

        ///
        /// Find the sign of x
        ///
        /// <param name="x">The value to find the sign of</param>
        /// <returns>-1, 0, or +1</returns>
        [Pure]
        public decimal Signum(decimal x) => Math.Sign(x);

        ///
        /// Generate a numeric value from an integer
        ///
        /// <param name="x">The integer to use</param>
        /// <returns>The equivalent of x in the Num</returns>
        [Pure]
        public decimal FromInteger(int x) => (decimal)x;

        ///
        /// Generate a numeric value from a decimal
        ///
        /// <param name="x">The decimal to use</param>
        /// <returns>The equivalent of x in the Num</returns>
        [Pure]
        public decimal FromDecimal(decimal x) => (decimal)x;

        ///
        /// Generate a numeric value from a float
        ///
        /// <param name="x">The float to use</param>
        /// <returns>The equivalent of x in the Num</returns>
        [Pure]
        public decimal FromFloat(float x) => (decimal)x;

        ///
        /// Generate a numeric value from a double
        ///
        /// <param name="x">The double to use</param>
        /// <returns>The equivalent of x in the Num</returns>
        [Pure]
        public decimal FromDouble(double x) => (decimal)x;

        ///
        /// Generates a fractional value from an integer ratio.
        ///
        /// <param name="x">The ratio to convert</param>
        /// <returns>The equivalent of x in the implementing type.</returns>
        [Pure]
        public decimal FromRational(Ratio<int> x) => x.Numerator / x.Denominator;

        ///
        /// Returns an approximation of pi.
        ///
        /// <returns>A reasonable approximation of pi in this type</returns>
        [Pure]
        public decimal Pi() => (decimal)Math.PI;

        ///
        /// The exponential function.
        ///
        /// <param name="x">The value for which we are calculating the exponential</param>
        /// <returns>The value of <c>e^x</c></returns>
        [Pure]
        public decimal Exp(decimal x) => (decimal)Math.Exp((double)x);

        ///
        /// Calculates the square root of a value.
        ///
        /// <param name="x">The value for which we are calculating the square root.</param>
        /// <returns>The value of <c>sqrt(x)</c>.</returns>
        [Pure]
        public decimal Sqrt(decimal x) => (decimal)Math.Sqrt((double)x);

        ///
        /// Calculates the natural logarithm of a value.
        ///
        /// <param name="x">
        /// The value for which we are calculating the natural logarithm.
        /// </param>
        /// <returns>The value of <c>ln(x)</c>.</returns>
        [Pure]
        public decimal Log(decimal x) => (decimal)Math.Log((double)x);

        /// Raises x to the power y
        ///
        /// <param name="x">The base to be raised to y</param>
        /// <param name="y">The exponent to which we are raising x</param>
        /// <returns>The value of <c>x^y</c>.</returns>
        [Pure]
        public decimal Pow(decimal x, decimal y) => (decimal)Math.Pow((double)x, (double)y);

        ///
        /// Calculates the logarithm of a value with respect to an arbitrary base.
        ///
        /// <param name="x">The base to use for the logarithm of t</param>
        /// <param name="y">The value for which we are calculating the logarithm.</param>
        /// <returns>The value of <c>log x (y)</c>.</returns>
        [Pure]
        public decimal LogBase(decimal b, decimal x) => (decimal)Math.Log((double)x, (double)b);

        ///
        /// Calculates the sine of an angle.
        ///
        /// <param name="x">An angle, in radians</param>
        /// <returns>The value of <c>sin(x)</c></returns>
        [Pure]
        public decimal Sin(decimal x) => (decimal)Math.Sin((double)x);

        ///
        /// Calculates the cosine of an angle.
        ///
        /// <param name="x">An angle, in radians</param>
        /// <returns>The value of <c>cos(x)</c></returns>
        [Pure]
        public decimal Cos(decimal x) => (decimal)Math.Cos((double)x);

        ///
        ///     Calculates the tangent of an angle.
        ///
        /// <param name="x">An angle, in radians</param>
        /// <returns>The value of <c>tan(x)</c></returns>
        [Pure]
        public decimal Tan(decimal x) => (decimal)Math.Tan((double)x);

        ///
        /// Calculates an arcsine.
        ///
        /// <param name="x">The value for which an arcsine is to be calculated.</param>
        /// <returns>The value of <c>asin(x)</c>, in radians.</returns>
        [Pure]
        public decimal Asin(decimal x) => (decimal)Math.Asin((double)x);

        ///
        /// Calculates an arc-cosine.
        ///
        /// <param name="x">The value for which an arc-cosine is to be calculated</param>
        /// <returns>The value of <c>acos(x)</c>, in radians</returns>
        [Pure]
        public decimal Acos(decimal x) => (decimal)Math.Acos((double)x);

        ///
        /// Calculates an arc-tangent.
        ///
        /// <param name="x">The value for which an arc-tangent is to be calculated</param>
        /// <returns>The value of <c>atan(x)</c>, in radians</returns>
        [Pure]
        public decimal Atan(decimal x) => (decimal)Math.Atan((double)x);

        ///
        /// Calculates a hyperbolic sine.
        ///
        /// <param name="x">The value for which a hyperbolic sine is to be calculated</param>
        /// <returns>The value of <c>sinh(x)</c></returns>
        [Pure]
        public decimal Sinh(decimal x) => (decimal)Math.Sinh((double)x);

        ///
        /// Calculates a hyperbolic cosine.
        ///
        /// <param name="x">The value for which a hyperbolic cosine is to be calculated</param>
        /// <returns>The value of <c>cosh(x)</c></returns>
        [Pure]
        public decimal Cosh(decimal x) => (decimal)Math.Cosh((double)x);

        ///
        /// Calculates a hyperbolic tangent.
        ///
        /// <param name="x">
        /// The value for which a hyperbolic tangent is to be calculated.
        /// </param>
        /// <returns>The value of <c>tanh(x)</c></returns>
        [Pure]
        public decimal Tanh(decimal x) => (decimal)Math.Tanh((double)x);

        /// Calculates an area hyperbolic sine
        /// <param name="x">The value for which an area hyperbolic sine is to be calculated.
        /// </param>
        /// <returns>The value of <c>asinh(x)</c>.</returns>
        [Pure]
        public decimal Asinh(decimal x) => Log(x + Sqrt((x * x) + 1m));

        ///
        /// Calculates an area hyperbolic cosine.
        ///
        /// <param name="x">The value for which an area hyperbolic cosine is to be calculated.
        /// </param>
        /// <returns>The value of <c>acosh(x)</c>.</returns>
        [Pure]
        public decimal Acosh(decimal x) => Log(x + Sqrt((x * x) - 1m));

        ///
        /// Calculates an area hyperbolic tangent.
        ///
        /// <param name="x">The value for which an area hyperbolic tangent is to be calculated.
        /// </param>
        /// <returns>The value of <c>atanh(x)</c></returns>
        [Pure]
        public decimal Atanh(decimal x) => 0.5m * Log((1m + x) / (1m - x));

        ///
        /// Negate the value
        ///
        /// <param name="x">Value to negate</param>
        /// <returns>The negated source value</returns>
        [Pure]
        public decimal Negate(decimal x) => -x;

        ///
        /// Semigroup append (sum)
        ///
        /// <param name="x">left hand side of the append operation</param>
        /// <param name="y">right hand side of the append operation</param>
        /// <returns>x + y</returns>
        [Pure]
        public decimal Append(decimal x, decimal y) => x + y;

        ///
        /// Zero
        ///
        [Pure]
        public decimal Empty() => 0;

        ///
        /// Get the hash-code of the provided value
        ///
        /// <returns>Hash code of x</returns>
        [Pure]
        public int GetHashCode(decimal x) =>
            x.GetHashCode();

        [Pure]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Task<bool> EqualsAsync(decimal x, decimal y) =>
            Equals(x, y).AsTask();

        [Pure]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Task<int> GetHashCodeAsync(decimal x) =>
            GetHashCode(x).AsTask();

        [Pure]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Task<int> CompareAsync(decimal x, decimal y) =>
            Compare(x, y).AsTask();
    }
}


text:
from owslib.csw import CatalogueServiceWeb
from owslib import fes
import netCDF4
import numpy as np

# ## Find model results at NODC (geoportal)

# In[2]:

endpoint = 'http://www.nodc.noaa.gov/geoportal/csw'   # NODC/UAF Geoportal: granule level
csw = CatalogueServiceWeb(endpoint,timeout=60)
print csw.version

# In[3]:

csw.get_operation_by_name('GetRecords').constraints

# In[4]:

val = 'level'
filter1 = fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [ filter1 ]

# In[5]:

csw.getrecords2(constraints=filter_list,maxrecords=100,esn='full')
len(csw.records.keys())

# In[6]:

choice=np.random.choice(list(csw.records.keys()))
print(csw.records[choice].title)
csw.records[choice].references

# ## Find model results at NGDC  (geoportal)

# In[161]:

endpoint = 'http://www.ngdc.noaa.gov/geoportal/csw' #  NGDC/IOOS Geoportal
csw = CatalogueServiceWeb(endpoint,timeout=60)
csw.version

# In[162]:

csw.get_operation_by_name('GetRecords').constraints

# In[163]:

try:
    csw.get_operation_by_name('GetDomain')
    csw.getdomain('apiso:ServiceType', 'property')
    print(csw.results['values'])
except:
    print('GetDomain not supported')

# In[164]:

val = 'level'
filter1 = fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [ filter1 ]

# In[165]:

val = 'erddap'
filter1 = fes.PropertyIsLike(propertyname='apiso:ServiceType',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [ filter1 ]

# In[166]:

csw.getrecords2(constraints=filter_list,maxrecords=1000,esn='full')
len(csw.records.keys())

# In[167]:

choice=np.random.choice(list(csw.records.keys()))
print choice
csw.records[choice].references

# ## Find model data at CATALOG.DATA.GOV (pycsw)

# In[56]:

endpoint = 'http://catalog.data.gov/csw-all' #  catalog.data.gov CSW
#endpoint = 'http://csw.data.gov.uk/geonetwork/srv/en/csw' # data.gov.uk
#endpoint = 'http://www.nationaalgeoregister.nl/geonetwork/srv/eng/csw'
#endpoint = 'http://www.rndt.gov.it/RNDT/CSW'
csw = CatalogueServiceWeb(endpoint,timeout=60)
csw.version

# In[57]:

for oper in csw.operations:
    print(oper.name)

# In[58]:

csw.get_operation_by_name('GetRecords').constraints

# In[59]:

try:
    csw.get_operation_by_name('GetDomain')
    csw.getdomain('apiso:ServiceType', 'property')
    print(csw.results['values'])
except:
    print('GetDomain not supported')

# In[60]:

val = 'salinity'
filter1 = fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [ filter1 ]

# In[61]:

csw.getrecords2(constraints=filter_list,maxrecords=1000,esn='full')
len(csw.records.keys())

# In[ ]:

csw.getrecords2()

# In[51]:

choice=np.random.choice(list(csw.records.keys()))
print csw.records[choice].title
csw.records[choice].references

# ## Search at geoport.whoi.edu (geoportal)

# In[ ]:

endpoint = 'http://geoport.whoi.edu/geoportal/csw' #  catalog.data.gov CSW
csw = CatalogueServiceWeb(endpoint,timeout=60)
print csw.version

# In[ ]:

for oper in csw.operations:
    if oper.name == 'GetRecords':
        print '\nISO Queryables:\n',oper.constraints['SupportedISOQueryables']['values']

# In[ ]:

csw.getrecords2(constraints=filter_list,maxrecords=1000,esn='full')
len(csw.records.keys())

# In[ ]:

choice=random.choice(list(csw.records.keys()))
print choice
csw.records[choice].references

# ## Search at PACIOOS (pycsw)

# In[175]:

endpoint='http://oos.soest.hawaii.edu/pacioos/ogc/csw.py'

# In[176]:

csw = CatalogueServiceWeb(endpoint,timeout=60)
csw.version

# In[177]:

csw.get_operation_by_name('GetRecords').constraints

# In[178]:

try:
    csw.get_operation_by_name('GetDomain')
    csw.getdomain('apiso:ServiceType', 'property')
    print(csw.results['values'])
except:
    print('GetDomain not supported')

# In[179]:

val = 'ROMS'
filter1 = fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [ filter1 ]

# In[180]:

csw.getrecords2(constraints=filter_list,maxrecords=1000,esn='full')
len(csw.records.keys())

# In[181]:

choice=np.random.choice(list(csw.records.keys()))
print choice
csw.records[choice].references

# Working!  Woo hoo!!!

# ## EPA

# In[ ]:

endpoint = 'https://edg.epa.gov/metadata/csw'
csw = CatalogueServiceWeb(endpoint,timeout=60)
csw.version

# In[ ]:

# trying to do this search:
# ('roms' OR 'selfe' OR 'adcirc' OR 'ncom' OR 'hycom' OR 'fvcom') AND 'ocean' NOT 'regridded' NOT 'espresso'
# should return 11 records from NODC geoportal

search_text = ['waves','selfe','adcirc','ncom','hycom','fvcom']
filt=[]
for val in search_text:
    filt.append(fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val),
                                   escapeChar='\\',wildCard='*',singleChar='?'))
filter1=fes.Or(filt)

val = 'ocean'
filter2=fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')

val = 'regridded'
filt=fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter3 = fes.Not([filt])

val = 'espresso'
filt=fes.PropertyIsLike(propertyname='apiso:AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter4 = fes.Not([filt])

filter_list = [fes.And([filter1, filter2, filter3, filter4])]

# In[ ]:

csw.getrecords2(constraints=filter_list,maxrecords=1000,esn='full')
len(csw.records.keys())

# In[ ]:

choice=random.choice(list(csw.records.keys()))
print choice
csw.records[choice].references

# In[ ]:

try:
    csw.get_operation_by_name('GetDomain')
    csw.getdomain('apiso:SupportedISOQueryables', 'apiso:ServiceType')
    print(csw.results['values'])
except:
    print('GetDomain not supported')

# ## USGS CGDMS server (geonetwork)

# In[ ]:

endpoint = 'http://cmgds.marine.usgs.gov/geonetwork/srv/en/csw'
csw = CatalogueServiceWeb(endpoint,timeout=60)
csw.version

# ## USGS CIDA Server (geonetwork)

# In[ ]:

endpoint = 'http://cida.usgs.gov/gdp/geonetwork/srv/en/csw'
csw = CatalogueServiceWeb(endpoint,timeout=60)
csw.version

# In[ ]:

foo=csw.get_operation_by_name('GetRecords')
foo.constraints

# In[ ]:

try:
    csw.get_operation_by_name('GetDomain')
    csw.getdomain('SupportedISOQueryables', 'ServiceType')
    print(csw.results['values'])
except:
    print('GetDomain not supported')

# In[ ]:

val = 'dap'
service_type = fes.PropertyIsLike(propertyname='ServiceType',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [ service_type]

# In[ ]:

csw.getrecords2(constraints=filter_list,maxrecords=1000,esn='full')
len(csw.records.keys())

# In[ ]:

val = 'climate'
filter1 = fes.PropertyIsLike(propertyname='AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [ filter1 ]

# In[ ]:

csw.getrecords2(constraints=filter_list,maxrecords=1000,esn='full')
len(csw.records.keys())

# In[ ]:

choice=random.choice(list(csw.records.keys()))
print choice
csw.records[choice].references

# ## INSPIRE

# In[63]:

endpoint ='http://inspire-geoportal.ec.europa.eu/GeoportalProxyWebServices/resources/OGCCSW202/AT'
csw = CatalogueServiceWeb(endpoint,timeout=60)
csw.version

# In[ ]:

csw.get_operation_by_name('GetRecords').constraints

# In[14]:

try:
    csw.get_operation_by_name('GetDomain')
    csw.getdomain('apiso:ServiceType', 'property')
    print(csw.results['values'])
except:
    print('GetDomain not supported')

# In[15]:

val = 'data'
filter1 = fes.PropertyIsLike(propertyname='AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [ filter1 ]

# In[16]:

csw.getrecords2(constraints=filter_list,maxrecords=1000,esn='full')
len(csw.records.keys())

# In[62]:

choice=random.choice(list(csw.records.keys()))
print(csw.records[choice].title)
csw.records[choice].references

# ## Italy

# In[18]:

endpoint = 'http://www.rndt.gov.it/RNDT/CSW'
csw = CatalogueServiceWeb(endpoint,timeout=60)
csw.version

# In[19]:

csw.get_operation_by_name('GetRecords').constraints

# In[27]:

val = 'water'
filter1 = fes.PropertyIsLike(propertyname='AnyText',literal=('*%s*' % val),
                        escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [ filter1 ]

# In[28]:

csw.getrecords2(constraints=filter_list,maxrecords=100,esn='full')
len(csw.records.keys())

# In[53]:

choice=random.choice(list(csw.records.keys()))
print(csw.records[choice].title)
print(csw.records[choice].references)

# In[152]:

endpoint='http://172.21.173.15/geonetwork/srv/eng/csw'
csw = CatalogueServiceWeb(endpoint,timeout=60)
csw.version

# In[ ]:


text:
<?php

namespace Pingpong\Testing;

use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Facade;

abstract class TestCase extends \Illuminate\Foundation\Testing\TestCase
{
    /**
     * Creates the application.
     *
     * Needs to be implemented by subclasses.
     *
     * @return \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    public function createApplication()
    {
        $app = new Application($this->getBasePath());

        Facade::clearResolvedInstances();
        Facade::setFacadeApplication($app);

        $this->resolveExceptionsHandler($app);
        $this->resolveApplicationConfig($app);
        $this->resolveHttpKernel($app);
        $this->resolveConsoleKernel($app);
        $this->detectEnvironment($app);

        $this->bootstrap($app);

        $this->registerBootedCallback($app);

        return $app;
    }

    /**
     * @param Application $app
     */
    protected function resolveApplicationConfig(Application $app)
    {
        $app->make('Illuminate\Foundation\Bootstrap\LoadConfiguration')->bootstrap($app);

        date_default_timezone_set($this->getApplicationTimezone($app));

        $aliases = array_merge($this->getApplicationAliases($app), $this->getPackageAliases($app));
        $app['config']['app.aliases'] = $aliases;

        $providers = array_merge($this->getApplicationProviders($app), $this->getPackageProviders($app));
        $app['config']['app.providers'] = $providers;
    }

    /**
     * Get application providers.
     *
     * @param \Illuminate\Foundation\Application $app
     *
     * @return array
     */
    protected function getApplicationProviders($app)
    {
        return [
            'Illuminate\Foundation\Providers\ArtisanServiceProvider',
            'Illuminate\Auth\AuthServiceProvider',
            'Illuminate\Bus\BusServiceProvider',
            'Illuminate\Cache\CacheServiceProvider',
            'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider',
            'Illuminate\Routing\ControllerServiceProvider',
            'Illuminate\Cookie\CookieServiceProvider',
            'Illuminate\Database\DatabaseServiceProvider',
            'Illuminate\Encryption\EncryptionServiceProvider',
            'Illuminate\Filesystem\FilesystemServiceProvider',
            'Illuminate\Foundation\Providers\FormRequestServiceProvider',
            'Illuminate\Hashing\HashServiceProvider',
            'Illuminate\Mail\MailServiceProvider',
            'Illuminate\Database\MigrationServiceProvider',
            'Illuminate\Pagination\PaginationServiceProvider',
            'Illuminate\Pipeline\PipelineServiceProvider',
            'Illuminate\Queue\QueueServiceProvider',
            'Illuminate\Redis\RedisServiceProvider',
            'Illuminate\Auth\Passwords\PasswordResetServiceProvider',
            'Illuminate\Database\SeedServiceProvider',
            'Illuminate\Session\SessionServiceProvider',
            'Illuminate\Translation\TranslationServiceProvider',
            'Illuminate\Validation\ValidationServiceProvider',
            'Illuminate\View\ViewServiceProvider',
        ];
    }

    /**
     * Get application aliases.
     *
     * @param \Illuminate\Foundation\Application $app
     *
     * @return array
     */
    protected function getApplicationAliases($app)
    {
        return [
            'App' => 'Illuminate\Support\Facades\App',
            'Artisan' => 'Illuminate\Support\Facades\Artisan',
            'Auth' => 'Illuminate\Support\Facades\Auth',
            'Blade' => 'Illuminate\Support\Facades\Blade',
            'Bus' => 'Illuminate\Support\Facades\Bus',
            'Cache' => 'Illuminate\Support\Facades\Cache',
            'Config' => 'Illuminate\Support\Facades\Config',
            'Cookie' => 'Illuminate\Support\Facades\Cookie',
            'Crypt' => 'Illuminate\Support\Facades\Crypt',
            'DB' => 'Illuminate\Support\Facades\DB',
            'Eloquent' => 'Illuminate\Database\Eloquent\Model',
            'Event' => 'Illuminate\Support\Facades\Event',
            'File' => 'Illuminate\Support\Facades\File',
            'Hash' => 'Illuminate\Support\Facades\Hash',
            'Input' => 'Illuminate\Support\Facades\Input',
            'Inspiring' => 'Illuminate\Foundation\Inspiring',
            'Lang' => 'Illuminate\Support\Facades\Lang',
            'Log' => 'Illuminate\Support\Facades\Log',
            'Mail' => 'Illuminate\Support\Facades\Mail',
            'Password' => 'Illuminate\Support\Facades\Password',
            'Queue' => 'Illuminate\Support\Facades\Queue',
            'Redirect' => 'Illuminate\Support\Facades\Redirect',
            'Redis' => 'Illuminate\Support\Facades\Redis',
            'Request' => 'Illuminate\Support\Facades\Request',
            'Response' => 'Illuminate\Support\Facades\Response',
            'Route' => 'Illuminate\Support\Facades\Route',
            'Schema' => 'Illuminate\Support\Facades\Schema',
            'Session' => 'Illuminate\Support\Facades\Session',
            'Storage' => 'Illuminate\Support\Facades\Storage',
            'URL' => 'Illuminate\Support\Facades\URL',
            'Validator' => 'Illuminate\Support\Facades\Validator',
            'View' => 'Illuminate\Support\Facades\View',
        ];
    }

    /**
     * @return string
     */
    abstract public function getBasePath();

    /**
     * Get package aliases.
     *
     * @return array
     */
    protected function getPackageAliases()
    {
        return [];
    }

    /**
     * Get package providers.
     *
     * @return array
     */
    protected function getPackageProviders()
    {
        return [];
    }

    /**
     * @param $app
     */
    protected function registerBootedCallback($app)
    {
        //
    }

    /**
     * @param Application $app
     */
    protected function resolveExceptionsHandler(Application $app)
    {
        $app->singleton(
            'Illuminate\Contracts\Debug\ExceptionHandler',
            'Pingpong\Testing\Exceptions\Handler'
        );
    }

    /**
     * @param Application $app
     */
    protected function resolveConsoleKernel(Application $app)
    {
        $app->singleton(
            'Illuminate\Contracts\Console\Kernel',
            'Pingpong\Testing\Console\Kernel'
        );
    }

    /**
     * @param Application $app
     */
    protected function resolveHttpKernel(Application $app)
    {
        $app->singleton(
            'Illuminate\Contracts\Http\Kernel',
            'Pingpong\Testing\Http\Kernel'
        );
    }

    /**
     * @param Application $app
     *
     * @return string
     */
    protected function getApplicationTimezone(Application $app)
    {
        return 'UTC';
    }

    /**
     * @param $app
     */
    protected function detectEnvironment(Application $app)
    {
        $app->detectEnvironment(function () {
            return 'testing';
        });
    }

    /**
     * @param Application $app
     */
    protected function bootstrap(Application $app)
    {
        $bootstrappers = [
            'Illuminate\Foundation\Bootstrap\ConfigureLogging',
            'Illuminate\Foundation\Bootstrap\HandleExceptions',
            'Illuminate\Foundation\Bootstrap\RegisterFacades',
            'Illuminate\Foundation\Bootstrap\RegisterProviders',
            'Illuminate\Foundation\Bootstrap\BootProviders',
        ];

        foreach ($bootstrappers as $class) {
            $app->make($class)->bootstrap($app);
        }
    }
}


text:
'use strict';

const { EventEmitter } = require('events');
const { DROP_FEATURES } = require('../event-type');

const EVENT_COLUMNS = ['id', 'type', 'created_by', 'created_at', 'data'];

class EventStore extends EventEmitter {
    constructor(db) {
        super();
        this.db = db;
    }

    async store(event) {
        await this.db('events').insert({
            type: event.type,
                created_by: event.createdBy, // eslint-disable-line
            data: event.data,
        });
        this.emit(event.type, event);
    }

    async getEvents() {
        const rows = await this.db
            .select(EVENT_COLUMNS)
            .from('events')
            .limit(100)
            .orderBy('created_at', 'desc');

        return rows.map(this.rowToEvent);
    }

    async getEventsFilterByName(name) {
        const rows = await this.db
            .select(EVENT_COLUMNS)
            .from('events')
            .limit(100)
            .whereRaw("data ->> 'name' = ?", [name])
            .andWhere(
                'id',
                '>=',
                this.db
                    .select(this.db.raw('coalesce(max(id),0) as id'))
                    .from('events')
                    .where({ type: DROP_FEATURES }),
            )
            .orderBy('created_at', 'desc');

        return rows.map(this.rowToEvent);
    }

    rowToEvent(row) {
        return {
            id: row.id,
            type: row.type,
            createdBy: row.created_by,
            createdAt: row.created_at,
            data: row.data,
        };
    }
}

module.exports = EventStore;


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:title="@string/profile_preferences_category_application"
    app:key="prf_pref_applicationCategory" >

    <PreferenceCategory
        app:key="prf_pref_applicationDisableScanningCategory"
        app:title="@string/profile_preferences_applicationEnableScanning"
        app:layout="@layout/mp_preference_category">
        <ListPreference
            app:title="@string/profile_preferences_applicationEnableWifiScanning"
            app:summary="@string/array_pref_no_change"
            app:key="prf_pref_applicationDisableWifiScanning"
            app:defaultValue="0"
            app:entries="@array/applicationDisableScanningArray"
            app:entryValues="@array/applicationDisableScanningValues"
            app:layout="@layout/mp_preference_material_widget" />
        <ListPreference
            app:title="@string/profile_preferences_applicationEnableBluetoothScanning"
            app:summary="@string/array_pref_no_change"
            app:key="prf_pref_applicationDisableBluetoothScanning"
            app:defaultValue="0"
            app:entries="@array/applicationDisableScanningArray"
            app:entryValues="@array/applicationDisableScanningValues"
            app:layout="@layout/mp_preference_material_widget" />
        <ListPreference
            app:title="@string/profile_preferences_applicationEnableLocationScanning"
            app:summary="@string/array_pref_no_change"
            app:key="prf_pref_applicationDisableLocationScanning"
            app:defaultValue="0"
            app:entries="@array/applicationDisableScanningArray"
            app:entryValues="@array/applicationDisableScanningValues"
            app:layout="@layout/mp_preference_material_widget" />
        <ListPreference
            app:title="@string/profile_preferences_applicationEnableMobileCellScanning"
            app:summary="@string/array_pref_no_change"
            app:key="prf_pref_applicationDisableMobileCellScanning"
            app:defaultValue="0"
            app:entries="@array/applicationDisableScanningArray"
            app:entryValues="@array/applicationDisableScanningValues"
            app:layout="@layout/mp_preference_material_widget" />
        <ListPreference
            app:title="@string/profile_preferences_applicationEnableOrientationScanning"
            app:summary="@string/array_pref_no_change"
            app:key="prf_pref_applicationDisableOrientationScanning"
            app:defaultValue="0"
            app:entries="@array/applicationDisableScanningArray"
            app:entryValues="@array/applicationDisableScanningValues"
            app:layout="@layout/mp_preference_material_widget" />
        <ListPreference
            app:title="@string/profile_preferences_applicationEnableNotificationScanning"
            app:summary="@string/array_pref_no_change"
            app:key="prf_pref_applicationDisableNotificationScanning"
            app:defaultValue="0"
            app:entries="@array/applicationDisableScanningArray"
            app:entryValues="@array/applicationDisableScanningValues"
            app:layout="@layout/mp_preference_material_widget" />
        <ListPreference
            app:title="@string/profile_preferences_applicationEnablePeriodicScanning"
            app:summary="@string/array_pref_no_change"
            app:key="prf_pref_applicationDisablePeriodicScanning"
            app:defaultValue="0"
            app:entries="@array/applicationDisableScanningArray"
            app:entryValues="@array/applicationDisableScanningValues"
            app:layout="@layout/mp_preference_material_widget" />
    </PreferenceCategory>
    <PreferenceCategory
        app:key="prf_pref_applicationOthers"
        app:title="@string/profile_preferences_category_others"
        app:layout="@layout/mp_preference_category">
        <ListPreference
            app:title="@string/profile_preferences_applicationEnableGlobalEventsRun"
            app:summary="@string/array_pref_no_change"
            app:key="prf_pref_applicationDisableGloabalEventsRun"
            app:defaultValue="0"
            app:entries="@array/applicationDisableGlobalEventsRunArray"
            app:entryValues="@array/applicationDisableGlobalEventsRunValues"
            app:layout="@layout/mp_preference_material_widget" />
    </PreferenceCategory>

</androidx.preference.PreferenceScreen>


text:
package com.octopod.util.event;

import java.lang.reflect.Method;

/**
 *
 *
 * @author Octopod <octopodsquad@gmail.com>
 */
public abstract class AsyncEventHandler<T extends Event>
{
	private final Object lock = new Object();
	private final Object last = new Object();
	private int executionsLeft;
	private EventBus bus;

	public AsyncEventHandler(EventBus bus)
	{
		this(bus, 1);
	}

	public AsyncEventHandler(EventBus bus, int executions)
	{
		this.bus = bus;
		this.executionsLeft = executions;
		register();
	}

	public abstract boolean handle(T event);

	public void finish(boolean success) {}

	@SuppressWarnings("unchecked")
	public final Class<T> type()
	{
		for(Method method: this.getClass().getDeclaredMethods())
		{
			if(method.getName().equals("handle")) return (Class<T>)method.getParameterTypes()[0];
		}
		return null;
	}

	@EventSubscribe
	public final void process(Event event)
	{
		Class<T> type = type();
		if(executionsLeft > 0 && type.isInstance(event))
		{
			try
			{
				if(handle(type.cast(event)))
				{
					synchronized(lock)
					{
						if(--executionsLeft == 0) unregister();
						lock.notify();
					}
				}
			}
			catch (Exception e) {e.printStackTrace();}
		}
	}

	private void register()
	{
		bus.register(this);
	}

	private void unregister()
	{
		synchronized(last) {last.notify();}
		bus.unregister(this);
	}

	/**
	 * Waits for the filter to get its executions.
	 * Use timeout (in ms) to timeout afterwards and return anyway.
	 *
	 * @param timeout the timeout, in ms
	 * @param unregister unregister on timeout?
	 * @return whether the listener succesfully did its executions within the timeout
	 */
	public final boolean waitFor(long timeout, boolean unregister)
	{
		long start = System.currentTimeMillis();
		try
		{
			synchronized(lock) {lock.wait(timeout);}
		}
		catch (InterruptedException e) {}
		System.out.println("timeout= " + timeout + "\ntime elapsed= " + (System.currentTimeMillis() - start));
		boolean success = (System.currentTimeMillis() - start) < timeout;
		if(!success && unregister) unregister();
		AsyncEventHandler.this.finish(success);
		return success;
	}

	public final boolean waitFor(long timeout)
	{
		return waitFor(timeout, true);
	}

	public final void awaitFor(final long timeout, final boolean unregister)
	{
		new Thread()
		{
			public void run()
			{
				waitFor(timeout, unregister);
			}
		}.start();
	}

	public final void awaitFor(long timeout)
	{
		awaitFor(timeout, true);
	}

	public interface Finish
	{
		/**
		 * An implementation for awaitFor() that will run after the wait.
		 * @param successful false if awaitFor() timed out
		 */
		public void finish(boolean successful);
	}

}


text:
/** \file encoding_analyzer.h
 * Definition of class EncodingAnalyzer.
 *
 * \author Jun Jiang
 * \version 0.1
 * \date Dec 25, 2009
 */

#ifndef LANGID_ENCODING_ANALYZER_H
#define LANGID_ENCODING_ANALYZER_H

#include "langid/language_id.h"

NS_ILPLIB_LANGID_BEGIN

class ProfileModel;

/**
 * EncodingAnalyzer identifies character encoding such as UTF-8, GB18030, EUC-JP, EUC-KR, etc.
 */
class EncodingAnalyzer
{
public:
    /**
     * Constructor.
     * \param profileModel profile model for encoding identification
     */
    EncodingAnalyzer(const ProfileModel& profileModel);

    /**
     * Identify the character encoding of \e str.
     * \param[in] str string
     * \param[out] id the character encoding as identification result
     * \param[in] maxInputSize maximum analysis size in bytes, the entire string would be analyzed if a non-positive value is given.
     * \return true for success, false for failure
     */
    bool encodingFromString(const char* str, EncodingID& id, int maxInputSize) const;

    /**
     * Identify the character encoding of file \e fileName.
     * \param[in] fileName file name
     * \param[out] id the character encoding as identification result
     * \param[in] maxInputSize maximum analysis size in bytes, the entire file would be analyzed if a non-positive value is given.
     * \return true for success, false for failure
     */
    bool encodingFromFile(const char* fileName, EncodingID& id, int maxInputSize) const;

private:
    /** profile model for encoding identification */
    const ProfileModel& profileModel_;
};

NS_ILPLIB_LANGID_END

#endif // LANGID_ENCODING_ANALYZER_H